branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <repo_name>rick2785/CustomLBTATabBar<file_sep>/README.md
# CustomLBTATabBar
Custom Tab bar component with Image Picker | SwiftUI 2.0
<p align="center">
<img src="CustomLBTATabBar.gif" width="256" height="550" title="Courses">
</p>
<file_sep>/CustomLBTATabBar/ContentView.swift
//
// ContentView.swift
// CustomLBTATabBar
//
// Created by <NAME> on 1/11/21.
//
import SwiftUI
extension UIApplication {
var keyWindowInConnectedScenes: UIWindow? {
return windows.first(where: { $0.isKeyWindow })
}
}
struct CoursesView: View {
struct Course: Hashable {
let name, imageName: String
let numLessons: Int
let totalTime: Float
}
let courses: [Course] = [
.init(name: "SwiftUI Mastery", imageName: "course1", numLessons: 35, totalTime: 10.35),
.init(name: "FullStack Social", imageName: "course2", numLessons: 50, totalTime: 20.5),
.init(name: "Maps UIKit SwiftUI", imageName: "course3", numLessons: 44, totalTime: 16.3)
]
var body: some View {
NavigationView {
ScrollView {
VStack(alignment: .leading) {
ForEach(courses, id: \.self) { course in
Image(course.imageName)
.resizable()
.scaledToFill()
HStack(alignment: .top) {
VStack(alignment: .leading) {
Text(course.name)
.font(.system(size: 16, weight: .bold))
Text("\(course.numLessons) lessons")
}
Spacer()
HStack {
Image(systemName: "deskclock")
.font(.system(size: 14, weight: .bold))
Text(course.totalTime.description + " hrs")
.font(.system(size: 15, weight: .semibold))
}.foregroundColor(.white)
.padding(.vertical, 6)
.padding(.horizontal, 12)
.background(Color.blue)
.cornerRadius(16)
}.padding(.top, 8)
.padding(.horizontal)
.padding(.bottom, 16)
}
}
}.navigationTitle("Courses")
}
}
}
struct TasksView: View {
@State var tasks: [Int] = Array(0..<20)
var body: some View {
NavigationView {
List {
ForEach(tasks, id: \.self) { num in
Text("Task \(num)")
}
.onDelete(perform: { indexSet in
tasks.remove(at: indexSet.first ?? 0)
})
}
.navigationTitle("Tasks")
}
}
}
import SwiftUIX
struct ContentView: View {
init() {
// UITabBar.appearance().barTintColor = .systemBackground
// UINavigationBar.appearance().barTintColor = .systemBackground
UINavigationBar.appearance().barTintColor = .white
}
@State var selectedTabIndex = 0
// @State var shouldShowModal = false
private let tabBarImageNames = ["pencil", "lasso", "plus.app.fill", "person.fill", "trash"]
@State var imageData: Data?
@State var shouldShowImagePicker = false
var body: some View {
GeometryReader { proxy in
ZStack {
Spacer()
.fullScreenCover(isPresented: $shouldShowImagePicker, content: {
ImagePicker(data: $imageData, encoding: .png)
})
VStack(spacing: 0) {
switch selectedTabIndex {
case 0:
CoursesView()
case 1:
TasksView()
default:
NavigationView {
VStack {
Text("\(tabBarImageNames[selectedTabIndex])")
Spacer()
}
.navigationTitle("\(tabBarImageNames[selectedTabIndex])")
}
}
Divider()
HStack {
ForEach(0..<5, id: \.self) { num in
HStack {
Button(action: {
if num == 2 {
shouldShowImagePicker.toggle()
return
}
self.selectedTabIndex = num
}, label: {
Spacer()
if num == 2 {
Image(systemName: tabBarImageNames[num])
.foregroundColor(Color.red)
.font(.system(size: 44, weight: .semibold))
} else {
Image(systemName: tabBarImageNames[num])
.foregroundColor(selectedTabIndex == num ? .black : .init(white: 0.7))
}
Spacer()
})
}.font(.system(size: 24, weight: .semibold))
}
}
.padding(.top, 12)
.padding(.bottom, 12)
.padding(.bottom, proxy.safeAreaInsets.bottom)
}.edgesIgnoringSafeArea(.bottom)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 38a791c4a23f53cfe8c200229be2bad0e69c0989 | [
"Markdown",
"Swift"
] | 2 | Markdown | rick2785/CustomLBTATabBar | 4c02f6845b4ed441a984e3ee48d406ada7a424cc | 18207392c45199471abe238700c76a719cfe763a |
refs/heads/master | <repo_name>JackHunag/News<file_sep>/News/src/base/impl/menu/NewMenuDetailPager.java
package base.impl.menu;
import java.util.ArrayList;
import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import base.BaseMenuDetailPager;
import com.android.news.MainActivity;
import com.android.news.R;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.viewpagerindicator.TabPageIndicator;
import domain.NewMenu.NewTagData;
/**
* 菜单详情页-新闻中心
*
* @author hsssf
*
*/
/*
* 思路:在新闻页面因为为每一个头部分类栏目的布局都一样,所以创建一个布局对象统一处理
* 在该类中传递相应数据过去
* 注意:
* 事件的处理和布局框架的编写
* 开源框架ViewPagerIndicatorLibray使用:
* 1.引入库 2.解决support-v4冲突(让两个版本一致) 3.从例子程序中拷贝布局文件
* 4.从例子程序中拷贝相关代码(指示器和viewpager绑定; 重写getPageTitle返回标题) 5.在清单文件中增加样式 6.背景修改为白色
* 7.修改样式-背景样式&文字样式
* @Override public boolean dispatchTouchEvent(MotionEvent ev) { 该方法使到所有父控件
* 不拦截子控件的事件 getParent().requestDisallowInterceptTouchEvent(true); return
* super.dispatchTouchEvent(ev); }
*/
public class NewMenuDetailPager extends BaseMenuDetailPager implements
OnPageChangeListener {
private ViewPager mViewPager;
private TabPageIndicator indicator;
private ArrayList<NewTagData> mTagData;
private TagDetailPager mDetailPager;
private ArrayList<TagDetailPager> mPagerList;
public NewMenuDetailPager(Activity mActivity, ArrayList<NewTagData> children) {
super(mActivity);
//从新闻中心传递过来相应的新闻数据
mTagData = children;
}
@Override
public View initView() {
View view = View
.inflate(mActivity, R.layout.new_menu_detailpager, null);
mViewPager = (ViewPager) view.findViewById(R.id.vp_news_menu_detail);
indicator = (TabPageIndicator) view.findViewById(R.id.indicator);
ImageButton btn_next = (ImageButton) view.findViewById(R.id.btn_next);
btn_next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//给分类栏目的按键添加点击事件
//得到被选中的item值,并设置相应的item
int currentItem = mViewPager.getCurrentItem();
currentItem++;
mViewPager.setCurrentItem(currentItem);
}
});
indicator.setOnPageChangeListener(this);
return view;
}
@Override
public void initData() {
mPagerList = new ArrayList<TagDetailPager>();
//把获取到的新闻头部栏目数据对象封装好
for (int i = 0; i < mTagData.size(); i++) {
mDetailPager = new TagDetailPager(mActivity, mTagData.get(i));
mPagerList.add(mDetailPager);
}
mViewPager.setAdapter(new DetailPagerAdapter());
indicator.setViewPager(mViewPager);
}
class DetailPagerAdapter extends PagerAdapter {
@Override
public CharSequence getPageTitle(int position) {
// 获取 json中childre的数据
NewTagData data = mTagData.get(position);
return data.title;
}
@Override
public int getCount() {
return mPagerList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TagDetailPager tagPager = mPagerList.get(position);
View view = tagPager.mRootView;
container.addView(view);
// 初始化数据
tagPager.initData();
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
@Override
public void onPageSelected(int position) {
if (position == 0) {
setSlidingMenuEnable(true);
} else {
setSlidingMenuEnable(false);
}
}
private void setSlidingMenuEnable(boolean b) {
// 获取slipmenu对象,才可禁止侧边栏
MainActivity mainUI = (MainActivity) mActivity;
SlidingMenu slidingMenu = mainUI.getSlidingMenu();
// 设置它触摸的模式
if (b) {
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
} else {
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
}
}
@Override
public void onPageScrollStateChanged(int position) {
}
@Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
}
<file_sep>/README.md
News为主项目,SlidingMenu-master,ViewPagerIndicator-master,xUtils-master是相应的类库,zhbj为服务器代码,将它放到自己的Tomcat的目录下 \webapps\ROOT
<file_sep>/News/src/com/android/news/NewDetailActivity.java
package com.android.news;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
public class NewDetailActivity extends Activity implements OnClickListener {
private ProgressBar mProgress;
private String mUrl;// 新闻详情内容链接
private WebView mWebView;
private ImageButton btn_back;
private ImageButton mTextSize;
private ImageButton mShare;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_new_detail);
initView();
initWebView();
}
private void initView() {
mWebView = (WebView) findViewById(R.id.wv_detail);
mProgress = (ProgressBar) findViewById(R.id.pb_new_finish);
btn_back = (ImageButton) findViewById(R.id.btn_back);
mTextSize = (ImageButton) findViewById(R.id.btn_change_textsize);
mShare = (ImageButton) findViewById(R.id.btn_share);
Intent intent = getIntent();
mUrl = intent.getStringExtra("url");
btn_back.setOnClickListener(this);
mTextSize.setOnClickListener(this);
mShare.setOnClickListener(this);
}
private void initWebView() {
mWebView.loadUrl(mUrl);
mSettings = mWebView.getSettings();
mSettings.setJavaScriptEnabled(true);// 网页可显示js效果
mSettings.setBuiltInZoomControls(true);// 显示缩放按钮(wap网页不支持)
mSettings.setUseWideViewPort(true);// 双击缩放(wap网页不支持)
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
// 网页进度的变化
super.onProgressChanged(view, newProgress);
System.out.println("newProgress------" + newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
// 网页标题
super.onReceivedTitle(view, title);
System.out.println("title------" + title);
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// 网页开始加载时调用
super.onPageStarted(view, url, favicon);
mProgress.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
// 网页结束加载时调用
super.onPageFinished(view, url);
mProgress.setVisibility(View.GONE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// 所有网页链接都会走这个方法
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_back:
finish();
break;
case R.id.btn_change_textsize:
// 展示对话框
showDialog();
break;
case R.id.btn_share:
showShare();
break;
default:
break;
}
}
private void showShare() {
ShareSDK.initSDK(this);
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle("分享");
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://sharesdk.cn");
// text是分享文本,所有平台都需要这个字段
oks.setText("我是分享文本");
//分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://sharesdk.cn");
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment("我是测试评论文本");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("ShareSDK");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
oks.show(this);
}
private int mWhich;// 单选框被选中条目的位置id
private int mCurrentWhich=2;
private WebSettings mSettings;
private void showDialog() {
// 创建AlertDialog.Builder 对象
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("字体设置");
String[] items = new String[] { "超大号字体", "大号字体", "正常字体", "小号字体",
"超小号字体" };
// 设置单选框
builder.setSingleChoiceItems(items, mCurrentWhich,
new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mWhich = which;
System.out.println("which----" + which);
}
});
builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (mWhich) {
case 0:
//"超大号字体"
mSettings.setTextSize(TextSize.LARGEST);
break;
case 1:
// "大号字体"
mSettings.setTextSize(TextSize.LARGER);
break;
case 2:
//, "正常字体"
mSettings.setTextSize(TextSize.NORMAL);
break;
case 3:
//"小号字体",
mSettings.setTextSize(TextSize.SMALLER);
break;
case 4:
//"超小号字体"
mSettings.setTextSize(TextSize.SMALLEST);
break;
default:
break;
}
mCurrentWhich =mWhich;
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
}
<file_sep>/News/src/com/android/news/GuideActivity.java
package com.android.news;
import java.util.ArrayList;
import utils.ConstantValue;
import utils.DensityUtils;
import utils.SpUtils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class GuideActivity extends Activity implements OnClickListener {
private Button btn_start;
private ViewPager vp_guide;
private LinearLayout ll_container;
private int[] resimage = new int[] { R.drawable.guide_1,
R.drawable.guide_2, R.drawable.guide_3 };
private ArrayList<ImageView> mImgList;
private ImageView iv_red_ponit;
private ImageView mPonitView;
private int mPonitDes;
private int OldPosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_guide);
initUI();
initData();
}
private void initData() {
mImgList = new ArrayList<ImageView>();
for (int i = 0; i < resimage.length; i++) {
// 初始化viewpager
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(resimage[i]);
mImgList.add(imageView);
// 初始化小圆点
mPonitView = new ImageView(this);
mPonitView.setImageResource(R.drawable.guide_ponit_selector);
// 设置布局参数
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
params.leftMargin = DensityUtils.dip2Px(this, 10);
mPonitView.setEnabled(false);
}
mPonitView.setLayoutParams(params);
ll_container.addView(mPonitView);
}
ll_container.getChildAt(0).setEnabled(true);
vp_guide.setAdapter(new GuideAdpter());
/*
* iv_red_ponit.getViewTreeObserver().addOnGlobalLayoutListener( new
* OnGlobalLayoutListener() {
*
* @Override public void onGlobalLayout() {
* iv_red_ponit.getViewTreeObserver()
* .removeGlobalOnLayoutListener(this); mPonitDes =
* ll_container.getChildAt(1).getLeft() -
* ll_container.getChildAt(0).getLeft();
*
* } });
*/
}
class GuideAdpter extends PagerAdapter {
@Override
public int getCount() {
return mImgList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
// 初始化item
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView view = mImgList.get(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
private void initUI() {
btn_start = (Button) findViewById(R.id.btn_start);
vp_guide = (ViewPager) findViewById(R.id.vp_guide);
ll_container = (LinearLayout) findViewById(R.id.ll_container);
// iv_red_ponit = (ImageView) findViewById(R.id.iv_red_ponit);
btn_start.setOnClickListener(this);
vp_guide.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// 当页面被选时调用
if (position == mImgList.size() - 1) {
btn_start.setVisibility(View.VISIBLE);
} else {
btn_start.setVisibility(View.INVISIBLE);
}
int newPosition = position % mImgList.size();
ll_container.getChildAt(OldPosition).setEnabled(false);
ll_container.getChildAt(newPosition).setEnabled(true);
OldPosition = newPosition;
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
// 当页面在滑动时回调
/*
* int leftMargin = (int)
* (mPonitDes*positionOffset)+position*mPonitDes;
* RelativeLayout.LayoutParams params =
* (RelativeLayout.LayoutParams) iv_red_ponit.getLayoutParams();
* params.leftMargin=leftMargin;
* iv_red_ponit.setLayoutParams(params);
*/
}
@Override
public void onPageScrollStateChanged(int state) {
// 当页面在状态改变时回调
}
});
}
@Override
public void onClick(View v) {
SpUtils.setBoolean(GuideActivity.this, ConstantValue.IS_FIRST_ENTER,
false);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
<file_sep>/News/src/base/impl/NewsCenterPager.java
package base.impl;
import java.util.ArrayList;
import utils.CacheUtils;
import utils.GlobalConstants;
import android.app.Activity;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import base.BaseMenuDetailPager;
import base.BasePager;
import base.impl.menu.InteractMenuDetailPager;
import base.impl.menu.NewMenuDetailPager;
import base.impl.menu.PhotosMenuDetailPager;
import base.impl.menu.TopicMenuDetailPager;
import com.android.news.MainActivity;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import domain.NewMenu;
import fragment.LeftMenuFragment;
public class NewsCenterPager extends BasePager {
private NewMenu mJsonData;
private ArrayList<BaseMenuDetailPager> mMenuDetailPager;
private BaseMenuDetailPager basePager;
public NewsCenterPager(Activity mActivity) {
super(mActivity);
}
public void initData() {
System.out.println("新闻初始化了.....");
btnMenu.setVisibility(View.VISIBLE);
String cache = CacheUtils.getCache(GlobalConstants.CATEGORY_URL,
mActivity);
// 判断是否有缓存,如果有则加载缓存数据
if (!TextUtils.isEmpty(cache)) {
processResult(cache);
}
getDataFromServer();
}
/**
* 请求服务器获取数据
*/
private void getDataFromServer() {
// 获取Xutil对象
HttpUtils xutil = new HttpUtils();
// 向服务器发送一个请求,通过回调获取数据
/*
* 三个参数:请求方式,服务器地址,回调接口
*/
xutil.send(HttpMethod.GET, GlobalConstants.CATEGORY_URL,
new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
// 请求成功时调用
// 获取服务器返回结果
String result = responseInfo.result;
System.out.println("服务器返回结果" + result);
processResult(result);
loadPagerData();
CacheUtils.setCache(result,
GlobalConstants.CATEGORY_URL, mActivity);
}
@Override
public void onFailure(HttpException error, String msg) {
// 请求失败时调用
error.printStackTrace();
Toast.makeText(mActivity, msg, 1);
}
});
}
/**
* 加载侧边栏菜单页面
*/
protected void loadPagerData() {
mMenuDetailPager = new ArrayList<BaseMenuDetailPager>();
mMenuDetailPager.add(new NewMenuDetailPager(mActivity, mJsonData.data
.get(0).children));
mMenuDetailPager.add(new TopicMenuDetailPager(mActivity));
mMenuDetailPager.add(new PhotosMenuDetailPager(mActivity,btn_photo));
mMenuDetailPager.add(new InteractMenuDetailPager(mActivity));
// 当加载页面时,就设置默认新闻中心为首页
setCurrentDetailPager(0);
}
/**
* 解析服务器返回的数据 GSON
*/
protected void processResult(String json) {
// 创建GSON对象
Gson gson = new Gson();
mJsonData = gson.fromJson(json, NewMenu.class);
// 给leftfragment填充数据
/*
* 思路: 在左侧边栏的fragment里面写一个接收数据的方法,在此调用,进行数据传递 获取leftfragment对象?
* 在mainactivity中写一个获取leftfragment对象的方法,通过mactivity调用
*/
MainActivity mainActivity = (MainActivity) mActivity;
LeftMenuFragment leftMenuFragment = mainActivity.getLeftMenuFragment();
leftMenuFragment.setMenuData(mJsonData.data);
}
/**
* 设置侧边栏菜单页面,通过点击的条目更换页面
*
* @param Position
*/
public void setCurrentDetailPager(int Position) {
flContent.removeAllViews();
if (mMenuDetailPager != null) {
basePager = mMenuDetailPager.get(Position);
View rootView = basePager.mRootView;// 获取指定的页面view
// 添加前应把之前页面清除,避免页面重叠
// 动态将指定view添加进basePager里的帧布局
flContent.addView(rootView);
// 设置title
tvTitle.setText(mJsonData.data.get(Position).title);
// 初始化页面的数据
basePager.initData();
if (basePager instanceof PhotosMenuDetailPager ){
btn_photo.setVisibility(View.VISIBLE);
}else{
btn_photo.setVisibility(View.GONE);
}
} else {
TextView textView = new TextView(mActivity);
textView.setText("网络错误");
textView.setTextSize(22);
textView.setTextColor(Color.BLACK);
flContent.addView(textView);
textView.setGravity(Gravity.CENTER);
}
}
}
<file_sep>/News/src/fragment/LeftMenuFragment.java
package fragment;
import java.util.ArrayList;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import base.BasePager;
import base.impl.NewsCenterPager;
import com.android.news.MainActivity;
import com.android.news.R;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import domain.NewMenu.MenuData;
public class LeftMenuFragment extends BaseFragment {
@ViewInject(R.id.lv_left_menu)
private ListView listView;
private ArrayList<MenuData> mMenuDataList;
private int mCurrentPos;
private LeftMenuAdapter mAdapter;
@Override
public View initView() {
View view = View.inflate(mActivity, R.layout.left_menu_fragment, null);
ViewUtils.inject(this, view);
return view;
}
@Override
public void initData() {
}
public void setMenuData(ArrayList<MenuData> data) {
mMenuDataList = data;
mCurrentPos = 0;
mAdapter = new LeftMenuAdapter();
listView.setAdapter(mAdapter);
// 通过点击条目改变字体和图片颜色,默认第一个条目为enable=true
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mCurrentPos = position;
mAdapter.notifyDataSetChanged();
toggle();
setCurrentDetailPager(position);
}
});
}
/**
* 加载侧边菜单详情页
*
* @param position
*/
protected void setCurrentDetailPager(int position) {
MainActivity mainUI = (MainActivity) mActivity;
ContentFragment cfm = mainUI.getContentFragment();
NewsCenterPager newsCenterPager = cfm.getNewsCenterPager();
// 设置newsCenterPager里面的布局
newsCenterPager.setCurrentDetailPager(position);
}
protected void toggle() {
MainActivity mainUI = (MainActivity) mActivity;
SlidingMenu slidingMenu = mainUI.getSlidingMenu();
slidingMenu.toggle();// 如果当前状态是开, 调用后就关; 反之亦然
}
class LeftMenuAdapter extends BaseAdapter {
@Override
public int getCount() {
return mMenuDataList.size();
}
@Override
public MenuData getItem(int position) {
return mMenuDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(mActivity,
R.layout.listview_leftmenu_item, null);
TextView tv_menu = (TextView) view.findViewById(R.id.tv_menu);
tv_menu.setText(mMenuDataList.get(position).title);
if (position == mCurrentPos) {
tv_menu.setEnabled(true);
} else {
tv_menu.setEnabled(false);
}
// 设置字体颜色变化,默认新闻为红色
return view;
}
}
}
<file_sep>/News/src/view/NewTagViewPager.java
package view;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class NewTagViewPager extends ViewPager {
private int downX;
private int downY;
public NewTagViewPager(Context context) {
super(context);
}
public NewTagViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// 根据不同情况来判断是否要父控件拦截事件
getParent().requestDisallowInterceptTouchEvent(true);
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = (int) ev.getX();
downY = (int) ev.getY();
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) ev.getX();
int moveY = (int) ev.getY();
int dx = moveX - downX;
int dy = moveY - downY;
if (Math.abs(dy) < Math.abs(dx)) {
int currentItem = getCurrentItem();
// 左右滑动
if (dx > 0) {
// 向右划
if (currentItem == 0) {
// 第一个页面,需要拦截
getParent().requestDisallowInterceptTouchEvent(false);
}
} else {
// 向左划
int count = getAdapter().getCount();// item总数
if (currentItem == count - 1) {
// 最后一个页面,需要拦截
getParent().requestDisallowInterceptTouchEvent(false);
}
}
} else {
// 上下滑动,需要拦截
getParent().requestDisallowInterceptTouchEvent(false);
}
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
}
| f713f7254486ee44d3b96cfaa918c63efccfbc16 | [
"Markdown",
"Java"
] | 7 | Java | JackHunag/News | 66575003cc27ab05f6c8786b0358cad5d8dfeb2d | 98bf050f4813bcf9ea668e2e875fcb842cff362d |
refs/heads/master | <repo_name>sujinkim123/javaStudy<file_sep>/20210621-자바기본문법정리/src/배열활용_중복없는난수.java
import java.util.Arrays;
// 1 ~ 45 => 중복 없는 정수 6개
public class 배열활용_중복없는난수 {
public static void main(String[] args) {
/*
int[] lotto = new int[6];
for (int i=0; i<lotto.length; i++) {
lotto[i] = (int) (Math.random()*45) + 1; // 1~45 사이의 임의 정수 대입
}
System.out.println(Arrays.toString(lotto));
*/
// 난수를 발생 시에 중복 체크는 하지 않는다
/* int[] arr = new int[10];
for (int i=0; i<arr.length; i++) {
arr[i] = (int) (Math.random()*10)+1; // 1~10
}
System.out.println(Arrays.toString(arr));
*/
int[] com = new int[10];
boolean bCheck = false;
/*
* bCheck => false => com 배열에 저장
* true => 난수를 다시 발생 (중복이 없는 경우)
*/
int rand = 0; // 난수 발생
/*
* i
*/
for (int i=0; i<com.length; i++) {
bCheck = true;
while (bCheck) {
rand = (int) (Math.random() * 45)+1; // 1~10
bCheck = false; // for, while문은 무조건 처음부터 수행
for (int j=0; j<i; j++) {
if (com[j]==rand) {
bCheck = true; // while문을 다시 수행 ==> 중복된 수가 있기 때문에
break; // 자신의 제어문만 제어한다 ==> for
}
}
}
// while문 종료가 되면 중복이 없다
com[i] = rand;
}
System.out.println(Arrays.toString(com));
}
}
<file_sep>/20210622-자바메소드응용/src/달력만들기.java
//. 입력
import java.util.Scanner;
/*
* 달력 만들기
* 1. 사용자 입력 => year, month
* 2. 요청한 달의 요일 확인 (1일)
* 3. 달력 출력
* ================================
* = 중복 코딩을 제거
* = 다음에 사용할 수 있는 기능
*/
public class 달력만들기 {
// 사용자 입력 => 메소드
static int input(String s) {
Scanner stdIn = new Scanner(System.in);
System.out.print(s + " 입력:");
return stdIn.nextInt();
}
// 처리 => 요일 구하기
static int getWeek(int year, int month) {
// 각 달의 마지막 날짜
int[] lastday = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 6월 1일자의 요일 구하기
// 전 년도까지의 총날 수
int total = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
// 전 달까지의 총 날 수
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) // 윤년
// 2월달이 29
lastday[1] = 29;
else
lastday[1] = 28;
for (int i = 0; i < month - 1; i++) {
total += lastday[i];
}
// +1
total++; // 6월 1일자
// %7 => 요일을 구할 수 있다
int week = total % 7; // 1년도 1월 1일 => 월
return week;
}
static void datePrint(int year, int month) {
int week = getWeek(year, month);
int[] lastday = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) // 윤년 조건 (ERP)
// 2월달이 29
lastday[1] = 29;
else
lastday[1] = 28;
System.out.printf("%d년도 %d월\n", year, month);
String[] strWeek = { "일", "월", "화", "수", "목", "금", "토" };
for (int i = 0; i < strWeek.length; i++) {
System.out.print(strWeek[i] + "\t");
}
System.out.println("\n");
// 출력 (달력)
for (int i = 1; i <= lastday[month - 1]; i++) {
if (i == 1) // 첫줄에 출력시에는 요일까지 공백 출력
{
// 빈공백 출력
for (int j = 0; j < week; j++) {
System.out.print("\t");
}
}
// 1일부터 출력
System.out.printf("%2d\t", i);
week++;// 요일 증가
if (week > 6) // 일요일이면 (6=토요일)
{
week = 0;
System.out.println();
}
}
}
public static void main(String[] args) {
int year = input("년도");
int month = input("월");
datePrint(year, month);
}
}
<file_sep>/20210616-자바제어문(do~while)/자바제어문2.java
import java.util.Scanner;
// 짝수의 합, 홀수의 합, 총합 (사용자가 입력한 숫자까지) => do ~ while
public class 자바제어문2 {
public static void main(String[] args) {
// 1. Scanner 생성
Scanner stdIn = new Scanner(System.in);
System.out.print("정수 입력 : ");
int num = stdIn.nextInt();
int sum = 0, even =0, odd = 0;
int i = 1;
do {
if (i%2==0) {
even+=i;
} else {
odd+=i;
}
sum+=i;
i++; // 증가식
} while(i<=num);
System.out.println("1~"+num+"까지의 총합 : " + sum);
System.out.println("1~"+num+"까지의 짝수의 합 : " + even);
System.out.println("1~"+num+"까지의 홀수의 합 : " + odd);
}
}
<file_sep>/20210618-자바배열/src/자바배열응용7.java
/*
* 3) 배열의 값 변경
* index 번호를 이용해서 배열의 값 변경 (index번호는 0부터 시작)
* 2번째 값을 변경
* 배열명[1]=값
* *** index번호가 length-1을 초과하면 오류 발생
*
* 4) 전체 데이터 출력
* 일반 for : 데이터 변경, 두개의 이상 배열에 데이터를 동시 출력
* for~each : 한개의 배열에서 데이터 출력할 경우 주로 사용 (출력 전용)
*
* *** 배열의 단점
* 1) 고정적 => 크기를 늘리기 위해서는 더 큰 배열을 생성후 => 복사
* => 가변형 (컬렉션)
* => 값을 삭제할 수 없다
* => 추가, 수정, 찾기....
*
*/
public class 자바배열응용7 {
public static void main(String[] args) {
}
}
<file_sep>/20210611-자바연산자/src/자바형변환.java
/*
* 1. 형변환 => 데이터형을 변경 (제외 : boolean)
* int => double ==> 10 => 10.0
* double => int (*********) 10.5 => 10 (소수점 제외)
* int => char ==> 65 ==> 'A'
* char => int ==> 'A' ==> 65
*
* 2. 연산처리
* => 같은 데이터형을 만든다 (가장 큰 데이터형으로 변경)
* int + double = double
* ===
* double ===> 자동형변환
*
* double d = 10; ==> 10.0
* int a = 'A'; ==> 65
* ===
* 65
* => int 이하 (byte, short, char) => 연산결과값 int
*
* => 강제 변환 : (데이터형)값
* (int)10.5 ==> 10
* (char)65 => 'A'
* => 라이브러리
* Math.random() ==> 0.0 ~ 0.99
*
* 변수 설정
* 1) 선언
* int a;
* 2) 초기값
* a = 10; ==> 1. 사용자의 입력값을 받아서 저장 Scanner
* ==> 2. 컴퓨터에서 난수
* ===========
* 3) 선언과 동시에 초기값
* int a = 10;
*
*/
public class 자바형변환 {
public static void main(String[] args) {
// double => int
// 변수 선언
int a;
// 초기화
a = (int) (Math.random() * 100); // 0.0~0.99 * 100 => 0.0~99.0 => (int)로 형변환 : 0~99
System.out.println(a);
int b = 'A' + 32; // b=97
System.out.println((char) b); // b에 해당하는 알파벳 확인
}
}
<file_sep>/20210623-자바메소드/src/자바메소드_1.java
import java.util.Arrays;
/*
* 변수 => 변수, 상수, 배열
* 메소드 : 동작 (목록출력, 입력유도...) => 연산자, 제어문
* ====================================== 클래스 (유지보수가 쉽게)
* =========================
* 객체지향 프로그램
* = 데이터 보호 (캡슐화)
* = 재사용 (상속)
* = 다형성 (수정, 추가)
*
* 1. 사용자 정의
* 2. 라이브러리
* ================ 조립
* ======================================= 프로그램이 종료하지 않게 정상상태 유지 (예외처리)
*
* 메소드 VS 함수 : 한개의 작업을 수행하는 명령문의 집합
* ------------
* => 메소드는 클래스 종속
* => 독립적으로 생성 (함수) : C언어, 파이썬, 코틀린
* 1) 메소드의 구성요소
* = 리턴형(처리 결과값: 반드시 한개 사용)
* = 매개변수 : 0 이상 =============> 요청 (클라이언트:user)
* 2) 메소드의 형식
* = 리턴형 메소드명(매개변수...) => 선언
* => 유저가 데이터 봬주면 처리후에 리턴값을 보내준다
* = {
* 구현부
* ---
* ---
* ---
* 결과값 도출
* return 결과값; ==> 결과값이 없는 경우 (return 생략이 가능: 컴파일러가 자동으로 추가)
* }
* = 메소드의 종료시점 => return이 있으면 종료 (return은 항상 마지막에 있는 것이 아니다, 중간에 첨부)
*
* 메소드() {
* if ()
* return;
* else
* return;
* }
*
* 리턴형 메소드명(매개변수...) : 선언부
* {
* 구현부
* return 결과값 전송
* }
*
* 3) 모든 프로그램 : 메소드가 4개
* = 입력 (변수의 초기화)
* = 처리 부분
* = 출력
* = main() => 프로그램의 시작점 (전체 메소드를 호출 = 메소드 조립)
*
* 4) 메소드 종류
* 리턴형 / 매개변수
* O O ===> String substring(int begin, int end)
* String replace(char o, char n)
* O X ===> double random() , String trim()
* ===> 결과값을 받아서 전송 (윈도우, 웹, 모바일)
* =========================================================================
* X O ===> void print(String s) : 결과값이 없는 경우 : void
* void main(String[] a)
*
* X X ===> void println() => 다음줄에 출력
* 구구단 출력
* ========================================================================= 자체 처리
* *** 메소드명은 소문자로 시작
* 단어가 2개 이상 : 첫자를 대문자, _
* boardList , boardDetail , board_list , board_detail , boardFind , board_find
* ====> 변수명 => 식별자와 동일
*
* 5) 메소드 호출
* int input() {
* return 값(int)
* }
*
* ==> 호출
* int a = input();
* === long, double, flaot ==> 전송값과 일치
* ============= boolean, String
* String s = "Hello";
* String s1 = "Hello Java" ==> s , s1 = 4byte : 클래스의 객체 (주소)
*
* void display() {
*
* }
*
* => display();
*
* 매개변수가 있는 경우
* int add(int a, int b) { => a-10, b=20
* return a + b;
* }
*
* int res = add(10, 20);
* res = 30
* ===============================================
* * 한개의 클래스 안에서 메소드명은 유일하다
* 예외) 매개변수의 개수나 데이터형이 다르면 다른 메소드로 인식
* class A {
* int add(int a, int b) {}
* double add(double d1, doubled2)
* void add(String s1, String s2) {}
* void add(int a, int b) {} ==> 중복된 메소드
* }
* bus(좌석) , bus(고속엔진) , bus(마을) , bus(입석)
* ** 리턴형 => 정수 입력 => 정수
* 정수 여러개 => 배열 (결과값이 여러개) , 클래스
* 영화제목 => 10 Stirng[]
* 국어 점수 => int[]
* 평균 점수 => 10 double[]
* 학점 => 10 char[]
* ** 매개변수 : 사용자 요청
* login => String id, String pwd
* idcheck => String id
* 우편번호 => String dong
* 평균(국어,영어,수학) => int kor, int eng, int math
* *** 매개변수가 많은 경우 (3개 이상) => 1. 배열(같은 데이터 여러개) ,
* 2. 클래스 (다른 데이터 여러개)
* *** 첫번째 ==> 정수 5개를 넘겨주고, 최대값, 최소값
* ==================== ===============
* 매개변수 리턴형
*
* ==> 기능상
* 정수 5개를 입력하는 기능
* 최소값 기능
* 최대값 기능
* 출력
*/
public class 자바메소드_1 {
static int[] input() {
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 100) + 1; // 1~100 사이 => 5개 추출
}
return arr;
}
static int max(int[] arr) {
int max = arr[0];
for (int i : arr) { // arr 안에서 실제 데이터를 한개씩 가지고 온다
if (max < i)
max = i;
}
return max;
}
static int min(int[] arr) {
int min = arr[0];
for (int i : arr) {
if (min > i)
min = i;
}
return min;
}
public static void main(String[] args) {
int[] arr = input();
System.out.println(Arrays.toString(arr));
// 최대값
int max = max(arr);
// 최소값
int min = min(arr);
System.out.printf("최대값:%d, 최소값:%d\n", max, min);
}
}
<file_sep>/20210618-3차문제/src/Question01.java
public class Question01 {
public static void main(String[] args) {
int count = 0;
int sum = 0;
for (int i = 100; i <= 999; i++) {
if (i % 7 == 0) {
count++;
sum += i;
}
}
System.out.println("7의 배수 개수: " + count);
System.out.println("7의 배수 합: " + sum);
}
}
<file_sep>/20210621-자바기본문법정리/src/달력만들기프로그램.java
import java.util.Scanner;
public class 달력만들기프로그램 {
public static void main(String[] args) {
// 입력값 받기
Scanner stdIn = new Scanner(System.in);
System.out.print("년도 입력: ");
int year = stdIn.nextInt();
System.out.print("월 입력: ");
int month = stdIn.nextInt();
System.out.printf("%d년도 %d월\n", year, month);
String[] strWeek = {"일", "월", "화", "수", "목", "금", "토"};
for (int i=0; i<strWeek.length;i++) {
System.out.print(strWeek[i]+"\t");
}
System.out.println("\n");
// 각 달의 마지막 날짜
int[] lastday = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 6월 1일자의 요일 구하기
// 전년도까지의 총 일 수 구하기
int total = (year-1)*365 + (year-1)/4 - (year-1)/100 + (year-1)/400;
// 전달까지의 총 일 수 구하기
if ((year%4==0) && year%100!=0 || (year%400==0)) // 윤년 조건 (ERP)
// 2월달이 29
lastday[1] = 29;
else
lastday[1]=28;
for (int i=0; i<month-1;i++) {
total+=lastday[i];
}
// +1
total++; // 6월 1일자
// %7 => 요일을 구할 수 있다
int week = total%7; // 1년도 1월 1일 => 월
// 달력 출력
for (int i=1; i<=lastday[month-1];i++) {
if (i==1) { // 첫 줄에 출력시에는 요일까지 공백 출력
// 빈 공백 출력
for (int j=0; j<week; j++) {
System.out.print("\t");
}
}
// 1일부터 출력
System.out.printf("%2d\t", i);
week++; // 요일 증가
if (week>6) { // 일요일이면 (6=토요일)
week=0;
System.out.println();
}
}
}
}
<file_sep>/20210701-객체지향연습문제/src/Practice.java
public class Practice {
// Question 01
// 다음과 같은 멤버변수를 갖는 SutdaCard 클래스를 정의하시오.
class SutdaCard {
private int num;
private boolean isKwang;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public boolean isKwang() {
return isKwang;
}
public void setKwang(boolean isKwang) {
this.isKwang = isKwang;
}
}
// Question 02
// 다음과 같은 멤버변수를 갖는 Student 클래스를 정의하시오
class Student {
private String name;
private int ban;
private int no;
private int kor;
private int eng;
private int math;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBan() {
return ban;
}
public void setBan(int ban) {
this.ban = ban;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
}
// Question 03
// 다음의 코드에 정의된 변수들을 종류별로 구분해서 적으시오
/* class PlayingCard {
int kind; //인스턴스 변수
int num; // 인스턴스 변수
static int width; // 정적변수 (공유변수)
static int height; // 정적변수 (공유변수)
Playing Card (int k, int n) {
kind = k; // 지역변수
num = n; // 지역변수
}
}*/
// Question 04
// 다음 중 생성자에 대한 설명으로 옳지 않은 것은? (모두 고르시오)
/*a. 모든 생성자의 이름은 클래스의 이름과 동일해야한다.
b. 생성자는 객체를 생성하기 위한 것이다.
c. 클래스에는 생성자가 반드시 하나 이상 있어야 한다.
d. 생성자가 없는 클래스는 컴파일러가 기본 생성자를 추가한다.
e. 생성자는 오버로딩 할 수 없다.
답 : b , e
b => 객체 생성 : new 생성자 (초기값 설정)
c => 오버로딩 여러개 사용 , 만약에 없는 경우 => 컴파일러가 1개 생성(디폴트 생성자)
*/
// Question 05
// 다음 중 this에 대한 설명으로 맞지 않은 것은? (모두 고르시오)
/* a. 객체 자신을 가리키는 참조변수이다.
b. 클래스 내에서라면 어디서든 사용할 수 있다.
c. 지역변수와 인스턴스변수를 구별할 때 사용한다.
d. 클래스 메서드 내에서는 사용할 수 없다
답: b
b => static 안에서는 this가 존재하지 않는다 / this는 생성자 , 인스턴스 메소드 안에서만 사용이 가능하다
c => 변수명이 동일 할 때
*/
// Question 06
// 다음 중 오버로딩이 성립하기 위한 조건이 아닌 것은? (모두 고르시오)
/* a. 메서드의 이름이 같아야 한다.
b. 매개변수의 개수나 타입이 달라야 한다.
c. 리턴타입이 달라야 한다.
d. 매개변수의 이름이 달라야 한다.
답: c , d
c => 리턴형과 관계없다
d => 이름은 상관없다
*/
// Question 07
// 오버로딩의 조건
/* 1. 메소드 이름이 같아야 한다
* 2. 매개변수의 개수 또는 타입이 달라야 한다
* 3. 매개변수는 같고 리턴형이 다른 경우는 오버로딩이 성립되지 않는다
*/
//Question 08
// 다음 중 아래의 add 메서드를 올바르게 오버로딩 한 것은? (모두 고르시오)
/* long add(int a, int b) { return a+b; }
* a. long add(int x, int y) { return x+y; }
b. long add(long a, long b) { return a+b; }
c. int add(byte a, byte b) { return a+b; }
d. int add(long a, int b) { return (int)(a+b); }
답: b , c , d
*/
//Question 09
// 다음 중 초기화에 대한 설명으로 옳지 않은 것은? (모두 고르시오)
/* a. 멤버변수는 자동 초기화되므로 초기화하지 않고도 값을 참고할 수 있다.
b. 지역변수는 사용하기 전에 반드시 초기화해야 한다.
c. 초기화 블럭보다 생성자가 먼저 수행된다.
d. 명시적 초기화를 제일 우선적으로 고려해야 한다.
e. 클래스변수보다 인스턴스변수가 먼저 초기화된다.
답: c , e
c : 명시적 초기화 => 초기화 블록 => 생성자
e : 컴파일 시 초기화 (static)
*/
//Question 10
// 다음 중 인스턴스 변수의 초기화 순서가 올바른 것은?
/* a. 기본값-명시적초기화-초기화블럭-생성자
b. 기본값-명시적초기화-생성자-초기화블럭
c. 기본값-초기화블럭-명시적초기화-생성자
d. 기본값-초기화블럭-생성자-명시적초기화
답: a
*/
//Question 11
// 다음 중 지역변수에 대한 설명으로 옳지 않은 것은? (모두 고르시오)
/* a. 자동 초기화되므로 별도의 초기화가 필요없다.
b. 지역변수가 선언된 메서드가 종료되면 지역변수도 함께 소멸된다.
c. 메서드의 매개변수로 선언된 변수도 지역변수이다.
d. 클래스변수나 인스턴스변수보다 메모리 부담이 적다.
e. 힙(heap)영역에 생성되며 가비지 컬렉터에 의해 소멸된다. => 클래스변수나 인스턴스변수
답: a , e
e : stack => {} 종료 메모리 자체 관리
*/
//Question 12
// 호출 스택이 다음과 같은 상황일 때 옳지 않은 설명은? (모두 고르시오)
/* a. 제일 먼저 호출스택에 저장된 것은 main메서드이다.
b. println메서드를 제외한 나머지 메서드들은 모두 종료된 상태이다.
c. method2메서드를 호출한 것은 main메서드이다.
d. println메서드가 종료되면 method1메서드가 수행을 재개한다.
e. main-method2-method1-println의 순서로 호출되었다.
f. 현재 실행중인 메서드는 println뿐이다.
답 :
*/
//Question 13
// 오버라이딩의 조건으로 옳지 않은 것운? (모두 고르시오)
/* a. 조상의 메서드와 이름이 같아야 한다.
b. 매개변수의 수와 타입이 모두 같아야 한다.
c. 접근 제어자는 조상의 메서드보다 좁은 범위로만 변경할 수 있다.
d. 조상의 메서드보다 더 많은 수의 예외를 선언할 수 있다
답: c , d
*/
//Question 14
// 다음 중 접근제어자를 접근범위가 넓은 것에서 좁은 것의 순으로 바르게 나열한 것은?
/* a. public-protected-(default)-private
b. public-(default)-protected-private
c. (default)-public-protected-private
d. private-protected-(default)-public
답: a
*/
//Question 15
// 접근 제어자가 사용될 수 있는 곳 - 클래스, 멤버변수, 메서드, 생성자
/* ( private ) - 같은 클래스 내에서만 접근이 가능하다.
( default ) - 같은 패키지 내에서만 접근이 가능하다.
( protected ) - 같은 패키지 내에서, 그리고 다른 패키지의 자손클래스에서 접근이 가능하다.
( public ) - 접근 제한이 전혀 없다.
*/
//Question 16
// 다음 중 접근 제어자에 대한 설명으로 옳지 않은 것은? (모두 고르시오)
/* a. public은 접근제한이 전혀 없는 접근 제어자이다.
b. (default)가 붙으면, 같은 패키지 내에서만 접근이 가능하다.
c. 지역변수에도 접근 제어자를 사용할 수 있다.
d. protected가 붙으면, 같은 패키지 내에서도 접근이 가능하다.
e. protected가 붙으면, 다른 패키지의 자손 클래스에서 접근이 가능하다.
답: c
*/
public static void main(String[] args) {
}
}
<file_sep>/20210624-클래스구성요소/src/데이터형만들기.java
/*
* 1. 변수
* ===========
* 2. 연산자
* 3. 제어문
* =========== 기본 코딩
* 4. 묶어서 사용
* = 데이터 묶는 방법
* = 같은 것끼리 묶어서 (크기가 동일:배열)
* = 다른 것기리 묶어서 (클래스)
* ===> 클래스 안에서 설정 할 수 있는 데이터형
* 기본형 (int, byte, short, char, long, float, double, boolean)
* 클래스 (클래스 , 배열)
* = 명령문 묶는 방법
* = 메소드 (연산자, 제어문, 지역변수)
* ============================================================================== 클래스 + 메소드 (242 page)
* 5. 클래스 영역
* 클래스 (구성요소)
* =======================
* 변수
* = 인스턴스 => new를 사용해서 메모리 생성 => 따라 메로리가 생성
* = 정적변수(클래스변수) => static => 메모리 한개만 생성 => 공유 데이터
*
* => 생성 방법
* class A {
* int aa;
* static int bb;
* }
*
* A a = new A(); ===> a(aa) ==> a가 aa에 접근시에는 a.aa
* A b = new B(); ===> b(aa) ==> b가 aa에 접근시에는 b.aa
* => 별도로 bb가 생성 =========> a,b 공통으로 사용이 가능하다
* a.bb (객체명으로 접근이 가능) , A.bb (클래스명.변수)
* =======================
* 메소드
* =======================
* 생성자
* =======================
*/
class A {
String name;
int aa;
static int bb;
// 변수 => 초기화(지역변수) , 멤버변수 (인스턴스, static) => 자동 초기화
/*
* String => null char => ' ' double => 0.0 float => 0.0f int => 0 long => 0L
* 클래스 => 주소값이 없는 경우 (null)
*/
}
public class 데이터형만들기 {
public static void main(String[] args) {
// A a = new A();
// 249 page
System.out.println(A.bb);
A a = new A(); // name, aa
System.out.println(a.aa);
a.bb=100;
System.out.println(a.name);
}
}
<file_sep>/20210610-자바연산자/src/연산자의종류.java
/*
* 단항연산자
* *** 증감연산자 (++ , --)
* *** 부정연산자 (!) => boolean : true->false , false -> true
* boolean bCheck = false
* while(true) {
* bCheck != bCheck;
* if (bCheck == true) // 컴퓨터 턴
* else
* 사용자 게임 // 사용자 턴
*
* }
* 반전연산자 (~) => 양수->음수 , 음수->양수 (1의 보수)
* *** 형변환연산자 (type) => 10.5 -> 정수형 -> (int)10.5 -> 소수점 제외
*
* 이항연산자
* *** 산술연산자 (+ , - , * , / , %(나머지))
* *** 비교연산자 (== , != , < , > , <= , >=)
* *** 논리연산자 (&&(직렬) , || (병렬))
* *** 대입연산자 (=)
* *** 대입복합연산자 (+= , -= , *= , /= , op= )
* 비트연산자 (& , | , ^)
* 쉬프트연산자 ( << , >>)
*
* 삼항연산자
* (조건) ? 값1 : 값2 ==> 웹 (if~else)
* 예) sex==1 ? "남자" : "여자"
* if (sex==1)
* 남자
* else
* 여자
*/
// 증감연산자 ++ , --
/*
* ++ , --
* 전치연산자
* 후치연산자
*
* 예) int a = 10;
* ++a;
* a++; ==> a값을 1 증가
* 출력 : a값 => 12
*/
public class 연산자의종류 {
public static void main(String[] args) {
int a = 10;
int b = a++;
/*
* int b = a++
* =====
* 1. a가 가지고 있는 값을 b에 대입한다
* 2. a 값을 1 증가한다
*
* int b = ++a
* ==
* =======
* 1. a 값을 1 증가한다
* 2. 증가된 값을 b에 대입한다
*
* =================================== a는 무조건 1 증가한다
*/
}
}<file_sep>/20210622-자바메소드형식/src/자바메소드_사용목적.java
public class 자바메소드_사용목적 {
public static void main(String[] args) {
자바메소드_결과값_매개변수.calc();
}
}
<file_sep>/20210629-객체지향프로그램-생성자(매개변수)/src/생성자.java
/*
* 매개변수를 가지고 있는 생성자 => 입력값을 받아서 변수의 초기화
* => 다른 클래스의 주소값을 받아서 처리(윈도우에 주로 사용(X), 스프링)
* => 스프링(메모리 할당 => 스프링 자체에서 처리) => 생성자 , setter 이용
* => new를 사용하지 않는다 (싱글턴)
* class ClassName {
* ClassName() {} ==============> 기본 생성자
* ClassName(매개변수...){} ====> 매개변수가 있는 생성자
* }
* ======> 생성자 멤버에 대한 초기화
* 일반값 : 명시적 int a=100
* =====================
* = 입력값을 처리
* = 난수
* ===================== 선언 (X) , 구현 (O) => 클래스 블록 안에서는 사용이 안된다
* ==> 생성자 => 클래스를 메모리에 저장할 때 (가장 처음에 호출되는 함수)
*/
import java.util.Scanner;
class Student {
String name="홍길동";
int hakbun=3;
Student(int h, String n) {
hakbun=h;
name=n;
}
}
public class 생성자 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.print("학번 입력: ");
int h = stdIn.nextInt();
System.out.print("이름 입력: ");
String n = stdIn.next();
Student s1 = new Student(h, n);
System.out.println("s"+(i+1)+".hakbun"+s1.hakbun+",s"+(i+1)+".name"+s1.name);
}
/*
Student s1 = new Student();
System.out.println("s1.hakbun="+s1.hakbun+",s1.name="+s1.name);
Student s2 = new Student();
System.out.println("s2.hakbun="+s2.hakbun+",s2.name="+s2.name);
Student s3 = new Student();
System.out.println("s3.hakbun="+s3.hakbun+",s3.name="+s3.name);
*/
}
}
<file_sep>/20210618-자바배열/src/자바배열5.java
import java.util.Scanner;
public class 자바배열5 {
public static void main(String[] args) {
/*
// 5명의 이름 저장
String[] names = {"홍길동", "심청이", "춘향이", "박문수", "이순신"};
String[] sex = {"남", "여", "여", "남", "남"};
// 출력 => for~each (한 개의 배열에서 데이터 출력)
// 일반 for
for (int i=0; i < names.length; i++) {
System.out.printf("%s(%s)\n", names[i], sex[i]);
}
*/
String[] book = {
"자바와 오라클",
"자바와 JSP",
"HTML & Ajax",
"자바 & 코틀린",
"혼자 배우는 스프링",
"혼자 배우는 자바",
"자바와 AI",
"모바일 코틀린",
"모바일과 자바"};
Scanner stdIn = new Scanner(System.in);
System.out.print("검색어를 입력하세요: ");
String data = stdIn.next();
for (String s : book) {
if (s.startsWith(data) || s.endsWith(data)) { // 카페 id_board ==> cookie
try {
Thread.sleep(500);
} catch (Exception e) {}
System.out.println(s);
}
}
}
}
<file_sep>/20210616-1차문제/Question13.java
public class Question13 {
public static void main(String[] args) {
int sum = 0;
for (int i=1; i<=10; i++) {
if (i%2==0) {
sum-=i;
} else {
sum+=i;
}
}
System.out.println("1-2+3..-10까지의 합:"+sum);
}
}
<file_sep>/20210622-자바메소드형식/src/자바메소드_호출_결과값.java
import java.util.Scanner;
public class 자바메소드_호출_결과값 {
// 메소드 처리는 한개의 기능만 받아서 처리한다
static boolean login(String id, String pwd) {
final String MID="admin";
final String MPWD = "<PASSWORD>";
boolean bCheck = false;
if (MID.equals(id) && MID.equals(pwd)) {
bCheck = true;
} else {
bCheck = false;
}
return bCheck;
}
public static void main(String[] args) {
// 사용자로부터 입력값 받기
Scanner stdIn = new Scanner(System.in);
System.out.print("ID 입력: ");
String id = stdIn.next();
System.out.print("비밀번호 입력: ");
String pwd = <PASSWORD>();
// 메소드를 통해서 결과값을 받는다
boolean check = login(id, pwd);
if (check==true) {
System.out.println("메인 화면으로 이동");
} else {
System.out.println("ID나 비밀번호가 틀립니다");
}
}
}
<file_sep>/20210615-자바제어문(조건문)/src/자바조건문정리.java
/*
* 조건문 => 오류방지 (처리가 안되는 프로그램 => try ~ catch 예외처리)
*
* *** = 선택 조건문 : true / false => 따로 처리 ( if , else => 한개만 처리)
* 형식)
* if (조건문) {
* 조건이 true일 때 처리 문장
* }
* else {
* 조건이 false일 때 처리 문장
* }
*
* = 다중조건문 : 해당되는 조건만 수행이 가능하게 만든다 (한개의 조건만 실행)
* 형식)
* if(조건문) {
* 조건이 true일 때 수행하는 문장 ==> 수행 후에 if문을 종료
* }
* else if (조건문) {
* 조건이 true일 때 수행하는 문장 ==> 수행 후에 if문을 종료
* }
* else if (조건문) {
* 조건이 true일 때 수행하는 문장 ==> 수행 후에 if문을 종료
* }
* else {
* 해당 조건이 없는 경우 처리하는 문장 (생략 가능)
* }
* = 중첩조건문 : ==> &&로 바꿔서 사용이 가능
* if(a==1) {
* if (b==1) {
*
* }
* else if (b==2) {
* }
* }
*
* ===> if (a==1 && b==1) {
* }
* if (a==1 && b==2) {
* }
*/
public class 자바조건문정리 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
<file_sep>/20210628-객체지향프로그램1/src/변수초기화4.java
public class 변수초기화4 {
int a = 10; // 1
{
a=100; // 2
}
변수초기화4() {
a=1000; // 3
}
public static void main(String[] args) {
변수초기화4 aa = new 변수초기화4();
System.out.println(aa.a);
}
}
<file_sep>/20210625-3주차자바정리/src/자바메소드1.java
import java.util.Arrays;
// 1. 영화 데이터 출력 ==> 리턴형(X) , 매개변수(X)
/*
* 메소드를 사용하는 이유
* = 단락을 나눠서 가독성이 좋게 만든다 ==================> 프로그램 구조화
* ============= 기능별 (입력기능, 처리기능, 출력기능)
* ========= 새부화
* = 재사용성
* = 반복을 제거하는 방법
* = 다른 클래스에서 필요시마다 사용이 가능하게 만든다
* =================================================
*
* 메소드
* ======
*
* 프로그램 만든다
*
* 1. 요구사항 분석 ==> 2. 데이터베이스 설계 ==> 3. 화면 UI ==> 4. 구현 ==> 5. 테스트 ==> 6. 배포
* =============
* 기능 (메소드)
* ==> 아이템 발표 ==> 데이터 수집 ==> 템플릿 찾기 ==> JSP 구현 ==> 발표
*
*
*/
public class 자바메소드1 {
// 중복 없는 난수 => 재사용성이 좋은 메소드
static int[] rand(int num) {
int[] com = new int[num]; // 중복 난수 저장 ===> 예매
int su = 0; // 난수값 저장
// 중복여부 확인
boolean bCheck = false;
// 지역변수 => 외부에서는 사용할 수 없고 {] 에서만 사용되는 변수
for (int i=0; i<num; i++) {
bCheck=true; // 난수 발생 준비
while (bCheck) { // 난수를 발생 => 중복체크 => 중복 (다시 while문을 수행, false이면 while문 종료 => com 저장)
// 난수 발생
su = (int) (Math.random()*31)+1; // 1~31 => 예매가 가능한 일
bCheck = false; // 중복이 없으면 while문을 벗어난다
for(int j=0; j<i; j++) { // com에 저장된 데이터를 읽어온다 => su와 같은지 비교
if (com[j]==su) { // while을 처음부터 수행 => 다시 발생 (중복된 데이터가 존재)
bCheck = true;
break;
}
}
}
com[i]=su; // 중복되지 않은 데이터 저장
}
return com;
}
public static void main(String[] args) {
int[] reday = rand(7);
System.out.println(Arrays.toString(reday));
}
}
<file_sep>/20210630-객체지향프로그램1/src/MainClass1.java
/*
* 클래스 구성요소 : 필요할 때 사용
* =============== 객체지향답게 프로그램 (데이터 보호(캡슐화), 재사용(상속,포함), 수정, 추가(다형성))
* ============ 문법사항은 아니다 , 권장사항
* 1. 클래스의 구성요소
* 1) 변수 => 초기값을 지정 (메모리에 저장하기 위해서는 반드시 초기화)
* = 멤버변수 (클래스 블록 안에 선언) : 프로그램 종료시까지 메모리 유지
* => 여러개를 따로 저장이 가능 (인스턴스 변수)
* ========(객체) => new 사용시마다 메모리 각자 생성 (가장 많이 사용하는 변수)
* => 게임 : 비행기 좌표, 총알 ...
* = 공통변수(공유변수, 정적변수 : static) : 한개의 메모리에서 사용 (점수)
* = 지역변수 메소드 안에서 사용 (메소드 호출시마다 메모리 저장) => 메소드 종료를 하면 자동으로 사라진다
* ======== 메소드 안에 선언, 매개변수 (사용자가 처리를 요청할 때)
* ** 멤버변수, 공통변수는 자동 초기화가 된다
* =======================================
* 정수형(int,byte,short) = 0
* 실수형(float,double) = 0.0
* 문자형(char) = ' '
* 논리형(boolean) = false
* 모든클래스(String..) = null (클래스에 저장되는 것은 메모리 주소(메모리 주소가 없는 상태))
* int[] arr; // arr=null
* A a; // a=null
* String s; // s=null
* ======================= 참조형 데이터 (배열,클래스)
* ** 다른 값을 가지고 초기화
* = 직접 변수 초기화 : 명시적 초기화
* class A {
* int a=100; // int a; (a=0) => 이미지출력 (좌표점,자동로그인:id)
* ====== 캡슐화 위반 (데이터 보호 => 공개)
* id, pwd ==> 파일에 저장 , cookie
* String id="hong";
* String pwd="<PASSWORD>";
* }
* = 직접 변수값을 설정하지 못하는 경우
* ** class A (선언만 가능 (구현이 불가능): 연산처리, 제어문, 메소드 호출 ....))
* 초기화 블록 : 실행시에 자동 호출 (인식)
* class A {
* {
* // 인스턴스 블록 (인스턴스 변수, 초기화)
* // 구현이 가능
* =========================================
* 스프링
* 마이바티스 (오라클 연동하는 라이브러리) : 답변형 게시판 (자바 코딩 => 700줄)
* 마이바티스 (자바 코딩 => 52줄)
* ========================================= 동작이 셋팅 => XML
* }
*
* static {
* // static 변수 초기화
* // 구현이 가능
* }
* }
* 2) 생성자 : 멤버변수가 명시적인 초기화가 안될 경우
* = 변수에 대한 초기화
* = 변수값을 다르게 생성 => 매개변수
* = 매개변수가 없는 생성자 (디폴트 생성자)
* ** 생성자가 없는 경우에는 컴파일러가 자동으로 디폴트 생성자 자동 추가
* = 매개변수가 있는 생성자 : 저장시마다 변수값을 다르게 저장할 때
* 생성자
* 특징
* 1. 클래스명 동일 class A ==> A() A(매개변수)
* 2. 리턴형이 없다 (리턴형을 사용하면 => 생성자 아니라 일반메소드) void A()
* 3. 오버로딩 : 중복함수정의 (생성자 이름이 동일 => 여러개를 동시에 만들 수 있다)
* ========
* 메소드명 동일
* 매개변수의 개수나 데이터형이 다르다
* 리턴형은 관계없다
* =================================== 다형성 (한개를 가지고 여러개 기능을 만든다) => 기능 추가 (new)
* 3) 메소드 : 기능 처리 (멤버변수, 지역변수를 이용해서 기능 처리)
* 리턴형 메소드명(매개변수...) { // 메소드 선언
* // 메소드 구현
* }
* => 접근시에
* class A {
* int a=10; // 인스턴스
* static int b=20;
* A() {
* }
* void display() { // 인스턴스
* }
* static void print() {
* }
* }
* 1) 클래스 객체 생성
* A에 설정 변수와 메소드를 메모리에 저장 => new
* 컴파일러에 의해 자동 저장 : static ==> b변수, print()
* a, display()를 저장하기 위해서는 반드시 new를 이용해서 저장
* ============================================================
* A aa = new A(); // aa(주소)라는 공간 => a, display()
*
* 1) 인스턴스
* aa.메소드명 (aa.display()) , aa.변수명 (aa.a)
* 2) 정적변수, 메소드
* aa.메소드명(aa.print()) , aa.변수(aa.b)
* 클래스명.메소드명 (A.print()) , A.b
* ============================================================
* 클래스
* = 데이터만 선언 (사용자 정의 데이터형) : 변수만 가지고 있다 (~VO, ~DTD) => 데이터 저장용으로 사용
* => 데이터형 클래스
* = 메소드만 가지고 있는 클래스 : 서버 (~DAO , ~Manager) => 액션 클래스
* = 데이터+기능 (변수+메소드)
*/
class Card {
String type="◆"; // ◆ ♡ ♤ ♣
int number=1;
static int width=300;
static int height=350; // 공유변수 ...
// 생성자 ==> 카드 3장 (다른 카드) => 3개를 생성 => 다른 값으로 초기화
Card(String type, int number) {
this.type = type;
this.number = number; // this => 클래스가 가지고 있는 변수
// 멤버변수(전역변수:클래스 전체에서 사용되는 변수, 프로그램 종료시까지 유지하는 메모리)
// 지역변수(메소드 종료시 사라진다)
// 우선시 (지역변수 => 멤버변수) => 지역변수 우선순위
}
}
public class MainClass1 {
public static void main(String[] args) {
Card.height=250;
Card.width=300;
Card c1 = new Card("♡", 7);
System.out.println("모양: "+c1.type);
System.out.println("숫자: "+c1.number);
System.out.println("Width: "+c1.width);
System.out.println("Height: "+c1.height);
Card c2 = new Card("♣", 5);
System.out.println("모양: "+c2.type);
System.out.println("숫자: "+c2.number);
System.out.println("Width: "+c2.width);
System.out.println("Height: "+c2.height);
Card c3 = new Card("♤", 2);
System.out.println("모양: "+c3.type);
System.out.println("숫자: "+c3.number);
System.out.println("Width: "+c3.width);
System.out.println("Height: "+c3.height);
}
}
<file_sep>/20210701-객체지향프로그램(상속_포함)/src/상속클래스.java
/*
* 상속 : 기존의 클래스를 재사용 (import) => 새로운 클래스(기존의 클래스 + 새로운 기능 추가)
* 상속을 내리는 클래스 : 공통적인 내용 => 공통 모듈
* 상속을 받는 클래스
* => 유지보수가 쉽게 만든다
* => 반복 코딩을 제거할 수 있다
* => 관리하기가 용이하다
* => extends
* 형식)
* class 공통 => 기능을 추가 , 변경 ==> include
* class A extends 공통
* class B extends 공통
*
* 예)
* 게시판
* 글쓰기 , 내용보기 , 수정하기 , 삭제하기 , 찾기 , 목록
* 답변형게시판
* => 기능 (답변달기) => 추가
* => 목록 ==============> 클래스에 맞게 재정의(오버라이딩)
* =>
* =>
* 갤러리게시판
* => 업로드 => 추가
* => 목록 ====================> 오버라이딩
* ============================================= 기존에 클래스에서 만든 메소드 변경해서 사용이 가능
* 재사용 기법 : 상속 , 포함(그대로 사용) Scanner, System
* ====
* 상위클래스의 기능 변경해서 사용
* ***** 부담 : 라이브러리 (기능 변경) .jar(.class) => 포함
* 변경 : 스프링 (스프링 => 전자정부프레임워크, 애니프레임워크)
* ====== 자바소스
* 라이브러리 VS 프레임워크 JSOUP => mvnrepository
* (완제품) (레고)
* 상속 : 상속(키워드 : extends => 확장된 클래스 (다른 기능 추가, 변수 추가 + 기존의 클래스 내용)
* => 상속이 있는 경우에만 클래스의 크기 결정
* 상속이 없는 경우는 모든 클래스 (4byte) => 동일
* 상속을 내린 클래스 > 상속을 받는 클래스보다 크다
* ================================================= 형변환
* => 모든 클래스는 Object 상속을 받는다
* ====== 최상위 클래스 => int a = (int)10.5
* A a = (A) new Object()
* => 단일상속
* 예)
* class A extends B, C ==> 오류
* ==== 다중 상속
* => class B extends C ==> B, C
* class A extends B ==> B, C, A
* => 상속의 예외
* 생성자 , 초기화 블록 , static (상속은 아니고 사용이 가능) , private (상속=>사용이 불가능)
* => private
* => 메모리 크기는 상속을 받은 클래스가 크다 (long < float)
* 8 4 => 표현수
* => 클래스는 범위(포함)
* 동물
* |
* -------------
* | | |
* 포유류 양서류 조류
* |
* -----------
* | | |
* 개 말 인간
* |
* ------
* | |
* 남자 여자
*
* => 상속이 불가능한 클래스 : 종단클래스 (final) => String, Math, System ...
* 포함해서 사용 .....
*/
/*
* 오버라이딩 : 기존의 상속을 받은 클래스의 기능을 변경해서 사용
* 조건)
* 1. 상속관계 (상속이 없어도 오버라이딩이 가능)
* 2. 메소드명이 동일
* 3. 매개변수 동일
* 4. 리턴형이 동일
* 5. 접근지정어의 확장은 가능 , 축소는 불가능
* ==========
* 접근지정어 접근 범위
* public > protected > default > private
*
* class A {
* protected void display() {
* }
* }
*
* class B {
* // A가 가지고 있는 display()가 변경하지 않아도 사용이 가능 (변경할 것이 없으면)
* // B에서는 다른 기능이 필요 ==> 오버라이딩
* protected void display() {
* ========= public void display() (O) => 확장
* ========= void display() (X) => 축소
* 내용 변경
* }
* }
*/
class 동물 {
void run() {
System.out.println("네발로 달린다");
}
}
class 개 extends 동물{
// 그대로 사용
/*
void run() {
System.out.println("네발로 달린다");
}
*/
}
class 사람 extends 동물{
/*
void run() {
System.out.println("네발로 달린다");
}
*/
// public void run() {
// protected void run() {
void run() {
// private void run() { ==> 오류 (축소했기 때문에)
System.out.println("두발로 달린다"); // 수정이 가능하게 만든다 => 유지보수 시 사용이 가능
}
}
public class 상속클래스 {
public static void main(String[] args) {
개 dog = new 개();
dog.run();
사람 human = new 사람();
human.run();
}
}
<file_sep>/20210629-객체지향프로그램-생성자(매개변수)/src/생성자2.java
// 생성자 종류 => 매개변수가 없다(디폴트 생성자), 매개변수가 있다(입력값을 받아서 초기화, 파일 읽기, 데이터베이스 읽기)
class Sawon {
String name="홍길동"; // null
String dept="개발부"; // null
String loc="서울"; // null
Sawon(String n, String d, String l) {
name = n;
dept = d;
loc = l;
}
}
public class 생성자2 {
public static void main(String[] args) {
Sawon s1 = new Sawon("홍길동","개발부","서울");
System.out.println(s1.name);
System.out.println(s1.dept);
System.out.println(s1.loc);
System.out.println("==================");
Sawon s2 = new Sawon("심청이","기획부","경기");
System.out.println(s2.name);
System.out.println(s2.dept);
System.out.println(s2.loc);
System.out.println("==================");
Sawon s3 = new Sawon("박문수","영업부","부산");
System.out.println(s3.name);
System.out.println(s3.dept);
System.out.println(s3.loc);
System.out.println("==================");
}
}
<file_sep>/20210618-자바배열/src/자바배열3.java
import java.util.Scanner;
/*
* 3명의 학생
* 국어, 영어, 수학 ===> 점수를 입력해서
* 1. 총점
* 2. 평균
* 3. 학점
* 4. 등수
* ============ 일반 => 변수 21개
*
* 변수 ==> 응용
* 연산자 ===> 응용
* 제어문 =====> 응용
* ====== 배열 =====>
* 메소드 =====> 응용
* 클래스 (객체)
*/
public class 자바배열3 {
public static void main(String[] args) {
int[] kor = new int[3];
int[] eng = new int[3];
int[] math = new int[3];
int[] total = new int[3];
double[] avg = new double[3];
int[] gpa = new int[3];
int[] rank = new int[3];
// int[][] info = new int[3][5];
// --- ---
// 인원수 데이터개수
// 1. 키보드 값 받기
Scanner stdIn = new Scanner(System.in);
for (int i=0; i<3; i++) {
System.out.printf("%d번째 국어점수 입력: ", (i+1));
kor[i] = stdIn.nextInt();
System.out.printf("%d번째 영어점수 입력: ", (i+2));
eng[i] = stdIn.nextInt();
System.out.printf("%d번째 수학점수 입력: ", (i+3));
math[i] = stdIn.nextInt();
total[i] = kor[i]+eng[i]+math[i];
avg[i] = total[i]/3.0;
}
// 학점
for (int i=0; i<3; i++) {
char c = 'A';
if (avg[i] >=90)
c='A';
if (avg[i]>=80)
c='B';
if (avg[i] >=70)
c='C';
if (avg[i]>=60)
c='d';
else
c='F';
gpa[i]=c;
}
// 등수
for(int i=0; i<3; i++) {
rank[i] =1;
for (int j=0; j<3; j++) {
if (total[i]<total[j])
rank[i]++;
}
}
// 출력
System.out.println("=============== 성적 목록 ===============");
System.out.printf("%-1s %-3s%-3s%-5s%-3s%-3s%-5s\n", "국어", "영어", "수학", "총점", "평균", "학점", "등수");
for (int i=0; i<3; i++) {
System.out.printf("%-5d%-5d%-5d%-7d%-7.2f%-5c%-5d\n", kor[i], eng[i], math[i], total[i], avg[i], gpa[i], rank[i]);
}
}
}
<file_sep>/20210616-자바제어문(반복문)/src/자바제어문_응용문제1.java
public class 자바제어문_응용문제1 {
public static void main(String[] args) {
// 주사위 2개를 던진다
// 두 개의 합이 6이 될 경우의 수를 출력
/* int count = 0;
for (int i = 1; i <= 6; i++) { // 1번째 주사위
for (int j = 1; j <= 6; j++) { // 2번째 주사위
if (i + j == 6) {
System.out.println("["+i+", "+j+"]");
count1++;
}
}
}
System.out.println("경우의 수 : " + count);
*/
// 주사위 2개를 던진다
// 두 개의 합이 10 이상이 될 경우의 수를 출력
/*
int count = 0;
for (int i=1; i<=6; i++) {
for (int j=1; j<=6; i++) {
if (i+j >= 10) {
System.out.println("["+i+", "+j+"]");
count++;
}
}
}
System.out.println("경우의 수 : " + count);
*/
}
}
<file_sep>/20210618-자바배열/src/자바배열응용6.java
import java.util.Arrays;
import java.util.Scanner;
public class 자바배열응용6 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("정수 입력:");
int num = scan.nextInt();
// System.out.println(Integer.toBinaryString(num));
int[] binary = new int[32]; // 0,1 => 0으로 채워져 있다
int index = 31;
while (true) {
binary[index] = num % 2;
num = num / 2;
if (num == 0)
break;
index--;
}
// System.out.println(Arrays.toString(binary));
for (int i = 0; i < binary.length; i++) {
if (i % 4 == 0 && i != 0)
System.out.print(" ");
System.out.print(binary[i]);
}
}
}
<file_sep>/20210629-객체지향프로그램-생성자(매개변수)/src/생성자3.java
class Member {
int no; // 0
String name; // null
String addr; // null
/*
* Member m1 = new Member();
* Member m2 = new Member();
*/
Member() {
no=1;
name="홍길동";
addr="서울";
}
Member(int n, String s) {
this(s); // 생성자 자신 ==> Member(s) => this(s)
// this 메소드는 생상자 안에서 다른 생성자를 호출할 때 사용
// 주의점은 항상 생성자 안에서만 사용한다
// 항상 첫줄에 온다
no=n;
}
Member(int n) {
no=n;
}
Member(String n) {
name=n;
}
Member(String n, String a) {
name=n;
addr=a;
}
Member(int n, String s, String a) {
no=n;
name=s;
addr=a;
}
}
public class 생성자3 {
public static void main(String[] args) {
Member m1 = new Member();
System.out.println(m1.no);
System.out.println(m1.name);
System.out.println(m1.addr);
System.out.println("=====================");
Member m2 = new Member(2,"강감찬");
System.out.println(m2.no); // 2
System.out.println(m2.name); // 강감찬
System.out.println(m2.addr); // null
System.out.println("=====================");
Member m3 = new Member("심청이");
System.out.println(m3.no); // 0
System.out.println(m3.name); // 심청이
System.out.println(m3.addr); // null
System.out.println("=====================");
Member m4 = new Member("박문수","경기");
System.out.println(m4.no); // 0
System.out.println(m4.name); // 박문수
System.out.println(m4.addr); // 경기
System.out.println("=====================");
Member m5 = new Member(3,"이순신","인천");
System.out.println(m5.no); // 3
System.out.println(m5.name); // 박문수
System.out.println(m5.addr); // 경기
System.out.println("=====================");
}
}
<file_sep>/20210615-자바제어문(조건문)/src/자바다중조건문2.java
// A(추상클래스), F(종단클래스)= > final = >변경해서사용이안된다(제공한 내용 그대로 사용)
import java.util.Scanner;
// 국어 , 영어 , 수학 ==> 총점 , 평균 , 평균에 대한 학점부여 A(90), B(80), C(70), D(60), F(60미만)
public class 자바다중조건문2 {
public static void main(String[] args) {
// 입력값을 받는다
Scanner stdIn = new Scanner(System.in);
System.out.print("국어점수 영어점수 수학점수 입력 (90 90 90) : ");
int kor = stdIn.nextInt();
int eng = stdIn.nextInt();
int math = stdIn.nextInt();
int total = kor + eng + math;
double avg = total / 3.0;
int res = (int) avg;
char grade = 'A';
if (res >= 90)
grade = 'A';
else if (res >= 80)
grade = 'B';
else if (res >= 70)
grade = 'C';
else if (res >= 60)
grade = 'D';
else
grade = 'F';
// 결과값 출력
System.out.println("국어 점수: " + kor);
System.out.println("영어 점수: " + eng);
System.out.println("수학 점수: " + math);
System.out.println("총점: " + total);
System.out.printf("평균: %.2f\n", avg);
System.out.println("학점: " + grade);
}
}
<file_sep>/20210618-3차문제/src/Question03.java
public class Question03 {
public static void main(String[] args) {
int even = 0;
int odd = 0;
for (int i = 1; i <= 30; i++) {
if (i % 2 == 0) {
even += i;
} else {
odd += i;
}
}
System.out.println("짝수합: " + even);
System.out.println("홀수합: " + odd);
}
}
<file_sep>/20210616-자바제어문(반복문)/src/자바제어문_반복문2.java
/*
* 161 PAGE 중첩 for (이중 for)
* 형식)
* 1 2 => false 전체 종료
* for(초기값;조건식;증가식) { ========> 줄 수
* |
* |true
* 3 4 => false
* 6
* for(초기값;조건식;증가식) { ======> 데이터 출력
* 5
* 반복 실행문장
* }
* }
*
* 구구단
* ======
* 2*1=2 3*1=3 4*1=4 ..... 9*1=9
* 2*2=4 .......................
* ...
* ...
* ...
* 2*9=18 9*9=81
* =============================== 줄 수 (9)
* ===> 2차 for ===> 2 ~ 9
*
* ***** 가로 (2차)
* *****
* *****
* ***** => 1 ~ 4
* 세로 (1차)
*
* *****
* *****
* *****
* *****
* *****
*/
public class 자바제어문_반복문2 {
public static void main(String[] args) {
// 구구단 출력
/*
* for (int i=1; i<= 9; i++) { for (int j=2; j<=9; j++) { // 구구단 출력 (한줄)
* System.out.printf("%d * %d = %2d\n", j , i , j*i); } System.out.println(); }
*/
// 별 가로세로 5개
/*
* for(int i=1; i<=5; i++) { for (int j=1; j<=5; j++) { System.out.print("*"); }
* System.out.println(); }
*/
// 별 가로10 세로5
/*
for (int i =1; i<=5; i++) { for (int j=1; j<=10; j++) {
System.out.print("*"); } System.out.println(); }
*/
/* for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
if (j % 2 == 0)
System.out.print("☆");
else
System.out.print("★");
}
System.out.println();
} */
// ABCD
// ABCD
// ABCD
// ABCD
/* for (int i=1; i<=4; i++) {
char c='A';
for (int j=1; j<=4; j++) {
System.out.print(c++);
}
System.out.println();
} */
// ABCD
// EFGH
// IJKL
// MNOP
/* char c='A';
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
System.out.print(c++);
}
System.out.println();
}*/
}
}
<file_sep>/20210615-자바제어문(조건문)/src/자바다중조건문1.java
/*
* 141 page 다중 조건문
* => if이 여러개 존재 -> 수행은 1개만 수행
* 형식)
* if(조건문) {
* ↓ true
* 실행 문장 ==========> if문 종료
*
* } ↓ false
* else if (조건문) {
* ↓ true
* true일 때 수행하는 문장 ===> 문장 수행 후에 종료
*
* } ↓ false
* else if (조건문) {
* ↓ true
* true일 때 수행하는 문장 ==> 문장 수행 후에 종료
*
* } ↓ false
* ===================
* else {
* 조건 중에 해당하는 조건이 없는 경우에 수행하는 문장
* }
* =================== 조건에 해당되는 내용이 없는 경우 처리 (default)
*/
// 가위 바위 보 => 컴퓨터 ==> 0(가위) , 1(바위) , 2(보) ==> 컴퓨터가 난수 발생
import java.util.Scanner;
public class 자바다중조건문1 {
public static void main(String[] args) {
// 1. 컴퓨터가 가위바위보
int com = (int) (Math.random() * 3); // 0~2 사이의 정수를 발생
// 2. 사용자가 선택
Scanner stdIn = new Scanner(System.in); // 키보드 입력값을 받아서 메모리에 저장
System.out.print("가위(0), 바위(1), 보(2) : ");
int user = stdIn.nextInt();
// 결과 (컴퓨터)
if (com == 0)
System.out.println("컴퓨터: 가위");
else if (com == 1)
System.out.println("컴퓨터 바위");
else
System.out.println("컴퓨터 보");
// 결과(사용자)
if (user == 0)
System.out.println("Player: 가위");
else if (user == 1)
System.out.println("Player: 바위");
else if (user == 2)
System.out.println("Player: 보");
else
System.out.println("Player는 게임을 포기했습니다");
// 게임 결과
if (user > 2) {
System.out.println("게임 종료 : 컴퓨터 Win!!!");
}
/*
* 컴퓨터 =============================> user-com
* 사용자가 이기는 숫자 => 1, -2
* 컴퓨터가 이기는 숫자 => 2, -1
* 나머지는 0 (비겼다)
* 가위(0)
* => 사용자
* 가위(0) => 비겼다 ===> 0
* 바위(1) => 사용자 ===> 1
* 보(2) => 컴퓨터 ===> 2
*
* 바위(1)
* => 사용자
* 가위(0) => 컴퓨터 ===> -1
* 바위(1) => 비겼다 ===> 0
* 보(2) => 사용자 ===> 1
* 보(2)
* => 사용자
* 가위(0) => 사용자 ===> -2
* 바위(1) => 컴퓨터 ===> -1
* 보(2) => 비겼다 ===> 0
*
*/
else {
// 정상 입력이 된 경우
int result = user - com;
if (result == -1 || result == 2) {
System.out.println("컴퓨터 Win!!!");
} else if (result == 1 || result == -2) {
System.out.println("Player Win!!!");
} else {
System.out.println("비겼다!!!");
}
}
}
}
<file_sep>/20210614-자바제어문(조건문)/src/자바제어문_조건문2.java
public class 자바제어문_조건문2 {
public static void main(String[] args) {
// 컴퓨터가 임의로 숫자를 저장
// 1~100까지 사이의 수를 임의로 추출
int com = (int) ((Math.random()*100)+1); // 1 ~ 100 사이의 임의의 수
/*
* Math.random() => 0.0~0.99 => 임의로 추출
* 0.0 ~ 0.99 * 100 ==> 0.0 ~ 99.0 +1 ==> 1.0 ~ 100.0
*
* (int)(Math.random()*100)+1
* ===================
* 1 0.81*100 ==> 81.0
* =====
* 2 ==> 81
* ==
* 3 ==> 82
* ** 자바에서 지원하는 메소드는 반드시 결과값 (결과값이 없는 경우 void)
*
*/
// int com = 105; // 단일 조건문은 따로따로 독립적으로 실행
if(com%3==0)
System.out.println(com+"는(은) 3의 배수입니다");
if(com%5==0)
System.out.println(com+"는(은) 5의 배수입니다");
if(com%7==0)
System.out.println(com+"는(은) 7의 배수입니다");
if (!(com%3==0 || com%5==0 || com%7==0))
System.out.println(com+"는(은) 3,5,7의 배수가 아닙니다");
}
}
<file_sep>/20210616-1차문제/Question09.java
public class Question09 {
public static void main(String[] args) {
for (int i=5; i<=50; i+=5) {
System.out.print(i+"\t");
}
}
}
<file_sep>/20210611-자바연산자/src/자바연산자.java
/*
* 데이터 저장 ========> 데이터 처리 ===========> 출력
* ===========
* 변수 (한개의 데이터만 저장할 수 있는 메모리 공간)
* => 프로그램이 종료시까지 기억(휘발성메모리:RAM=>프로그램 종료시 삭제)
*
* 데이터 처리
* 연산자
* 제어문
*
* 출력
* 가로 / 세로
* 가로 => 일정 간격 \t
* 다음 줄에 출력 \n (new line)
* "를 출력 ==> \"
* \를 출력 ==> \\
* System.out.print() => 가로
* System.out.println() => 세로 => \n 포함
*/
public class 자바연산자 {
public static void main(String[] args) {
System.out.print("Hello\n");
System.out.print("Java!!\n");
System.out.print("\"홍길동\"\n"); // "홍길동"
System.out.print("c:\\javaDev\\JavaStudy");
System.out.println("C:\\javaDev\\eclipse");
}
}
<file_sep>/20210617-자바기본프로그램정리/src/자바문자열데이터3.java
/*
* substring(int begin)
* substring(int begin, int end)
*
* "Hello Java!!"
*/
public class 자바문자열데이터3 {
public static void main(String[] args) {
String s = "Hello Java!!";
System.out.println(s.substring(6)); // Java!!
System.out.println(s.substring(6,10)); // Java
System.out.println(s.substring(0,5)); // Hello
}
}
<file_sep>/20210621-자바배열문제/src/Question4.java
import java.util.Scanner;
public class Question4 {
public static void main(String[] args) {
// 1) 10개의 문자를 가지는 배열 c를 생성하는 코드를 한 줄로 쓰라.
char[] c = new char[10];
// 2) 0에서 5까지 정수 값으로 초기화된 정수 배열 n을 선언하라.
int[] n = {0, 1, 2, 3, 4, 5};
// 3) '일', '월', '화', '수', '목', '금', '토'로 초기화된 배열 day를 선언하라.
String[] day = {"일", "월", "화", "수", "목", "금", "토"};
// 4) 4개의 논리 값을 가진 배열 bool을 선언하고 true, false, false, true로 선언하라.
boolean[] bool = {true, false, false, true};
}
}
<file_sep>/20210621-자바배열문제/src/Question6.java
import java.util.Scanner;
public class Question6 {
public static void main(String[] args) {
int[] arr = new int[10];
Scanner stdIn = new Scanner(System.in);
System.out.println("↓양의 정수 10개를 입력하세요↓");
for (int i = 0; i < arr.length; i++) {
arr[i] = stdIn.nextInt();
if (arr[i]%3==0) {
System.out.print(arr[i] + " ");
}
}
}
}
<file_sep>/20210615-자바제어문(조건문)/src/자바조건문2.java
import java.util.Scanner;
// Math, String, System(클래스) => java.lang ==> 생략이 가능
// 3개 ===> 정수 2개 , 연산자 1개
public class 자바조건문2 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.print("첫번째 정수를 입력하세요 : ");
int a = stdIn.nextInt();
System.out.print("두번째 정수를 입력하세요 : ");
int b = stdIn.nextInt();
// 연산자 입력
// Scanner의 단점 : 문자 1개는 받을 수 없다 => String
System.out.print("연산자(+,-*,/)를 입력하세요 : ");
char op = stdIn.next().charAt(0);
// Hello Java ==> charAt(0) ==> H char(1) ==> 문자열은 시작 번호가 0부터 시작한다 char[]
if (op == '+' || op == '-' || op == '*' || op == '/') {
if (op == '+')
System.out.printf("%d + %d = %d\n", a, b, a + b);
if (op == '-')
System.out.printf("%d - %d = %d\n", a, b, a - b);
if (op == '*')
System.out.printf("%d * %d = %d\n", a, b, a * b);
// if ~ else => 오류 처리일 경우
if (op == '/') {
if (b == 0) { // 0으로 나눌 수 없다
System.out.println("0으로 나눌 수 없습니다!!"); // 오류 처리
} else {
System.out.printf("%d / %d = %.2f\n", a, b, a / (double) b); // 정상 수행
}
}
}
else {
System.out.println("사칙연산자가 아닙니다");
}
}
}
<file_sep>/20210616-자바제어문(do~while)/자바제어문3.java
/*
* 반복제어문 : 반복문을 제어하는 프로그램
* =======
* 1. 반복문을 중단 ==> break
* 2. 반복문에서 특정 부분 제외 ==> continue
* *** 주의점 : break, continue는 소속 반복문만 제어할 수 있다
* outer:
* for (int i=1; i<=5; i++) {
* for (int j=1; j<=5; j++) {
* if (j==3)
* break; ==> 2차 for문 제어
* if (j==5)
* break outer;
* }
* }
*/
public class 자바제어문3 {
public static void main(String[] args) {
for3:
for (int i=1; i<=10; i++) {
System.out.println("i="+i);
}
for1 :
for (int i=1; i<=5; i++) {
for2 :
for (int j=1; j<=5; j++) {
// if (j==3)
// break for2;
if (j==3)
// break for1;
continue; // 3 제외 => 증가식 ==> j++ (4...)
System.out.println("i="+i+", j="+j);
}
}
/*
* i=1 j=1
* j=2
*
* i=2 j=1
* j=2
*
* i=3 j=1
* j=2
*
* i=4 j=1
* j=2
* i=5 j=1
* j=2
*/
}
}
<file_sep>/20210628-객체지향프로그램1/src/객체지향프로그램.java
/*
* 웹 / 앱
* =======
* 1. 클래스 제작
* ===========
* => 캡슐화 , 오버라이딩
* (변수) (메소드)
* => 포함 클래스 (재사용)
* 2. 데이터 연결 => 제어
* 3. 예외처리
* 4. IO , 컬렉션
* 5. 인터페이스
* ============================ 변수/메소드 (라이브러리 : XML,HTML,JSON)
*/
/*
* 1. 문법
* 변수, 클래스 (배열 가끔..) => 문자열 분리
* 메소드 제작방법
* ====== 처리 (연산, 제어문)
* ========================================== 절차적 언어 (동작 순서대로 일괄 코딩: 재사용X)
* ========================================== 간단한 프로그램 계산기...)
* 2. 객체지향 프로그램 : 대규모
* CGV / 롯데시네마 / 메가박스 => 재사용 ==> 예매
* 지니뮤직 / 멜론 / 바이브 ==> 음반 판매
* 서적 (출판사) ==> 장바구니
* ==> 포함 , 상속 (속도가 느리다) : Spring에서는 상속이 없다 => POJO
* ====
* 3. 객체지향 프로그램
* = 클래스 자체를 보관 (재사용) => 상속
* = 수정, 추가 가능 => 유지 보수 => 다형성
* ==== 오버라이딩(modify) , 오버로딩(new)
* = 데이터를 보호 (은닉화/캡슐화)
* 캡슐화 : 데이터 감춘다 => 필요시마다 사용이 가능, 경계선
* ============================================================= 객체지향의 3대 요소
* page 231
* => 목적 : 재사용, 데이터 보호
* ====== 있는 그대로(포함) , 변경(상속)
* => 뜻 : 상속 , 다형성 , 캡슐화
*
* 1) 클래스의 구성요소
* 2) 변수 => 초기화 하는 방법
* => 명시적 초기화
* => 생성자
* => 초기화 블록
* 3) 메소드에서 변수를 제어
* ===============================
*
* 데이터 저장 =====> 데이터 활용(가공) =====> 출력(윈도우,도스,모바일,브라우저)
* =========== =================
* 변수 요청처리(유저) => 필요하면 변경 (메소드)
* 변수를 관련된 내용끼리 묶어서 저장 => 찾기 (클래스, 배열)
*
* 1. 구성요소 (클래스) => 한개만 선언 ==> 저장을 여러개 해서 사용
* 학생 => 100명
* class ClassName {
* // 선언만 가능 : 변수, 메소드
* ===============================================
* 필요한 데이터 저장 : 변수 , 배열 , 클래스 ...
* 1) 따로 사용 변수 (인스턴스 변수, 객체변수)
* 2) 공통으로 사용하는 변수 (정적변수, 공통변수, 클래스 변수) ==> static
*
* // class 안에서는 X
* // 오류 코드
* int a; // 선언
* for (int i=1; i<=100; i++) { // 구현 (제어문, 라이브러리 메소드 호출)
* a+=i;
* }
*
* int a=10+20; (O)
* ===============================================
* // 구현 : 연산자 , 제어문 , 화면 출력 => 메소드
* 구현은 => class 블록 안에서 구현이 가능
* ===============================================
* 메소드의 종류
* *** 1. 선언(구현(X)) : 추상메소드 abstract => 프로그램에 맞게 구현해서 사용
* button : actionPerformed()
* *** 2. 선언과 동시에 구현 : void display() {}
* 3. 미리 메모리 저장 (공통) : static void display() {}
* 4. 상속 => 수정이 없는 방법 : final void display() {}
* => String, Math, System ...
*
* ===============================================================================
* 생성자 함수
* = 특징 : 클래스명과 동일
* = 메모리에 저장시 호출 => new 다음에 붙는다
* = 생략을 하면 컴파일러가 자동으로 하나를 추가 (***)
* = 객체 생성시에 항상 호출되는 메소드
* }
*/
public class 객체지향프로그램 {
int a=100;; // 명시적 초기화
// 초기화 블록 => 파일 읽기 , 웹 연결 ...
{
for (int i = 1; i <= 100; i++) {
a += i;
}
}
// 생성자 함수
객체지향프로그램() {
for (int i = 1; i <= 100; i++) {
a += i;
}
}
public static void main(String[] args) {
객체지향프로그램 a = new 객체지향프로그램(); // 변수 초기화 담당
}
}<file_sep>/20210701-객체지향프로그램(패키지_import)/src/com/sist/main/MainClass.java
package com.sist.main;
import com.sist.dao.Oracle;
/*
* 패키지 => 재사용 (관련된 클래스를 묶어서 저장)
* => 사용시 => import
*/
public class MainClass {
public static void main(String[] args) {
Oracle o = new Oracle();
o.connection();
o.disconnection();
}
}
<file_sep>/20210630-객체지향응용(캡슐화,상속-변경)/src/NaverReserve.java
// Naver에 맞게 변경 -> 오버라이딩
public class NaverReserve extends Reserve {
public NaverReserve( ) {
System.out.println("NaverReserve 생성자()...");
}
}
<file_sep>/20210628-객체지향프로그램1/src/변수초기화3.java
import java.util.Scanner;
// 변수 초기화
/*
* class A {
* ================================
* 변수 => 초기화 (시작값을 지정)
* = 명시적 초기화
* = 구현 후에 값 초기화
* = 생성자
* = 초기화 블록
* ================================
* }
*/
/*
* 구성요소
* ========
* 멤버변수 : 데이터 저장
* 메소드 : 저장된 데이터 가공
* 생성자 : 메모리 할당 => 데이터베이스 연결 (자바 <===> 오라클)
*/
public class 변수초기화3 {
String[] data = new String[10];
// 멤버변수 초기화 블록 => 자동호출 (명시적 초기화 => 초기화 블록 => 생성자 (특별한 경우가 아니면 생성자를 이용한다) )
{
data[0] = "홍길동";
data[1] = "심청이";
data[2] = "춘향이";
data[3] = "박문수";
data[4] = "이순신";
data[5] = "김두환";
data[6] = "을지문덕";
data[7] = "강감찬";
data[8] = "이산";
data[9] = "소서노";
}
public static void main(String[] args) {
// 출력 => 반드시 메모리에 저장
변수초기화3 a = new 변수초기화3(); // a.data
// 출력
for (String name : a.data) {
System.out.println(name);
}
System.out.println("============");
Scanner scan = new Scanner(System.in);
System.out.print("이름 입력: ");
String n = scan.next();
// 이름이 있는 경우에는 이름을 출력 , 없는 경우에는 "이름이 없다" 출력
boolean bCheck = false;
for (String name : a.data) {
if (n.equals(name)) {
System.out.println("찾은 이름: " + name); // 1번 수행
bCheck = true;
break;
} /*
* else { System.out.println("찾는 이름이 없습니다"); // 9번 수행
*/
}
if (bCheck == false) {
System.out.println("찾는 이름이 없습니다");
}
}
}
<file_sep>/20210621-자바기본문법정리/src/배열활용_최대최소값.java
import java.util.Arrays;
public class 배열활용_최대최소값 {
public static void main(String[] args) {
int arr[] = new int[7];
// 값 대입
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 100) + 1; // 1~100 사이의 정수 대입
}
System.out.println(Arrays.toString(arr));
int max = arr[0];
int min = arr[0];
for (int i : arr) {
if (max < i) // 저장된 데이터 중에 큰 값이 있으면 변경
max = i;
if (min > i) // 저장된 데이터 중에 작은 값이 있으면 변경
min = i;
}
System.out.println("최대값: " + max);
System.out.println("최소값: " + min);
}
}
<file_sep>/20210621-자바배열문제/src/Question1.java
public class Question1 {
public static void main(String[] args) {
int sum=0, i=1;
while (i<100) {
if(i%3 != 0) {
i++;
continue;
}
else sum += i;
i++;
}
}
}
<file_sep>/20210615-자바제어문(조건문)/src/자바중첩조건문1.java
import java.util.Scanner;
/*
* 중첩 조건문
* 형식)
* if (조건문) ===> 아이디 존재하고 {
* if (조건문) ==> 비밀번호가 같다 {
* }
* }
*
* if (컴퓨터==가위) {
* if (사용자 == 가위)
* else if (사용자 == 가위)
* else if (사용자 == 보)
* }
*
* 점수 입력
* if (socre>=90) ==> A {
* if (score>=98) {
* }
* else
* 94 이하
* }
*/
public class 자바중첩조건문1 {
public static void main(String[] args) {
// 1. Scanner 생성 => 입력값을 받아서 저장
Scanner stdIn = new Scanner(System.in);
// 2. 사용자 입력 요청
System.out.print("0~100 사이의 정수를 입력하세요 : ");
// 3. 사용자가 입력한 정수를 받아서 저장
int score = stdIn.nextInt();
char grade = ' '; // A , B , C , D, F
char option = ' '; // +(98) , -(94이하) , 0
// 결과값을 출력
if (score >= 90) {
grade = 'A';
if (score >= 98)
option = '+';
else if (score < 94)
option = '-';
else
option = 'O';
} else if (score >= 80) {
grade = 'B';
if (score >= 88)
option = '+';
else if (score < 94)
option = '-';
else
option = 'O';
} else if (score >= 70) {
grade = 'B';
if (score >= 78)
option = '+';
else if (score < 74)
option = '-';
else
option = 'O';
} else if (score >= 60) {
grade = 'B';
if (score >= 68)
option = '+';
else if (score < 64)
option = '-';
else
option = 'O';
} else {
grade = 'F';
}
System.out.printf("학점은 %c%c\n", grade, option);
}
}
<file_sep>/20210617-자바기본프로그램정리/src/자바문자열데이터7.java
/*
* trim() , valueOf() , 모바일(kotlin) , 웹(JSP/Spring)
* ================================ 전송데이터, 수신데이터 (모든 데이터 String)
* 모든 데이터형 => String 변환 (valueOf())
* valueOf(10) => "10"
* valueOf(true) => "true"
* ======= trim() : 좌우 공백문자 제거 ==> 입력창에 trim() => 사용자의 실수 " admin" "admin"
*/
public class 자바문자열데이터7 {
public static void main(String[] args) {
String s = " Hello Java ";
System.out.println(s);
System.out.println(s.length());
System.out.println(s.trim()); // 로그인 (id, password, 회원가입, 글쓰기...)
System.out.println(s.trim().length());
System.out.println(10+String.valueOf(true)); // + : 실수, 정수 => 문자열
// instance , static => 클래스명.메소드() => ex) Math.random()
}
}
<file_sep>/20210610-자바데이터형(변수)/src/자바데이터형.java
/*
* 평문 조건문 반복문 ==> 기능별로 나눠서 출력(메소드) (재사용)
* Application : dos, window => 네트워크(쓰레드), IO
* Web : 데이터베이스 , HTML
* Mobile : 네트워크 , 데이터베이스 (XML, JSON) => JS
*
* 변수 : 한 개의 데이터를 저장하는 메모리 공간
* 변경할 수 있는 값
*
* 설정
* 데이터형(메모리 크기) 변수명=값;
* 상수 : 한 개의 데이터를 저장하는 메모리 공간
* 변경할 수 없는 값 (서버 IP, 오라클 주소...)
* final 데이터형(메모리 크기) 변수명=값;
* ===== 상수
*
* 메모리 크기 (기본 데이터형 / 기본 자료형) => 자바에서 설정된 데이터 크기
*
*
* 프로그램
* ================
* 1. 변수 => 메모리에 저장 => 메모리 크기 결정(종류설정)
* ===========
* 2. 연산자
* 3. 제어문
* =========== 메소드
* =========================== 클래스 (재사용) => 객체지향프로그램
*
* 데이터 저장 종류
* 정수형
* byte (1byte) => -128~127 : 네트워크 통신, 파일 입출력, 파일전송
* short (2byte) => C언어 호환 => -32768~32767
* * int (4byte) => default : 평상시에 컴퓨터에 숫자 사용하면 인식하는 데이터형 (많이 사용)
* => -21억 4천 ~ 21억 4천
* long (8byte) => 빅데이터, 데이터 수집 ... (금융권) => 많이 사용
* * int / long => 숫자 뒤에 (100(int), 100L(long), 1001(long))
* 실수형
* float : (4byte) => 소수점 이하 (6자리)
* double : (8btye) => 소수점 이하 (15자리) ===> 평상시에 사용하는 실수 10.5 (default)
* 문자형
* char : (멀티바이트) => 2byte
* ============
* 싱글바이트 (1byte) => ASCII (0~255)
* 멀티바이트 (2byte) => Unicode (0~65535) : 모든 언어(한국어, 일본어, 중국어...) UTF-8
* => '' : 한 글자 저장 (int와 호환) 문자마다 고유번호
* 'A' , 'a' , '0'
* === === ==
* 65 97 48
* 논리형
* true / false 저장 : 1byte ( true/1 , false/0 ) => 형변환 제외 (독립적으로 사용)
* ===============================
* 참조형 (배열, 클래스) => String
* ==> 데이터 수집 => 통계(단어별)
*
* 변수를 설정
* ===========
* 1. 데이터형 (메모리 크기) 변수명 = 값
* 국어 점수
* int kor = 80; => 4btye 메모리에 80을 저장한다 , kor으로 메모리 설정
* kor = 90;
*
* 2. 이름을 저장
* 홍길동
* char f = '홍';
* char s = '길';
* char t = '동';
* => String name = "홍길동";
*
* 3. 평균
* 85.5 => double
* double avg = 85.5D; (D, d는 생략 가능)
* float avg = 85.5f;
*
* 4. true/false : 조건문 6 < 7 ==> true
* boolean bCheck = true;
* boolean bCheck = false;
*
* 기본 데이터형
* =============
*
* ===============================================================
* 1byte 2byte 4byte 8btye
* ===============================================================
* 정수형 byte short int long(L,l)
* ================
* 범위 초과하지 않는다
* byte => -127 ~ 128
* short => -32768 ~ 32767
*
* ===============================================================
* 실수형 float(F,f) double(D,d,생략)
* ===============================================================
* 문자형 char => 문자 1개 저장
* ===============================================================
* 논리형 boolean => true/false : 비교연산, 논리연산, 부정
* 로그인, 아이디중복체크, 비밀번호 체크 ....
* ===============================================================
* => 대표적으로 사용하는 데이터형
* 네트워크, 파일 => byte (파일업로드, 파일 다운로드)
* 웹, 코틀린 : int, double, boolean, String
*
* => ******** 암기!!!!! 데이터형의 크기 (중요!!!) ********
* 정수/문자/실수
* byte < char, short < int < long < float < double
* ================================ ================= 수의 표현
* 1 1.000000
* 1.111111
* 1.000001
* UP Casting (데이터형 높게)
* Down Casting (데이터형 낮게)
*
* => char c = 'A'; => int i = (int)'A';
* char c = (char)65;
* => int avg = (int)(100 / 3.0);
*/
public class 자바데이터형 {
public static void main(String[] args) {
byte b = (byte) 300;
short s = 100; // 일반 숫자 => byte, short, int => long : L
double d = 85.5D; // D, F, L
System.out.println(b);
/*
* =======================================================
* 256 128 64 32 16 8 4 2 1(0)
* =======================================================
* 1 0 0 1 0 1 1 0 0
* =====================================
* 32 + 8 + 4 ==> 44
*/
/* 국어, 수학, 영어 점수를 입력받아서 총점(int), 평균(double), 등수, 학점
* ================ ==========
* => int int char
*
*/
}
}
<file_sep>/20210615-자바제어문(조건문)/src/자바중첩조건문2.java
import java.util.Scanner;
// 가위바위보 => 중첩 조건문 ==> 다중 조건 검색 (대분류 => 중분류 => 소분류)
/*
* if (대분류) {
* if (중분류) {
* if (소분류) {
* }
* }
* }
*
* ===> if (대분류 && 중분류 && 소분류)
*
* *
* **
* ***
* ****
*
* System.out.println("*");
* System.out.println("**");
* System.out.println("***");
* System.out.println("****");
*
* for (int i=1; i<=4; i++) {
* for (int j=1; j<=i; j++) {
* System.out.print("*");
* }
* System.out.println("\n"):
* }
*/
public class 자바중첩조건문2 {
public static void main(String[] args) {
// 1. 난수 (컴퓨터)
int com = (int) (Math.random() * 3); // 0 (가위) , 1 (바위) , 2 (보)
// 임의로 숫자 => double (0.0 ~ 0.99) ==>
// 2. 사용자가 입력
Scanner stdIn = new Scanner(System.in);
System.out.print("가위(0), 바위(1), 보(2) : ");
int user = stdIn.nextInt();
// 컴퓨터
if (com == 0)
System.out.println("컴퓨터: 가위");
else if (com == 1)
System.out.println("컴퓨터 : 바위");
else
System.out.println("컴퓨터 : 보");
// 사용자
if (user == 0)
System.out.println("사용자: 가위");
else if (user == 1)
System.out.println("사용자 : 바위");
else
System.out.println("사용자 : 보");
// 게임 결과
if (com == 0) { // 컴퓨터 ==> 가위 => 중첩 ==> &&로 사용할 수 있다
if (user == 0) { // 가위 ==> if (com==0 && user==0)
System.out.println("비겼다!!");
} else if (user == 1) { // 바위
System.out.println("사용자 Win!!");
} else if (user == 2) { // 보
System.out.println("컴퓨터 Win!!");
}
} else if (com == 1) { // 컴퓨터 => 바위
if (user == 0) { // 가위
System.out.println("컴퓨터 Win!!");
} else if (user == 1) { // 바위
System.out.println("비겼다!!");
} else if (user == 2) { // 보
System.out.println("사용자 Win!!");
}
} else { // 컴퓨터 => 보
if (user == 0) { // 가위
System.out.println("사용자 Win!!");
} else if (user == 1) { // 바위
System.out.println("컴퓨터 Win!!");
} else if (user == 2) { // 보
System.out.println("비겼다!!");
}
}
}
}
<file_sep>/20210617-자바기본프로그램정리/src/자바기본프로그램정리1.java
import java.util.Scanner;
/*
* 1. 변수 (데이터 저장) ==> 변수 (데이터를 묶어서 사용:배열)
* 배열 : 고정 , 같은 데이터형만 모아서 처리 => 클래스 (다른 데이터형)
* ====================================================================
* 메모리 저장 (한번 사용 후 종료) ==> 파일, RDBMS(오라클)(영구적인 저장 장치)
* 2. 연산자 : 변경 사항이 없다
* 단항연산자
* ++,--(증감연산자) , !(부정) , (type) => 형변환
* =======
* 선증가(++a), 후증가(a++)
* 이항연산자
* 산술연산자( + , - , * , /, % )
* 비교연산자( == , != , < , > , <= , >= ) => true/false => if , for , while(조건식)
* 논리연산자 (범위 ,기간) &&(포함) , ||(미포함)
* 대입연산자 ( = , += , -= )
* 삼항연산자 ( (조건) ? 값1 : 값2 ) => if ~ else
* ======
* true : 값1
* false : 값2
* *** 우선순위 ==> () 최우선순위 연산
* 3. 제어문 : 변경 사항이 없다
* 조건문
* if : 단일 조건문 : 여러개 동시에 수행이 가능
* if~else : 선택 조건문
* if~ else if ~ else if ~ else : 다중조건문 : 조건에 맞는 문장만 수행
* 선택문
* 값 1개가 선택시에 처리
* switch(문자, 정수, 문자열) ~ case ...
* 반복문
* for ==> 2차 for => 반복 횟수가 있는 경우
* while => 반복횟수가 없는 경우 (데이터베이스 연결)
* 반복제어문
* break : 반복문장을 종료
* continue : 특정부분을 제외 ===> 게임 (입력이 잘못된 경우 => 처음 상태)
*/
public class 자바기본프로그램정리1 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
// 변수 초기화
int score = 0;
while (true) { // 무한 루프
System.out.print("0~100까지 사이의 정수를 입력:");
score = stdIn.nextInt();
if (score<0 || score>100) {
System.out.println("잘못된 입력입니다");
continue;
/*
* 1. for : 증가식으로 이동
* 2. while : 조건식으로 이동
*/
}
break;
}
System.out.println("socre="+score);
}
}<file_sep>/20210622-자바메소드형식/src/자바메소드_결과값_매개변수.java
import java.util.Scanner;
// 사칙연산 처리 => 메소드
public class 자바메소드_결과값_매개변수 {
static int plus(int a, int b) {
return a + b;
}
static int minus(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
static double divide(int a, int b) {
return a / (double) b;
}
static void calc() {
Scanner stdIn = new Scanner(System.in);
System.out.print("첫번째 정수 입력: ");
int a = stdIn.nextInt();
System.out.print("두번째 정수 입력: ");
int b = stdIn.nextInt();
System.out.print("연산자 입력(+,-,*,/): ");
// Scanner의 단점 : char를 받을 수 없다 => 문자열
String op = stdIn.next();
switch (op) {
case "+": {
int c = plus(a, b);
System.out.println(c);
}
break;
case "-": {
int c = minus(a, b);
System.out.println(c);
}
break;
case "*": {
int c = multiply(a, b);
System.out.println(c);
}
break;
case "/": {
if (b == 0) {
System.out.println("0으로 나눌 수 없습니다");
} else {
double d = divide(a, b);
System.out.printf("%.2f\n", d);
}
}
break;
}
}
public static void main(String[] args) {
calc();
}
}
<file_sep>/20210617-자바기본프로그램정리/src/자바문자열데이터6.java
/*
* 낙지철판덮밥 8,000원 돼지철판덮밥8,000원 돌솥비빔밥 7,500원 콩나물해장국 7,000원 항아리수제비 7,500원
*/
public class 자바문자열데이터6 {
public static void main(String[] args) {
String menu = "낙지철판덮밥 8,000원 돼지철판덮밥8,000원 돌솥비빔밥"
+ "7,500원 콩나물해장국 7,000원 항아리수제비 7,500원";
String[] s = menu.split("원");
for (String m : s) { // for~each
System.out.println(m.trim() + "원");
}
}
}<file_sep>/20210628-객체지향프로그램(메소드)/src/MainClass5.java
public class MainClass5 {
public static void main(String[] args) {
// static
MainClass4.display2();
MainClass4 m = new MainClass4();
m.display1();
}
}
<file_sep>/20210616-1차문제/Question04.java
import java.util.Scanner;
public class Question04 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.print("정수 입력:");
int num = stdIn.nextInt();
if (num<0) {
System.out.println("a="+num*(-1));
} else if (num==0) {
System.out.println("a=0");
} else {
System.out.println("a="+num);
}
}
}
<file_sep>/FirstProject/src/MainClass.java
public class MainClass {
public static void main(String[] args) { // main 입력 후 ctrl + spacebar 후 enter
// 출력 (주석)
System.out.println("Hello Java!");
}
}
<file_sep>/20210623-자바메소드정리(문제풀이)/src/윤년처리.java
public class 윤년처리 {
// 윤년 처리
static boolean isYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return true;
} else {
return false;
}
}
// 출력
static void print() {
int year = 자바메소드정리.input("년도");
boolean check = isYear(year);
if (check)
System.out.println(year + "년도는 윤년입니다.");
else
System.out.println(year + "년도는 윤년이 아닙니다");
}
public static void main(String[] args) {
print();
}
}
<file_sep>/20210618-3차문제/src/Question09.java
public class Question09 {
public static void main(String[] args) {
int[] num = new int[10];
for (int i =0; i<num.length; i++) {
num[i] = (int) (Math.random() * 10)+1;
}
for (int i : num) {
System.out.printf("%d ", i);
}
System.out.println();
int total = 0;
for (int i : num) {
total += i;
}
System.out.println("평균 : " + total / (double)num.length);
}
}
<file_sep>/20210618-3차문제/src/Question07.java
import java.util.Scanner;
public class Question07 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.print("점수 입력: ");
int score = stdIn.nextInt();
if (score >= 60)
System.out.println("합격");
else
System.out.println("불합격");
}
}
<file_sep>/20210618-자바배열/src/자바배열2.java
// 5개의 정수를 저장 => 합과 평균을 구해서 처리
public class 자바배열2 {
public static void main(String[] args) {
/*
// 난수 => 임의로 데이터 저장
// 1. 일반 변수
int a = (int) (Math.random() * 100) + 1; // 1~100
int b = (int) (Math.random() * 100) + 1; // 1~100
int c = (int) (Math.random() * 100) + 1; // 1~100
int d = (int) (Math.random() * 100) + 1; // 1~100
int e = (int) (Math.random() * 100) + 1; // 1~100
System.out.printf("a=%d, b=%d, c=%d, d=%d, e=%d\n", a, b, c, d, e);
System.out.printf("합:%d\n", a + b + c + d + e);
System.out.printf("평균:%.2f\n", (a + b + c + d + e) / 5.0);
// 최대값, 최소값 구하기
int max = a;
int min = a;
// 최대값
if (max < a)
max = a;
if (max < b)
max = b;
if (max < c)
max = c;
if (max < d)
max = d;
if (max < e)
max = e;
System.out.println("최대값:" + max);
// 최소값
if (min > a)
min = a;
if (min > b)
min = b;
if (min > c)
min = c;
if (min > d)
min = d;
if (min > e)
min = e;
System.out.println("최소값:" + min);
*/
// 데이터를 모아서 처리 (변수명이 1개로 통일) ==> 인덱스 번호를 0
// 선언
int[] arr = new int[10];
// 초기값
for (int i =0; i<arr.length; i++) {
arr[i] = (int) (Math.random()*100)+1;
}
for (int i : arr) {
System.out.printf("%d\t", i);
}
System.out.println();
// 총합
int total = 0;
for (int i : arr) {
total += i;
}
System.out.println("합:" + total);
// 평균
System.out.println("평균:"+(total/(double)arr.length));
// 최소값, 최대값
int min = arr[0];
int max = arr[0];
for (int i : arr) {
if (i<min)
min = i;
if (i>max)
max = i;
}
System.out.println("최대값:" + max);
System.out.println("최소값:" + min);
}
}<file_sep>/FirstProject/src/MainClass2.java
public class MainClass2 {
public static void main(String[] args) {
// Hello 출력
System.out.println("Hello");
}
}
<file_sep>/20210629-객체지향프로그램-생성자(매개변수)/src/변수초기화.java
/*
* 변수의 초기화
* 변수 : 한개를 저장하는 공간 (반드시 값을 입력)
* 멤버변수 => 자동 초기화
* class A {
* int a; => 0
* double d; => 0.0
* boolean b; => false
* String s; => null
* long l; => 0L
* }
* 지역변수 => 자동 초기화 (x) : 사용전까지 반드시 값을 설정
* ==========
* 연산처리전 , 출력전 ...
*
* 멤버변수에 대한 초기값
* 1. 명시적 초기화
* class A {
* int a; => 0
* int b=100; // 게임, 위치(출력)
* String name; // null => 나중에 변경해서 사용
* String n = "홍길동";
* }
* 2. 생성자 : 외부에서 데이터를 읽어서 초기화
* => 자동 로그인
* 파일 읽기 => 데이터를 초기화
* 3. 초기화 블럭
* class A {
* int sum;
*
* 인스턴스 블록
* {
* for (int i=1; i<=1000; i++) {
* sum +=i;
* }
* }
*
* // 공유변수일 경우 (static)
* static ==> 마이바티스 (XML을 읽어 초기화)
* }
*/
class B {
int a=10;
static int b=20;
// 복잡한 초기화 => for , 난수 ... , 객체마다 변수 초기값이 다르게 만든다
{ // 2
System.out.println("인스턴스 초기화 블록");
a=100;
}
static { // 1
System.out.println("static 초기화 블록");
b=200;
}
B() { // 3
System.out.println("생성자에서 초기화");
a=1000;
b=2000;
}
}
public class 변수초기화 {
public static void main(String[] args) {
B b = new B();
System.out.println(b.b); // 2000
System.out.println(b.a); // 1000
}
}
<file_sep>/20210614-자바연산자정리/src/자바연산자정리4.java
import java.util.Scanner;
// 국어 영어 수학 점수를 받아서 평균, 총점 구하기
// => 직접 입력 , 사용자 입력값 , 난수(컴퓨터)
/*
* ① 직접 입력
* int kor = 90;
* int eng = 100;
*
* ② 사용자 입력값
* Scanner 사용
*
* ③ 난수(컴퓨터)
* Math.random
*/
public class 자바연산자정리4 {
public static void main(String[] args) {
// Scanner를 생성 => 클래스는 생성 => new => 메모리에 저장
Scanner stdIn = new Scanner(System.in);
// System.in(입력값을 읽는 경우 : inputStream, System.out(화면 출력 : outputStream)
System.out.print("국어 점수를 입력하세요 : ");
int korean = stdIn.nextInt(); // 입력된 정수를 받아오는 기능 (nextInt())
System.out.print("영어 점수를 입력하세요 : ");
int english = stdIn.nextInt();
System.out.print("수학 점수를 입력하세요 : ");
int math = stdIn.nextInt();
System.out.println("=============결과=============");
System.out.printf("세 과목의 평균 점수는 %.1f점입니다.\n", (double)(korean+english+math)/3);
System.out.printf("세 과목의 총점은 %d점입니다.", korean+english+math);
/*
* next() ===> 문자열(String)
* nextInt() ===> 정수(int)
* nextBoolean() ===> true/false
* nextDouble() ===> 실수
*/
}
}
<file_sep>/20210701-객체지향프로그램(패키지_import)/src/com/sist/dao/Oracle.java
package com.sist.dao;
public class Oracle {
public void connection() {
System.out.println("오라클 연결");
}
public void disconnection() {
System.out.println("오라클 연결 해제");
}
}
<file_sep>/20210616-자바제어문(while)/src/자바제어문2.java
import java.util.Scanner;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/*
* while
* 형식)
* 초기값 ==== 1
* while(조건식) { ==== 2
* 반복실행문장 === 3
* 증가식 === 4 ===> 이동 (증가 후 2번 조건식)
* }
* 2번에서 조건식이 false이면 while을 종료
*
*
* public static void main(String[] args) {
* int a=10;
* if (a==10) {
* int b=20;
* if (b==20) {
* int c-30;
*
* // a, b, c 변수 사용가능
* } ====> c 변수는 메모리에서 사라진다
* // a, b 변수 사용가능
* } =====> b 변수는 메모리에서 사라진다 ===> 시스템에서 메모리를 관리하는 영역 (스택 => 메모리 자체 관리)
* 사라지는 시기 => {} (블록변수, 지역변수)
* // a 변수는 사용이 가능
* }
*
* 변수의 종류
* => 지역변수
* = 누적변수
* = 루프변수
* = 플로그변수
*
* for (int i=1; i<=10; i++) {
* 처리
* } // i는 사라진다
* for(int i=1;i<=10;i++) {
*
* } // i는 사라진다
*
*/
public class 자바제어문2 {
public static void main(String[] args) throws Exception {
// // 알파벳
// char c = 'A'; // 메모리가 main이 종료시까지 유지
// while(c<='Z') {
// char c1='A'; // while에서만 사용 => while이 시작할 때 새롭게 메모리 생성
// System.out.println(c1++);
// c++;
// }
Scanner stdIn = new Scanner(System.in);
while (true) {// 무한루프 => 종료하는 방법 설정
System.out.println("======= 메뉴 =======");
System.out.println("1. 현재 상영 영화");
System.out.println("2. 개봉 예정 영화");
System.out.println("3. 영화 예매");
System.out.println("4. 종료");
System.out.println("=====================");
System.out.print("메뉴 선택: ");
int menu = stdIn.nextInt();
if (menu == 1) {
// System.out.println("현재 상영 영화 목록입니다");
Document doc = Jsoup.connect("https://movie.daum.net/ranking/reservation").get();
Elements title = doc.select("strong.tit_item");
for (int i = 0; i < title.size(); i++) {
System.out.println(title.get(i).text());
}
} else if (menu == 2) {
// System.out.println("개봉 예정 영화입니다");
Document doc = Jsoup.connect("https://movie.daum.net/ranking/boxoffice/weekly").get();
Elements title = doc.select("strong.tit_item");
for (int i = 0; i < title.size(); i++) {
System.out.println(title.get(i).text());
}
} else if (menu == 3) {
System.out.println("영화 예매 화면입니다");
} else if (menu == 4) {
System.exit(0); // 프로그램 종료 (0=>정상종료)
}
}
}
}
<file_sep>/20210614-자바제어문(조건문)/src/자바제어문_조건문3.java
public class 자바제어문_조건문3 {
public static void main(String[] args) {
// char ch = (Math.random())
// System.out.println((int) 'Z'); // 90
// System.out.println((int) 'z'); //122
int a = (int)(Math.random()*2); // 0.0*2 ==> 0.0 , 0.99 * 2 => 1.9 ...
char ch = (char) ((Math.random() * 26) + 65); // 0 ~ 25 발생 => 65 'A'=>65 , 'Z'=>90 => 0~25+65
if (a==0)
ch = (char) ((Math.random() * 26) + 65); // 대문자
if (a==1)
ch = (char) ((Math.random() * 26) + 97); // 소문자
if (a==2)
ch = (char) ((Math.random() * 10) + 48); // '0' , '1' ~~~ '9'
// System.out.println(ch);
// 대문자 조건 (ch>='A' && ch<='Z') &&: 범위 포함 (이고)
if(ch>='A' && ch<='Z')
System.out.println(ch+"는(은) 대문자입니다");
// 소문자 조건 (ch>='Z' && ch<='z') ||: 범위 밖에 있는 경우 (이거나)
if (ch>='a' && ch<='z')
System.out.println(ch+"는(은) 소문자입니다");
// 알파벳이 아닌 경우 (대문자나 소문자가 아닌 경우)
if (!((ch>='A' && ch<='Z') || (ch>='a' && ch<='z')))
System.out.println(ch + "은(는) 알파벳이 아닙니다");
}
}
<file_sep>/20210623-자바메소드정리(문제풀이)/src/정렬.java
import java.util.Arrays;
public class 정렬 {
static int[] rand() {
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random()*100) + 1;
}
return arr;
}
// 정렬 DESC(내림차순)
static int[] sortDesc(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[i] < arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
// 정렬 ASC (내림차순)
static int[] sortAsc(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[i] > arr[j]) { // DESC(내림차순)
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
// 출력
static void print() {
int[] arr = rand();
System.out.println("정렬 전: ");
System.out.println(Arrays.toString(arr));
System.out.println("내림차순 정렬 후: ");
int[] a = sortDesc(arr);
System.out.println(Arrays.toString(a));
System.out.println("오름차순 정렬 후: ");
int[] b = sortAsc(arr);
System.out.println(Arrays.toString(b));
}
public static void main(String[] args) {
print();
}
}
| 1c0c49784825d1a588dc1b1884018ab6dba1b04b | [
"Java"
] | 65 | Java | sujinkim123/javaStudy | c5f20542fba1802dcb6418e0f61336958b3e1eb3 | 261be203d0e62cd6091be4651ff60f8fe93aab72 |
refs/heads/master | <repo_name>Hanoo2002/Protons-Final-Project-master<file_sep>/Protons-Final-Project-master/GUI.py
from tkinter import *
from Algorithm import *
import calendar
create_table()
def raise_frame(parent):
parent.tkraise()
root = Tk()
Home = Frame(root)
AddActivity = Frame(root)
AddCategory = Frame(root)
EditActivity = Frame(root)
EditCategory = Frame(root)
Calendar = Frame(root)
Todo = Frame(root)
Today = Frame(root)
Now = Frame(root)
for frame in (Home, AddActivity, AddCategory, EditActivity, EditCategory, Calendar, Todo, Today, Now):
frame.grid(row=0, column=0, sticky='news')
########################################################################################################################
# Home Frame
class Edit:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Edit").pack()
Label(top, text='What do you want to edit?')
cate = Button(top, text="Category", command=lambda: raise_frame(EditCategory))
cate.pack(pady=5, padx=5, side=LEFT)
activity = Button(top, text="Activity", command=lambda: raise_frame(EditActivity))
activity.pack(pady=5, padx=5, side=LEFT)
def edit():
ed = Edit(Home)
Home.wait_window(ed.top)
class Add:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Add").pack()
Label(top, text='What do you want to add?')
cat = Button(top, text="Category", command=lambda: raise_frame(AddCategory))
cat.pack(pady=5, padx=5, side=LEFT)
act = Button(top, text="Activity", command=lambda: raise_frame(AddActivity))
act.pack(pady=5, padx=5, side=LEFT)
def add():
ad = Add(Home)
Home.wait_window(ad.top)
TopFrame = Frame(Home)
MiddleFrame = Frame(Home, padx=200)
BottomFrame = Frame(Home)
LastFrame_Home = Frame(Home)
TopFrame.pack(side='top', fill=X)
MiddleFrame.pack(side='top', ipady=5, fill=X)
BottomFrame.pack(side='top', ipady=5, fill=X)
LastFrame_Home.pack(side='top', ipady=5, fill=X)
HomeLabel = Label(TopFrame, text='Home')
HomeLabel.pack(side=LEFT)
AddButton = Button(TopFrame, text='Add', command=add)
AddButton.pack(side=RIGHT)
CalendarButton = Button(MiddleFrame, text='Calendar', command=lambda: raise_frame(Calendar))
CalendarButton.pack(padx=5, pady=10, side=LEFT)
TodoButton = Button(MiddleFrame, text='Todo', command=lambda: raise_frame(Todo))
TodoButton.pack(padx=5, pady=10, side=LEFT)
TodayButton = Button(MiddleFrame, text='Today', command=lambda: raise_frame(Today))
TodayButton.pack(padx=5, pady=10, side=LEFT)
NowButton = Button(MiddleFrame, text='Now', command=lambda: raise_frame(Now))
NowButton.pack(padx=5, pady=10, side=LEFT)
category_name = strainer('name', 'sort', 'category')
number = 0
# if category_name[number][0]
for i in range(0, len(category_name)):
if number == 10:
break
CategoryButton = Button(BottomFrame, text='{}'.format(category_name[number][0]), width=5, anchor="w")
CategoryButton.pack(padx=5, pady=5, fill=X)
number += 1
EditButton = Button(LastFrame_Home, text='Edit', command=edit)
EditButton.pack()
########################################################################################################################
# AddActivity Frame
# The layout is devided in many frames
def on_entry_click(event):
"""
when any entry widget is clicked, this code comes to action.
This deletes what was written in the entry widget and makes the font-colour black
"""
global FirstClick
entry = event.widget
if FirstClick:
FirstClick = False
entry.config(fg='black')
entry.delete(0, "end")
FirstClick = True
return
def back():
"""
is called when the BackButton is clicked.
It gets the user back to home
"""
raise_frame(Home)
def insert():
"""
This saves the data of the user and brings him back to home
"""
list_of_days = [Mon.get(), Tue.get(), Wed.get(), Thu.get(), Fri.get(), Sat.get(), Sun.get()]
number_of_day = 0
list_of_calendar_day_names = calendar.day_name
frequency = []
for day in list_of_days:
if day == 1:
frequency.append(list_of_calendar_day_names[number_of_day])
number_of_day += 1
date_of_activity = "{}/{}/{}".format(Day.get(), Month.get(), Year.get())
if Category.get() == 'todo':
insert_todo(NameOfActivity.get(), Category.get(), HoursFrom.get(), MinTo.get(), date_of_activity,
Importance.get(), frequency)
else:
insert_event(NameOfActivity.get(), Category.get(), HoursFrom.get(), MinTo.get(), date, Importance.get(),
frequency)
raise_frame(Home)
# The first frame contains the name of the event the user will write
NameFrame = Frame(AddActivity)
NameFrame.pack(side='top', fill=X, ipady=5)
NameLabel = Label(NameFrame, text='Name: ')
NameLabel.pack(side=LEFT)
FirstClick = True
NameOfActivity = Entry(NameFrame, fg='grey')
NameOfActivity.insert(0, "Enter the name of your event ...", )
NameOfActivity.bind('<FocusIn>', on_entry_click)
NameOfActivity.pack(ipadx=25, side=LEFT)
# This frame includes a DropDownMenu which gets all of the categories in the database
CategoryFrame = Frame(AddActivity)
CategoryFrame.pack(side='top', ipady=5, fill=X)
category_names = []
category_name = strainer('name', 'sort', 'category')
number = 0
for loop in range(0, len(category_name)):
category_names.append(category_name[number][0])
number += 1
Category = StringVar(CategoryFrame)
Category.set('None')
option = OptionMenu(CategoryFrame, Category, *category_names)
option.pack(fill=X, pady=5)
event = StringVar(CategoryFrame)
event.set('Todo')
category = OptionMenu(CategoryFrame, event, "Todo", 'Event')
category.pack(fill=X, pady=5)
# This Frame contains two entry widgets, where the user will write the from and to time, aka hours and min
EstimatedFrame = Frame(AddActivity)
EstimatedFrame.pack(side='top', ipady=5, fill=X)
HoursFrom = Entry(EstimatedFrame, fg='grey')
HoursFrom.insert(0, "Hours: 2 / From: 7:30", )
HoursFrom.bind('<FocusIn>', on_entry_click)
HoursFrom.pack(ipadx=25, side=LEFT, padx=5)
MinTo = Entry(EstimatedFrame, fg='grey')
MinTo.insert(0, "Min: 15 / To: 9:30")
MinTo.bind('<FocusIn>', on_entry_click)
MinTo.pack(ipadx=25, side=RIGHT, padx=5)
# Here the user will type the date of the event
DateFrame = Frame(AddActivity)
DateFrame.pack(side='top', ipady=5, fill=X, padx=10)
Day = Entry(DateFrame, fg='grey')
Day.insert(0, "DD")
Day.bind('<FocusIn>', on_entry_click)
Day.pack(ipadx=25, side=LEFT, padx=5)
Month = Entry(DateFrame, fg='grey')
Month.insert(0, "MM")
Month.bind('<FocusIn>', on_entry_click)
Month.pack(ipadx=25, side=LEFT, padx=5)
Year = Entry(DateFrame, fg='grey')
Year.insert(0, "YYYY")
Year.bind('<FocusIn>', on_entry_click)
Year.pack(ipadx=25, side=LEFT, padx=5)
# Here the user will say in wich days the activity should be done
FrequencyFrame = Frame(AddActivity)
FrequencyFrame.pack(side='top', ipady=5, fill=X)
Sun = IntVar()
Mon = IntVar()
Tue = IntVar()
Wed = IntVar()
Thu = IntVar()
Fri = IntVar()
Sat = IntVar()
Checkbutton(FrequencyFrame, text='Sunday', variable=Sun).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Monday', variable=Mon).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Tuesday', variable=Tue).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Wednesday', variable=Wed).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Thursday', variable=Thu).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Friday', variable=Fri).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Saturday', variable=Sat).pack(side=LEFT, padx=5)
# Here the user will determine how important is the activity for him
PriorityFrame = Frame(AddActivity)
PriorityFrame.pack(side='top', ipady=5, fill=X, padx=200)
Importance = IntVar()
Radiobutton(PriorityFrame, text='1', variable=Importance, value=1).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='2', variable=Importance, value=2).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='3', variable=Importance, value=3).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='4', variable=Importance, value=4).pack(side=LEFT, padx=5)
# This frame contains two buttons
LastFrame_AddActivity = Frame(AddActivity)
LastFrame_AddActivity.pack(side='top', fill=X)
Back_AddActivity = Button(LastFrame_AddActivity, text='Back', command=back).pack(side=LEFT, ipadx=20)
Insert_AddActivity = Button(LastFrame_AddActivity, text='Insert', command=insert).pack(side=RIGHT, ipadx=20)
########################################################################################################################
# AddCategory Frame
NameFrame = Frame(AddCategory)
PriorityFrame = Frame(AddCategory)
LastFrame_AddCategory = Frame(AddCategory)
NameFrame.pack(side='top', fill=X, ipady=5)
PriorityFrame.pack(side='top', ipady=5, fill=X, padx=200)
LastFrame_AddCategory.pack(side='top', fill=X)
NameLabel = Label(NameFrame, text='Name: ')
NameLabel.pack(side=LEFT)
name = Entry(NameFrame, fg='grey')
name.insert(0, "Enter the name of your event ...", )
name.bind('<FocusIn>', on_entry_click)
name.pack(ipadx=25, side=LEFT)
Importance = IntVar()
Radiobutton(PriorityFrame, text='1', variable=Importance, value=1).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='2', variable=Importance, value=2).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='3', variable=Importance, value=3).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='4', variable=Importance, value=4).pack(side=LEFT, padx=5)
def back():
raise_frame(Home)
def insert():
insert_category(name.get(), Importance.get())
raise_frame(Home)
Insert_AddCategory = Button(LastFrame_AddCategory, text='Back', command=insert).pack(side=LEFT, ipadx=20)
Back_AddCategory = Button(LastFrame_AddCategory, text='Back', command=back).pack(side=LEFT, ipadx=20)
########################################################################################################################
# EditActivity Frame
LastFrame = Frame(EditActivity)
LastFrame.pack(side='top', fill=X)
Back_EditActivity = Button(LastFrame, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Here you should let the user edit his/her activities
# Functions you will use: edit, done, delete, del_done, strainer
########################################################################################################################
# EditCategory Frame
LastFrame = Frame(EditCategory)
LastFrame.pack(side='top', fill=X)
Back_EditCategory = Button(LastFrame, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Here you should let the user edit his/her categories
# Functions you will use: edit, delete, strainer
########################################################################################################################
# Calendar Frame
LastFrame = Frame(Calendar)
LastFrame.pack(side='top', fill=X)
Back_Calendar = Button(LastFrame, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Here the user should see all of his events
# Functions you will use: strainer, done
########################################################################################################################
# Todo Frame
LastFrame_Todo = Frame(Todo)
LastFrame_Todo.pack(side='top', fill=X)
Back_Todo = Button(LastFrame_Todo, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Here the user should see all of his Todo
# Functions you will use: strainer, done
########################################################################################################################
# Today Frame
LastFrame_Today = Frame(Today)
LastFrame_Today.pack(side='top', fill=X)
Back_Today = Button(LastFrame_Today, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Functions you will use: strainer, organize(propabily you will need to make an extra db for this)
########################################################################################################################
# Now Frame
LastFrame_Now = Frame(Now)
LastFrame_Now.pack(side='top', fill=X)
Back_Now = Button(LastFrame_Now, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Functions you will use: strainer(propabily you will need to make an extra db for this)
raise_frame(Home)
root.mainloop()
<file_sep>/edit_activity.py
from home_frame import *
def delete_something(string):
delete(string)
back()
print(string)
def build_activity_frame():
EditActivityFrame = Frame(EditActivity)
EditActivityFrame.pack(side='top', fill=X)
Label(EditActivityFrame,text="Enter the name of the activity you want to edit").pack(side=LEFT)
name_of_edited_actvity=Entry(EditActivityFrame)
name_of_edited_actvity.pack(side=LEFT)
Label(EditActivityFrame,text='Change its name into(optional if deleting):').pack(side=LEFT)
change_to=Entry(EditActivityFrame)
change_to.pack(side=LEFT)
def change(frm,to):
edit_anything(frm,'name',to)
back()
Button(EditActivityFrame,text='Change',command=lambda :change(name_of_edited_actvity.get(),change_to.get())).pack(side=RIGHT)
Back_EditActivity = Button(EditActivityFrame, text='Back', command=back).pack(side=RIGHT)
Button(EditActivityFrame,text='Delete',command=delete_something(name_of_edited_actvity.get())).pack(side=RIGHT)<file_sep>/GUI.py
from today_frame import *
########################################################################################################################
# Home Frame
build_home_frame()
########################################################################################################################
# AddActivity Frame
# The layout is divided in many frames
def on_entry_click(event):
"""
when any entry widget is clicked, this code comes to action.
This deletes what was written in the entry widget and makes the font-colour black
"""
global FirstClick
entry = event.widget
if FirstClick:
FirstClick = False
entry.config(fg='black')
entry.delete(0, "end")
FirstClick = True
return
def back():
"""
is called when the BackButton is clicked.
It gets the user back to home
"""
raise_frame(Home)
def insert():
"""
This saves the data of the user and brings him back to home
"""
list_of_days = [Mon.get(), Tue.get(), Wed.get(), Thu.get(), Fri.get(), Sat.get(), Sun.get()]
number_of_day = 0
list_of_calendar_day_names = calendar.day_name
frequency = []
for day in list_of_days:
if day == 1:
frequency.append(list_of_calendar_day_names[number_of_day])
number_of_day += 1
date_of_activity = "{}/{}/{}".format(Day.get(), Month.get(), Year.get())
if event.get() == 'Todo':
insert_todo(NameOfActivity.get(), Category.get(), HoursFrom.get(), MinTo.get(), date_of_activity,
Importance.get(), frequency)
else:
insert_event(NameOfActivity.get(), Category.get(), HoursFrom.get(), MinTo.get(), date_of_activity, Importance.get(),
frequency)
raise_frame(Home)
# The first frame contains the name of the event the user will write
NameFrame = Frame(AddActivity)
NameFrame.pack(side='top', fill=X, ipady=5)
NameLabel = Label(NameFrame, text='Name: ')
NameLabel.pack(side=LEFT)
FirstClick = True
NameOfActivity = Entry(NameFrame, fg='grey')
NameOfActivity.insert(0, "Enter the name of your event ...", )
NameOfActivity.bind('<FocusIn>', on_entry_click)
NameOfActivity.pack(ipadx=25, side=LEFT)
# This frame includes a DropDownMenu which gets all of the categories in the database
CategoryFrame = Frame(AddActivity)
CategoryFrame.pack(side='top', ipady=5, fill=X)
category_names = []
category_name = strainer('name', 'sort', 'category')
number = 0
for loop in range(0, len(category_name)):
category_names.append(category_name[number][0])
number += 1
Category = StringVar(CategoryFrame)
Category.set('None')
option = OptionMenu(CategoryFrame, Category, *category_names)
option.pack(fill=X, pady=5)
event = StringVar(CategoryFrame)
event.set('Todo')
category = OptionMenu(CategoryFrame, event, "Todo", 'Event')
category.pack(fill=X, pady=5)
# This Frame contains two entry widgets, where the user will write the from and to time, aka hours and min
EstimatedFrame = Frame(AddActivity)
EstimatedFrame.pack(side='top', ipady=5, fill=X)
HoursFrom = Entry(EstimatedFrame, fg='grey')
HoursFrom.insert(0, "Hours: 2 OR From: 7:30", )
HoursFrom.bind('<FocusIn>', on_entry_click)
HoursFrom.pack(ipadx=25, side=LEFT, padx=5)
MinTo = Entry(EstimatedFrame, fg='grey')
MinTo.insert(0, "Min: 15 OR To: 9:30")
MinTo.bind('<FocusIn>', on_entry_click)
MinTo.pack(ipadx=25, side=RIGHT, padx=5)
# Here the user will type the date of the event
DateFrame = Frame(AddActivity)
DateFrame.pack(side='top', ipady=5, fill=X, padx=10)
Day = Entry(DateFrame, fg='grey')
Day.insert(0, "DD")
Day.bind('<FocusIn>', on_entry_click)
Day.pack(ipadx=25, side=LEFT, padx=5)
Month = Entry(DateFrame, fg='grey')
Month.insert(0, "MM")
Month.bind('<FocusIn>', on_entry_click)
Month.pack(ipadx=25, side=LEFT, padx=5)
Year = Entry(DateFrame, fg='grey')
Year.insert(0, "YYYY")
Year.bind('<FocusIn>', on_entry_click)
Year.pack(ipadx=25, side=LEFT, padx=5)
# Here the user will say in wich days the activity should be done
FrequencyFrame = Frame(AddActivity)
FrequencyFrame.pack(side='top', ipady=5, fill=X)
Sun = IntVar()
Mon = IntVar()
Tue = IntVar()
Wed = IntVar()
Thu = IntVar()
Fri = IntVar()
Sat = IntVar()
Checkbutton(FrequencyFrame, text='Sunday', variable=Sun).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Monday', variable=Mon).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Tuesday', variable=Tue).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Wednesday', variable=Wed).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Thursday', variable=Thu).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Friday', variable=Fri).pack(side=LEFT, padx=5)
Checkbutton(FrequencyFrame, text='Saturday', variable=Sat).pack(side=LEFT, padx=5)
# Here the user will determine how important is the activity for him
PriorityFrame = Frame(AddActivity)
PriorityFrame.pack(side='top', ipady=5, fill=X, padx=200)
Importance = IntVar()
Radiobutton(PriorityFrame, text='1', variable=Importance, value=1).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='2', variable=Importance, value=2).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='3', variable=Importance, value=3).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='4', variable=Importance, value=4).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='5', variable=Importance, value=5).pack(side=LEFT, padx=5)
# This frame contains two buttons
LastFrame_AddActivity = Frame(AddActivity)
LastFrame_AddActivity.pack(side='top', fill=X)
Back_AddActivity = Button(LastFrame_AddActivity, text='Back', command=back).pack(side=LEFT, ipadx=20)
Insert_AddActivity = Button(LastFrame_AddActivity, text='Insert', command=insert).pack(side=RIGHT, ipadx=20)
########################################################################################################################
# AddCategory Frame
NameFrame = Frame(AddCategory)
PriorityFrame = Frame(AddCategory)
LastFrame_AddCategory = Frame(AddCategory)
NameFrame.pack(side='top', fill=X, ipady=5)
PriorityFrame.pack(side='top', ipady=5, fill=X, padx=200)
LastFrame_AddCategory.pack(side='top', fill=X)
NameLabel = Label(NameFrame, text='Name: ')
NameLabel.pack(side=LEFT)
event_name = Entry(NameFrame, fg='grey')
event_name.insert(0, "Enter the name of your event ...", )
event_name.bind('<FocusIn>', on_entry_click)
event_name.pack(ipadx=25, side=LEFT)
Importance = IntVar()
Label(PriorityFrame,text='What is its priority? 1-Best').pack(side=LEFT)
Radiobutton(PriorityFrame, text='1', variable=Importance, value=1).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='2', variable=Importance, value=2).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='3', variable=Importance, value=3).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='4', variable=Importance, value=4).pack(side=LEFT, padx=5)
Radiobutton(PriorityFrame, text='5', variable=Importance, value=5).pack(side=LEFT, padx=5)
def back():
raise_frame(Home)
def insert():
insert_category(event_name.get(), Importance.get())
raise_frame(Home)
Insert_AddCategory = Button(LastFrame_AddCategory, text='Insert', command=insert).pack(side=LEFT, ipadx=20)
Back_AddCategory = Button(LastFrame_AddCategory, text='Back', command=back).pack(side=LEFT, ipadx=20)
########################################################################################################################
# EditActivity Frame todo
build_activity_frame()
# Functions you will use: edit, done, delete, del_done, strainer
# EditCategory Frame
build_edit_category_frame()
# Calendar Frame todo
LastFrame = Frame(Calendar)
LastFrame.pack(side='top', fill=X)
Back_Calendar = Button(LastFrame, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Here the user should see all of his events
# Functions you will use: strainer, done
########################################################################################################################
#To_do frame
build_todo_frame()
########################################################################################################################
# Today Frame
build_today_frame()
# Functions you will use: strainer, organize(propabily you will need to make an extra db for this)
########################################################################################################################
# Now Frame todo
LastFrame_Now = Frame(Now)
LastFrame_Now.pack(side='top', fill=X)
Back_Now = Button(LastFrame_Now, text='Back', command=back).pack(side=LEFT, ipadx=20)
# Functions you will use: strainer(propabily you will need to make an extra db for this)
raise_frame(Home)
root.mainloop()
<file_sep>/todo_frame.py
from edit_activity import *
def build_todo_frame():
right_todoframe = Frame(Todo,width = 320,height = 350)
right_todoframe.grid(row = 0)
left_todoframe = Frame(Todo,width = 320,height = 350)
left_todoframe.grid(row = 0,column = 1)
Back_Todo = Button(right_todoframe, text='Back', command=back)
Back_Todo.place(relx = .04,rely = .9)
todo_listM = strainer('name', 'sort','event')
todo_list_timefrmM = strainer('frm', 'sort','event')
todo_list_timetoM = strainer('till', 'sort','event')
print(todo_list_timefrmM)
xv1 = .2
yv1 = .1
for i in range(len(todo_listM)):
todo_listM[i] = Checkbutton(right_todoframe,text = todo_listM[i])
todo_listM[i].place(relx = xv1,rely = yv1)
todo_list_timefrmM[i] = Label(left_todoframe,text = todo_list_timefrmM[i])
todo_list_timefrmM[i].place(relx=xv1, rely=yv1)
labelmark = Label(left_todoframe,text = ".")
labelmark.place(relx=xv1+.05, rely=yv1)
todo_list_timetoM[i] = Label(left_todoframe, text=todo_list_timetoM[i])
todo_list_timetoM[i].place(relx=xv1+.08, rely=yv1)
if todo_listM[i].config(state = "active"):
done(todo_listM[i])
yv1 += .1
<file_sep>/today_frame.py
from edit_category import*
def build_today_frame():
right_todayframe = Frame(Today, width=320, height=350)
right_todayframe.grid(row=0)
left_todayframe = Frame(Today, width=320, height=350)
left_todayframe.grid(row=0, column=1)
Back_Today = Button(right_todayframe, text='Back', command=back)
Back_Today.place(relx=.04, rely=.9)
# events_list = strainer("","event","sort")
search_box1 = Entry(right_todayframe, width=40)
search_box1.insert(0, "Search")
search_box1.place(relx=.05, rely=.05)
search_button1 = Button(right_todayframe, text="Search")
search_button1.place(relx=.83, rely=.048)
seached_item = search_box1.get()
# today_listM = strainer('name','sort','event')
# today_listM.extend(strainer('name','sort','todo'))
today_listM = organizeM()
today_list_timefrmM = strainer('frm', 'sort', 'event')
today_list_timetoM = strainer('till', 'sort', 'event')
xv2 = .05
yv2 = .15
for i in range(len(today_listM)):
today_listM[i] = Checkbutton(right_todayframe, text=str(today_listM[i])[2:(len(str(today_listM[i])) - 3)])
today_listM[i].place(relx=xv2, rely=yv2)
yv2 += .1
for i in range(len(today_list_timefrmM)):
if today_list_timefrmM[i] in today_list_timetoM or today_list_timefrmM[i] > today_list_timetoM[i]:
popup1 = Frame(Home)
label1 = Label(popup1, text="you have two events at the same time. please select one of them to have")
raise_frame(popup1)
# sbar = Scrollbar(right_todayframe).pack(side = LEFT,fill = Y)
# sbaror = Listbox(right_todayframe,yscrollcommand = sbar.set)
def do_search(event):
if seached_item in today_listM:
seached_item_widget = Checkbutton(right_todayframe, text=seached_item)
seached_item_widget.place(relx=xv2, rely=yv2)
else:
seached_item_widget = Label(right_todayframe, text="Nothing found")
seached_item_widget.place(relx=.15, rely=.15)
search_button1.bind("<Button-1>", do_search)<file_sep>/edit_category.py
from todo_frame import *
def build_edit_category_frame():
LastFrame = Frame(EditCategory)
LastFrame.pack(side='top', fill=X)
category_names = []
category_name = strainer('name', 'sort', 'category')
number = 0
for x in range(0, len(category_name)):
category_names.append(category_name[number][0])
number += 1
Category_1 = StringVar(LastFrame)
option = OptionMenu(LastFrame, Category_1, *category_names)
option.pack(fill=X, pady=5)
def option_changed():
deleted_or_edited = Category_1.get()
return deleted_or_edited
Back_EditCategory = Button(LastFrame, text='Back', command=back).pack(side=LEFT, ipadx=20)
Insert_EditCategory = Button(LastFrame, text='Delete', command=lambda: delete_something(option_changed()))
Insert_EditCategory.pack(side=LEFT, ipadx=20)<file_sep>/home_frame.py
from tkinter import *
from Algorithm import *
import calendar
create_table()
def back():
raise_frame(Home)
def raise_frame(parent):
parent.tkraise()
root = Tk()
Home = Frame(root)
AddActivity = Frame(root)
AddCategory = Frame(root)
EditActivity = Frame(root)
EditCategory = Frame(root)
Calendar = Frame(root)
Todo = Frame(root)
Today = Frame(root)
Now = Frame(root)
for frame in (Home, AddActivity, AddCategory, EditActivity, EditCategory, Calendar, Todo, Today, Now):
frame.grid(row=0, column=0, sticky='news')
def build_home_frame():
def destroy_pop_up(parent,pop_up):
raise_frame(parent)
pop_up.destroy()
class Edit:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Edit").pack()
Label(top, text='What do you want to edit?')
cate = Button(top, text="Category", command=lambda: destroy_pop_up(EditCategory,top))
cate.pack(pady=5, padx=5, side=LEFT)
activity = Button(top, text="Activity", command=lambda: destroy_pop_up(EditActivity,top))
activity.pack(pady=5, padx=5, side=LEFT)
def edit():
ed = Edit(Home)
Home.wait_window(ed.top)
class Add:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Add").pack()
Label(top, text='What do you want to add?')
cat = Button(top, text="Category", command=lambda: destroy_pop_up(AddCategory,top))
cat.pack(pady=5, padx=5, side=LEFT)
act = Button(top, text="Activity", command=lambda: destroy_pop_up(AddActivity,top))
act.pack(pady=5, padx=5, side=LEFT)
def add():
ad = Add(Home)
Home.wait_window(ad.top)
TopFrame = Frame(Home)
MiddleFrame = Frame(Home, padx=200)
BottomFrame = Frame(Home)
LastFrame_Home = Frame(Home)
TopFrame.pack(side='top', fill=X)
MiddleFrame.pack(side='top', ipady=5, fill=X)
BottomFrame.pack(side='top', ipady=5, fill=X)
LastFrame_Home.pack(side='top', ipady=5, fill=X)
HomeLabel = Label(TopFrame, text='Home')
HomeLabel.pack(side=LEFT)
AddButton = Button(TopFrame, text='Add', command=add)
AddButton.pack(side=RIGHT)
CalendarButton = Button(MiddleFrame, text='Calendar', command=lambda: raise_frame(Calendar))
CalendarButton.pack(padx=5, pady=10, side=LEFT)
TodoButton = Button(MiddleFrame, text='Todo', command=lambda: raise_frame(Todo))
TodoButton.pack(padx=5, pady=10, side=LEFT)
TodayButton = Button(MiddleFrame, text='Today', command=lambda: raise_frame(Today))
TodayButton.pack(padx=5, pady=10, side=LEFT)
NowButton = Button(MiddleFrame, text='Now', command=lambda: raise_frame(Now))
NowButton.pack(padx=5, pady=10, side=LEFT)
category_name = strainer('name', 'sort', 'category')
number = 0
# if category_name[number][0]
for i in range(0, len(category_name)):
if number == 10:
break
CategoryButton = Button(BottomFrame, text='{}'.format(category_name[number][0]), width=5, anchor="w")
CategoryButton.pack(padx=5, pady=5, fill=X)
number += 1
EditButton = Button(LastFrame_Home, text='Edit', command=edit)
EditButton.pack()
<file_sep>/Algorithm.py
from datetime import *
import sqlite3
# This is our connection to the database
conn = sqlite3.connect('activities.db')
# This is the cursor. Using it we can add, delete or update information in the database
c = conn.cursor()
def create_table():
"""
This function creates a table with some columns that will be used later
"""
c.execute('CREATE TABLE IF NOT EXISTS activities(name TEXT, sort TEXT, category TEXT, estimated_time_hours REAL, '
'estimated_time_min REAL, '
'ratio REAL, date_now TEXT, date TEXT, frm TEXT, till TEXT, priority REAL, status TEXT, score TEXT, '
'frequency TEXT, Sunday TEXT, Monday TEXT, Tuesday TEXT, Wednesday TEXT, Thursday TEXT, Friday TEXT, '
'Saturday TEXT)')
data = strainer("", 'sort', 'category')
if data == []:
insert_category('None', 3)
def insert_todo(name, category, estimated_time_hours, estimated_time_min, day_when, priority, frequency):
# date: Time when the user has made this activity. It'll work later as an id for the activity
now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# score: Score of the activity. If the score is smaller, the activity is more important
# c.execute("SELECT priority FROM activities WHERE name=(?)"), [category]
category_int = strainer('priority', 'name', category)
score = int(len(frequency) + priority + category_int[0][0])
# The next code will be adding the information to the database
# First we tell the database in which table to put the info(here activities)
# After that we tell him which variables we will be writing
# Lastly we give him the variable
c.execute("INSERT INTO activities (name, sort, category, estimated_time_hours, estimated_time_min, date_now, date, "
"priority, score, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(name, 'todo', category, int(estimated_time_hours), int(estimated_time_min), now, day_when, priority,
score, 'undone'))
# Now we must commit the changes that happened in the database
conn.commit()
# The next bit of code will work at the frequency
# This is a list of all days in the week written in capital just like the one's in the database
list_of_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
# This for loop either puts in the column of the day a 1 if the activity will be done on that day. If not,
# the loop will ignore it
for i in list_of_days:
if i in frequency:
c.execute("UPDATE activities SET {} = 1 WHERE date_now=(?)".format(i), [now])
c.execute("UPDATE activities SET frequency='correct' WHERE date_now=(?)", [now])
# Now we must commit the changes that happened in the database
conn.commit()
def insert_event(name, category, frm, to, day_when, priority, frequency):
# root=Tk()
# frame=Frame(root)
# Label(frame,text="INSERTED").pack(side=LEFT)
# date: Time when the user has made this activity. It'll work later as an id for the activity
now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# score: Score of the activity. If the score is smaller, the activity is more important
# c.execute("SELECT priority FROM activities WHERE name=(?)"), [category]
category_int = strainer('priority', 'name', category)
score = len(frequency) + priority + category_int[0][0]
print("INSERT INTO activities (name, sort, category, frm, till, date_now, date, "
"priority, score, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(name, 'event', category, frm, to, now, day_when, priority,score, 'undone'))
# The next code will be adding the information to the database
# First we tell the database in which table to put the info(here activities)
# After that we tell him which variables we will be writing
# Lastly we give him the variable
c.execute("INSERT INTO activities (name, sort, category, frm, till, date_now, date, "
"priority, score, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(name, 'event', category, frm, to, now, day_when, priority,score, 'undone'))
# Now we must commit the changes that happened in the database
conn.commit()
# The next bit of code will work at the frequency
# This is a list of all days in the week written in capital just like the one's in the database
list_of_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
# This for loop either puts in the column of the day a 1 if the activity will be done on that day. If not,
# the loop will ignore it
for i in list_of_days:
if i in frequency:
c.execute("UPDATE activities SET {} = 1 WHERE date_now=(?)".format(i), [now])
c.execute("UPDATE activities SET frequency='correct' WHERE date_now=(?)", [now])
# Now we must commit the changes that happened in the database
conn.commit()
def insert_category(name, priority):
# The next code will be adding the information to the database
# First we tell the database in which table to put the info(here activities)
# After that we tell him which variables we will be writing
# Lastly we give him the variable
c.execute("INSERT INTO activities (name, sort, ratio, priority) VALUES (?, ?, ?, ?)",
(name, 'category', 1, priority))
# Now we must commit the changes that happened in the database
conn.commit()
def edit_anything(name, what, to):
"""
Using this function, the user can edit anything he wants in the activity
:param name: name of the activity
:param what: what the user wants to change in the activity
:param to: what that column should be
"""
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write UPDATE.
# WHERE determines which activity the user wants to change
c.execute("UPDATE activities SET {} = (?) WHERE name=(?)".format(what), [to, name])
# Now we must commit the changes that happend in the database
conn.commit()
def done(name):
"""
This function marks an activity as done
:param name: name of the activity
"""
# This here works just like the updating function
c.execute("UPDATE activities SET status = 'done' WHERE name=(?)", [name])
conn.commit()
def delete(name):
"""
This function deletes an activity from the database
:param name: name of the activity
"""
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write DELETE FROM.
# WHERE determines which activity the user wants to change
c.execute("DELETE FROM activities WHERE name = (?)", [name])
# Now we must commit the changes that happened in the database
conn.commit()
def del_done():
"""
This function deletes all of the done activities which don't repeat every now and then
"""
# This function works just like the deleting function
c.execute("DELETE FROM activities WHERE status = 'done' AND Frequency != 'correct'")
conn.commit()
def strainer(select, strain, equals):
"""
This function works as a strainer. Using it you can get something specific from the database
:param select: Do you want to get all of the columns or only specific ones?
:param strain: What should all things you want to see have in common?
:param equals: What should it be equal to?
:return a list of what the user wants to see
"""
# This selects everything if the user didn't enter something for select
if select == "":
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write DELETE FROM.
# WHERE determines which activity the user wants to change
c.execute("SELECT * FROM activities WHERE {}=(?)".format(strain), [equals])
return c.fetchall()
else:
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write DELETE FROM.
# WHERE determines which activity the user wants to change
c.execute("SELECT {} FROM activities WHERE {}=(?)".format(select.upper(), strain), [equals])
return c.fetchall()
def organize(select, strain, equals):
"""
This function returns a list of numbers. These numbers are the numbers of scores in a specific order. The first
element is the most important one
:parameters all of these parameters are used to get the scores of specific activities in the table!
"""
scores = []
data = list(strainer(select, strain, equals))
while len(data) != 0:
number = lowest_number(data)
scores.append(number)
data.remove(number)
return scores
def lowest_number(list_int):
"""
This function uses recursion to find the lowest number of a list
:param list_int: list of int
:return: smallest number
"""
if len(list_int) == 1:
return list_int[0]
number = lowest_number(list_int[1:])
if list_int[0] < number:
return list_int[0]
else:
return number
def no_category():
if len(strainer('', 'sort', 'category')) == 0:
return False
else:
return True
def organizeM():
"""
This function returns a list of numbers. These numbers are the numbers of scores in a specific order. The first
element is the most important one
:parameters all of these parameters are used to get the scores of specific activities in the table!
"""
scores = []
today_listM = strainer('name', 'sort', 'event')
today_listM.extend(strainer('name', 'sort', 'todo'))
data = list(today_listM)
while len(data) != 0:
number = lowest_number(data)
scores.append(number)
data.remove(number)
return scores<file_sep>/README.md
# Protons-Final-Project | c5e3f74fa81003b723870f7d392b3e7c3a4be731 | [
"Markdown",
"Python"
] | 9 | Python | Hanoo2002/Protons-Final-Project-master | 66f5c0ecf56d32a362814af867da30be7def3b54 | 5c1383ac5bcbbad2422ad9a673cb22bdd145b6dd |
refs/heads/master | <repo_name>oswalde-p/parking-booking<file_sep>/readme.md
The API allows users to create accounts, find available spaces near
a chosen location, book spaces, and view and cancel existing bookings
To start the app, run:
node app.js
The app will then be listening on port 3000
An internet connection is required to access the mongodb
# Example calls:
create a user:
POST: localhost:3000/users/addUser {"email": "<EMAIL>", "password":"<PASSWORD>"}
add a parking space
POST: localhost:3000/slots/addSlot {"lat": -37.806, "long": 144.960, "description": "Behind Aldi supermarket", "isOccupied":false}
find available spaces
GET: localhost:3000/slots/findSlots?lat=-37.810&long=144.95&within=6&isFree=true
create a booking
POST: localhost:3000/bookings/create {"userId": "<EMAIL>",
"parkingSpotId": "1",
"timeStart": "2018-09-10T15:45:00.000Z",
"timeEnd": "2018-09-10T16:00:00.000Z"}
find current bookings
GET: http://localhost:3000/bookings/findBookings?userId=<EMAIL>
GET: http://localhost:3000/bookings/findBookings?slotId=1
mark booking as paid
GET: http://localhost:3000/bookings/payBooking?bookingId=5b96739c2a821144f5b21d0f
cancel booking
GET: http://localhost:3000/bookings/cancelBooking?bookingId=5b967387a821144f5b21d0e
************************************
# NOTE:
Unfortunately due to a change in how bookings are handled mid-challenge, the search feature
does not currently take current bookings into account when returning results
All methods are insecure, any user could modify any other user's booking, etc
<file_sep>/routes/slots.js
var express = require('express');
var router = express.Router();
const dbController = require('../controllers/slots');
router.post('/addSlot', dbController.addSlot);
router.get('/findSlots', dbController.getSlots); // params: within (km), lat, long, free
module.exports = router;
<file_sep>/controllers/users.js
var mongoose = require('mongoose');
var User = mongoose.model('users');
module.exports.addUser = function(req, res){
console.log(req.body);
var user = new User(req.body);
User.count({email: req.body.email}, function (err, count){
if(count>0){
res.statusMessage = "User already exists";
res.sendStatus(400);
}else{
user.save(function(err, newUser){
if(!err){
res.send(newUser);
console.log("New user added: " + newUser.email);
}else{
res.sendStatus(404);
}
});
}
});
};
module.exports.authenticateUser = function(req, res) {
var email = req.body.email;
var password = <PASSWORD>;
if (email && password){
User.findOne({email: email}, function (err, user) {
if (!err) {
if(user && (user.password === req.body.<PASSWORD>)) { // do this more securely!
res.statusMessage = "Good user details";
res.sendStatus(200);
} else {
res.statusMessage = "Invalid user details";
res.sendStatus(200);
}
} else {
res.sendStatus(404);
}
})
}else{
res.sendStatus(400);
}
};
<file_sep>/routes/bookings.js
var express = require('express');
var router = express.Router();
const dbController = require('../controllers/bookings');
/* GET users listing. */
router.get('/findBookings', dbController.findBookings);
router.get('/cancelBooking', dbController.cancelBooking);
router.get('/payBooking', dbController.markPaid);
router.post('/create', dbController.createBooking);
module.exports = router;
| cf0fdf20ea52029d5ea3fd8b7f2a4da034c65160 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | oswalde-p/parking-booking | c316115949f1921191f8c75d5f0c73ac17809081 | 39aa1ed8f8365fb837b8e4eb1bf0ae81ca25ed6d |
refs/heads/main | <repo_name>tamirisrgarcia/Imersao-DEV<file_sep>/README.md
# IMERSÃO DEV - ALURA 2021
Olá, tudo bem?
Este repositório foi criado para disponibilizar os trabalhos realizados durante a Imersão DEV - Alura.
Os projetos foram desenvolvidos no Codepen e as tecnologias utilizadas foram:
- HTML
- CSS
- JavaScript

#### Desafio 1:
##### Calculadora de Média:
Calculadora elaborada para verificar se o estudante foi aprovado ou não no ano letivo. Solicita-se as quatro notas das provas realizadas e é calculado a média das mesmas. Caso o aluno consiga média superior a 70%, o computador emite a mensagem de que ele foi aprovado.
##### Conversor de Temperatura:
Permite converter a temperatura de graus Celsius para Fahrenheit e vice-versa.
#### Desafio 2:
##### Conversor de Moedas:
Permite converter o valor em Real (R$) para Dólar ou Euro, considerando os valores referentes ao dia 14 de setembro de 2021.
#### Desafio 3:
##### O Mentalista:
Solicita que o participante escolha um número entre 0 e 10 e, caso acerte, o computador emitirá uma mensagem de acerto.
<file_sep>/Calculadora de Media e Temperatura/CalculadoraMediaTemperatura.js
function media(){
let nome = document.querySelector('#nome').value;
let primeiraNota = Number(document.querySelector('#primeiraNota').value);
let segundaNota = Number(document.querySelector('#segundaNota').value);
let terceiraNota = Number(document.querySelector('#terceiraNota').value);
let quartaNota = Number(document.querySelector('#quartaNota').value);
let notaFinal = (primeiraNota+segundaNota+terceiraNota+quartaNota)/4;
let nota = notaFinal.toFixed(1);
if (nota < 7) {
document.querySelector('.result').innerHTML = `Olá, ${nome}. Sua média final foi de: ${nota}. Infelizmente você não atingiu a média mínima para aprovação. Continue estudando!`
} else {
document.querySelector('.result').innerHTML = `Olá, ${nome}. Sua média final foi de: ${nota}. Parabéns, você foi aprovado!`
}
}
function convertF(){
var tempF= document.getElementById("grauf").value;
if(tempF.length === 0){
document.getElementById("grauc").value = undefined;
return;
}
var tempC = (Number(tempF) - 32) / 1.8;
document.getElementById("grauc").value = tempC
}
function convertC(){
var tempC= document.getElementById("grauc").value;
if(tempC.length === 0){
document.getElementById("grauf").value = undefined;
return;
}
var tempF = Number(tempC) * 1.8 + 32;
document.getElementById("grauf").value = tempF;
} | 79dbcd1569c773ec02779b74ce8dddc14ad90efc | [
"Markdown",
"JavaScript"
] | 2 | Markdown | tamirisrgarcia/Imersao-DEV | 035ca5c4b06b8655a07f16bf93fc2afc0820756a | 67cdf94a8e10fd33a4c561eface149db81d83b34 |
refs/heads/master | <repo_name>mana-sys/adhesive<file_sep>/pkg/packager/packager.go
// Package packager provides a mechanism for packaging CloudFormation templates
// and exporting the resultant artifacts to S3. The functionality of this
// package is similar to that of the "aws cloudformation package" command.
package packager
import (
"errors"
"io"
"net/http"
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/awslabs/goformation/v4"
"github.com/awslabs/goformation/v4/cloudformation"
"github.com/mholt/archiver/v3"
)
type Format bool
const (
FormatJSON Format = false
FormatYAML Format = true
)
var (
ErrUnknownFormat = errors.New("unknown format")
)
func isZipFile(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
var buf [512]byte
if _, err := io.ReadFull(f, buf[:]); err != nil {
return false, nil
}
return http.DetectContentType(buf[:]) == "application/zip", nil
}
type Packager struct {
Format Format
KMSKeyID string
S3Bucket string
S3Prefix string
artifacts map[string]string
exportedResources ExportedResources
svc s3iface.S3API
}
func New(cfgs ...*aws.Config) (*Packager, error) {
sess, err := session.NewSession(cfgs...)
if err != nil {
return nil, err
}
return &Packager{
svc: s3.New(sess),
exportedResources: defaultExportedResources,
}, nil
}
func NewFromS3(svc s3iface.S3API) *Packager {
return &Packager{
Format: FormatYAML,
exportedResources: defaultExportedResources,
svc: svc,
}
}
func (p *Packager) PackageTemplateFile(name string) ([]byte, error) {
template, err := goformation.Open(name)
if err != nil {
return nil, err
}
if err := p.exportTemplateArtifacts(template); err != nil {
return nil, err
}
return p.marshalTemplate(template)
}
func tempZipFile(sources []string, dir, pattern string) (string, error) {
name, err := tempName(dir, pattern+"*.zip")
if err != nil {
return "", nil
}
if err := archiver.Archive(sources, name); err != nil {
return "", err
}
return name, nil
}
// exportTemplateArtifacts exports the template's artifacts by uploading them
// to S3.
func (p *Packager) exportTemplateArtifacts(template *cloudformation.Template) error {
p.artifacts = make(map[string]string)
for _, resource := range template.Resources {
for _, exportedResource := range p.exportedResources {
untyped, ok := exportedResource.GetProperty(resource)
if !ok {
continue
}
switch path := untyped.(type) {
case string:
// Skip if the path is an S3 path.
if strings.HasPrefix(path, "s3://") {
continue
}
// Upload the file.
remotePath, err := p.ProcessAndUpload(path, exportedResource.ForceZip)
if err != nil {
return err
}
// Replace the original path with the new remote path.
exportedResource.ReplaceProperty(resource, remotePath)
p.artifacts[path] = remotePath
default:
return errors.New("invalid property type")
}
}
}
return nil
}
func (p *Packager) marshalTemplate(template *cloudformation.Template) ([]byte, error) {
if p.Format == FormatJSON {
return template.JSON()
} else {
return template.YAML()
}
}
func (p *Packager) Artifacts() map[string]string {
return p.artifacts
}
<file_sep>/internal/cli/config/config.go
package config
import "github.com/BurntSushi/toml"
type DeployOptions struct {
Guided bool `toml:"-"`
NoConfirmChangeSet bool `toml:"no-confirm-change-set"`
NoExecuteChangeSet bool `toml:"no-execute-change-set"`
StackName string `toml:"stack-name"`
TemplateFile string `toml:"template-file"`
}
type LocalOptions struct {
}
type PackageOptions struct {
TemplateFile string `toml:"template-file"`
S3Bucket string `toml:"s3-bucket"`
S3Prefix string `toml:"s3-prefix"`
KmsKeyID string `toml:"kms-key-id"`
OutputTemplateFile string `toml:"output-template-file"`
UseJSON bool `toml:"use-json"`
ForceUpload bool `toml:"force-upload"`
}
type HistoryServerOptions struct {
Port int
LogDirectory string `toml:"log-directory"`
}
type RemoveOptions struct {
StackName string `toml:"stack-name"`
}
type StartJobRunOptions struct {
JobName string `toml:"job-name"`
JobRunID string `toml:"job-run-id"`
StackName string `toml:"stack-name"`
TailLogs bool `toml:"tail-logs"`
}
type Config struct {
Deploy DeployOptions
StartJobRun StartJobRunOptions `toml:"start-job-run"`
Local LocalOptions
Package PackageOptions
Remove RemoveOptions
HistoryServer HistoryServerOptions `toml:"history-server"`
// Root command options.
ConfigFile string `toml:"-"`
Profile string
Region string
Debug bool `toml:"-"`
}
func defaultConfig() *Config {
return &Config{
Region: "us-west-2",
}
}
func NewConfig() *Config {
return defaultConfig()
}
func (conf *Config) MergeConfig(other *Config) {
// Merge root command options.
if other.ConfigFile != "" {
conf.ConfigFile = other.ConfigFile
}
if other.Profile != "" {
conf.Profile = other.Profile
}
if other.Region != "" {
conf.Region = other.Region
}
if other.Debug {
conf.Debug = other.Debug
}
// Merge "local" options.
conf.Local.mergeLocalOptions(&other.Local)
// Merge "package" options.
conf.Package.mergePackageOptions(&other.Package)
// Merge "remove" options.
conf.Remove.mergeRemoveOptions(&other.Remove)
// Merge "history-server" options.
conf.HistoryServer.mergeHistoryServerOptions(&other.HistoryServer)
// Merge "start-job-run" options.
conf.StartJobRun.mergeStartJobRunOptions(&other.StartJobRun)
// Merge "deploy" options.
conf.Deploy.mergeDeployOptions(&other.Deploy)
}
func (opts *LocalOptions) mergeLocalOptions(other *LocalOptions) {
}
func (opts *PackageOptions) mergePackageOptions(other *PackageOptions) {
if other.TemplateFile != "" {
opts.TemplateFile = other.TemplateFile
}
if other.KmsKeyID != "" {
opts.KmsKeyID = other.KmsKeyID
}
if other.OutputTemplateFile != "" {
opts.OutputTemplateFile = other.OutputTemplateFile
}
if other.S3Bucket != "" {
opts.S3Bucket = other.S3Bucket
}
if other.S3Prefix != "" {
opts.S3Prefix = other.S3Prefix
}
if other.UseJSON {
opts.UseJSON = other.UseJSON
}
if other.ForceUpload {
opts.ForceUpload = other.ForceUpload
}
}
func (opts *HistoryServerOptions) mergeHistoryServerOptions(other *HistoryServerOptions) {
if other.Port != 0 {
opts.Port = other.Port
}
if other.LogDirectory != "" {
opts.LogDirectory = other.LogDirectory
}
}
func (opts *RemoveOptions) mergeRemoveOptions(other *RemoveOptions) {
if other.StackName != "" {
opts.StackName = other.StackName
}
}
func (opts *StartJobRunOptions) mergeStartJobRunOptions(other *StartJobRunOptions) {
if other.JobName != "" {
opts.JobName = other.JobName
}
if other.StackName != "" {
opts.StackName = other.StackName
}
if other.JobRunID != "" {
opts.JobRunID = other.JobRunID
}
if other.TailLogs {
opts.TailLogs = other.TailLogs
}
}
func (opts *DeployOptions) mergeDeployOptions(other *DeployOptions) {
if other.StackName != "" {
opts.StackName = other.StackName
}
if other.TemplateFile != "" {
opts.TemplateFile = other.TemplateFile
}
if other.NoConfirmChangeSet {
opts.NoConfirmChangeSet = other.NoConfirmChangeSet
}
if other.Guided {
opts.Guided = other.Guided
}
if other.NoExecuteChangeSet {
opts.NoExecuteChangeSet = other.NoExecuteChangeSet
}
}
func LoadConfigFileInto(config *Config, path string) error {
_, err := toml.DecodeFile(path, &config)
return err
}
// LoadConfigFile reads configuration from the adhesive.toml file.
func LoadConfigFile(path string) (*Config, error) {
config := defaultConfig()
if _, err := toml.DecodeFile(path, &config); err != nil {
return nil, err
}
return config, nil
}
<file_sep>/internal/cli/command/local/pip.go
package local
import (
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/spf13/cobra"
)
func NewPipCommand(adhesiveCli *command.AdhesiveCli, opts *dockerOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "pip",
Short: "Install Python dependencies for local job runs",
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
return buildAndRunDockerCommand(adhesiveCli, "pip", opts, args)
},
}
return cmd
}
<file_sep>/configs/adhesive.toml
# The region in which all operations will take place.
region = "us-west-2"
# The AWS profile to use for authentication.
# profile = "dev"
# Default options for the "adhesive deploy" command.
[deploy]
# no-confirm-change-set = false
# no-execute-change-set = false
# The name of the CloudFormation stack being deployed to.
# stack-name = "my-stack"
# The path where your AWS CloudFormation template is located.
# template-file = "template.yml"
# Default options for the "adhesive local" command.
[local]
# Default options for the "adhesive package" command.
[package]
# The path where your AWS CloudFormation template is located.
# template-file = "template2.yml"
# The S3 bucket where artifacts will be uploaded.
# s3-bucket = "bucket"
# The prefix added to the names of the artifacts uploaded to the S3 bucket.
# s3-prefix = "prefix"
# The ID of the KMS key used to encrypt artifacts in the S3 bucket.
# kms-key-id = "<KEY>"
# The path to the file to which the packaged template will be written.
# output-template-file = "template-packaged.yml"
<file_sep>/pkg/opts/opts.go
package opts
import "strings"
func ParseKeyValueStringsMap(values []string) map[string]*string {
args := make(map[string]*string, len(values))
for _, value := range values {
parts := strings.SplitN(value, "=", 2)
if len(parts) == 2 {
args[parts[0]] = &parts[1]
} else {
args[parts[0]] = nil
}
}
return args
}
<file_sep>/internal/cli/command/cli.go
package command
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/service/glue"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/mana-sys/adhesive/internal/cli/config"
log "github.com/sirupsen/logrus"
)
// State represents the state of the Adhesive workflow.
type State struct {
workflow string
}
// Adhesive represents a running instance of the Adhesive application.
type AdhesiveCli struct {
State *State
Config *config.Config
FoundConfigFile bool
cfn *cloudformation.CloudFormation
s3 *s3.S3
glue *glue.Glue
sess *session.Session
}
func NewAdhesiveCli() *AdhesiveCli {
return &AdhesiveCli{}
}
func (cli *AdhesiveCli) ReloadConfigFile(path string) error {
var (
conf = config.NewConfig()
failFileNotFound = true
foundConfigFile bool
)
if path == "" {
path = "adhesive.toml"
failFileNotFound = false
}
// Try reading configuration from adhesive.toml.
err := config.LoadConfigFileInto(conf, path)
if pathErr, ok := err.(*os.PathError); ok && os.IsNotExist(pathErr) {
// If a configuration file was explicitly specified, then fail if it
// can't be read.
if failFileNotFound {
return err
}
log.Debugf("Unable to read default configuration file adhesive.toml. " +
"Continuing with defaults.")
} else if err != nil {
fmt.Println("Failing")
return err
} else {
foundConfigFile = true
}
cli.FoundConfigFile = foundConfigFile
cli.Config = conf
return nil
}
func (cli *AdhesiveCli) InitializeClients() error {
sess, err := session.NewSessionWithOptions(session.Options{
Config: aws.Config{
Logger: aws.LoggerFunc(func(args ...interface{}) {
log.Debug(args...)
}),
LogLevel: aws.LogLevel(aws.LogDebugWithHTTPBody),
Region: aws.String(cli.Config.Region),
},
Profile: cli.Config.Profile,
SharedConfigState: session.SharedConfigEnable,
})
if err != nil {
return err
}
cli.cfn = cloudformation.New(sess)
cli.s3 = s3.New(sess)
cli.glue = glue.New(sess)
cli.sess = sess
return nil
}
func (cli *AdhesiveCli) S3() *s3.S3 {
return cli.s3
}
func (cli *AdhesiveCli) CloudFormation() *cloudformation.CloudFormation {
return cli.cfn
}
func (cli *AdhesiveCli) Glue() *glue.Glue {
return cli.glue
}
func (cli *AdhesiveCli) Session() *session.Session {
return cli.sess
}
<file_sep>/internal/cli/cobra.go
package cli
import (
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/mana-sys/adhesive/internal/cli/command/deploy"
"github.com/mana-sys/adhesive/internal/cli/command/historyserver"
"github.com/mana-sys/adhesive/internal/cli/command/local"
package1 "github.com/mana-sys/adhesive/internal/cli/command/package"
"github.com/mana-sys/adhesive/internal/cli/command/remove"
"github.com/mana-sys/adhesive/internal/cli/command/startjobrun"
"github.com/mana-sys/adhesive/internal/cli/config"
"github.com/mana-sys/adhesive/internal/cli/version"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func NewRootCommand(adhesiveCli *command.AdhesiveCli) *cobra.Command {
var (
conf config.Config
configFile string
debug bool
)
cmd := &cobra.Command{
Use: "adhesive",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Load configuration from the specified configuration file, or
// adhesive.toml if no file was specified.
if err := adhesiveCli.ReloadConfigFile(configFile); err != nil {
return err
}
// Set debug mode.
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
// Merge configuration from flags.
adhesiveCli.Config.MergeConfig(&conf)
return nil
},
SilenceErrors: true,
SilenceUsage: true,
TraverseChildren: true,
Version: version.Version,
}
flags := cmd.Flags()
flags.BoolVarP(&debug, "debug", "d", false, "Enable debug mode")
flags.StringVar(&conf.Profile, "profile", "", "The profile to use")
flags.StringVar(&conf.Region, "region", "", "Region to execute in")
flags.StringVarP(&configFile, "config", "c", "",
"Path to Adhesive configuration file")
cmd.AddCommand(
deploy.NewDeployCommand(adhesiveCli, &conf.Deploy),
local.NewLocalCommand(adhesiveCli),
package1.NewPackageCommand(adhesiveCli, &conf.Package),
remove.NewRemoveCommand(adhesiveCli, &conf.Remove),
historyserver.NewHistoryServerCommand(adhesiveCli, &conf.HistoryServer),
startjobrun.NewStartJobRunCommand(adhesiveCli, &conf.StartJobRun),
)
cmd.SetVersionTemplate(version.Template)
return cmd
}
<file_sep>/internal/cli/command/startjobrun/cmd.go
package startjobrun
import (
"errors"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/glue"
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/mana-sys/adhesive/internal/cli/config"
"github.com/spf13/cobra"
)
func NewStartJobRunCommand(adhesiveCli *command.AdhesiveCli, opts *config.StartJobRunOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "start-job-run",
Short: "Remove the current deployment of your CloudFormation template.",
RunE: func(cmd *cobra.Command, args []string) error {
return startJobRun(adhesiveCli, opts)
},
}
flags := cmd.Flags()
flags.StringVar(&opts.StackName, "stack-name", "", "The name of the CloudFormation stack to remove")
flags.StringVar(&opts.JobName, "job-name", "", "The name of the Glue job to run. This can also be the logical resource ID.")
return cmd
}
func startJobRun(adhesiveCli *command.AdhesiveCli, opts *config.StartJobRunOptions) error {
if err := adhesiveCli.InitializeClients(); err != nil {
return err
}
glu := adhesiveCli.Glue()
cfn := adhesiveCli.CloudFormation()
name := opts.JobName
if name == "" {
return errors.New("option --job-name is required")
}
// If stack-name is specified, then interpret job-name as the logical resource ID
// of the job to be run.
if opts.StackName != "" {
out, err := cfn.DescribeStackResource(&cloudformation.DescribeStackResourceInput{
StackName: aws.String(opts.StackName),
LogicalResourceId: aws.String(opts.JobName),
})
if err != nil {
return err
}
if *out.StackResourceDetail.ResourceType != "AWS::Glue::Job" {
return errors.New(name + " is not of type AWS::Glue::Job")
}
name = *out.StackResourceDetail.PhysicalResourceId
}
// Start the job.
_, err := glu.StartJobRun(&glue.StartJobRunInput{
JobName: aws.String(name),
})
if err != nil {
return err
}
// TODO: If the --tail-logs option is enabled, then stream the logs to the console.
return nil
}
<file_sep>/internal/cli/command/deploy/cmd.go
package deploy
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/fatih/color"
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/mana-sys/adhesive/internal/cli/config"
"github.com/mana-sys/adhesive/internal/cli/util"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
)
func NewDeployCommand(adhesiveCli *command.AdhesiveCli, opts *config.DeployOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "deploy",
Short: "Deploy your AWS Glue jobs with CloudFormation",
RunE: func(cmd *cobra.Command, args []string) error {
return deploy(adhesiveCli)
},
}
flags := cmd.Flags()
flags.BoolVarP(&opts.Guided, "guided", "g", false, "Allow Adhesive to guide you through the deployment")
flags.StringVar(&opts.StackName, "stack-name", "", "The name of the CloudFormation stack being deployed to")
flags.StringVar(&opts.TemplateFile, "template-file", "", "The path to your CloudFormation template")
flags.BoolVar(&opts.NoExecuteChangeSet, "no-execute-change-set", false, "Specifies if change set execution is disabled")
flags.BoolVarP(&opts.NoConfirmChangeSet, "no-confirm-change-set", "y", false, "Don't prompt for confirmation before executing a change set")
return cmd
}
func promptOptions(adhesiveCli *command.AdhesiveCli, opts *config.DeployOptions) (bool, error) {
var err error
sc := bufio.NewScanner(os.Stdin)
if adhesiveCli.FoundConfigFile {
fmt.Println("Defaults loaded from adhesive.toml")
} else {
fmt.Println("Could not find adhesive.toml")
}
// Prompt stack name.
prompt := "stack name: "
if opts.StackName != "" {
prompt += "(" + opts.StackName + ") "
}
opts.StackName, err = util.ScannerPrompt(sc, prompt, nil)
if err != nil {
return false, err
}
// Prompt confirm change set before deployment.
prompt = fmt.Sprintf("confirm changes before deployment: (%s) ", strconv.FormatBool(!opts.NoConfirmChangeSet))
confirmChangeSet, err := util.ScannerPrompt(sc, prompt, []string{"true", "false"})
if err != nil {
return false, err
}
// Parsing here is infallible. We actually need to get the opposite of what the user specified.
opts.NoConfirmChangeSet, _ = strconv.ParseBool(confirmChangeSet)
opts.NoConfirmChangeSet = !opts.NoConfirmChangeSet
return false, nil
}
func deploy(adhesiveCli *command.AdhesiveCli) error {
opts := adhesiveCli.Config.Deploy
if err := adhesiveCli.InitializeClients(); err != nil {
return err
}
sc := bufio.NewScanner(os.Stdin)
cfn := adhesiveCli.CloudFormation()
// If the --guided flag was set, prompt for default options.
if opts.Guided {
if _, err := promptOptions(adhesiveCli, &opts); err != nil {
return err
}
}
// Option validation.
if opts.StackName == "" {
return errors.New("--stack-name must be specified")
}
if opts.TemplateFile == "" {
opts.TemplateFile = "template.yml"
}
// Read the template file.
b, err := ioutil.ReadFile(opts.TemplateFile)
if err != nil {
return err
}
// Check if the stack exists. If the stack does not exist, or if the stack
// status is "REVIEW_IN_PROGRESS", then the change set type will be "CREATE."
// Otherwise, the change set type will be "UPDATE."
var changeSetType string
changeSetName := fmt.Sprintf("adhesive-%d", time.Now().Unix())
fmt.Println("Retrieving stack information...")
out, err := cfn.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(opts.StackName),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "ValidationError" {
changeSetType = cloudformation.ChangeSetTypeCreate
} else {
return err
}
} else if *out.Stacks[0].StackStatus == cloudformation.StackStatusReviewInProgress {
changeSetType = cloudformation.ChangeSetTypeCreate
} else {
changeSetType = cloudformation.ChangeSetTypeUpdate
}
// Create the change set.
fmt.Println("Creating change set...")
out2, err := cfn.CreateChangeSet(&cloudformation.CreateChangeSetInput{
StackName: aws.String(opts.StackName),
ChangeSetName: aws.String(changeSetName),
ChangeSetType: aws.String(changeSetType),
TemplateBody: aws.String(string(b)),
})
if err != nil {
return err
}
// Wait for the change set to finish creating.
var changeSetOutput *cloudformation.DescribeChangeSetOutput
for {
changeSetOutput, err = cfn.DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: out2.Id,
StackName: out2.StackId,
})
if err != nil {
return err
}
status := *changeSetOutput.Status
if status == cloudformation.ChangeSetStatusCreateComplete {
break
} else if status == cloudformation.ChangeSetStatusFailed {
if strings.HasPrefix(*changeSetOutput.StatusReason, "The submitted information didn't contain changes.") {
fmt.Printf("\nNo changes to make.\n")
return nil
}
return fmt.Errorf("failed to create change set: %s", *changeSetOutput.StatusReason)
}
time.Sleep(time.Second)
}
fmt.Printf(`
Finished creating change set.
The following changes will be made as part of the deployment:
`)
var (
numAdd int
numRemove int
numUpdate int
)
for _, change := range changeSetOutput.Changes {
if *change.ResourceChange.Action == "Add" {
numAdd += 1
} else if *change.ResourceChange.Action == "Remove" {
numRemove += 1
} else if *change.ResourceChange.Action == "Update" {
numUpdate += 1
}
}
// Output the proposed changes.
renderChangeSet(os.Stdout, changeSetOutput.Changes)
// If the --no-execute-change-set flag is present, we are done.
if opts.NoExecuteChangeSet {
return nil
}
fmt.Printf("\nChange set: %s, %s, %s\n",
color.GreenString("%d to add", numAdd),
color.YellowString("%d to update", numUpdate),
color.RedString("%d to remove", numRemove),
)
// If the --confirm-change-set flag is present, prompt for confirmation.
if !opts.NoConfirmChangeSet {
confirm, err := util.ScannerPrompt(sc, `
Do you want to apply this change set?
Only "yes" will be accepted to approve.
Enter a value: `, nil)
if err == io.EOF {
fmt.Println("Abort.")
return nil
}
if err != nil {
return err
}
if confirm != "yes" {
fmt.Printf("\nDeploy cancelled.\n")
return nil
}
}
fmt.Println()
_, err = cfn.ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
StackName: changeSetOutput.StackId,
ChangeSetName: changeSetOutput.ChangeSetName,
})
if err != nil {
return err
}
fmt.Printf("Sent the change set execution request. You may track the stack status below:\n\n")
// Wait until stack completion is done.
stackOut, err := util.MonitorStack(cfn, *changeSetOutput.StackId, *changeSetOutput.StackName, util.OpUpdate)
if err != nil {
return err
}
// Print change set execution summary.
fmt.Println()
color.Green("Change set execution complete!")
fmt.Printf("Summary of changes: %s, %s, %s\n\n",
color.GreenString("%d added", numAdd),
color.YellowString("%d updated", numUpdate),
color.RedString("%d removed", numRemove),
)
// Print stack outputs.
fmt.Println("Outputs: ")
for _, output := range stackOut.Stacks[0].Outputs {
fmt.Printf("%s = %s\n", *output.OutputKey, *output.OutputValue)
}
return nil
}
func stringElseDash(s *string) string {
if s == nil {
return "-"
}
return *s
}
func renderChangeSet(w io.Writer, changes []*cloudformation.Change) {
data := make([][]string, 0, len(changes))
// Translate from *cloudformation.Change to []string
for _, change := range changes {
row := []string{
stringElseDash(change.ResourceChange.Action),
stringElseDash(change.ResourceChange.LogicalResourceId),
stringElseDash(change.ResourceChange.PhysicalResourceId),
stringElseDash(change.ResourceChange.ResourceType),
stringElseDash(change.ResourceChange.Replacement),
}
data = append(data, row)
}
table := tablewriter.NewWriter(w)
table.SetHeader([]string{"Action", "Logical ID", "Physical ID", "Resource type", "Replacement"})
table.SetAutoFormatHeaders(false)
for _, v := range data {
var color int
if v[0] == "Add" {
color = tablewriter.FgGreenColor
} else if v[0] == "Remove" {
color = tablewriter.FgRedColor
} else if v[0] == "Modify" {
color = tablewriter.FgYellowColor
}
table.Rich(v, []tablewriter.Colors{
{color},
{tablewriter.FgWhiteColor},
{tablewriter.FgWhiteColor},
{tablewriter.FgWhiteColor},
{tablewriter.FgWhiteColor},
})
}
table.Render()
}
<file_sep>/internal/cli/command/remove/cmd.go
package remove
import (
"bufio"
"fmt"
"io"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/fatih/color"
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/mana-sys/adhesive/internal/cli/config"
"github.com/mana-sys/adhesive/internal/cli/util"
"github.com/spf13/cobra"
)
func NewRemoveCommand(adhesiveCli *command.AdhesiveCli, opts *config.RemoveOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "remove",
Short: "Remove the current deployment of your CloudFormation template.",
RunE: func(cmd *cobra.Command, args []string) error {
return remove(adhesiveCli)
},
}
flags := cmd.Flags()
flags.StringVar(&opts.StackName, "stack-name", "", "The name of the CloudFormation stack to remove")
return cmd
}
func remove(adhesiveCli *command.AdhesiveCli) error {
opts := adhesiveCli.Config.Remove
if err := adhesiveCli.InitializeClients(); err != nil {
return err
}
sc := bufio.NewScanner(os.Stdin)
cfn := adhesiveCli.CloudFormation()
// Make sure the stack exists.
fmt.Println("Retrieving stack information...")
out, err := cfn.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(opts.StackName),
})
if err != nil {
return err
}
stack := out.Stacks[0]
// Prompt user for confirmation.
confirm, err := util.ScannerPrompt(sc, `This action will delete all stack resources and CANNOT be undone.
Do you wish to continue? Only "yes" will be accepted to continue.
Enter a value: `, nil)
if err == io.EOF {
fmt.Println("Abort")
return nil
}
if err != nil {
return err
}
if confirm != "yes" {
fmt.Println("Remove cancelled.")
return nil
}
// Delete the stack.
_, err = cfn.DeleteStack(&cloudformation.DeleteStackInput{
StackName: stack.StackId,
})
if err != nil {
return err
}
fmt.Printf("\nSent stack deletion request. You may track the stack status below:\n\n")
// Wait for the stack to finish deleting and stream CloudFormation events to the user.
_, err = util.MonitorStack(cfn, *stack.StackId, *stack.StackName, util.OpDelete)
if err != nil {
return err
}
fmt.Println()
color.Green("Deletion complete!")
return nil
}
<file_sep>/internal/cli/util/ui.go
package util
import (
"bufio"
"context"
"fmt"
"io"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/mana-sys/adhesive/pkg/watchstack"
)
type stackOp int
type StackOpError string
func (err StackOpError) Error() string {
return string(err)
}
const (
OpCreate stackOp = iota
OpUpdate
OpDelete
)
const (
GlueErrorLogsPrefix = "/awsglue-"
)
type stackMonitorState struct {
name string
op stackOp
start time.Time
uiInterval time.Duration
}
func isSuccess(status string) bool {
return status == cloudformation.StackStatusCreateComplete ||
status == cloudformation.StackStatusDeleteComplete ||
status == cloudformation.StackStatusUpdateComplete
}
func isFailed(status string) bool {
return status == cloudformation.StackStatusDeleteFailed ||
strings.HasSuffix(status, "ROLLBACK_COMPLETE") ||
strings.HasSuffix(status, "ROLLBACK_FAILED")
}
func MonitorStack(cfn *cloudformation.CloudFormation, stackId, stackName string, op stackOp) (*cloudformation.DescribeStacksOutput, error) {
var (
err error
out *cloudformation.DescribeStacksOutput
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
state := stackMonitorState{
name: stackName,
op: OpCreate,
start: time.Now().Round(time.Second),
uiInterval: 5 * time.Second,
}
w := watchstack.New(cfn)
go w.StreamEvents(ctx, stackId)
for range time.Tick(1 * time.Second) {
out, err = cfn.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(stackId),
})
if err != nil {
return nil, err
}
stack := out.Stacks[0]
if isSuccess(*stack.StackStatus) {
break
} else if isFailed(*stack.StackStatus) {
return nil, StackOpError(fmt.Sprintf("operation failed with status %s: %s",
*stack.StackStatus, *stack.StackStatusReason))
}
}
fmt.Printf("\nOperation complete after %v.\n",
time.Now().Round(1*time.Second).Sub(state.start))
return out, nil
}
func MonitorJobLogs(cwl *cloudwatchlogs.CloudWatchLogs, name, id string) error {
//ctx, cancel := context.WithCancel(context.Background())
//w := watchlog.NewWatchLog(cwl)
// Wait for the log streams to become available.
return nil
}
func ConsoleMonitorStack(ctx context.Context, state stackMonitorState) {
ticker := time.NewTicker(state.uiInterval)
var message string
switch state.op {
case OpCreate:
message = "Still creating..."
case OpDelete:
message = "Still deleting..."
case OpUpdate:
message = "Still updating..."
default:
panic("unreachable")
}
for {
select {
case <-ctx.Done():
return
case t := <-ticker.C:
fmt.Printf("%s: %s (%v elapsed)\n", state.name, message, t.Round(time.Second).Sub(state.start))
}
}
}
func ScannerPrompt(sc *bufio.Scanner, text string, allowed []string) (string, error) {
for {
fmt.Print(text)
if !sc.Scan() {
if sc.Err() == nil {
return "", io.EOF
}
return "", sc.Err()
}
got := sc.Text()
if len(allowed) == 0 {
return got, nil
}
for _, v := range allowed {
if v == got {
return got, nil
}
}
fmt.Println("Invalid input; please try again.")
}
}
<file_sep>/pkg/watchstack/watchstack.go
package watchstack
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/fatih/color"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface"
)
// WatchLog represents a CloudFormation events watcher. It will stream events
// to the configured destination until canceled. Adapted from <NAME>'s
// github.com/TylerBrock/saw repository.
type WatchStack struct {
cfn cloudformationiface.CloudFormationAPI
PollInterval time.Duration
W io.Writer
}
func New(cfn cloudformationiface.CloudFormationAPI) *WatchStack {
return &WatchStack{
cfn: cfn,
PollInterval: time.Second,
W: os.Stdout,
}
}
func isFailedResource(status string) bool {
return strings.HasSuffix(status, "FAILED")
}
func isSuccessResource(status string) bool {
return strings.HasSuffix(status, "COMPLETE")
}
func (w *WatchStack) StreamEvents(ctx context.Context, stackId string) error {
var (
lastSeenTime time.Time
seenEvents map[string]struct{}
)
input := &cloudformation.DescribeStackEventsInput{
StackName: aws.String(stackId),
}
pageHandler := func(output *cloudformation.DescribeStackEventsOutput, last bool) bool {
for _, event := range output.StackEvents {
// Filter out any events that occurred before that last seen timestamp.
// If we see a new timestamp, then we set the last seen timestamp to that
// new timestamp. We can also clear the set of seen events.
if event.Timestamp.Before(lastSeenTime) {
continue
} else if event.Timestamp.After(lastSeenTime) {
lastSeenTime = *event.Timestamp
seenEvents = make(map[string]struct{})
}
// If we have already seen this event, don't output it. Otherwise, we
// can output the event.
if _, ok := seenEvents[*event.EventId]; ok {
continue
}
c := color.YellowString
if isSuccessResource(*event.ResourceStatus) {
c = color.GreenString
} else if isFailedResource(*event.ResourceStatus) {
c = color.RedString
}
fmt.Fprintf(w.W, "[%s] %s (%s): %s\n",
color.WhiteString(event.Timestamp.Format(time.RFC3339)),
*event.LogicalResourceId,
*event.ResourceType,
c(*event.ResourceStatus),
)
seenEvents[*event.EventId] = struct{}{}
}
return !last
}
for {
err := w.cfn.DescribeStackEventsPages(input, pageHandler)
if err != nil {
return err
}
time.Sleep(w.PollInterval)
}
}
<file_sep>/internal/cli/command/local/cmd.go
package local
import (
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/spf13/cobra"
)
type dockerOptions struct {
arg []string
credentials string
env []string
volumes []string
}
type localOptions struct {
dockerOptions
}
func NewLocalCommand(adhesiveCli *command.AdhesiveCli) *cobra.Command {
var opts localOptions
cmd := &cobra.Command{
Use: "local",
Short: "Run AWS Glue jobs and test suites locally",
}
flags := cmd.Flags()
flags.StringSliceVarP(&opts.arg, "docker-env", "e", nil, "Set Docker environment variables.")
flags.StringSliceVarP(&opts.volumes, "docker-volumes", "v", nil, "Mount Docker volumes.")
flags.StringSliceVarP(&opts.arg, "docker-arg", "a", nil,
"Pass additional arguments to the \"docker run\" command.")
dockerOpts := &opts.dockerOptions
cmd.AddCommand(
NewPipCommand(adhesiveCli, dockerOpts),
NewPySparkCommand(adhesiveCli, dockerOpts),
NewPytestCommand(adhesiveCli, dockerOpts),
NewSparkSubmitCommand(adhesiveCli, dockerOpts),
)
return cmd
}
<file_sep>/README.md
# Adhesive
Adhesive is a tool to facilitate local development for AWS Glue. Based on the
[AWS SAM CLI](https://github.com/awslabs/aws-sam-cli), Adhesive provides a
local Glue execution environment for writing and testing your Glue
scripts.
## Table of Contents
- [Installation](#Installation)
- [Getting Started](#getting-started)
- [CLI Command Reference](#cli-command-reference)
* [deploy](#adhesive-deploy)
* [history-server](#adhesive-history-server)
* [local](#adhesive-local)
* [package](#adhesive-package)
* [remove](#adhesive-remove)
## Installation
To install Adhesive, follow the appropriate instructions for your platform.
### Prerequisites
The following prerequisites must be installed for Adhesive to work correctly:
- [Docker](https://docs.docker.com/install/)
### MacOS (Homebrew)
```shell script
brew tap mana-sys/adhesive
brew install adhesive
```
### Downloading the Binaries
The binaries are also available in the Releases section of this repository.
Simply navigate over to the releases and download the executable corresponding
to your platform. Currently, builds for Windows, MacOS, and Linux are provided.
## <a name="getting-started"></a>Getting Started
## <a name="cli-command-reference"></a>CLI Command Reference
### `adhesive`
The following global options may be specified after the `adhesive` root command
and will be propagated to all child commands:
| Option | Description |
| --- | --- |
| `-c`, `--config` | The path to the Adhesive configuration file. |
| `-d`, `--debug` | Enable debug mode |
| `--profile` | Use a specific profile from your credentials file. |
| `--region` | The region to execute in. |
### `adhesive deploy`
The `adhesive deploy` command deploys your Glue jobs using CloudFormation.
Like the AWS SAM CLI, `adhesive deploy` comes with a guided mode, which walks
you through setting the parameters required for your deployment. This mode also
offers the option for setting default arguments in the `adhesive.toml`
configuration file. After these default arguments are set, subsequent
deployments may be done by simply executing `adhesive deploy` again.
| Option | Description |
| --- | --- |
| `-g`, `--guided` | Allow Adhesive to guide you through the deployment |
| `--stack-name` | The name of the CloudFormation stack being deployed to |
| `--template-file` | The path to your CloudFormation template (default "template.yml") |
| `-y`, `--no-confirm-change-set` | Don't prompt for confirmation before executing a change set |
| `--no-execute-change-set` | Specifies if change set execution is disabled
### `adhesive history-server`
The `adhesive history-server` command runs the Spark history server locally
via Docker. You can provide the log directory, which must be formatted as
an `s3a://` path (e.g. `s3a://path/to/logs`).
| Option | Description |
| --- | --- |
| `--log-directory` | The location of the Spark logs. Must be an `s3a//` formatted path. |
| `--port` | The port to listen on. Defaults to 18080. |
### `adhesive local`
The `adhesive local` command is a top level command for subcommands that
allow for executing Glue jobs and test suites locally. It is comprised
of the following subcommands:
- `pip` - Install Python dependencies in the local environment
- `pyspark` - Run `pyspark` in the local execution environment
- `pytest` - Run test suites for Glue scripts written in Python
- `spark-submit` - Run a Glue job
### `adhesive package`
The `adhesive package` command packages the Glue jobs in the specified
AWS CloudFormation template. It uploads your scripts and their dependencies
to Amazon S3 and outputs a copy of the original template, with references
to local artifacts replaced with their corresponding Amazon S3 locations.
**Usage**:
```
adhesive package [flags]
```
| Option | Description |
| --- | --- |
| `--template-file` | The path where your AWS CloudFormation template is located. |
| `--s3-bucket` | The S3 bucket where artifacts will be uploaded. |
| `--s3-prefix` | The prefix added to the names of the artifacts uploaded to the S3 bucket. |
### `adhesive remove`
The `adhesive remove` command removes the current deployment of your Glue jobs.
| Option | Description |
| --- | --- |
| `--stack-name` | The name of the CloudFormation stack to remove |
<file_sep>/pkg/packager/exporter.go
package packager
import (
"github.com/awslabs/goformation/v4/cloudformation"
"github.com/awslabs/goformation/v4/cloudformation/glue"
)
type ExportedResources []ExportedResource
type ExportedResource struct {
GetProperty func(cloudformation.Resource) (interface{}, bool)
ReplaceProperty func(resource cloudformation.Resource, path string)
ForceZip bool
}
var (
// Command.ScriptLocation property of AWS::Glue::Job.
glueJobCommandScriptLocationResource = ExportedResource{
GetProperty: func(resource cloudformation.Resource) (interface{}, bool) {
if job, ok := resource.(*glue.Job); ok {
return job.Command.ScriptLocation, true
}
return nil, false
},
ReplaceProperty: func(resource cloudformation.Resource, path string) {
resource.(*glue.Job).Command.ScriptLocation = path
},
}
// DefaultArguments."--extra-py-files" property of AWS::Glue::Job
glueJobDefaultArgumentsExtraPyFilesResource = ExportedResource{
GetProperty: func(resource cloudformation.Resource) (interface{}, bool) {
if job, ok := resource.(*glue.Job); ok {
if args, ok := job.DefaultArguments.(map[string]interface{}); ok {
if v, ok := args["--extra-py-files"]; ok {
return v, true
}
}
}
return nil, false
},
ReplaceProperty: func(resource cloudformation.Resource, path string) {
resource.(*glue.Job).DefaultArguments.(map[string]interface{})["--extra-py-files"] = path
},
}
// DefaultArguments."--extra-files" property of AWS::Glue::Job
glueJobDefaultArgumentsExtraFilesResource = ExportedResource{
GetProperty: func(resource cloudformation.Resource) (interface{}, bool) {
if job, ok := resource.(*glue.Job); ok {
if args, ok := job.DefaultArguments.(map[string]interface{}); ok {
if v, ok := args["--extra-files"]; ok {
return v, true
}
}
}
return nil, false
},
ReplaceProperty: func(resource cloudformation.Resource, path string) {
resource.(*glue.Job).DefaultArguments.(map[string]interface{})["--extra-files"] = path
},
}
)
var defaultExportedResources = ExportedResources{
glueJobCommandScriptLocationResource,
glueJobDefaultArgumentsExtraFilesResource,
glueJobDefaultArgumentsExtraPyFilesResource,
}
<file_sep>/pkg/packager/upload.go
package packager
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
)
func (p *Packager) ProcessAndUpload(path string, forceZip bool) (string, error) {
// Make sure the path refers to an actual file.
stat, err := os.Stat(path)
if err != nil {
return "", err
}
// If the file is a directory, create a ZIP archive from the
// directory and upload it. Otherwise, upload the file directly.
if stat.IsDir() {
path, err = tempZipFile([]string{path}, "", "artifacts")
if err != nil {
return "", err
}
defer os.Remove(path)
}
// TODO: Implement forceZip
// Upload the file.
return p.UploadFileWithDedup(path)
}
// Upload uploads the content of the reader to S3. The object will be named
// using the specified key.
func (p *Packager) Upload(r io.ReadSeeker, key string) (string, error) {
fmt.Printf("Uploading %s\n", key)
input := &s3.PutObjectInput{
Bucket: aws.String(p.S3Bucket),
Body: r,
Key: aws.String(key),
}
if p.KMSKeyID != "" {
input.ServerSideEncryption = aws.String("aws:kms")
input.SSEKMSKeyId = aws.String(p.KMSKeyID)
}
_, err := p.svc.PutObject(input)
if err != nil {
return "", err
}
return fmt.Sprintf("s3://%s/%s", p.S3Bucket, key), nil
}
// UploadFileWithDedup uploads a file to S3. The S3 key of the resultant object is
// based on the file's MD5 sum.
func (p *Packager) UploadFileWithDedup(path string) (string, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return p.UploadWithDedup(b)
}
// UploadWithDedup
func (p *Packager) UploadWithDedup(data []byte) (string, error) {
sum := md5.Sum(data)
remotePath := hex.EncodeToString(sum[:])
if p.S3Prefix != "" {
remotePath = p.S3Prefix + "/" + remotePath
}
return p.Upload(bytes.NewReader(data), remotePath)
}
<file_sep>/internal/cli/command/local/pyspark.go
package local
import (
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/spf13/cobra"
)
func NewPySparkCommand(adhesiveCli *command.AdhesiveCli, opts *dockerOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "pyspark",
Short: "Run PySpark locally",
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
return buildAndRunDockerCommand(adhesiveCli, "pyspark", opts, args)
},
}
return cmd
}
<file_sep>/pkg/packager/upload_test.go
package packager
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/stretchr/testify/mock"
)
type mockS3 struct {
mock.Mock
s3iface.S3API
}
func (m *mockS3) PutObject(input *s3.PutObjectInput) (*s3.PutObjectOutput, error) {
args := m.Called(input)
return args.Get(0).(*s3.PutObjectOutput), nil
}
func TestPackager_Upload(t *testing.T) {
m := &mockS3{}
p := NewFromS3(m)
p.S3Bucket = "bucket"
r := bytes.NewReader([]byte("content"))
m.On("PutObject", &s3.PutObjectInput{
Bucket: aws.String(p.S3Bucket),
Body: r,
Key: aws.String("key"),
}).Return(&s3.PutObjectOutput{})
key, err := p.Upload(r, "key")
assert.Nil(t, err)
assert.Equal(t, "s3://bucket/key", key)
m.AssertExpectations(t)
}
func TestPackager_UploadWithDedup(t *testing.T) {
m := &mockS3{}
p := NewFromS3(m)
p.S3Bucket = "bucket"
data := []byte("content")
hash := md5.Sum(data)
key := hex.EncodeToString(hash[:])
m.On("PutObject", &s3.PutObjectInput{
Bucket: aws.String(p.S3Bucket),
Body: bytes.NewReader(data),
Key: aws.String(key),
}).Return(&s3.PutObjectOutput{})
remoteKey, err := p.UploadWithDedup(data)
assert.Nil(t, err)
assert.Equal(t, fmt.Sprintf("s3://%s/%s", p.S3Bucket, key), remoteKey)
}
<file_sep>/go.mod
module github.com/mana-sys/adhesive
go 1.13
require (
github.com/BurntSushi/toml v0.3.1
github.com/aws/aws-sdk-go v1.28.0
github.com/awslabs/goformation/v4 v4.1.0
github.com/fatih/color v1.9.0
github.com/mholt/archiver/v3 v3.3.0
github.com/olekukonko/tablewriter v0.0.4
github.com/sirupsen/logrus v1.4.2
github.com/spf13/cobra v0.0.5
github.com/stretchr/testify v1.4.0
github.com/urfave/cli v1.22.2
gopkg.in/yaml.v2 v2.2.7
)
<file_sep>/internal/cli/command/local/pytest.go
package local
import (
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/spf13/cobra"
)
func NewPytestCommand(adhesiveCli *command.AdhesiveCli, opts *dockerOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "pytest",
Short: "Run pytest locally.",
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
return buildAndRunDockerCommand(adhesiveCli, "pytest", opts, args)
},
}
return cmd
}
<file_sep>/cmd/main.go
package main
import (
"fmt"
"os"
"os/exec"
"github.com/mana-sys/adhesive/internal/cli"
"github.com/mana-sys/adhesive/internal/cli/command"
)
func main() {
adhesiveCli := command.NewAdhesiveCli()
cmd := cli.NewRootCommand(adhesiveCli)
if err := cmd.Execute(); err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
os.Exit(exitErr.ExitCode())
}
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
os.Exit(1)
}
}
<file_sep>/Makefile
MOD=github.com/mana-sys/adhesive
PREFIX=/usr/local
.PHONY: clean cli test
cli:
go build -o bin/adhesive $(MOD)/cmd
test:
go test $(MOD)/...
install: cli
cp bin/adhesive $(DESTDIR)$(PREFIX)/bin/
chmod +x $(DESTDIR)$(PREFIX)/bin/adhesive
uninstall:
rm $(DESTDIR)$(PREFIX)/bin/adhesive
clean:
rm -rf bin/
<file_sep>/internal/cli/clierrors/error.go
package clierrors
type CliError struct {
message string
}
var (
//DeployCanceledError
)
<file_sep>/internal/cli/command/package/cmd.go
package package1
import (
"errors"
"fmt"
"io/ioutil"
"github.com/mana-sys/adhesive/internal/cli/config"
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/mana-sys/adhesive/pkg/packager"
"github.com/spf13/cobra"
)
func NewPackageCommand(adhesiveCli *command.AdhesiveCli, opts *config.PackageOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "package",
Short: "Packages the Glue jobs in your AWS CloudFormation template",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return package1(adhesiveCli)
},
}
flags := cmd.Flags()
flags.StringVar(&opts.TemplateFile, "template-file", "", "The path where your AWS CloudFormation template is located")
flags.StringVar(&opts.S3Bucket, "s3-bucket", "", "The S3 bucket where artifacts will be uploaded")
flags.StringVar(&opts.S3Prefix, "s3-prefix", "", "The prefix added to the names of the artifacts uploaded to the S3 bucket")
flags.StringVar(&opts.KmsKeyID, "kms-key-id", "", "The ID of the KMS key used to encrypt artifacts in the S3 bucket")
flags.StringVar(&opts.OutputTemplateFile, "output-template-file", "", "The path to the file to which the packaged template will be written")
flags.BoolVar(&opts.UseJSON, "use-json", false, "Use JSON for the template output format")
flags.BoolVar(&opts.ForceUpload, "force-upload", false, "Override existing files in the the S3 bucket")
return cmd
}
func package1(adhesiveCli *command.AdhesiveCli) error {
opts := adhesiveCli.Config.Package
if err := adhesiveCli.InitializeClients(); err != nil {
return err
}
// Determine packaging parameters. These may come from either the packageOptions
// or from the CLI instance itself.
if opts.S3Bucket == "" {
return errors.New("must specify an S3 bucket")
}
if opts.TemplateFile == "" {
opts.TemplateFile = "template.yml"
}
// Initialize a packager.
pack := packager.NewFromS3(adhesiveCli.S3())
pack.S3Bucket = opts.S3Bucket
pack.S3Prefix = opts.S3Prefix
pack.KMSKeyID = opts.KmsKeyID
if opts.UseJSON {
pack.Format = packager.FormatJSON
}
// Package the CloudFormation template.
b, err := pack.PackageTemplateFile(opts.TemplateFile)
if err != nil {
return err
}
// If an output file was specified, save the packaged template to
// that file. Otherwise, output the result to standard output.
if opts.OutputTemplateFile != "" {
return ioutil.WriteFile(opts.OutputTemplateFile, b, 0644)
}
fmt.Printf("%s", b)
return nil
}
<file_sep>/internal/cli/command/local/docker.go
package local
import (
"errors"
"os"
"os/exec"
"path/filepath"
"github.com/aws/aws-sdk-go/aws/credentials/processcreds"
"github.com/mana-sys/adhesive/internal/cli/command"
log "github.com/sirupsen/logrus"
)
const (
DockerImageName = "sysmana/aws-glue-dev-base"
DistPackagesVolume = "aws_glue_dist_packages"
DistPackagesDirectory = "/usr/local/lib/python2.7/dist-packages"
)
// buildDockerCommand builds an exec.Cmd to run the Docker container with the provided options.
func buildDockerCommand(adhesiveCli *command.AdhesiveCli, entrypoint string, options *dockerOptions,
args []string) (*exec.Cmd, error) {
var (
err error
envs []string
vols []string
)
for _, env := range options.env {
envs = append(envs, "-e "+env)
}
// Super hack: If we used the ProcessProvider, then we pass the credentials via environment variables to the
// Docker container.
if err := adhesiveCli.InitializeClients(); err != nil {
return nil, err
}
value, err := adhesiveCli.Session().Config.Credentials.Get()
if err != nil {
return nil, err
}
if value.ProviderName == processcreds.ProviderName {
envs = append(envs,
"-e", "AWS_ACCESS_KEY_ID="+value.AccessKeyID,
"-e", "AWS_SECRET_ACCESS_KEY="+value.SecretAccessKey,
"-e", "AWS_SESSION_TOKEN="+value.SessionToken,
)
}
for _, vol := range options.volumes {
vols = append(vols, "-v "+vol)
}
credsDir := options.credentials
if credsDir == "" {
if credsDir, err = os.UserHomeDir(); err != nil {
return nil, errors.New("unable to determine home directory")
}
credsDir = filepath.Join(credsDir, ".aws")
}
wd, err := os.Getwd()
dockerArgs := []string{"run", "--rm", "-it"}
dockerArgs = append(dockerArgs, envs...)
dockerArgs = append(dockerArgs, vols...)
dockerArgs = append(dockerArgs, "-v", credsDir+":/root/.aws",
"-v", DistPackagesVolume+":"+DistPackagesDirectory,
"-v", wd+":/project",
"--entrypoint", entrypoint, DockerImageName+":0.9")
dockerArgs = append(dockerArgs, args...)
return exec.Command("docker", dockerArgs...), nil
}
func buildAndRunDockerCommand(adhesiveCli *command.AdhesiveCli, entrypoint string, options *dockerOptions,
args []string) error {
dockerCmd, err := buildDockerCommand(adhesiveCli, entrypoint, options, args)
if err != nil {
return err
}
log.Debug("Running Docker command: ", dockerCmd.Args)
dockerCmd.Stdin = os.Stdin
dockerCmd.Stdout = os.Stdout
dockerCmd.Stderr = os.Stderr
if err = dockerCmd.Start(); err != nil {
return err
}
return dockerCmd.Wait()
}
<file_sep>/internal/cli/command/historyserver/cmd.go
package historyserver
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws/credentials/processcreds"
"github.com/mana-sys/adhesive/internal/cli/command"
"github.com/mana-sys/adhesive/internal/cli/config"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func NewHistoryServerCommand(adhesiveCli *command.AdhesiveCli, opts *config.HistoryServerOptions) *cobra.Command {
cmd := &cobra.Command{
Use: "history-server",
Short: "Launch the Spark history server",
RunE: func(cmd *cobra.Command, args []string) error {
return historyServer(adhesiveCli, opts)
},
}
flags := cmd.Flags()
flags.IntVarP(&opts.Port, "port", "p", 0, "The port to listen on")
flags.StringVar(&opts.LogDirectory, "log-directory", "", "The location of the Spark logs. Must be an s3a:// formatted path.")
return cmd
}
// buildDockerCommand builds an exec.Cmd to run the history server Docker container with the provided options.
func buildDockerCommand(adhesiveCli *command.AdhesiveCli, opts *config.HistoryServerOptions) (*exec.Cmd, error) {
credsDir, err := os.UserHomeDir()
if err != nil {
return nil, err
}
credsDir = filepath.Join(credsDir, ".aws")
dockerArgs := []string{"run", "--rm"}
dockerArgs = append(dockerArgs, "-v", credsDir+":/root/.aws")
dockerArgs = append(dockerArgs, "-p", strconv.FormatInt(int64(opts.Port), 10)+":18080")
// Super hack: If we used the ProcessProvider, then we pass the credentials via environment variables to the
// Docker container.
value, err := adhesiveCli.Session().Config.Credentials.Get()
if err != nil {
return nil, err
}
if value.ProviderName == processcreds.ProviderName {
dockerArgs = append(dockerArgs,
"-e", "AWS_ACCESS_KEY_ID="+value.AccessKeyID,
"-e", "AWS_SECRET_ACCESS_KEY="+value.SecretAccessKey,
"-e", "AWS_SESSION_TOKEN="+value.SessionToken,
)
}
// Environment variable for Spark history server options.
sparkHistoryOptsStringFormat := "SPARK_HISTORY_OPTS=-Dspark.hadoop.fs.s3a.aws.credentials.provider=com.amazonaws.auth.DefaultAWSCredentialsProviderChain " +
"-Dspark.history.fs.logDirectory=%s"
dockerArgs = append(dockerArgs, "-e", fmt.Sprintf(sparkHistoryOptsStringFormat, opts.LogDirectory))
dockerArgs = append(dockerArgs, "sysmana/sparkui:latest",
"/opt/spark/bin/spark-class org.apache.spark.deploy.history.HistoryServer")
return exec.Command("docker", dockerArgs...), nil
}
func historyServer(adhesiveCli *command.AdhesiveCli, opts *config.HistoryServerOptions) error {
if opts.LogDirectory == "" {
return errors.New("option --log-directory is required")
}
if opts.Port == 0 {
opts.Port = 18080
}
if !strings.HasPrefix(opts.LogDirectory, "s3a://") {
return errors.New("option --log-directory must be an s3a:// formatted path")
}
// Super hack: initialize the clients to retrieve the credentials. This is needed I couldn't
// figure out how to get credential_process to work for Java.
if err := adhesiveCli.InitializeClients(); err != nil {
return err
}
cmd, err := buildDockerCommand(adhesiveCli, opts)
if err != nil {
return err
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Debug("Running Docker command: ", cmd.Args)
if err = cmd.Start(); err != nil {
return err
}
return cmd.Wait()
}
<file_sep>/internal/cli/version/version.go
package version
import "fmt"
var (
Version = "unknown"
Commit = "unknown"
Date = "unknown"
Template = fmt.Sprintf("Adhesive version %s, commit %.7s, built on %s\n",
Version, Commit, Date)
)
<file_sep>/pkg/watchlog/watch.go
package watchlog
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs/cloudwatchlogsiface"
"github.com/fatih/color"
)
// WatchLog represents a CloudWatch Logs watcher. It will stream logs to the
// configured destination until canceled. Adapted from <NAME>'s
// github.com/TylerBrock/saw repository.
type WatchLog struct {
cwl cloudwatchlogsiface.CloudWatchLogsAPI
Destination io.Writer
Formatter Formatter
PollInterval time.Duration
}
// A mechanism to format a CloudWatch Logs filtered log event.
type Formatter interface {
FormatFilteredLogEvent(event *cloudwatchlogs.FilteredLogEvent) string
}
// An adapter type to allow the use of ordinary functions as Formatters.
type FormatterFunc func(event *cloudwatchlogs.FilteredLogEvent) string
func (f FormatterFunc) FormatFilteredLogEvent(event *cloudwatchlogs.FilteredLogEvent) string {
return f(event)
}
var (
// Default formatter. Formats the event with the timestamp, log stream
// name, and message.
defaultFormatter = FormatterFunc(func(event *cloudwatchlogs.FilteredLogEvent) string {
white := color.New(color.FgWhite).SprintFunc()
date := aws.MillisecondsTimeValue(event.Timestamp)
dateStr := date.Format(time.RFC3339)
return fmt.Sprintf("[%s] - %s", white(dateStr), *event.Message)
})
// Returns the message only.
rawFormatter = FormatterFunc(func(event *cloudwatchlogs.FilteredLogEvent) string {
return *event.Message
})
)
// NewWatchLog returns a WatchLog instance with the default configuration. By
// default, the output destination is os.Stdout, and the poll interval is 1
// second.
func NewWatchLog(cwl cloudwatchlogsiface.CloudWatchLogsAPI) *WatchLog {
return &WatchLog{
cwl: cwl,
Destination: os.Stdout,
Formatter: defaultFormatter,
PollInterval: time.Second,
}
}
// A configuration option for initializing a WatchLog instance.
type Opt func(w *WatchLog)
func NewWatchLogWithOpts(opts ...Opt) *WatchLog {
w := new(WatchLog)
for _, opt := range opts {
opt(w)
}
return w
}
func WithCloudWatchLogs(cwl *cloudwatchlogs.CloudWatchLogs) Opt {
return func(w *WatchLog) { w.cwl = cwl }
}
func WithDestination(dest io.Writer) Opt {
return func(w *WatchLog) { w.Destination = dest }
}
func WithFormatter(formatter Formatter) Opt {
return func(w *WatchLog) { w.Formatter = formatter }
}
func WithPollInterval(interval time.Duration) Opt {
return func(w *WatchLog) { w.PollInterval = interval }
}
// WatchLogStream watches the specified log stream using the configured polling
// interval. Adapted from the Blade Stream() method.
func (w *WatchLog) WatchLogStream(ctx context.Context, input *cloudwatchlogs.FilterLogEventsInput) error {
var (
// Need two errors so that we can keep track of errors in the handler.
err, wrErr error
lastSeenTime *int64
seenEventIDs map[string]bool
)
// Page handler function. Called for every page returned by
// FilterLogEventsPages().
handlePage := func(page *cloudwatchlogs.FilterLogEventsOutput, lastPage bool) bool {
for _, event := range page.Events {
// Update lastSeenTime, which will be used as the start time for
// the next call to FilterLogEventsPages().
if lastSeenTime == nil || *event.Timestamp > *lastSeenTime {
lastSeenTime = event.Timestamp
seenEventIDs = make(map[string]bool, 0)
}
// If we have not yet seen this event, write it to the destination.
if _, seen := seenEventIDs[*event.EventId]; !seen {
// Format the event with the formatter.
message := w.Formatter.FormatFilteredLogEvent(event)
message = strings.TrimRight(message, "\n")
// Write the message to the destination.
_, wrErr = fmt.Fprintln(w.Destination, message)
if wrErr != nil {
return false
}
// Don't process this event if we see it again.
seenEventIDs[*event.EventId] = true
}
}
return !lastPage
}
for {
err = w.cwl.FilterLogEventsPagesWithContext(ctx, input, handlePage)
if err != nil {
// If the request was canceled, return the cancellation error.
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode {
_, _ = fmt.Fprintf(w.Destination, "request was canceled: %v", err)
return ctx.Err()
}
// Otherwise, break the loop and return the error.
_, _ = fmt.Fprintf(w.Destination, "failed to retrieve logs: %v", err)
break
}
// Check possible errors from the log events handler.
if wrErr != nil {
return wrErr
}
// Set StartTime filter for the next query.
if lastSeenTime != nil {
input.SetStartTime(*lastSeenTime)
}
time.Sleep(w.PollInterval)
}
return err
}
| f245b8962792d53253d486b54705a3d2802b0fdd | [
"TOML",
"Markdown",
"Makefile",
"Go",
"Go Module"
] | 28 | Go | mana-sys/adhesive | 69af9ae34d2818960693441f0af3a917e581b14a | 762eabf4b59c960b1f76b5fb3ea917f418965091 |
refs/heads/master | <file_sep>var menu = $('select');
var articles = $('article');
menu.on('change', function(){
var menuValue = this.value;
if (menuValue !== 'all') {
articles.each(function(){
$(this).addClass('hide');
if ($(this).hasClass(menuValue)) {
$(this).removeClass('hide');
}
});
} else {
articles.each(function(){
$(this).removeClass('hide');
});
}
})
var mobileNav = $('nav');
var openMenu = $('.open-menu');
var closeMenu = $('.close-menu');
openMenu.on('click', function(){
mobileNav.fadeIn();
$('body').addClass('stop-scroll');
})
closeMenu.on('click', function(){
mobileNav.fadeOut();
$('body').removeClass('stop-scroll');
})
<file_sep># PFNP
## Lesson 4 - jQuery
<file_sep>var menu = document.querySelector('select');
var section = document.querySelector('section');
menu.addEventListener('change', function(){
if (menu.value !== 'none') {
section.classList = '';
section.classList.add(menu.value);
} else {
section.classList = '';
}
})
| 67850c8011cc5b3b64387200e73deff9c2dc573e | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | calvintan/pfnp-jquery | 8b2df49ad530784058127f1629e81597eb731092 | b8265235988fae70b77b99b8284ee49471e683ee |
refs/heads/main | <file_sep>import { assign, createMachine, spawn } from "xstate";
import { createSubredditMachine } from "./subreddit.machine";
export const redditMachine = createMachine({
id: "reddit",
initial: "idle",
states: {
idle: {},
selected: {},
},
context: {
subreddits: {},
subreddit: null,
},
on: {
SELECT: {
target: ".selected",
actions: assign((context: any, event: any) => {
let subreddit = context.subreddits[event.name];
if (subreddit) {
return { ...context, subreddit };
}
subreddit = spawn(createSubredditMachine(event.name));
return {
subreddits: {
...context.subreddits,
[event.name]: subreddit,
},
subreddit,
};
}),
},
},
});
<file_sep>import { assign, createMachine } from "xstate";
const invokeFetchSubreddit = (context) => {
const { subreddit } = context;
return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then((r) => r.json())
.then((json) => json.data.children.map((child) => child.data));
};
export const createSubredditMachine = (subreddit) => {
return createMachine({
id: "subreddit",
initial: "loading",
context: {
subreddit, // Passed in from `createSubredditMachine`
posts: null,
lastUpdated: null,
},
states: {
loading: {
invoke: {
id: "fetch-subreddit",
src: invokeFetchSubreddit,
onDone: {
target: "loaded",
actions: assign({
posts: (_, event) => event.data,
lastUpdated: () => Date.now(),
}),
},
onError: "failure",
},
},
loaded: {
on: {
REFRESH: "loading",
},
},
failure: {
on: {
RETRY: "loading",
},
},
},
});
};
<file_sep>import { defineConfig } from "windicss/helpers";
export default defineConfig({
attributify: false,
extract: {
include: ["./src/**/*.{svelte,html,ts,js}"],
exclude: ["node_modules", "node_modules/**"],
},
theme: {
extend: {},
container: {
center: true,
padding: "2rem",
},
},
});
| 42eb2613938b6fbc064068643d42acef576b9963 | [
"TypeScript"
] | 3 | TypeScript | dodiameer/xstate-reddit-client | 6e899cecad9cb1c4e747a9a02bf2b132ae05b1e0 | 28452b708d9f3f3efc72413f7345302a5c28b232 |
refs/heads/master | <file_sep>// File: sorting.cpp
// Author: <NAME>
// (your name)
// Date: 2015-06-10
// Description: Skeleton file for CMPT 225 assignment #3 sorting functions and helpers
// Function bodies to be completed by you!
// Complete your sorting algorithm function implementations here
// selection sort implementation.
//in reference to lecture note "07-exception-sorting-1154" page.10
template <class T>
int SelectionSort(T arr[], int n)
{
int comparison = 0;
for(int i = 0; i < n-1; i++)
{
int smallest = i;
for(int j = i+1; j<n;j++) //barometer function
{
if ( arr[j] < arr[smallest])
{
smallest = j;
}
comparison++;
}
T temp = arr[i];
arr[i]=arr[smallest];
arr[smallest]=temp;
}
return comparison;
}
//implementation of Quicksort
template <class T>
int Quicksort(T arr[], int n)
{
int baro = 0;
int high = n-1;
int low = 0;
QuicksortHelper(arr, low, high, baro);
return baro;
}
// Quicksort Helper function implementation
template <class T>
void QuicksortHelper(T arr[], int low, int high, int& counter)
{
if (low < high)
{
int pivot = QSPartition(arr, low, high, counter);
QuicksortHelper(arr, low, pivot-1, counter);
QuicksortHelper(arr, pivot+1, high, counter);
}
}
// the partition function for Quick Sort
// in reference to "http://www.sourcetricks.com/2011/06/what-is-quick-sort-algorithm-how-to.html#.VYpLnPlVhBc"
template <class T>
int QSPartition(T arr[], int low, int high, int& counter)
{
T pivot = arr[high]; //set pivot to the last item in the arr
while ( low < high )
{
while ( arr[low] < pivot || arr[high] > pivot) // barometer instruction
{
if(arr[low] < pivot) //increment low if item at position low is less than pivot;
{low++;}
else
{high--;}
counter++;
}
if ( arr[low] == arr[high] ) //if they are equal we dont have to swap any thing thus low++ allows us to terminate the loop
{low++;}
else if ( low < high )
{
T temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
}
}
return high;
}
// Mergesort Implementation
template <class T>
int Mergesort(T arr[], int n)
{
int low = 0;
int high = n-1;
int baro = 0;
MergesortHelper(arr, low, high, n, baro);
return baro;
}
// Mergesort helper function
template <class T>
void MergesortHelper(T arr[], int low, int high, int n, int& counter)
{
if (low < high)
{
int mid = (high+low)/2;
MergesortHelper(arr, low, mid,n,counter); // sort the left half
MergesortHelper(arr,mid+1,high,n,counter); //sort the right half
Merge(arr, low,mid,high,n,counter); // merge the sorted half
}
}
// in reference to textbook page 316
template <class T>
void Merge(T arr[], int low, int mid, int high, int n, int& counter)
{
T* tempArr= new T[n]; // need a dynamite temporary array of size n
int low1=low; //fisrt element of left subarray
int high1=mid; //last element of left subarray
int low2=mid+1; //first element of right subarray
int high2=high; //last element of right subarray
int i=low1; //next availilable location in temparry
while((low1 <= high1) && (low2<=high2)) //copy smaller item in to temparry
{
if (arr[low1] <= arr[low2])
{
tempArr[i] = arr[low1];
low1++;
}
else
{
tempArr[i]=arr[low2];
low2++;
}
i++;
}
while(low1<=high1) //finish the first subarray
{
tempArr[i] = arr[low1];
low1++;
i++;
}
while(low2<=high2) //finish the second subarray
{
tempArr[i] = arr[low2];
low2++;
i++;
}
for(i=low;i<=high;i++) // copy the result back to the original array
{
arr[i]= tempArr[i];
counter++; //this for loop executes the most among all for/while loop, thus it is the barometer function
}
delete[] tempArr;
}
// in reference to http://www.sanfoundry.com/cplusplus-program-implement-shell-sort/
template <class T>
int ShellSort(T arr[], int n)
{
int j;
int counter = 0;
//devide array by 2 everytime
for (int gap = n / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < n; ++i)
{
T temp = arr[i];
counter++;
for (j = i; j >= gap && temp < arr[j - gap]; j -= gap) //barometer instruction
{
arr[j] = arr[j - gap];
counter++;
}
arr[j] = temp;
}
}
return counter;
} | 9ea289a1fe39dbabc99179db9c6b494e57f0e6bf | [
"C++"
] | 1 | C++ | gary1122/sorting | eedae6215b92dbee8304a525d7aa9ef9f36a8283 | 0cc9a50e645e9abadf83cfb0e055c534175272cd |
refs/heads/develop | <file_sep>import zeroconf
from time import sleep
class zeroconfListener(object):
def __init__(self, print_on_discover = False):
self.brewpi_services = {}
self.print_on_discover = print_on_discover
def remove_service(self, zeroconf_obj, type, name):
if self.print_on_discover:
print("The device at '{}' is no longer available".format(self.brewpi_services[name]['server'][:-1]))
self.brewpi_services[name] = None
def add_service(self, zeroconf_obj, type, name):
info = zeroconf_obj.get_service_info(type, name)
self.brewpi_services[name] = info
if self.print_on_discover:
print("Found '{}' running version '{}' of branch '{}' on a {}".format(info.server[:-1], info.properties['version'], info.properties['branch'], info.properties['board']))
def locate_brewpi_services():
zeroconf_obj = zeroconf.Zeroconf()
listener = zeroconfListener()
browser = zeroconf.ServiceBrowser(zeroconf_obj, "_brewpi._tcp.local.", listener)
sleep(3) # We have to give zeroconf services time to respond
zeroconf_obj.close()
return listener.brewpi_services
if __name__ == '__main__':
zeroconf_obj = zeroconf.Zeroconf()
listener = zeroconfListener()
browser = zeroconf.ServiceBrowser(zeroconf_obj, "_brewpi._tcp.local.", listener)
try:
input("Press enter to exit...\n\n")
finally:
zeroconf_obj.close() | 07d479d4d6b620c88d324c16c99e5cc598d21308 | [
"Python"
] | 1 | Python | stone/brewpi-script | 3e021d3cecc16a86c5b50c77abc146a51d6f1ac3 | cab3a3542e75a2abf0003455634abc765f1d5ebe |
refs/heads/main | <file_sep>/*
===== Código de TypeScript =====
*/
function queTiposoy <T>(argumento:T) {
return argumento;
}
let soyTipoString = queTiposoy ("Hola mundo");
let soyTipoNumber = queTiposoy (20);
let soyTipoArray = queTiposoy ([1,2,3,4]);
let soyTipoExplisit = queTiposoy<number>(123);<file_sep>/*
===== Código de TypeScript =====
*/
let habilidades: string [] = ["bash","counter","healding"];
interface Personaje {
nombre:string;
hp:number;
habilidades:string [];
puebloNatal?: string;
}
const personaje : Personaje =
{
nombre: "Day",
hp: 100,
habilidades: ["bash","counter","healding"],
puebloNatal: "Pueblo Paleta"
}
console.table (personaje);<file_sep>/*
===== Código de TypeScript =====
*/
interface employeT {
name:string;
age: number;
direction : Direction,
showDirection: () => string;
}
interface Direction {
street: string;
country: string;
city: string;
}
const employe: employeT = {
name: "Vanesa",
age: 26,
direction: {
street: "Jazmin",
country: "Mexico",
city: "Edo. Mexico"
},
showDirection () {
return this.name + ", " + this.direction.street + ", " + this.direction.country;
}
}
const direction = employe.showDirection();
console.log (direction);
<file_sep>/*
===== Código de TypeScript =====
*/
import { calculaISV, Producto } from "./06-desestructuracion-argumentos";
const carritoCompras: Producto [] = [
{
descripcion: "Telefono 1",
precio: 243
},
{
descripcion: "Telefono 2",
precio: 300
}
]
const [Total, ISV] = calculaISV (carritoCompras);
console.log("Total", Total);
console.log("ISV", ISV);<file_sep>/*
===== Código de TypeScript =====
*/
export interface Producto {
descripcion: string;
precio: number;
}
const Chocolate: Producto ={
descripcion:"Kinder Delice",
precio: 15
}
const paleta: Producto ={
descripcion: "Magnum",
precio: 29
}
export function calculaISV (productos:Producto[]): [number, number]{
let total= 0;
productos.forEach( ({precio}) => {
total += precio
})
return [total, total* 0.15];
}
const articulos = [ Chocolate, paleta]
const [total, isv] = calculaISV(articulos);
console.log("Total:", total);
console.log("ISV:", isv);<file_sep>import { createSolutionBuilderWithWatchHost } from "typescript";
/*
===== Código de TypeScript =====
*/
interface Pasajero {
nombre: string;
mascotas?: string []
}
const pasajero1: Pasajero = {
nombre: "Vanesa"
}
const pasajero2: Pasajero = {
nombre: "Alejandro",
mascotas: ["Daysy","Spam","Kriko"]
}
function imprimirMascotas(pasajero:Pasajero) : void {
const cuantasMascotas = pasajero.mascotas.length || 0;
console.log(cuantasMascotas);
}
imprimirMascotas (pasajero2);
<file_sep>import { createSolutionBuilderWithWatchHost } from "typescript";
/*
===== Código de TypeScript =====
*/
<file_sep>/*
===== Código de TypeScript =====
*/
function sumar1(a:number,b:number): number{
return a+b;
}
const sumarFlecha1 = (a:number, b:number) => {
return a+b;
}
function muntiplicar1 (numero:number, otroNumero?:number, base:number = 2): number{
return numero*base;
}
const resultado = muntiplicar1 (5,9)
console.log(resultado);
interface PersonaLR1 {
nombre: string;
pv: number;
mostrarHp: () => void;
}
function aumento1 (persona1: PersonaLR1, aumentoX: number): void {
persona1.pv += aumentoX;
console.log (persona1);
}
const nuevoPersona1: PersonaLR1 = {
nombre : "Vane",
pv: 50,
mostrarHp() {
console.log("Total sueldo", this.pv);
}
}
aumento1 (nuevoPersona1, 30);
nuevoPersona1.mostrarHp();<file_sep>/*
===== Código de TypeScript =====
*/
let nombre1: string = "vane";
let edad1: number|string = 26;
let estaVivo1: boolean = true;
console.log (nombre1, edad1, estaVivo1);
<file_sep>/*
===== Código de TypeScript =====
*/
interface Reportuctor {
volumen: number;
segundo: number;
cancion: string;
detalles: Detalles
}
interface Detalles {
autor: string,
anio: number
}
const reproductor: Reportuctor = {
volumen: 50,
segundo: 30,
cancion: "Febrero Azul",
detalles: {
autor: "<NAME>",
anio: 2021
}
}
const{volumen, segundo, cancion, detalles} = reproductor;
const{autor, anio} = detalles;
//console.log("El volumen de la cancion acutal es", volumen);
//console.log("El segundo de la cancion acutal es", segundo);
//console.log("El cancion de la cancion acutal es", cancion);
//console.log("El autor de la cancion es", autor);
const mascotas: string[] = ["Bicho", "Kriko", "Daysi"];
const [pos0, pos1, pos2]= mascotas;
console.log("Gato:", pos0);
console.log("Huron 1:",pos1);
console.log("Huron 2:", pos2);
<file_sep>/*
===== Código de TypeScript =====
*/
function classDecorador<T extends { new (...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
};
}
@classDecorador
class MiSuperClass {
public miPropiedad: string = "ABC123";
imprimir () {
console.log("Hola mundo")
}
}
console.log (MiSuperClass);
const miClass =new MiSuperClass();
console.log (miClass.miPropiedad)
| a6b6d17f182cbde6ab3eab6ca7fe10fd284fcbe7 | [
"TypeScript"
] | 11 | TypeScript | vanesaDay17/intro-typescript | db9d21086b2dd111e2d22d9dcfcc6b24639ba70c | a9ec1f24c712c9d4bd02ee6e4e94bc7baed6660d |
refs/heads/master | <repo_name>cburnjohnson/expense-tracker<file_sep>/README.md
# Expense Tracker
#### MERN Stack application that keeps track of the user's expenses.
##### Deployed Version: https://expensetracker47.herokuapp.com/



<file_sep>/client/src/components/login/LoginForm.js
import React, { useState, useContext, useEffect } from 'react';
import { GlobalContext } from '../../context/GlobalState';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUser, faLock } from '@fortawesome/free-solid-svg-icons';
import { Link, Redirect } from 'react-router-dom';
import Alert from '../alerts/Alert';
import Avatar from './ProfilePic';
import Banking from './Banking';
const LoginForm = props => {
const {
login,
isAuthenticated,
token,
loadUser,
error,
setAlert,
removeError
} = useContext(GlobalContext);
const [user, setUser] = useState({
email: '',
password: ''
});
useEffect(() => {
if (token) {
loadUser();
}
if (error) {
setAlert(error);
removeError();
}
// eslint-disable-next-line
}, [error]);
const onSubmit = e => {
e.preventDefault();
login(user);
};
if (isAuthenticated) {
return <Redirect to='/' />;
}
return (
<div className='login-page-container'>
<div className='img'>
<Banking />
</div>
<div className='login-container'>
<form onSubmit={onSubmit}>
<Avatar />
<h2>Login</h2>
<Alert />
<div className='input-div one'>
<div className='i'>
<FontAwesomeIcon icon={faUser} />
</div>
<div>
<h5>Email</h5>
<input
type='text'
className='input'
onFocus={e =>
e.target.parentNode.parentNode.classList.add(
'focus'
)
}
onBlur={e =>
e.target.parentNode.parentNode.classList.remove(
'focus'
)
}
value={user.email}
onChange={e =>
setUser({ ...user, email: e.target.value })
}
/>
</div>
</div>
<div className='input-div two'>
<div className='i'>
<FontAwesomeIcon icon={faLock} />
</div>
<div>
<h5>Password</h5>
<input
type='password'
className='input'
onFocus={e =>
e.target.parentNode.parentNode.classList.add(
'focus'
)
}
onBlur={e =>
e.target.parentNode.parentNode.classList.remove(
'focus'
)
}
value={user.password}
onChange={e =>
setUser({
...user,
password: e.target.value
})
}
/>
</div>
</div>
<Link to='/register'>Register here</Link>
<input type='submit' value='Login' className='btn' />
</form>
</div>
</div>
);
};
export default LoginForm;
<file_sep>/client/src/components/pages/Home.js
import React, { useContext, useEffect } from 'react';
import { GlobalContext } from '../../context/GlobalState';
import Header from '../transactions/Header';
import Balance from '../transactions/Balance';
import IncomeExpenses from '../transactions/IncomeExpenses';
import TransactionList from '../transactions/TransactionList';
import AddTransaction from '../transactions/AddTransaction';
const Home = () => {
const { loadUser } = useContext(GlobalContext);
useEffect(() => {
loadUser();
// eslint-disable-next-line
}, []);
return (
<>
<Header />
<div className='container'>
<Balance />
<IncomeExpenses />
</div>
<div className='transaction-grid'>
<div className='transaction-list'>
<TransactionList />
</div>
<div className='transaction-form'>
<AddTransaction />
</div>
</div>
</>
);
};
export default Home;
<file_sep>/client/src/components/transactions/Header.js
import React, { useContext } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSignOutAlt } from '@fortawesome/free-solid-svg-icons';
import { GlobalContext } from '../../context/GlobalState';
const Header = () => {
const { logout } = useContext(GlobalContext);
return (
<>
<h2>
<span className='highlight'>E</span>xp
<span className='highlight'>e</span>ns
<span className='highlight'>e</span> Tr
<span className='highlight'>a</span>ck
<span className='highlight'>e</span>r
</h2>
<button id='logout' onClick={logout}>
<span className='logout-text'>Logout</span>
<FontAwesomeIcon icon={faSignOutAlt} className='logout-icon' />
</button>
</>
);
};
export default Header;
<file_sep>/client/src/components/register/RegisterForm.js
import React, { useContext, useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUser, faLock } from '@fortawesome/free-solid-svg-icons';
import { Link, Redirect } from 'react-router-dom';
import Avatar from '../login/ProfilePic';
import SignUpSVG from './SignUpSVG';
import Alert from '../alerts/Alert';
import { GlobalContext } from '../../context/GlobalState';
const LoginForm = () => {
const {
registerUser,
isAuthenticated,
loadUser,
token,
setAlert,
error,
removeError
} = useContext(GlobalContext);
const [user, setUser] = useState({
email: '',
password: '',
password2: ''
});
useEffect(() => {
if (token) {
loadUser();
}
if (error) {
setAlert(error);
removeError();
}
// eslint-disable-next-line
}, [error]);
if (isAuthenticated) {
return <Redirect to='/' />;
}
const onSubmit = e => {
e.preventDefault();
if (user.password !== <PASSWORD>) {
return setAlert('Passwords must match');
}
const newUser = {
email: user.email,
password: <PASSWORD>
};
registerUser(newUser);
};
return (
<div className='login-page-container'>
<div className='img'>
<SignUpSVG />
</div>
<div className='login-container'>
<form onSubmit={onSubmit}>
<Avatar />
<h2>Register</h2>
<Alert />
<div className='input-div one'>
<div className='i'>
<FontAwesomeIcon icon={faUser} />
</div>
<div>
<h5>Email</h5>
<input
type='email'
className='input'
onFocus={e =>
e.target.parentNode.parentNode.classList.add(
'focus'
)
}
onBlur={e =>
e.target.parentNode.parentNode.classList.remove(
'focus'
)
}
value={user.email}
onChange={e =>
setUser({ ...user, email: e.target.value })
}
/>
</div>
</div>
<div className='input-div two'>
<div className='i'>
<FontAwesomeIcon icon={faLock} />
</div>
<div>
<h5>Password</h5>
<input
type='password'
className='input'
minLength='6'
onFocus={e =>
e.target.parentNode.parentNode.classList.add(
'focus'
)
}
onBlur={e =>
e.target.parentNode.parentNode.classList.remove(
'focus'
)
}
value={user.password}
onChange={e =>
setUser({
...user,
password: e.target.value
})
}
/>
</div>
</div>
<div className='input-div two'>
<div className='i'>
<FontAwesomeIcon icon={faLock} />
</div>
<div>
<h5>Confirm Password</h5>
<input
type='password'
className='input'
minLength='6'
onFocus={e =>
e.target.parentNode.parentNode.classList.add(
'focus'
)
}
onBlur={e =>
e.target.parentNode.parentNode.classList.remove(
'focus'
)
}
value={user.password2}
onChange={e =>
setUser({
...user,
password2: e.target.value
})
}
/>
</div>
</div>
<Link to='/login'>Already have an account?</Link>
<input type='submit' value='Register' className='btn' />
</form>
</div>
</div>
);
};
export default LoginForm;
| 63a980adffce14f30685a919885513f7f1e8752a | [
"Markdown",
"JavaScript"
] | 5 | Markdown | cburnjohnson/expense-tracker | 0f2874034da3c4862e1fd6b4433f1da32d0b72a0 | 4f8f4b9f627da721d8e5ba022b05892f71c7961b |
refs/heads/master | <repo_name>canuradha/ML-Tests<file_sep>/SVM_Manual.py
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import numpy as np
df = pd.read_csv('Iris.csv')
x = df['SepalLengthCm']
y = df['PetalLengthCm']
setosa_x = x[:50]
setosa_y = y[:50]
versicolor_x = x[50:]
versicolor_y = y[50:]
plt.figure(figsize=(8,6))
plt.scatter(setosa_x, setosa_y, marker='+', color='blue')
plt.scatter(versicolor_x, versicolor_y, marker='_', color='green')
# plt.show()
Y = []
df = df.sample(frac=1).reset_index(drop=True)
# print(df)
target = df['Species']
for sp in target:
if(sp == 'Iris-setosa'):
Y.append(-1)
else:
Y.append(1)
X = df.loc[:,'SepalLengthCm':'PetalLengthCm'].values.tolist()
# print(X)
x_train, x_test, y_train, y_test = train_test_split(X, Y, train_size = 0.8)
x_train = np.array(x_train)
x_test = np.array(x_test)
y_train = np.array(y_train).reshape(80,1)
y_test = np.array(y_test).reshape(20,1)
## SVM
train_feature_1 = x_train[:,0].reshape(80,1)
train_feature_2 = x_train[:,1].reshape(80,1)
w1 = np.zeros((80,1))
w2 = np.zeros((80,1))
epochs = 1
alpha = 0.0001
prod = []
while(epochs < 1000):
y = w1* train_feature_1 + w2 * train_feature_2
prod = y* y_train
# print(epochs)
count = 0
for val in prod:
if(val >= 1):
cost = 0
w1 = w1 - alpha * (2 * 1/epochs * w1)
w2 = w2 - alpha * (2 * 1/epochs * w2)
else:
cost = 1 - val
w1 = w1 + alpha * (train_feature_1[count] * y_train[count] - 2 * 1/epochs * w1)
w2 = w2 + alpha * (train_feature_2[count] * y_train[count] - 2 * 1/epochs * w2)
count += 1
epochs += 1
# test the data
from sklearn.metrics import accuracy_score
#clip the trained data to fit the test data
index = list(range(20,80))
w1 = np.delete(w1,index)
w2 = np.delete(w2,index)
w1 = w1.reshape(20,1)
w2 = w2.reshape(20,1)
## Extract the test data features
test_f1 = x_test[:,0].astype(int).reshape(20,1)
test_f2 = x_test[:,1].astype(int).reshape(20,1)
## Predict
y_pred = w1 * test_f1 + w2 * test_f2
predictions = []
for val in y_pred:
if(val > 1):
predictions.append(1)
else:
predictions.append(-1)
print(accuracy_score(y_test,predictions))<file_sep>/SVM.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import numpy as np
wine = pd.read_csv("../datasets/wine.data", header=None)
wine.columns = [ "Type", "Alcohol", "Malic acid", "Ash","Alcalinity of ash" ,"Magnesium", "Total phenols",
"Flavanoids","Nonflavanoid phenols", "Proanthocyanins", "Color intensity", "Hue", "OD280_OD315" ,"Proline" ]
wine_features = wine.drop(["Type"], axis = 1)
wine_type = wine["Type"]
X_train, X_test, y_train, y_test = train_test_split(wine_features, wine_type, test_size = 0.3, random_state = 42)
reg_param = [ 1, 10, 50, 100, 500, 1000, 5000 ]
gamma = [1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
# for g in gamma:
# model = svm.SVC(kernel='linear', gamma=g)
# print ("training Model....")
# model.fit(X_train, y_train)
# predicted_types = model.predict(X_test)
# print("gamma = ", g, "Accuracy: ")
# print("accuracy: ", accuracy_score(y_test, predicted_types) )
# print("MSE: ", mean_squared_error(y_test, predicted_types))
model = svm.SVC(kernel='linear', gamma=0.01)
model.fit(X_train, y_train)
predicts = model.predict(X_test)
# --------------- Visualizing the predctions--------------------
fig, (ax1, ax2) = plt.subplots(1,2)
X_test.plot.scatter(x='Alcohol', y='OD280_OD315', c=predicts, colormap='Dark2', ax= ax1, title = 'Predicts' )
# plt.subplot(1,2,2)
X_test.plot.scatter(x='Alcohol', y='OD280_OD315', c=y_test, colormap='Dark2' , ax= ax2, title= 'Real Data')
plt.show()
# plt.scatter(features['Alcohol'], X_test['Color intensity'], color=colormap[predicts])<file_sep>/decisionTree.py
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#### the dataset can be found at https://www.kaggle.com/dgomonov/new-york-city-airbnb-open-data
data = pd.read_csv("../datasets/AB_NYC_2019.csv")
# s = (data.dtypes == 'object')
# print(list(s[s].index))
x_features = [
'neighbourhood', 'latitude', 'longitude', 'room_type', 'minimum_nights',
'number_of_reviews', 'availability_365'
]
###### Selecting features without categorical variables.
x_data = data[x_features].select_dtypes(exclude=['object'])
y_data = data['price']
train_X, test_X, train_y, test_y = train_test_split(x_data, y_data, train_size=0.8, random_state=1)
ds_model = DecisionTreeRegressor(max_leaf_nodes=250 ,random_state=1)
ds_model.fit(train_X, train_y)
print("training complete \n\nTesting....")
val_predictions = ds_model.predict(test_X)
error = mean_absolute_error(val_predictions, test_y)
print("error: ", error)
print("Encoding and including Categorical Variables....")
###### Transforming categorical variables
label_x_data = data[x_features].copy()
###### Applying label encoder to "room_types" column
label_encoder = LabelEncoder()
label_x_data['room_type'] = label_encoder.fit_transform(label_x_data['room_type'])
###### Applying one hot encoder to "neighbourhood" column. since there's one column categories are given in a list
OH_encoder = OneHotEncoder(sparse=False, categories=[label_x_data['neighbourhood'].unique()])
# print(label_x_data['neighbourhood'].to_frame())
OH_cols = pd.DataFrame(OH_encoder.fit_transform(label_x_data['neighbourhood'].to_frame()))
###### Removing categorical data and rplacing it with encoded data
num_x_data = label_x_data.drop(['neighbourhood'], axis=1)
x_data_encoded = pd.concat([num_x_data, OH_cols], axis = 1)
print("Encoding complete \n\nTrining Encoded Data...")
train_X, test_X, train_y, test_y = train_test_split(x_data_encoded, y_data, train_size=0.8, random_state=42)
###### the max_leaf_nodes are found as 50 by executing the commented code below
ds_model = DecisionTreeRegressor(max_leaf_nodes=50 ,random_state=42)
ds_model.fit(train_X, train_y)
encoded_predictions = ds_model.predict(test_X)
error = mean_absolute_error(encoded_predictions, test_y)
print("error: ", error)
####### Testing for optimal maximum leaf nodes in the tree
# candidate_max_leaf_nodes = [5, 25, 50, 100, 250, 500]
# for tree_size in candidate_max_leaf_nodes:
# ds_model = DecisionTreeRegressor(max_leaf_nodes=tree_size ,random_state=1)
# ds_model.fit(train_X, train_y)
# ds_model.fit(train_X, train_y)
# encoded_predictions = ds_model.predict(test_X)
# error = mean_absolute_error(encoded_predictions, test_y)
# print("Tree Siez, error: ",tree_size, error)<file_sep>/randomForest.py
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
#### the dataset can be found at https://www.kaggle.com/dgomonov/new-york-city-airbnb-open-data
data = pd.read_csv("../datasets/AB_NYC_2019.csv")
# print(data['neighbourhood'].value_counts())
# print(data['neighbourhood'].value_counts().plot())
# plt.show()
x_features = [
'neighbourhood', 'latitude', 'longitude', 'room_type', 'minimum_nights',
'number_of_reviews', 'availability_365'
]
x_data = data[x_features]
y_data = data['price']
##### Applying label encoder to "room_types" column
label_encoder = LabelEncoder()
x_data['room_type'] = label_encoder.fit_transform(x_data['room_type'])
x_data_w_o_cat = x_data.drop(['neighbourhood'], axis=1)
##### Applying one hot encoder to "neighbourhood" column. since there's one column categories are given in a list
OH_encoder = OneHotEncoder(sparse=False, categories=[x_data['neighbourhood'].unique()])
# print(label_x_data['neighbourhood'].to_frame())
OH_cols = pd.DataFrame(OH_encoder.fit_transform(x_data['neighbourhood'].to_frame()))
###### Removing and adding categorical data with encoded data in the original data
num_x_data = x_data.drop(['neighbourhood'], axis=1)
x_data_encoded = pd.concat([num_x_data, OH_cols], axis = 1)
print("Encoding complete \n\nTrining Encoded Data...")
############ Training model with encoded categorical varibles replaced
# train_X, test_X, train_y, test_y = train_test_split(x_data_encoded, y_data, train_size=0.8, random_state=42)
############ Training model without categorical variables (without 'neighbourhood')
train_X, test_X, train_y, test_y = train_test_split(x_data_w_o_cat, y_data, train_size=0.8, random_state=42)
###### training the random forest & Determining the optimum no of extimators (descion trees)
estimators = [10, 20, 50, 100, 250, 500, 1000]
for est in estimators:
rf_regressor = RandomForestRegressor(random_state= 0, n_estimators=est)
rf_regressor.fit(train_X, train_y)
predictions = rf_regressor.predict(test_X)
error = mean_absolute_error(predictions, test_y)
print("Estimators, error: ", est, error)
##### Vizualizing the results.
# X_grid = np.arange(min(test_X['minimum_nights']), max(test_X['minimum_nights']), 1)
# # print(X_grid)
# X_grid = X_grid.reshape((len(X_grid), 1))
# plt.scatter(test_X['minimum_nights'], test_y, color='red')
# plt.scatter(test_X['minimum_nights'], predictions, color='blue')
# plt.show()<file_sep>/CNN/MNISTCNN.py
# import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import struct
# -----------------all the necessary data to read the data file is given at http://yann.lecun.com/exdb/mnist/
Train_Data = open('../../Data/MNIST/train-images-idx3-ubyte', 'rb')
Train_Labels = open('../../Data/MNIST/train-labels-idx1-ubyte', 'rb')
# -----------------Skip the magic number
Train_Data.read(4)
Train_Labels.read(4)
# -----------------Get Dimensions
imageCount = struct.unpack('>i', Train_Data.read(4))[0]
imageSize = [struct.unpack('>i', Train_Data.read(4))[0], struct.unpack('>i', Train_Data.read(4))[0]]
LabelCount = struct.unpack('>i', Train_Labels.read(4))[0]
# -----------------Create a numpy array with all the images
Train_X = np.zeros([imageCount, imageSize[0], imageSize[1]], dtype=float)
# print(np.prod(imageSize))
for i in range(imageCount):
Train_X[i] = np.frombuffer(Train_Data.read(np.prod(imageSize)), dtype=np.uint8).reshape(imageSize)
# first_image = np.frombuffer(Train_Data.read(28* 28), dtype=np.uint8).reshape(28, 28)
Labels = np.frombuffer(Train_Labels.read(), dtype=np.uint8)
# plt.imshow(Train_X[0])
# plt.show()
<file_sep>/randomForest2.py
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from category_encoders import TargetEncoder
from collections import defaultdict
####### Dataset can be found at https://archive.ics.uci.edu/ml/datasets/Adult
adult = pd.read_csv("../datasets/US income/adult.data", header=None)
adult.columns = ["age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation",
"relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "salary"]
# names = pd.read_csv("lrn/datasets/US income/adult.names")
# adult = adult.dropna()
# adult = adult.sample(frac = 1).reset_index(drop = True)
# print(adult.head(10))
####### features to train
features = adult.drop(['education', 'salary'], axis = 1)
####### target feature set encoding
target = adult['salary'].to_frame()
target = target.replace([' <=50K', ' >50K'], [0, 1])
target = target['salary']
# print(features.head(20))
####### determinig missing values
# for col in features.columns:
# null_d = features.loc[features[col] == ' ?']
# print(col, ':', null_d.shape)
######### Train test Split
fet_train, fet_test, tar_train, tar_test = train_test_split(features, target, test_size= 0.2, random_state = 42)
# print(fet_train.head(10))
##### Categorical Encodings
########## lable encoding multiple columns
lbl_encoded_fet = ['workclass', 'sex']
encoder = defaultdict(LabelEncoder)
lbl_fet_train = fet_train[lbl_encoded_fet].apply(lambda x : encoder[x.name].fit_transform(x))
lbl_fet_test = fet_test[lbl_encoded_fet].apply(lambda x: encoder[x.name].transform(x))
# print(lbl_fet_test)
###### replacing original columns with concatenated columns
fet_train = pd.concat([fet_train.drop(lbl_encoded_fet, axis = 1), lbl_fet_train], axis = 1)
fet_test = pd.concat([fet_test.drop(lbl_encoded_fet, axis = 1), lbl_fet_test], axis = 1)
###### checking for an even distribution of selected columns for one hot encoding
# print(features['relationship'].value_counts()) # somewhat okay
# print(features['race'].value_counts()) # bad, not evenly distributed
##### One hot encoding 'relationships' using pandas
# print(fet_train['relationship'].unique())
dummy_train = pd.get_dummies(fet_train['relationship'], prefix = 'rel_')
dummy_test = pd.get_dummies(fet_test['relationship'], prefix = 'rel_')
# print(dummy_test.head(10))
###### filling cells if values that were missing in the training set but present in the test set with 0
dummy_test.reindex(columns = dummy_train.columns, fill_value = 0)
##### Replacing categorical column with encoded column
fet_train = fet_train.drop(['relationship'], axis = 1).join(dummy_train)
fet_test = fet_test.drop(['relationship'], axis = 1).join(dummy_test)
##### target encoding rest of the categorical features
target_enc = TargetEncoder()
fet_train = target_enc.fit_transform(fet_train, tar_train)
fet_test = target_enc.transform(fet_test)
# print(fet_train.head(10))
# print(fet_train.shape)
##### Training Random Forest and testing.
estimators = [10, 20, 50, 100, 250, 500, 1000]
# for est in estimators:
# print("Estimator: ", est)
# for leaves in estimators:
# rf_classifier = RandomForestClassifier(random_state= 0, n_estimators=est, max_leaf_nodes = leaves)
# rf_classifier.fit(fet_train, tar_train)
# predictions = rf_classifier.predict(fet_test)
# error = mean_absolute_error(predictions, tar_test)
# print("Leaves : ",leaves, " error: ", error)
rf_classifier = RandomForestClassifier(random_state= 0, n_estimators=500, max_leaf_nodes = 500)
rf_classifier.fit(fet_train, tar_train)
############# Validating the model
adult_Validate = pd.read_csv("../datasets/US income/adult.test", header=None)
adult_Validate.columns = adult.columns
valid_feat = adult_Validate.drop(['education', 'salary'], axis = 1)
valid_target = adult_Validate['salary'].to_frame()
valid_target = valid_target.replace([' <=50K.', ' >50K.'], [0, 1])
valid_target = valid_target['salary']
# print(adult_Validate.head())
##### Encoding categorical data in the validation set
##Label Encoding
valid_label_enc = valid_feat[lbl_encoded_fet].apply(lambda x: encoder[x.name].transform(x))
valid_feat = pd.concat([valid_feat.drop(lbl_encoded_fet, axis = 1), valid_label_enc], axis = 1)
## One hot encoding
dummy_valid = pd.get_dummies(valid_feat['relationship'], prefix = 'rel_')
dummy_valid.reindex(columns = dummy_train.columns, fill_value = 0)
valid_feat = valid_feat.drop(['relationship'], axis = 1).join(dummy_valid)
## Target Encoding
valid_feat = target_enc.transform(valid_feat)
# #####valid predictions
valid_predict = rf_classifier.predict(valid_feat)
valid_error = mean_absolute_error(valid_predict, valid_target)
print("error: ", valid_error)
<file_sep>/kMeans.py
import pandas as pd
import numpy as np
from numpy.linalg import norm
import matplotlib.pyplot as plt
np.random.seed(42)
data = pd.read_csv('../datasets/iris/Iris.csv')
feature_set = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']
features = data[feature_set]
clusters=3
# print(features.shape[1])
# # print(centeroids)
def init_centeroids(clusters, features):
centeroids = np.zeros([clusters, features.shape[1]]).transpose()
feature_max = features.loc[features[:].idxmax()].max()
for idx,value in enumerate(feature_max):
centeroids[idx] = np.random.randint(1, feature_max[idx], clusters)
centeroids = centeroids.transpose()
return centeroids
def compute_distance(features, clusters, centeroids):
distance = np.zeros([features.shape[0], clusters])
for i in range(clusters):
distance[:, i] = norm(features - centeroids[i,:], axis=1)
return distance
def within_cluter_sse(features, centeroids, labels):
distances = np.zeros(features.shape[0])
for i in range(clusters):
distances[labels == i] = norm(features[i == labels] - centeroids[i], axis=1)
return np.sum(np.absolute(distances))
def get_labels(distances):
return np.argmin(distances, axis=1)
def update_centeroid(features, distances, clusters, labels):
centeroids = np.zeros([clusters, features.shape[1]])
for k in range(clusters):
# print(np.mean(features[k == lables], axis=0))
centeroids[k, :] = np.mean(features[labels == k], axis= 0)
# print(within_cluter_sse(features,centeroids, labels))
return centeroids
def centeroid_distance_change(old, new):
return np.absolute(new - old)
def plot_data(features, centeroids, labels=None):
# fig = plt.figure(figsize=(5,5))
plt.clf()
colormap = [np.random.rand(3,) for i in range(clusters)]
if type(labels).__module__ != 'numpy':
plt.scatter(features.iloc[:,0], features.iloc[:,1], color='k')
else:
for i, value in enumerate(np.array([features.iloc[:,0], features.iloc[:,1]]).transpose()):
plt.scatter(value[0], value[1], color=colormap[labels[i]])
for i,point in enumerate(centeroids):
plt.scatter(point[0], point[1], color=colormap[i], marker='*', s=200, edgecolor='k')
plt.show()
def fit(features, clusters, sensivity = 0.001):
centeroids = init_centeroids(clusters, features)
plot_data(features, centeroids)
i = 0
while True:
distances = compute_distance(features,clusters, centeroids)
labels = get_labels(distances)
centeroids_new = update_centeroid(features, distances, clusters, labels)
# print(centeroid_distance_change(centeroids, centeroids_new))
if((centeroid_distance_change(centeroids, centeroids_new)).any() <= sensivity):
print('finished')
break
centeroids = centeroids_new
if(i % 3 == 0):
plot_data(features, centeroids, labels)
i += 1
plot_data(features, centeroids, labels)
return centeroids
fit(features, clusters)
<file_sep>/README.md
# ML-Tests
#### Current work
* Decision tree regression usage implementation from scikit learn
* Random Forest regression implementation.
* Random Forest Classifier implementation.
* Categorical data encoding testing
+ label Encoding
+ One-hot Encoding
+ Target Encoding
| 4390f416a093c7e8c1f595379e680aaa87dd4d4b | [
"Markdown",
"Python"
] | 8 | Python | canuradha/ML-Tests | 2f028bbb0181637be18cac434c64562d23d254a1 | 2c6039e9efe5382f5b95d1894c0c1adc70342ac1 |
refs/heads/main | <file_sep>asgiref==3.3.1
certifi==2020.12.5
chardet==4.0.0
Django==3.1.5
idna==2.10
pytz==2020.5
requests==2.25.1
sqlparse==0.4.1
urllib3==1.26.2
vaderSentiment==3.3.2
<file_sep>from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.template.response import TemplateResponse
# Create your views here.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
def Home(request):
sid_obj = SentimentIntensityAnalyzer()
res = request.POST
feedback = res.get('subject', False)
if feedback:
sentiment_dict = sid_obj.polarity_scores(feedback)
sentiment_value = sentiment_dict['compound']
print(sentiment_value)
if sentiment_dict['compound'] >= 0.1 :
sentiment = "Positive"
elif sentiment_dict['compound'] <= - 0.1 :
sentiment = "Negative"
else:
sentiment = "Neutral"
args = {}
args['value'] = sentiment_value
args['feedback'] = feedback
args['sentiment'] = sentiment
else:
args = {}
args['value'] = ''
args['feedback'] = ''
args['sentiment'] = ''
return TemplateResponse(request, 'products/home.html', args)
<file_sep># from django.db import models
# # Create your models here.
# # Note to self: Run makemigrations and migrate every time you make a change to this file
# class Product(models.Model):
# title = models.CharField(blank=True,max_length=100)
# descript = models.TextField(blank=True, null=True)
# price = models.DecimalField(max_digits=10 ,decimal_places=2)
# feedback = models.TextField(blank=True)
from django.db import models
class Review(models.Model):
author = models.CharField(max_length=150)
author_email = models.EmailField()
review_title = models.CharField(max_length=300, null=True)
review_body = models.TextField(blank=True)
creation_date = models.DateTimeField(auto_now_add=True, blank=True)
sentiment_score = models.DecimalField(max_digits=5, decimal_places=4)
def is_critical(self):
return True if self.sentiment_score < -0.2 else False
def __str__(self):
return self.review_title<file_sep># Generated by Django 3.1.5 on 2021-01-06 05:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0002_auto_20210105_1723'),
]
operations = [
migrations.CreateModel(
name='Review',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('author', models.CharField(max_length=150)),
('author_email', models.EmailField(max_length=254)),
('review_title', models.CharField(max_length=300, null=True)),
('review_body', models.TextField(blank=True)),
('creation_date', models.DateTimeField(auto_now_add=True)),
('sentiment_score', models.DecimalField(decimal_places=4, max_digits=5)),
],
),
migrations.DeleteModel(
name='Product',
),
]
<file_sep># Feedback-Sentiment
## How to run the project
Run the following commands on the Windows command prompt (Assuming you have git,Python and virtualenv installed):
Cloning the project files to your machine<br>
<ol>
<li> git clone https://github.com/Blues1998/Feedback-Sentiment.git<br>
Changing the active directory <br>
<li> cd Feedback-Sentiment<br>
Creating a virtual environment <br>
<li> python -m venv venv<br>
Activating the virtual environment <br>
<li> venv\Scripts\activate<br>
Installing project dependencies <br>
<li> pip install -r requirements.txt<br>
Changing the active directory <br>
<li> cd src <br>
Running the project <br>
<li> python manage.py runserver
<li> Navigate to the local host on which the django-server is running (Normally http://127.0.0.1:8000/)
</ol>
| fb99de3e2ff46ce75b9e40d26dc4cf9f9baa58a7 | [
"Markdown",
"Python",
"Text"
] | 5 | Text | Blues1998/Feedback-Sentiment | 6ff51466855f8989a1f170a697a05e8b1ce27299 | 232258655948c479ff5f964bd382bd55c5518e25 |
refs/heads/master | <file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersAndTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users_and_tasks', function (Blueprint $table) {
$table->bigInteger('task_id')->primary();
$table->integer('emp_id');
$table->string('status');
$table->foreign('emp_id')
->references('emp_id')->on('employees')
->onDelete('cascade');
// $table->foreign('task_id')
// ->references('task_id')->on('tasks')
// ->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users_and_tasks');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Tasks;
use App\Categories;
use App\Employees;
use App\UsersAndTasks;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TasksController extends Controller
{
public function createTask(Request $request) {
// Create a new task
$task = new Tasks();
$task->category_name = $request->input("category_name");
$task->desc = $request->input("desc");
$task->status = "pending";
// Save task
$task->save();
//Get category_id from category
$category_id = Categories::where('category_name', 'LIKE', '%'.$request->input("category_name").'%')->get();
$category_id = $category_id[0]->category_id;
//Get all employees of this category_id
$all_eid = Employees::where('category_id', $category_id)->get();
//Get number of tasks of each employee
$emptask_count = DB::table('users_and_tasks')
->select(DB::raw('emp_id, count(*) as numTasks'))
->groupBy('emp_id')
->where('status', "pending")
->get();
//Get the employee id who has the minimum number of tasks
$minTask = 100000000;
$minTaskEid = -1;
foreach ($emptask_count as $item) {
if($item->numTasks < $minTask) {
$minTask = $item->numTasks;
$minTaskEid = $item->emp_id;
}
}
//Get auto increment id(current task id)
$taskId = DB::table('tasks')->max('task_id');
//Insert into users_and_tasks table
$new_user_task_pair = new UsersAndTasks();
$new_user_task_pair->emp_id = $minTaskEid;
$new_user_task_pair->task_id = $taskId;
$new_user_task_pair->status = "pending";
$new_user_task_pair->save();
return $task;
// return response()->json($task);
}
}
| e66d3f563222f8977fed03915ef97817f51ae9d1 | [
"PHP"
] | 2 | PHP | arsh317/ticketing-backend | a5dd3f60bbc24d5aa39d47aa19bd46faebcbc44d | 9344e2cf387d4a0724ce1f084262a3dc165729b6 |
refs/heads/master | <file_sep>#include <stdio.h>
//For string Functions
#include <string.h>
//For calloc
#include <stdlib.h>
//For read
#include <unistd.h>
//For open
#include <fcntl.h>
//For inet_ntop and all the bulshit with the networking.
#include <arpa/inet.h>
#define MAX_ERRORS 20
//Type definitions
typedef struct sockaddr_in sockaddr_in;
//Functions
void reverse(char* s)
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = *(s + i);
*(s + i) = *(s + j);
*(s + j) = c;
}
}
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0)
n = -n;
i = 0;
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
char* get_line(int* data_fd)
{
char c;
char* buffer = calloc(1, 256 * sizeof(char));
int index = 0;
int if_readed = 0;
while(((if_readed = read(*data_fd, &c, 1)) != 0) && c!= '\n')
{
*(buffer + index) = c;
index++;
}
if (if_readed == 0) {
return NULL;
}
return buffer;
}
void add_new_user(char* ip_address, char* credentials, char* file_name)
{
int data_fd = 0;
char user_data[150] = {'\0'};
data_fd = open(file_name, O_WRONLY | O_APPEND);
if (data_fd < 0) {
printf("%s\n", "Cant open file");
return;
}
strcat(user_data, ip_address);
strcat(user_data, " ");
strcat(user_data, credentials);
strcat(user_data, " ");
strcat(user_data, "0");
strcat(user_data, "\n");
write(data_fd, user_data, strlen(user_data));
close(data_fd);
}
void increment_errors(char* ip_address, char* file_name, int errors)
{
int data_fd = 0;
int dest_fd = 0;
char* buffer = NULL;
char* first_space = NULL;
char* last_space = NULL;
char errors_as_string[3] = {'\0'};
char current_ip[INET_ADDRSTRLEN];
data_fd = open(file_name, O_RDONLY);
if (data_fd < 0) {
printf("%s\n", "Cant open file");
return;
}
dest_fd = open("result.txt", O_CREAT | O_WRONLY, 0777);
if (dest_fd < 0) {
printf("%s\n", "Cant open file");
close(data_fd);
return;
}
while((buffer = get_line(&data_fd)) != NULL) {
if (0 < strlen(buffer)) {
memset(current_ip, '\0', sizeof(current_ip));
first_space = strchr(buffer, ' ');
strncpy(current_ip, buffer, (int)(first_space - buffer));
if (0 == strcmp(ip_address, current_ip)) {
last_space = strrchr(buffer, ' ');
itoa(errors + 1, errors_as_string);
strcpy(last_space + 1, errors_as_string);
}
strcat(buffer, "\n");
write(dest_fd, buffer, strlen(buffer));
}
}
close(data_fd);
close(dest_fd);
remove(file_name);
rename ("result.txt", file_name);
return;
}
char* search_for_info(const char* ip_address, int* status, const char* file_name, int* errors)
{
int data_fd = 0;
char* buffer = NULL;
char* first_space = NULL;
char* last_space = NULL;
char* credentials = NULL;
char current_ip[INET_ADDRSTRLEN];
int number_of_bytes = 0;
data_fd = open(file_name, O_RDONLY);
if (data_fd < 0) {
printf("%s\n", "Cant open file");
*status = -1;
return credentials;
}
while((buffer = get_line(&data_fd)) != NULL) {
if (0 < strlen(buffer)) {
memset(current_ip, '\0', sizeof(current_ip));
first_space = strchr(buffer, ' ');
strncpy(current_ip, buffer, (int)(first_space - buffer));
if (0 == strcmp(ip_address, current_ip)) {
last_space = strrchr(buffer, ' ');
*errors = atoi(last_space + 1);
if (*errors >= MAX_ERRORS) {
free(buffer);
close(data_fd);
*status = -1;
return credentials;
}
number_of_bytes = (int)(last_space - first_space) - 1;
credentials = calloc(1, number_of_bytes * sizeof(char));
strncpy(credentials, first_space + 1, number_of_bytes);
free(buffer);
close(data_fd);
*status = 1;
return credentials;
}
}
free(buffer);
}
close(data_fd);
*status = 0;
return credentials;
}
void run_server(int server_fd)
{
int client_fd;
int client_length = 0;
int status = 0;
int errors = 0;
int choose_username_length = 0;
int enter_username_length = 0;
char ip_address[INET_ADDRSTRLEN];
char* credentials = NULL;
char* choose_username = "Choose username and password";
char* enter_username = "Enter username and <PASSWORD>";
char* client_message = NULL;
sockaddr_in client_address;
client_length = sizeof(client_address);
choose_username_length = strlen(choose_username);
enter_username_length = strlen(enter_username);
printf("%s\n", "Server is running");
listen(server_fd , 5);
while (1) {
memset(&client_address, 0, sizeof(client_address));
client_fd = accept(server_fd, (struct sockaddr*) &client_address, (socklen_t *) &client_length);
if (client_fd >= 0) {
printf("%s\n", "Some client is connected");
client_message = calloc(1, 100 * sizeof(char));
memset(ip_address, '\0', INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(client_address.sin_addr), ip_address, INET_ADDRSTRLEN);
credentials = search_for_info(ip_address, &status, "data.txt", &errors);
if (status > 0) {
status = write(client_fd, enter_username, enter_username_length);
if (status != -1) {
status = read(client_fd, client_message, 100);
if (status != -1) {
if (0 == strcmp(credentials, client_message)) {
printf("%s\n", "Client can connect to server");
} else {
printf("%s\n", "Increment errors about this client");
increment_errors(ip_address, "data.txt", errors);
}
}
}
free(credentials);
} else if (status == 0) {
status = write(client_fd, choose_username, choose_username_length);
if (status != -1) {
status = read(client_fd, client_message, 100);
if (status != -1) {
add_new_user(ip_address, client_message, "data.txt");
printf("%s\n", "New user is aded to the server");
}
}
}
close(client_fd);
}
free(client_message);
}
}
int main(int argc, char** args)
{
int status = 0;
int server_fd = 0;
int port_number = 5001;
sockaddr_in server_address;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
(void) printf("%s\n", "Error on creating socket");
return -1;
}
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(port_number);
status = bind(server_fd, (struct sockaddr* )&server_address, sizeof(server_address));
if (status < 0) {
(void) printf("%s\n", "Error on binding");
return -1;
}
run_server(server_fd);
close(server_fd);
return 0;
}
| 2fdbd8787557bfae0a52c0d49379a5cd23ca2257 | [
"C"
] | 1 | C | p-v-peev/SystemProgrraming | 8514feceea3870a27512d6336924f20306815f1e | b1ba2357bc51425d2a9f5ed81d7974bef15bca3b |
refs/heads/master | <repo_name>vlevko/go_mysql_task<file_sep>/main.go
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"strings"
"time"
)
const (
configFile = "config.json"
)
type configuration struct {
API string
Year int
CountryCode string
Location string
APILayout string
OutputLayout string
APITimeout uint
UseFakeAPI bool
UseFakeDate bool
Date string
}
type holiday struct {
Date string
LocalName string
Name string
CountryCode string
Fixed bool
Global bool
Counties []string
LaunchYear int
Type string
}
func exitWithErrorMessage(err error) {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
func loadConfiguration(useConfigFile bool) configuration {
var cfg configuration
if useConfigFile {
fp, err := os.Open(configFile)
if err != nil {
exitWithErrorMessage(err)
}
defer fp.Close()
if err = json.NewDecoder(fp).Decode(&cfg); err != nil {
exitWithErrorMessage(err)
}
} else {
cfg.API = "https://date.nager.at/api/v2/publicholidays/"
cfg.Year = 2020
cfg.CountryCode = "UA"
cfg.Location = "Europe/Kiev"
cfg.APILayout = "2006-01-02"
cfg.OutputLayout = "Jan 02"
cfg.APITimeout = 10
cfg.UseFakeAPI = false
cfg.UseFakeDate = false
cfg.Date = "2020-05-18"
}
return cfg
}
func loadHolidaysAPIData(cfg configuration) []holiday {
var holidays []holiday
if cfg.UseFakeAPI {
holidays = []holiday{
holiday{"2020-01-01", "Новий Рік", "New Year's Day", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-01-07", "Різдво", "(Julian) Christmas", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-03-08", "Міжнародний жіночий день", "International Women's Day", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-04-19", "Великдень", "(Julian) Easter Sunday", "UA", false, true, []string{}, 0, "Public"},
holiday{"2020-05-01", "День праці", "International Workers' Day", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-05-09", "День перемоги над нацизмом у Другій світовій війні", "Victory day over Nazism in World War II", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-06-07", "Трійця", "(<NAME>", "UA", false, true, []string{}, 0, "Public"},
holiday{"2020-06-28", "День Конституції", "Constitution Day", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-08-24", "День Незалежності", "Independence Day", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-10-14", "День захисника України", "Defender of Ukraine Day", "UA", true, true, []string{}, 0, "Public"},
holiday{"2020-12-25", "Різдво", "(Gregorian and Revised Julian) Christmas", "UA", true, true, []string{}, 0, "Public"},
}
} else {
httpClient := &http.Client{Timeout: time.Duration(cfg.APITimeout) * time.Second}
resp, err := httpClient.Get(fmt.Sprintf("%s/%d/%s", strings.Trim(cfg.API, "/"), cfg.Year, cfg.CountryCode))
if err != nil {
exitWithErrorMessage(err)
}
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&holidays); err != nil {
exitWithErrorMessage(err)
}
}
return holidays
}
func adjustWeekend(t time.Time, d time.Time, cfg configuration) string {
var w string
extendedWeekend := ", and the weekend will last 3 days: %s - %s"
remainingWeekend := ", and the weekend will last to %s"
if t.Weekday() == time.Friday || t.Weekday() == time.Saturday {
w = fmt.Sprintf(extendedWeekend, t.Format(cfg.OutputLayout), t.AddDate(0, 0, 2).Format(cfg.OutputLayout))
} else if t.Weekday() == time.Sunday {
if t.Equal(d) {
w = fmt.Sprintf(remainingWeekend, t.AddDate(0, 0, 1).Format(cfg.OutputLayout))
} else {
w = fmt.Sprintf(extendedWeekend, t.AddDate(0, 0, -1).Format(cfg.OutputLayout), t.AddDate(0, 0, 1).Format(cfg.OutputLayout))
}
} else if t.Weekday() == time.Monday {
if t.AddDate(0, 0, -1).Equal(d) {
w = fmt.Sprintf(remainingWeekend, t.AddDate(0, 0, 1).Format(cfg.OutputLayout))
} else if !t.Equal(d) {
w = fmt.Sprintf(extendedWeekend, t.AddDate(0, 0, -2).Format(cfg.OutputLayout), t.Format(cfg.OutputLayout))
}
}
return w
}
func timeToDate(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, t.Location())
}
func loadLocalDate(cfg configuration, holidays []holiday) (time.Time, []holiday) {
loc, err := time.LoadLocation(cfg.Location)
if err != nil {
exitWithErrorMessage(err)
}
var dateInLoc time.Time
if cfg.UseFakeDate {
dateInLoc, err = time.ParseInLocation(cfg.APILayout, cfg.Date, loc)
if err != nil {
exitWithErrorMessage(err)
}
} else {
dateInLoc = timeToDate(time.Now().In(loc))
}
if !cfg.UseFakeAPI && cfg.Year != dateInLoc.Year() {
fmt.Fprintf(os.Stderr, "warning: API data has wrong date, retrieving actual data...\n")
cfg.Year = dateInLoc.Year()
holidays = loadHolidaysAPIData(cfg)
}
return dateInLoc, holidays
}
func showNextHoliday(cfg configuration, holidays []holiday) {
dateInLoc, holidays := loadLocalDate(cfg, holidays)
for i, h := range holidays {
t, err := time.ParseInLocation(cfg.APILayout, h.Date, dateInLoc.Location())
if err != nil {
exitWithErrorMessage(err)
}
if t.Before(dateInLoc) {
if i+1 == len(holidays) {
if cfg.UseFakeDate || cfg.UseFakeAPI {
fmt.Fprintf(os.Stderr, "warning: wrong configuration or no more holidays this year, trying to retrieve first holiday in next year...\n")
}
cfg.Year++
holidays = loadHolidaysAPIData(cfg)
h = holidays[0]
t, err = time.ParseInLocation(cfg.APILayout, h.Date, dateInLoc.Location())
if err != nil {
exitWithErrorMessage(err)
}
fmt.Printf("The next holiday is %s, %s%s\n", h.Name, t.Format(cfg.OutputLayout), adjustWeekend(t, dateInLoc, cfg))
}
continue
} else if t.Equal(dateInLoc) {
fmt.Printf("Today is %s, %s%s\n", h.Name, t.Format(cfg.OutputLayout), adjustWeekend(t, dateInLoc, cfg))
} else {
fmt.Printf("The next holiday is %s, %s%s\n", h.Name, t.Format(cfg.OutputLayout), adjustWeekend(t, dateInLoc, cfg))
}
break
}
}
func parseArgumetns() bool {
useConfigFile := flag.Bool("conf", false, "load configuration from 'config.json' file")
flag.Parse()
return *useConfigFile
}
func main() {
useConfigFile := parseArgumetns()
cfg := loadConfiguration(useConfigFile)
holidays := loadHolidaysAPIData(cfg)
showNextHoliday(cfg, holidays)
}
<file_sep>/current_managers.sql
SELECT
`departments`.`dept_name` AS 'department',
`employees`.`first_name` AS 'first name',
`employees`.`last_name` AS 'last name',
`titles`.`title`,
`salaries`.`salary`
FROM `employees`
INNER JOIN `dept_manager`
ON `employees`.`emp_no` = `dept_manager`.`emp_no`
INNER JOIN `departments`
ON `dept_manager`.`dept_no` = `departments`.`dept_no`
INNER JOIN `titles`
ON `employees`.`emp_no` = `titles`.`emp_no`
INNER JOIN `salaries`
ON `employees`.`emp_no` = `salaries`.`emp_no`
WHERE `dept_manager`.`to_date` > NOW()
AND `titles`.`to_date` > NOW()
AND `salaries`.`to_date` > NOW()<file_sep>/all_departments.sql
SELECT
`departments`.`dept_name` AS 'department',
COUNT(`employees`.`emp_no`) AS 'employee count',
SUM(`salaries`.`salary`) AS 'sum salary'
FROM `departments`
INNER JOIN `dept_emp`
ON `departments`.`dept_no` = `dept_emp`.`dept_no`
INNER JOIN `employees`
ON `dept_emp`.`emp_no` = `employees`.`emp_no`
INNER JOIN `salaries`
ON `employees`.`emp_no` = `salaries`.`emp_no`
WHERE `dept_emp`.`to_date` > NOW()
AND `salaries`.`to_date` > NOW()
GROUP BY `departments`.`dept_name`<file_sep>/employees_hire_anniversary.sql
SELECT
`departments`.`dept_name` AS 'department',
`titles`.`title`,
`employees`.`first_name` AS 'first name',
`employees`.`last_name` AS 'last name',
`employees`.`hire_date` AS 'hire date',
TIMESTAMPDIFF(YEAR, `employees`.`hire_date`, NOW()) AS 'work years'
FROM `employees`
INNER JOIN `dept_emp`
ON `employees`.`emp_no` = `dept_emp`.`emp_no`
INNER JOIN `departments`
ON `dept_emp`.`dept_no` = `departments`.`dept_no`
INNER JOIN `titles`
ON `employees`.`emp_no` = `titles`.`emp_no`
WHERE `dept_emp`.`to_date` > NOW()
AND `titles`.`to_date` > NOW()
AND MONTH(NOW()) = MONTH(`employees`.`hire_date`)
| bef5a6ba7ffdeea55581242f727dd0eb7f6d2d59 | [
"SQL",
"Go"
] | 4 | Go | vlevko/go_mysql_task | dde08c07613e6323a869d233eaa84fd1264112ee | 908224f986c26d484b0d9c83c9caa301129e2a0a |
refs/heads/master | <file_sep>import { validateEmail } from '../utils/utils'
export function required(value: string) {
if (!value) {
return 'Произошла ошибка. Поле должно быть заполнено'
}
}
export function isEmail(value: string) {
if (!validateEmail(value)) {
return 'Поле должно быть типом E-mail'
}
}
export function minLength(value: string) {
if (value) {
if (value.length < 6) {
return 'Минимальная длинна пароля 6 символов'
}
}
}
export function composeValidators(...validators: Array<Function>) {
return function (value: string) {
return validators.reduce(
(error, validator) => error || validator(value),
undefined
)
}
}
<file_sep>export const PROCESS_LIST_RECEIVED = 'PROCESS_LIST_RECEIVED'
export const FETCH_CURRENT_USER = 'FETCH_CURRENT_USER'
export const FETCH_FULL_NAME = 'FETCH_FULL_NAME'
<file_sep>import { gql, DocumentNode } from '@apollo/client'
export const PROCESS_LIST: DocumentNode = gql`
query {
processList {
id
name
numberOfExecutions
averageLeadTime
averageActiveTime
employeesInvolvedProcess
numberOfScenarios
start
end
loading
}
}
`
<file_sep>import { FETCH_CURRENT_USER, FETCH_FULL_NAME } from './actionsTypes'
export const fetchCurrentUser = (id: number) => {
return {
type: FETCH_CURRENT_USER,
payload: id
}
}
export const fetchFullName = (fullName: Array<string>) => {
return {
type: FETCH_FULL_NAME,
payload: fullName
}
}
<file_sep>import { PROCESS_LIST_RECEIVED } from './actionsTypes'
import { IProcess } from '../../interfaces'
export const parseProcessList = (payload: Array<IProcess>) => {
return {
type: PROCESS_LIST_RECEIVED,
payload
}
}
<file_sep>import { combineReducers } from 'redux'
import userReducer from './user'
import processReducer from './process'
export default combineReducers({
user: userReducer,
process: processReducer
})
<file_sep>export interface ILink {
to: string
activeClassName: string
onClick: () => void
label: string
icon: string
}
export interface IField {
name: string
validators: Array<Function>
placeholder: string
type?: string
label?: string
}
export interface IProcess {
id?: number
name: string
numberOfExecutions: number
averageLeadTime: string
averageActiveTime: string
employeesInvolvedProcess: number
numberOfScenarios: number
start: number
end: number
loading: number
}
export interface IAction {
type: string
payload: any
}
export interface IObject {
[k: string]: any
}
<file_sep>import { PROCESS_LIST_RECEIVED } from '../actions/actionsTypes'
import { IProcess } from '../../interfaces'
const initialState = {
processList: []
}
export default function processReducer(
state = initialState,
action: { type: string; payload: IProcess }
) {
switch (action.type) {
case PROCESS_LIST_RECEIVED:
return {
...state,
processList: action.payload
}
default:
return state
}
}
<file_sep>import { gql, DocumentNode } from '@apollo/client'
export const CURRENT_USER: DocumentNode = gql`
query {
currentUser {
id
firstName
secondName
}
}
`
<file_sep>import { DocumentNode, gql } from '@apollo/client'
export const SIGN_UP: DocumentNode = gql`
mutation signup(
$firstName: String!
$secondName: String!
$email: String!
$password: String!
) {
signup(
firstName: $firstName
secondName: $secondName
email: $email
password: $password
)
}
`
export const LOGIN: DocumentNode = gql`
mutation login($email: String!, $password: String!) {
login(email: $email, password: $password) {
token
user {
id
firstName
secondName
email
}
}
}
`
export const EDIT_USER: DocumentNode = gql`
mutation editUser(
$id: Int!
$email: String!
$firstName: String!
$secondName: String!
$password: String
) {
editUser(
id: $id
email: $email
firstName: $firstName
secondName: $secondName
password: $password
) {
firstName
secondName
}
}
`
<file_sep>import { FETCH_CURRENT_USER, FETCH_FULL_NAME } from '../actions/actionsTypes'
const initialState = {
currentUser: null,
firstName: null,
secondName: null
}
export default function userReducer(
state = initialState,
action: { type: string; payload: Array<string> }
) {
switch (action.type) {
case FETCH_CURRENT_USER:
return {
...state,
currentUser: action.payload
}
case FETCH_FULL_NAME:
return {
...state,
firstName: action.payload[0],
secondName: action.payload[1]
}
default:
return state
}
}
| 960d02bf0696532df70e0be41bfedef89ba0a7ed | [
"JavaScript",
"TypeScript"
] | 11 | TypeScript | privatescriptL9/infomaximum_test | 24f550bf0198f99f64473b0e1fc84bbd1b6e9976 | 87ebb5fd9a6b14f1cb653e3f0be9e296d0d7156c |
refs/heads/master | <file_sep>#!/usr/bin/env python3
import cortex
import synth
import sys
import random
import argparse
import time
def save_random_sequence(size, number, duration, path, mode=None):
if mode is None:
mode = random.choice(["RGB", "HSV", "YCbCr", "CMYK"])
frame_duration = duration // number
seq =[cortex.derive_image(frame)
for frame in synth.random_sequence(size, number, mode)]
im = seq.pop(0)
im.save(path, save_all=True, duration=frame_duration, loop=0,
append_images=seq, comment=im.info["comment"][:255])
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Create form-constant style amimations.")
parser.add_argument("width", type=int, help="width in pixels")
parser.add_argument("height", type=int, help="height in pixels")
parser.add_argument("number", type=int, help="number of frames")
parser.add_argument("duration", type=int,
help="duration of image loop in milliseconds")
parser.add_argument("destination", help="destination path")
args = parser.parse_args()
start = time.time()
save_random_sequence((args.width, args.height), args.number,
args.duration, args.destination)
end = time.time()
print(end-start)
<file_sep>#!/usr/bin/env python3
import math
import cmath
import argparse
from PIL import Image
def get_mapped_pixel(size, imdata, derived_coord):
"""
Return the interpolated pixel value in an image at the given coordinate.
"""
# map coordinates outside of the image back into the image
# get the integer and fractional parts of the x and y coordinates
x_int, x_frac = divmod(derived_coord[0] % size[0], 1)
y_int, y_frac = divmod(derived_coord[1] % size[1], 1)
# get the values of the four bounding pixels
values = [
imdata[int((y_int * size[0]) + x_int)],
imdata[int((y_int * size[0]) + ((x_int +1) % size[0]))],
imdata[int((((y_int + 1) % size[1]) * size[0]) + x_int)],
imdata[int((((y_int + 1) % size[1]) * size[0]) +
((x_int + 1) % size[0]))]
]
# get the distance of the coord from its four bounding pixels
distances = [
math.hypot(x_frac, y_frac),
math.hypot(1-x_frac, y_frac),
math.hypot(x_frac, 1-y_frac),
math.hypot(1-x_frac, 1-y_frac)
]
total_dist = sum(distances)
distance_weights = [distances[0] / total_dist,
distances[1] / total_dist,
distances[2] / total_dist,
distances[3] / total_dist]
# get the number of channels in the image
return (
(int(round(
(values[0][0] * distance_weights[0]) +
(values[1][0] * distance_weights[1]) +
(values[2][0] * distance_weights[2]) +
(values[3][0] * distance_weights[3])))),
(int(round(
(values[0][1] * distance_weights[0]) +
(values[1][1] * distance_weights[1]) +
(values[2][1] * distance_weights[2]) +
(values[3][1] * distance_weights[3])))),
(int(round(
(values[0][2] * distance_weights[0]) +
(values[1][2] * distance_weights[1]) +
(values[2][2] * distance_weights[2]) +
(values[3][2] * distance_weights[3])))))
def derive_image(im):
"""
Return an image derived from a source image by mapping the x axis to
the log of r and the y axis to phi where r and phi are polar coordinates
"""
im = im.convert("RGB")
imdata = list(im.getdata())
# max_r is the log of the distance from the centre to a corner
max_r = math.log1p(math.sqrt(im.size[0]**2 + im.size[1]**2) / 2)
# max_phi is the constant 2*pi
max_phi = 2 * math.pi
phi_step = max_phi / im.size[1]
data = []
# for each pixel in the source image
for y in range(im.size[1]):
for x in range(im.size[0]):
# convert to polar coords
r, phi = cmath.polar(complex(x - im.size[0]/2, y - im.size[1]/2))
if phi < 0:
phi = max_phi + phi
# map x and y
data.append(get_mapped_pixel(im.size, imdata,
((math.log1p(r)/max_r) * im.size[0],
(phi/max_phi) * im.size[1])))
dest = Image.new("RGB", im.size)
dest.putdata(data)
try:
dest.info["comment"] = im.info["comment"]
except KeyError:
pass
return dest
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Convert an image into a form constant mapping of itself.")
parser.add_argument("source", help="source path")
parser.add_argument("destination", help="destination path")
args = parser.parse_args()
derive_image(Image.open(args.source)).save(args.destination)
<file_sep>#!/usr/bin/env python3
import math
import random
import argparse
import os.path
from PIL import Image
from collections import namedtuple
def create_image(size, func, prefunc=None, freq=1, phase=0):
"""
Return an image of the given size plotting intensity of the given
function of frequency and phase, with x and y mapped by prefunc.
"""
data = []
if prefunc is None:
prefunc = lambda x,y: (x,y)
for y in range(size[1]):
for x in range(size[0]):
x1,y1 = prefunc((x - (size[0]/2)) / (size[0]/2),
(y - (size[1]/2)) / (size[1]/2))
data.append((func(x1, y1, freq, phase) * 127.5) + 127.5)
dest = Image.new("L", size)
dest.putdata(data)
return dest
def shear_m(m, axis):
"""
Return a function returning an (x,y) tuple sheared by factor m
"""
if axis == "x":
def shear(x,y):
return (x + (y*m), y)
elif axis == "y":
def shear(x,y):
return (x, y + (x*m))
return shear
def make_phased_function(f, arg=0, r=math.pi):
"""
Return a function composition to take x, y, freq and phase arguments
"""
def _f(x, y, freq, phase):
return f((r/2) * (((freq*([x,y,(x*y)**2][arg]+1)%2)+((phase*2)))%2)-1)
_f.__name__ = f.__name__ + "(" + ["x", "y", "x*y"][arg] + ")"
_f.axis = ["x", "y", "x*y"][arg]
return _f
def triangle(v):
"""
Return a value corresponding to a triangle wave
"""
return (2 * abs(v - math.floor(v + (1/2)))) - 1
def sawtooth(v):
"""
Return a value corresponding to a sawtooth wave
"""
return 2*(v - math.floor(v + (1/2)))
# create a dictionary of phased functions for both x and y axes
functions = {f.__name__: f for f in [
make_phased_function(mathfunc, xy, funcrange)
for xy in [0,1]
for mathfunc, funcrange in [(math.sin, 2*math.pi),
(math.cos, 2*math.pi),
(triangle, 1),
(sawtooth, 1)]]}
def generate_greyscale_image(size, func, freq, prefunc, phase, phase_adjust):
"""
Return an image of the given size plotting the given function called with
the given arguments.
"""
return create_image(size, func, prefunc, freq, phase_adjust(phase))
GreyscaleArgs = namedtuple("GreyscaleArgs",
["size", "func", "freq", "prefunc", "phase"])
def random_greyscale_args(size):
"""
Return a GreyscaleArgs tuple with the given size and randomly chosen
values.
"""
func = functions[random.choice(list(functions.keys()))]
axis = func.axis
freq = random.randrange(1,min([64,round(min(size)/8)]))
prefunc = (shear_m(random.randrange(0,freq+1) *
random.choice([-1,1]), axis))
phase = random.random()
return GreyscaleArgs(size, func, freq, prefunc, phase)
def random_greyscale_image(size):
"""
Return an greyscale image of the given size plotting a random function
with random arguments
"""
return generate_greyscale_image(*random_greyscale_args(size))
modes = {
"RGB": 3,
"HSV": 3,
"YCbCr": 3,
"CMYK": 4
}
phase_adjustments = [
lambda p: p,
]
def create_image_from_spec(size, mode, channel_args):
channels = [generate_greyscale_image(*channel_arg)
for channel_arg in channel_args]
return Image.merge(mode, channels)
def random_image(size, mode=None):
"""
Return an image of the given mode with each channel as a random greyscale
image. If mode is None, select a random multi-channel mode.
"""
if mode is None:
mode = random.choice(list(modes.keys()))
if mode == "L":
return random_greyscale_image(size)
else:
channels = [random_greyscale_image(size) for _ in range(modes[mode])]
im = Image.merge(mode, channels)
if mode != "RGB":
im = im.convert("RGB")
return im
def random_sequence(size, number, mode=None):
"""
Yield Image objects of given size and mode in a sequence with length given
by number. The phase is varied producing a sequence that should loop. The
wave arguments for each channel are random.
"""
if mode is None:
mode = random.choice(list(modes.keys()))
number_of_channels = modes[mode]
phase_adjusts = [random.choice(phase_adjustments)
for _ in range(number_of_channels)]
channel_args = [random_greyscale_args(size)
for _ in range(number_of_channels)]
yield from create_sequence(size, number, mode, channel_args, phase_adjusts)
def create_sequence(size, number, mode, channel_args, phase_adjusts=None):
"""
Yield Image objects of given size and mode in a sequence with length given
by number. The phase is varied producing a sequence that should loop. The
wave arguments for each channel are provided by channel_args.
"""
number_of_channels = len(channel_args)
if phase_adjusts is None:
phase_adjusts = [(lambda p: p) for _ in range(number_of_channels)]
phase_dir = [random.choice([-1,1]) for _ in range(len(channel_args))]
info = [mode]
info.extend(["c %d: %s" %
(i,
"/".join(
[str(arg) if not hasattr(arg, "__name__")
else str(arg.__name__)
for arg in channel_args[i] + (phase_dir[i],)]))
for i in range(len(channel_args))])
for i in range(number):
phase = (1 / number) * i
channels = [generate_greyscale_image(
*channel_args[i][:-1] +
(channel_args[i][-1] + (phase*phase_dir[i]) % 1,
phase_adjusts[i]))
for i in range(number_of_channels)]
merged = Image.merge(mode, channels).convert("RGB")
merged.info["comment"] = "\n".join(info).encode()
yield merged
def parse_spec(s):
"""
Parse a command-line specification and return a list of (func, freq,
shear, phase) tuples.
"""
return [parse_channel(c) for c in s.split(";")]
def parse_channel(s):
"""
Parse one channel of a command-line specification and return a
(func, freq, shear, phase) tuple.
"""
fields = s.split(",")
if len(fields) != 4:
raise argparseArgumentTypeError(
"Unable to parse channel specification: %s" % (s,))
func = functions.get(fields[0])
if func is None:
raise argparse.ArgumentTypeError("Unknown function: %s" % (fields[0],))
try:
freq = float(fields[1])
except ValueError:
raise argparse.ArgumentTypeError(
"Unable to parse channel frequency field: %s" % (fields[1],))
try:
shear = int(fields[2])
except ValueError:
raise argparse.ArgumentTypeError(
"Unable to parse channel shear field: %s" % (fields[2],))
try:
phase = float(fields[3])
except ValueError:
raise argparse.ArgumentTypeError(
"Unable to parse channel phase field: %s" % (fields[3],))
return (func, freq, shear, phase)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Produce images synthesized from waves")
parser.add_argument("width", type=int, help="width in pixels")
parser.add_argument("height", type=int, help="height in pixels")
parser.add_argument("destination", help="destination path")
parser.add_argument("-m", "--mode",
choices=["L", "RGB", "HSV", "YCbCr", "CMYK"],
help="image mode")
parser.add_argument("-s", "--spec",
type=parse_spec,
help="list of func,freq,shear,phase;[...] arguments per channel ")
parser.add_argument("-n", "--number",
type=int,
help="number of images to produce in a sequence")
args = parser.parse_args()
if args.spec:
if args.mode is None:
raise argparse.ArgumentTypeError(
"Must specify mode with spec."
)
if args.mode == "L":
channels = 1
else:
channels = modes[args.mode]
if len(args.spec) != channels:
raise argparse.ArgumentTypeError(
"Wrong number of channels in spec for mode %s" % (args.mode,))
greyscale_args = []
for spec in args.spec:
greyscale_args.append(GreyscaleArgs(
(args.width, args.height),
spec[0],
spec[1],
shear_m(spec[2], spec[0].axis),
spec[3]))
if args.number is not None:
z = len(str(args.number))
if os.path.splitext(args.destination)[1] == ".gif":
seq = []
anim = True
else:
anim = False
for i, image in enumerate(create_sequence(
(args.width, args.height),
args.number,
args.mode,
greyscale_args)):
if not anim:
path, ext = os.path.splitext(args.destination)
image.save(path + "_" + str(i).zfill(z) + ext)
else:
seq.append(image)
if anim:
im = seq.pop(0)
im.save(args.destination, save_all=True,
duration=1000/24, loop=0, append_images=seq)
else:
im = create_image_from_spec(
(args.width, args.height), args.mode, greyscale_args)
im.save(args.destination)
else:
if args.mode is None:
mode = random.choice(["RGB", "HSV", "YCbCr", "CMYK"])
else:
mode = args.mode
if args.number is not None:
if os.path.splitext(args.destination)[1] == ".gif":
seq = []
anim = True
else:
anim = False
z = len(str(args.number))
for i, image in enumerate(random_sequence((args.width, args.height),
args.number,
mode)):
if not anim:
path, ext = os.path.splitext(args.destination)
image.save(path + "_" + str(i).zfill(z) + ext)
else:
seq.append(image)
if anim:
im = seq.pop(0)
im.save(args.destination, save_all=True,
duration=1000/24, loop=0, append_images=seq)
else:
im = random_image((args.width, args.height), mode)
im.save(args.destination)
<file_sep>formconstant is a set of utilities for creating images that mimic the visual effects of psychedelics
<file_sep>#!/usr/bin/env python3
import random
import math
import cortex
import sys
from PIL import Image
from collections import namedtuple
class Variable:
def __init__(self, phase_direction, phase_offset, frequency):
self.phase_direction = phase_direction
self.phase_offset = phase_offset
self.frequency = frequency
self.name = self.__class__.__name__.lower()
self.varidx = self.__class__.varidx
@classmethod
def random(cls):
return cls(random.choice([-1, 0, 1]),
random.random(),
math.ceil(random.expovariate(1)))
def __call__(self, variables, phase):
return (((((variables[self.varidx] + 1) +
((self.phase_direction + self.phase_offset) * 2)) *
self.frequency) % 2) - 1)
def __str__(self):
return "{0}(phase={1:.3f}{2}, freq={3:d})".format(
self.name,
self.phase_offset,
"=><"[self.phase_direction],
self.frequency
)
class X(Variable):
varidx = 0
class Y(Variable):
varidx = 1
class Function:
arity = 1
fmt = ""
func = None
def __init__(self, args, dimensions, phase_direction, phase_offset,
frequency):
self.args = args
self.dimensions = dimensions
self.phase_direction = phase_direction
self.phase_offset = phase_offset
self.frequency = frequency
self.fmt = self.__class__.fmt
self.func = self.__class__.func
@classmethod
def random(cls, probability, level, builder):
return cls([builder.build(probability*probability, level)
for _ in range(cls.arity)],
builder.dimensions,
cls.random_phase_direction(level),
random.random(),
math.ceil(random.expovariate(1)))
@classmethod
def random_phase_direction(cls, level):
return 0
def __str__(self):
funcname = self.func.__name__ if self.func is not None else ""
return self.fmt.format(*self.args,
name=funcname,
phase_offset=self.phase_offset,
phased="=><"[self.phase_direction],
freq=self.frequency)
class TrigfuncPi(Function):
fmt = "{name}((pi * {0} * {freq:d}) + phase({phase_offset:.3f}{phased}))"
@classmethod
def random_phase_direction(cls, level):
if level == 1:
return random.choice([-1,1])
else:
return 0
def __call__(self, variables, phase):
phase_term = (self.phase_direction *
((2 * math.pi * (phase + self.phase_offset)) %
(2 * math.pi)))
return self.func((math.pi *
self.args[0](variables, phase) *
self.frequency) +
self.phase_direction * phase_term)
class SinPi(TrigfuncPi):
func = math.sin
class CosPi(TrigfuncPi):
func = math.cos
class Times(Function):
fmt = "{0} * {1}"
arity = 2
@classmethod
def random(cls, probability, level, builder):
return super().random(probability, level-1, builder)
def __call__(self, variables, phase):
return self.args[0](variables, phase) * self.args[1](variables, phase)
class Builder:
def __init__(self, functions, variables):
self.functions = functions
self.variables = variables
self.dimensions = len(variables)
def build(self, probability=0.99, level=0):
if random.random() < probability:
return random.choice(self.functions).random(probability,
level+1,
self)
else:
return random.choice(self.variables).random()
phase_adjustments = [
lambda p: p,
lambda p: (1 / (1 + (math.e**(-1*(p-0.5)))) + 6)/12,
lambda p: (math.cos(math.pi + (p * math.pi)) + 1) / 2,
lambda p: math.sin(p * (math.pi/2)),
lambda p: (math.cos(math.pi + (2 * math.pi * p)) + 1) / 2
]
functions = [SinPi, CosPi, Times]
def create_image(size, expression, phase=0):
"""
Return an image of the given size plotting intensity of the given
nested function of frequency and phase, with x and y mapped by prefunc.
"""
data = []
for y in range(size[1]):
for x in range(size[0]):
x1,y1 = ((x - (size[0]/2)) / (size[0]/2),
(y - (size[1]/2)) / (size[1]/2))
data.append(
int(expression([x1,y1], phase) * 127.5) + 127.5)
dest = Image.new("L", size)
dest.putdata(data)
return dest
def generate_greyscale_image(size, expression, phase, phase_adjust):
"""
Return an image of the given size plotting the given function called with
the given arguments.
"""
return create_image(size, expression, phase_adjust(phase))
GreyscaleArgs = namedtuple("GreyscaleArgs",
["size", "expression", "phase"])
def random_greyscale_args(size):
"""
Return a GreyscaleArgs tuple with the given size and randomly chosen
values.
"""
expression = Builder(functions, [X,Y]).build(
probability=random.uniform(0.95,0.99))
phase = random.random()
return GreyscaleArgs(size, expression, phase)
def random_greyscale_image(size):
"""
Return an greyscale image of the given size plotting a random function
with random arguments
"""
return generate_greyscale_image(*random_greyscale_args(size))
modes = {
"RGB": 3,
"HSV": 3,
"YCbCr": 3,
"CMYK": 4
}
def random_image(size, mode=None):
"""
Return an image of the given mode with each channel as a random greyscale
image. If mode is None, select a random multi-channel mode.
"""
if mode is None:
mode = random.choice(list(modes.keys()))
if mode == "L":
return random_greyscale_image(size)
else:
channels = [random_greyscale_image(size) for _ in range(modes[mode])]
im = Image.merge(mode, channels)
if mode != "RGB":
im = im.convert("RGB")
return im
def random_sequence(size, number, mode=None):
"""
Yield Image objects of given size and mode in a sequence with length given
by number. The phase is varied producing a sequence that should loop. The
wave arguments for each channel are random.
"""
if mode is None:
mode = random.choice(list(modes.keys()))
number_of_channels = modes[mode]
channel_args = [random_greyscale_args(size)
for _ in range(number_of_channels)]
phase_adjusts = [random.choice(phase_adjustments)
for _ in range(number_of_channels)]
mapped = random.choice([True, False])
yield from create_sequence(size, number, mode, channel_args, phase_adjusts,
mapped)
def create_sequence(size, number, mode, channel_args, phase_adjusts, mapped):
"""
Yield Image objects of given size and mode in a sequence with length given
by number. The phase is varied producing a sequence that should loop. The
wave arguments for each channel are provided by channel_args.
"""
number_of_channels = len(channel_args)
phase_dir = [random.choice([-1,1]) for _ in range(len(channel_args))]
info = [mode]
info.extend(["c %d: %s" %
(i,
"/".join(
[str(arg) if not hasattr(arg, "__name__")
else str(arg.__name__)
for arg in channel_args[i] + (phase_dir[i],)]))
for i in range(len(channel_args))])
for i in range(number):
phase = (1/number)*i
channels = [generate_greyscale_image(
*channel_args[i][:-1] +
(channel_args[i][-1] + (phase*phase_dir[i]) % 1,
phase_adjusts[i]))
for i in range(number_of_channels)]
merged = Image.merge(mode, channels).convert("RGB")
if mapped:
merged = cortex.derive_image(merged)
merged.info["comment"] = "\n".join(info).encode()
yield merged
def save_random_sequence(size, number, duration, path, mode=None):
if mode is None:
mode = random.choice(["RGB", "HSV", "YCbCr", "CMYK"])
frame_duration = duration // number
seq = [frame for frame in random_sequence(size, number, mode)]
print(len(seq))
im = seq.pop(0)
im.save(path, save_all=True, duration=frame_duration, loop=0,
append_images=seq, comment=im.info["comment"][:255])
if __name__ == "__main__":
size = [int(sys.argv[1]), int(sys.argv[2])]
number = int(sys.argv[3])
duration = int(sys.argv[4])
path = sys.argv[5]
save_random_sequence(size, number, duration, path)
| 48a51bdf37cb64e33a0215310484e9c7c4775c79 | [
"Markdown",
"Python"
] | 5 | Python | niamhalhyme/formconstant | 961ba0d3eabd9ce06d845a680d46993f75f8bbcb | d8681a036baa42b48478dae5d5bc090c5bbff2b7 |
refs/heads/master | <file_sep>package herosauce.app1;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class EditMessages extends DialogFragment {
//TODO: for v.2, add a character counter to the dialog so users know how much room they have per SMS
//TODO: for v.2 update, subtract google gps prefix from the total count
public static final String MY_MESSAGES = "MyMessagesFile";
SharedPreferences sp;
private boolean existingMessage;
Button bSave, bCancel;
private EditText mTitle, mBody;
private String existingMessageTitle;
public interface UserDialog {
void onFinishUserDialog(String user);
}
public EditMessages() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_edit_messages, container);
mTitle = (EditText) view.findViewById(R.id.messageTitle);
mBody = (EditText) view.findViewById(R.id.messageBody);
String nullTitle = "NULL";
existingMessage = false;
if (!nullTitle.equals(this.getArguments().getString("Title"))){
existingMessageTitle = this.getArguments().getString("Title");
mTitle.setText(existingMessageTitle);
String existingMessageBody = this.getArguments().getString("Message");
mBody.setText(existingMessageBody);
existingMessage = true;
} else {
Log.i("TAG", "No bundle arguments, moving on.");
}
bSave = (Button) view.findViewById(R.id.bSave);
bCancel= (Button) view.findViewById(R.id.bCancel);
sp = this.getActivity().getSharedPreferences(MY_MESSAGES, Context.MODE_PRIVATE);
bSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
SharedPreferences.Editor editor = sp.edit();
if (existingMessage){
editor.remove(existingMessageTitle).apply();
}
String title = mTitle.getText().toString();
String messageBody = mBody.getText().toString();
editor.putString(title, messageBody);
editor.apply();
Toast.makeText(getActivity(), "saved!", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "well, nevermind then.", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
}
});
return view;
}
@Override
public void onDismiss(final DialogInterface dialog){
super.onDismiss(dialog);
final Activity activity = getActivity();
if (activity instanceof DialogInterface.OnDismissListener){
((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
}
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Return input text to activity
UserDialog activity = (UserDialog) getActivity();
activity.onFinishUserDialog(mTitle.getText().toString());
this.dismiss();
return true;
}
}
<file_sep>package herosauce.app1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ThreePartFragment extends Fragment{
// Store instance variables
private String title;
private String body;
private String body_middle;
private String body_bottom;
private int page;
// newInstance constructor for creating fragment with arguments
public static ThreePartFragment newInstance(int page, String title, String body, String body_middle, String body_bottom) {
ThreePartFragment fragment = new ThreePartFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("pageTitle", title);
args.putString("pageBody", body);
args.putString("pageMiddle", body_middle);
args.putString("pageBottom", body_bottom);
fragment.setArguments(args);
return fragment;
}
// Store instance variables based on arguments passed
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("pageTitle");
body = getArguments().getString("pageBody");
body_middle = getArguments().getString("pageMiddle");
body_bottom = getArguments().getString("pageBottom");
}
// Inflate the view for the fragment based on layout XML
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_quick_start_three_part_fragment, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.fragment_title);
TextView tvBody = (TextView) view.findViewById(R.id.fragment_body);
TextView tvMiddle = (TextView) view.findViewById(R.id.fragment_body_middle);
TextView tvBottom = (TextView) view.findViewById(R.id.fragment_body_bottom);
String pageTitle = String.valueOf(page) + " -- " + title;
tvLabel.setText(pageTitle);
tvBody.setText(body);
tvMiddle.setText(body_middle);
tvBottom.setText(body_bottom);
return view;
}
}
<file_sep>package herosauce.app1;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by herosauce on 2/24/2016.
*/
public class QuickStartFragment extends Fragment{
//TODO: rename this class and clean up the junk.
//TODO: v.2 Add a button to the last page that dismisses it
//TODO: v.2 make the pages more interesting, and have them show what to do. Or something.
// Store instance variables
private String title;
private String body;
private String body_bottom;
private int page;
// newInstance constructor for creating fragment with arguments
public static QuickStartFragment newInstance(int page, String title, String body, String body_bottom) {
QuickStartFragment fragment = new QuickStartFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("pageTitle", title);
args.putString("pageBody", body);
args.putString("pageBottom", body_bottom);
fragment.setArguments(args);
return fragment;
}
// Store instance variables based on arguments passed
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("pageTitle");
body = getArguments().getString("pageBody");
body_bottom = getArguments().getString("pageBottom");
}
// Inflate the view for the fragment based on layout XML
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_quick_start_fragment, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.fragment_title);
TextView tvBody = (TextView) view.findViewById(R.id.fragment_body);
TextView tvBottom = (TextView) view.findViewById(R.id.fragment_body_bottom);
String pageTitle = String.valueOf(page) + " -- " + title;
tvLabel.setText(pageTitle);
tvBody.setText(body);
tvBottom.setText(body_bottom);
return view;
}
}
<file_sep>package herosauce.app1;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class QuickStartActivity extends FragmentActivity{
FragmentPagerAdapter adapterViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quick_start);
ViewPager vpPager = (ViewPager) findViewById(R.id.pager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager(), this);
vpPager.setAdapter(adapterViewPager);
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 5;
Context context;
public MyPagerAdapter(FragmentManager fragmentManager, Context mContext) {
super(fragmentManager);
context = mContext;
}
// Returns total number of pages
@Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
String welcome = context.getString(R.string.page_one_title);
return QuickStartFragment.newInstance(1,
context.getString(R.string.page_one_title),
context.getString(R.string.page_one_body_top),
context.getString(R.string.page_one_body_bottom));
case 1:
return ThreePartFragment.newInstance(2,
context.getString(R.string.page_two_title),
context.getString(R.string.page_two_body_top),
context.getString(R.string.page_two_middle),
context.getString(R.string.page_two_body_bottom));
case 2:
return QuickStartFragment.newInstance(3,
context.getString(R.string.page_three_title),
context.getString(R.string.page_three_body_top),
context.getString(R.string.page_three_body_bottom));
case 3:
return QuickStartFragment.newInstance(4,
context.getString(R.string.page_four_title),
context.getString(R.string.page_four_body_top),
context.getString(R.string.page_four_body_bottom));
case 4:
return QuickStartFragment.newInstance(5,
context.getString(R.string.page_five_title),
context.getString(R.string.page_five_body_top),
context.getString(R.string.page_five_body_bottom));
default:
return null;
}
}
// Returns the page title for the top indicator
@Override
public CharSequence getPageTitle(int position) {
position +=1;
return "Page " + position;
}
}
}
<file_sep>package herosauce.app1;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Map;
public class EditGroupName extends DialogFragment{
public static final String MY_GROUPS = "MyGroupsFile";
public static final String GROUP_COUNTER = "CounterFile";
SharedPreferences sp, counterSP;
Button buttonCancel, buttonSave;
private EditText mGroupName;
private Boolean existing_group;
private Integer existing_group_id;
private String existingGroupName;
public interface UserDialog {
void onFinishUserDialog(String user);
}
public EditGroupName() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.edit_group_name, container);
mGroupName = (EditText) view.findViewById(R.id.group_name);
String nullName = "NULL";
existing_group = false;
counterSP = this.getActivity().getSharedPreferences(GROUP_COUNTER, Context.MODE_PRIVATE);
final SharedPreferences.Editor counterEditor = counterSP.edit();
if (!nullName.equals(this.getArguments().getString("GroupName"))){
existingGroupName = this.getArguments().getString("GroupName");
mGroupName.setText(existingGroupName);
existing_group = true;
existing_group_id = counterSP.getInt(existingGroupName, 2);
} else {
Log.i("TAG", "No bundle arguments, moving on.");
}
buttonSave = (Button) view.findViewById(R.id.save_group_name);
buttonCancel= (Button) view.findViewById(R.id.cancel_edit_group_name);
sp = this.getActivity().getSharedPreferences(MY_GROUPS, Context.MODE_PRIVATE);
//Going to set a counter number to zero.
if (!counterSP.contains("default_counter")){
counterEditor.putInt("default_counter", 2);
counterEditor.apply();
}
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sp.edit();
String groupName = mGroupName.getText().toString();
//Need to give each group a unique ID
//then, each group number needs to be set as a group holder layout ID
//Also, if this group already has an ID, it needs to maintain the same one
editor.putString(groupName, groupName);
editor.apply();
//see if group exists (meaninig, user is just editing the group name)
//if not, need to assign group ID and notch up the ID generator
if (existing_group){
//need to get previous group ID and reassign it to new group name
counterEditor.putInt(groupName, existing_group_id).apply();
//iterate through all contacts in existing group and add them to this new one.
final SharedPreferences existingGroupSP = getActivity().getSharedPreferences(existingGroupName, Context.MODE_PRIVATE);
final SharedPreferences newGroupSP = getActivity().getSharedPreferences(groupName, Context.MODE_PRIVATE);
Map<String, ?> groupContacts = existingGroupSP.getAll();
for (final Map.Entry<String, ?> contact : groupContacts.entrySet()) {
String contactNumber = contact.getValue().toString();
String contactName = contact.getKey();
//remove all contacts from that old one, for good measure
existingGroupSP.edit().remove(contactName).apply();
//Now add them to the new group SP file
newGroupSP.edit().putString(contactName, contactNumber).apply();
}
//Need to remove the counter ID from being associated with the old group name. Need to remove that old group from the counter and group SP files.
counterEditor.remove(existingGroupName).apply();
editor.remove(existingGroupName).apply();
} else {
Integer group_id = counterSP.getInt("default_counter", 0);
counterEditor.putInt(groupName, group_id);
group_id += 1;
counterEditor.putInt("default_counter", group_id);
counterEditor.apply();
}
Toast.makeText(getActivity(), "saved!", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
}
});
buttonCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "well, nevermind then.", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
}
});
return view;
}
@Override
public void onDismiss(final DialogInterface dialog){
super.onDismiss(dialog);
final Activity activity = getActivity();
if (activity instanceof DialogInterface.OnDismissListener){
((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
}
}
}
<file_sep>package herosauce.app1;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class ContactAdapter extends BaseAdapter {
ArrayList<ContactRow> list;
Context c;
private ArrayList<ContactRow> privateArray;
public ContactAdapter(Context c, ArrayList<ContactRow> list) {
this.list = list;
this.c = c;
privateArray = new ArrayList<>();
privateArray.addAll(list);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.contacts_list_item,null,false);
TextView name = (TextView) row.findViewById(R.id.user_details_displayname);
TextView number = (TextView) row.findViewById(R.id.user_details_phone_number);
ImageView image = (ImageView) row.findViewById(R.id.user_details_avatar);
ContactRow contactRow = list.get(position);
name.setText(contactRow.name);
number.setText(contactRow.number);
if (contactRow.image!= null) {
image.setImageURI(Uri.parse(contactRow.image));
}
return row;
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
list.clear();
if (charText.length()==0){
list.addAll(privateArray);
} else {
for (ContactRow s : privateArray) {
if (s.name.toLowerCase(Locale.getDefault()).contains(charText)){
list.add(s);
}
}
}
notifyDataSetChanged();
}
}
<file_sep>package herosauce.app1;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.Layout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Map;
public class Messages extends AppCompatActivity implements DialogInterface.OnDismissListener{
private int counter = 0;
LinearLayout containerLayout;
private static final String MY_MESSAGES = "MyMessagesFile";
private static final String FIRST_START = "FirstStartSetting";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
Log.i("Messages", "running");
//See if this is the first time opening this activity
SharedPreferences sharedPreferences = getSharedPreferences(FIRST_START, MODE_PRIVATE);
Boolean first_use = sharedPreferences.getBoolean("messages_first_time", true);
if (first_use) {
//firstUseMessage(); Removing for now - not sure this adds value
//Change the value so this method doesn't run twice
sharedPreferences.edit().putBoolean("messages_first_time", false).apply();
} else {
//Otherwise, populate the saved messages
populateSavedMessages();
}
Button newMessage = (Button) findViewById(R.id.bNewMessage);
newMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
if (counter > 15)
return;
FragmentManager manager = getFragmentManager();
Fragment frag = manager.findFragmentByTag("fragment_edit_id");
if (frag != null) {
manager.beginTransaction().remove(frag).commit();
}
EditMessages newDialog = new EditMessages();
//pass null title so new message creation won't crash
Bundle nullBundle = new Bundle();
nullBundle.putString("Title", "NULL");
newDialog.setArguments(nullBundle);
newDialog.show(manager, "fragment_edit_id");
}
});
}
@Override
public void onDismiss(final DialogInterface dialog){
populateSavedMessages();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void populateSavedMessages(){
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final SharedPreferences prefs = getSharedPreferences(MY_MESSAGES, MODE_PRIVATE);
containerLayout = (LinearLayout)findViewById(R.id.msgs);
//Clear existing TextViews
containerLayout.removeAllViews();
Map<String, ?> allMessages = prefs.getAll();
for (final Map.Entry<String, ?> entry : allMessages.entrySet()){
/*
<LinearLayout
style="@style/Dashboard_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/holder_alert_settings"
android:layout_below="@+id/ll_circle">
*/
final LinearLayout rowLayout = new LinearLayout(getApplicationContext());
rowLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
//Dash Text Style
rowLayout.setPadding(16,16,16,16);
rowLayout.setElevation(4);
rowLayout.setBackgroundColor(Color.WHITE);
/*
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:id="@+id/iv_trigger_settings"
android:background="@drawable/ic_alert_settings"/>
*/
final ImageView messageIcon = new ImageView(getApplicationContext());
messageIcon.setLayoutParams(new ViewGroup.LayoutParams(124,124));
messageIcon.setImageResource(R.drawable.ic_message_settings);
messageIcon.setPadding(4,4,4,4);
rowLayout.addView(messageIcon);
/*
<LinearLayout
android:layout_width="250dp"
android:layout_height="wrap_content"
android:orientation="vertical"
style="@style/Dash_text_layout">
*/
LinearLayout layoutMessageDetails = new LinearLayout(getApplicationContext());
layoutMessageDetails.setLayoutParams(new ViewGroup.LayoutParams(950, ViewGroup.LayoutParams.WRAP_CONTENT));
layoutMessageDetails.setOrientation(LinearLayout.VERTICAL);
//Dash Text Style
layoutMessageDetails.setPadding(16,16,16,16);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
layoutMessageDetails.setElevation(4);
}
layoutMessageDetails.setBackgroundColor(Color.WHITE);
layoutMessageDetails.setPadding(0,0,0,8);
/*
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Message Title"
android:textColor="#C2185B"/>
*/
//make textview with key = message title
final TextView titleView = new TextView(getApplicationContext());
titleView.setLayoutParams(layoutParams);
titleView.setTextSize(16);
titleView.setText(entry.getKey());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
titleView.setTextColor(getColor(R.color.colorPrimary));
}
layoutMessageDetails.addView(titleView);
/*
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13sp"
android:id="@+id/tv_click_count"
android:text="Message Text"/>
*/
//adding textview with message contents
final TextView messageBody = new TextView(getApplicationContext());
messageBody.setLayoutParams(layoutParams);
messageBody.setTextSize(13);
messageBody.setTextColor(Color.BLACK);
messageBody.setText(entry.getValue().toString());
layoutMessageDetails.addView(messageBody);
rowLayout.addView(layoutMessageDetails);
/*
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_ask_pink"
android:id="@+id/ask_trigger"
android:layout_gravity="end|center_vertical"/>
*/
//add edit and delete buttons
final Button editButton = new Button(getApplicationContext());
editButton.setLayoutParams(new ViewGroup.LayoutParams(96,96));
editButton.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_edit));
final Button deleteButton = new Button(getApplicationContext());
deleteButton.setLayoutParams(new ViewGroup.LayoutParams(96,96));
deleteButton.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_delete));
rowLayout.addView(editButton);
rowLayout.addView(deleteButton);
containerLayout.addView(rowLayout);
View spacer = new View(getApplicationContext());
spacer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,20));
containerLayout.addView(spacer);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//bundle up the title and message
Bundle bundle = new Bundle();
bundle.putString("Title", entry.getKey());
bundle.putString("Message", entry.getValue().toString());
//launch dialog
FragmentManager manager = getFragmentManager();
Fragment frag = manager.findFragmentByTag("fragment_edit_id");
if (frag != null) {
manager.beginTransaction().remove(frag).commit();
}
EditMessages editDialog = new EditMessages();
editDialog.setArguments(bundle);
editDialog.show(manager, "fragment_edit_id");
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//get shared preferences, delete title/key pair
prefs.edit().remove(entry.getKey()).apply();
//make toast
Toast.makeText(getApplicationContext(), "deleted.", Toast.LENGTH_SHORT).show();
//remove row
containerLayout.removeView(rowLayout);
}
});
}
}
public int getCounter(){
return counter;
}
/*public void firstUseMessage(){
//Now create a default message - the code below copied and modified from populateMessages() - should really combine these methods
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 110, 1);
layoutParams.setMargins(8, 8, 8, 8);
final SharedPreferences prefs = getSharedPreferences(MY_MESSAGES, MODE_PRIVATE);
containerLayout = (LinearLayout)findViewById(R.id.msgs);
final String defaultMessageTitle = "Default SOS Message";
final String defaultMessageBody = "If I don't call/text you within 5 minutes, please call or come find me. (-powered by 5/5)";
prefs.edit().putString(defaultMessageTitle, defaultMessageBody).apply();
final TextView titleView = new TextView(getApplicationContext());
titleView.setLayoutParams(layoutParams);
titleView.setTextColor(Color.WHITE);
titleView.setTextSize(16);
titleView.setPadding(8, 8, 8, 8);
titleView.setText(defaultMessageTitle);
containerLayout.addView(titleView);
//adding textview with message contents
final TextView messageBody = new TextView(getApplicationContext());
messageBody.setLayoutParams(layoutParams);
messageBody.setTextColor(Color.WHITE);
messageBody.setTextSize(12);
messageBody.setPadding(8, 8, 8, 8);
messageBody.setText(defaultMessageBody);
containerLayout.addView(messageBody);
//add edit and delete buttons
final Button editButton = new Button(getApplicationContext());
editButton.setText("edit");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
editButton.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.button_border));
}
editButton.setTextColor(Color.parseColor("#FFA9CEF3"));
editButton.setLayoutParams(layoutParams);
editButton.setAllCaps(false);
final Button deleteButton = new Button(getApplicationContext());
deleteButton.setText("delete");
deleteButton.setTextColor(Color.parseColor("#FFFB6E9D"));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
deleteButton.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.delete_button_border));
}
deleteButton.setLayoutParams(layoutParams);
deleteButton.setAllCaps(false);
final LinearLayout buttonHolder = new LinearLayout(getApplicationContext());
buttonHolder.setOrientation(LinearLayout.HORIZONTAL);
containerLayout.addView(buttonHolder);
buttonHolder.addView(editButton);
buttonHolder.addView(deleteButton);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//bundle up the title and message
Bundle bundle = new Bundle();
bundle.putString("Title", defaultMessageTitle);
bundle.putString("Message", defaultMessageBody);
//launch dialog
FragmentManager manager = getFragmentManager();
Fragment frag = manager.findFragmentByTag("fragment_edit_id");
if (frag != null) {
manager.beginTransaction().remove(frag).commit();
}
EditMessages editDialog = new EditMessages();
editDialog.setArguments(bundle);
editDialog.show(manager, "fragment_edit_id");
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//get shared preferences, delete title/key pair
prefs.edit().remove(defaultMessageTitle).apply();
//make toast
Toast.makeText(getApplicationContext(), "deleted forever. no take-backsies.", Toast.LENGTH_SHORT).show();
//remove buttons and textview
buttonHolder.removeAllViews();
containerLayout.removeView(buttonHolder);
containerLayout.removeView(titleView);
}
});
}*/
}
<file_sep>package herosauce.app1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TriggerBR extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent launchMissiles = new Intent(context, Welcome.class);
context.startActivity(launchMissiles);
}
}
<file_sep>package herosauce.app1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startService = new Intent(context, AlarmTrigger.class);
context.startService(startService);
}
}
<file_sep>package herosauce.app1;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import static android.content.Context.MODE_PRIVATE;
import static herosauce.app1.R.id.bCancel;
import static herosauce.app1.Settings.FUSE_LENGTH;
/**
* Created by herosauce on 1/27/2017.
*/
public class TriggerDialog extends DialogFragment {
public TriggerDialog() {
}
public interface UserDialog {
void onFinishUserDialog(String user);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View view = inflater.inflate(R.layout.dialog_trigger, container);
//Setting up buttons
Button bSave = (Button) view.findViewById(R.id.bSave);
Button bCancel= (Button) view.findViewById(R.id.bCancel);
final SharedPreferences clicksSP = this.getActivity().getSharedPreferences(FUSE_LENGTH, MODE_PRIVATE);
final EditText editText = (EditText) view.findViewById(R.id.et_timer_length);
editText.setText(String.valueOf(clicksSP.getInt("fuse",15)));
bSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int numClicks = Integer.parseInt(editText.getText().toString());
clicksSP.edit().putInt("fuse", numClicks).apply();
getDialog().dismiss();
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getDialog().dismiss();
}
});
return view;
}
@Override
public void onDismiss(final DialogInterface dialog){
super.onDismiss(dialog);
final Activity activity = getActivity();
if (activity instanceof DialogInterface.OnDismissListener){
((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
}
}
}
<file_sep>package herosauce.app1;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class DelayedAlarm extends AppCompatActivity {
//Designed to look and feel like Settings activity
//Users will choose a group, a message, and a time interval (default 15 minutes)
//Big confirmation button on the bottom launches service that waits specified interval before sending messages
//On confirm, button becomes a cancel button; requires confirmation to cancel
//Cancel halts service and resets page to default values. No groups selected by default, nor message.
//TODO: set up service and BR to run counter in background, and get TextView updates from service
//TODO: make the timer clickable, so users can specify a time
//TODO: make the timer more attractive
Button bStartTimer, bStopTimer;
TextView tvTimer;
EditText etFuseLength;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delayed_alarm);
bStartTimer = (Button) findViewById(R.id.button_timer);
tvTimer = (TextView) findViewById(R.id.tvTimer);
etFuseLength = (EditText) findViewById(R.id.et_timer_length);
int fuse = Integer.parseInt(etFuseLength.getText().toString());
tvTimer.setText(parseTime(fuse));
CountDownTimer myTimer = new CountDownTimer(fuse*60*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
int minutesUntilFinished = (int) millisUntilFinished/60000;
int s = (int) millisUntilFinished / 1000;
s = s % 60;
String ms = String.valueOf(minutesUntilFinished) + ":" + String.valueOf(s);
tvTimer.setText(ms);
}
@Override
public void onFinish() {
//TODO This is where the message gets sent
}
};
//final CounterClass timer = new CounterClass(900000, 1000);
startButtonHandler(bStartTimer, myTimer, tvTimer);
}
private String parseTime(int fuse) {
//converts an integer value of minutes into HH:MM:SS format
int h = 0;
int m = fuse;
while (fuse>60){
h++;
m = m-60;
}
return String.valueOf(h) + ":" + String.valueOf(m) + ":00";
}
public void startButtonHandler (final Button startButton, final CountDownTimer counter, final TextView tv){
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter.start();
startButton.setText("disarm and reset alarm");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startButton.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.delete_button_border));
}
startButton.setTextColor(Color.parseColor("#FFFB6E9D"));
disarmButtonHandler(startButton, counter, tv);
}
});
}
//Note: updated middle param to be CountDownTimer instead of custom timer object reference
public void disarmButtonHandler(final Button disarmButton, final CountDownTimer counter, final TextView tv){
disarmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter.cancel();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
disarmButton.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.dark_green_button_border));
}
disarmButton.setTextColor(Color.parseColor("#006b60"));
tv.setText("00:15:00");
disarmButton.setText("light the fuse");
//TODO: stop the service that is set to send the SMS
startButtonHandler(disarmButton, counter, tv);
}
});
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis )),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
tvTimer.setText(hms);
}
@Override
public void onFinish() {
tvTimer.setText("Message sent.");
//TODO: this is where the SMS get sent
}
}
}
| 08fa7572916754cc6dd571016860bd72d5890da0 | [
"Java"
] | 11 | Java | herosauce/Five-for-Five | 67d8d374440623014e4402b3ff949012d617c919 | c1a8de9cd8c2401685552d31266aa6cddb986655 |
refs/heads/main | <file_sep># Outbound SMS in Twilio Flex
You must have an existing FlexFlow of IntegrationType=task configured for this to work. See Step #1 in [Send Outbound Messages via SMS, WhatsApp and Other Channels]('https://www.twilio.com/docs/flex/developer/messaging/outbound-messages-channels#') for more information.
This script creates a Flex Chat Channel, sets up the Twilio Proxy session, adds the agent to the Proxy Session, and updates the Chat Channel attributes with the Proxy Session so that Channel Janitor deletes the Proxy session when the task wraps up.
## Getting started
To get started, clone the repository, ```npm install``` the required packages, and run the following script:
```mv .example.env .env```
and add your variables. If you don't keep your __Twilio Account SID__, __Auth Token__ and phone numbers (both Twilio and personal) in your local environment variables, you can add those to the .env file, as well.
This is only the backend implementation - when you run this script, it will automatically create a task for the agent. If you want to trigger this when clicking a button, you will need to build a Flex UI component with a plugin.
## Author
* **<NAME>** -
[Framinus](https://github.com/Framinus)
<file_sep>require('dotenv').config();
const accountSid = process.env.FLEX_ACCOUNT_SID;
const authToken = process.env.FLEX_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
const myPhone = process.env.MY_PHONE_NUMBER;
const flexPhone = process.env.FLEX_PHONE_NUMBER;
const flexFlowSid = process.env.FLEX_FLOW_SID;
const proxyServiceSid = process.env.PROXY_SERVICE_SID;
const chatServiceSid = process.env.CHAT_SERVICE_SID;
client.flexApi.channel
.create({
target: myPhone,
taskAttributes: JSON.stringify({
to: myPhone,
direction: 'outbound',
name: 'Blake',
from: flexPhone,
targetWorker: 'client:jingraham',
autoAnswer: true
}),
identity: `sms_${myPhone}`,
chatFriendlyName: 'Outbound Chat',
flexFlowSid,
chatUserFriendlyName: 'James'
})
.then((channel) => {
console.log("channel_sid", channel.sid);
createProxySession(channel.sid)
})
.catch((err) => {
console.log(`Error creating channel: ${err}`);
})
function createProxySession(channelSid) {
client.proxy.services(proxyServiceSid)
.sessions
.create({
uniqueName: channelSid,
mode: 'message-only',
participants: [{"Identifier": `${myPhone}`}]
})
.then((session) => {
console.log("session sid", session.sid);
addAgentToProxySession(channelSid, session.sid);
})
.catch((err) => {
console.log(`Error creating proxy session: ${err}`);
})
}
function addAgentToProxySession(channelSid, sessionSid) {
client.proxy.services(proxyServiceSid)
.sessions(sessionSid)
.participants
.create({
proxyIdentifier: flexPhone,
friendlyName: myPhone,
identifier: channelSid,
})
.then((participant) => {
console.log("participant sid", participant.sid);
getChannelAttributes(channelSid, sessionSid)
})
.catch((err) => {
console.log(`Failed to update attributes: ${err}`);
})
}
function getChannelAttributes(channelSid, sessionSid) {
client.chat.services(chatServiceSid)
.channels(channelSid)
.fetch()
.then((channel) => {
const initialAttributes = channel.attributes;
updateChannelAttributeswithProxy(channelSid, sessionSid, initialAttributes)
})
.catch((err) => {
console.log(`Could not return channel attributes: ${err}`);
return err;
})
}
function updateChannelAttributeswithProxy(channelSid, sessionSid, initialAttributes) {
let attributes = JSON.parse(initialAttributes);
let proxySessionAttr = {proxySession: sessionSid};
let newAttributes = JSON.stringify(Object.assign(attributes, proxySessionAttr));
client.chat.services(chatServiceSid)
.channels(channelSid)
.update({attributes: newAttributes})
.then((channel) => {
console.log(`${channel.friendlyName} has been updated with ${channel.attributes}`);
return channel.attributes;
})
.catch((err) => {
console.log(`Channel failed to update: ${err}`);
return err;
})
};
| 5db27236c3c1e4c01b61e37a9d6f46d9d9d7aede | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Framinus/outbound-sms-from-flex | 24e27d755491d0723e0e8a921a7dfc245ff9ab0d | ad847b921cdde78c90e3ba400b6dbdd06cd63d39 |
refs/heads/master | <file_sep>const path = require('path');
const {getLoader, loaderNameMatches} = require('react-app-rewired');
function createRewireLless(lessLoaderOptions = {}){
return function(config,env){
const lessExtension = /\.less?$/;
const fileLoader = getLoader(config.module.rules,
(rule)=>loaderNameMatches(rule,'file-loader'));
fileLoader.exclude.push(lessExtension);
const cssLoader = getLoader(config.module.rules,
(rule)=>String(rule.test)===String(/\.css$/));
let lessRules;
if(env==='production'){
lessRules = {
test:lessExtension,
loader:[
...cssLoader.loader,
{loader:'less-loader',options:lessLoaderOptions}
]
};
}else{
lessRules = {
test:lessExtension,
use: [
...cssLoader.use,
{loader:'less-loader',options:lessLoaderOptions}
]
};
}
const oneOfRule = config.module.rules.find((rule)=>rule.oneOf!==undefined);
if(oneOfRule){
oneOfRule.oneOf.unshift(lessRules);
}else{
config.module.rules.push(lessExtension);
}
return config;
};
}
module.exports = createRewireLless;
<file_sep>const path = require('path');
const {getLoader, loaderNameMatches} = require('react-app-rewired');
function createRewireSass(sassRewireOptions = {}){
return function(config,env){
const sassExtension = /\.scss?$/;
const fileLoader = getLoader(config.module.rules,
(rule)=>loaderNameMatches(rule,'file-loader'));
fileLoader.exclude.push(sassExtension);
const cssLoader = getLoader(config.module.rules,
(rule)=>String(rule.test)===String(/\.css$/));
let sassRules;
if(env === 'production'){
// production environment
// use 'loader'
sassRules = {
test: sassExtension,
loader:[
...cssLoader.loader,
{loader:'sass-loader',options:sassRewireOptions}
]
};
}else{
sassRules = {
test: sassExtension,
use:[
...cssLoader.use,
{loader:'sass-loader',options:sassRewireOptions}
]
};
}
let oneOfRule = config.module.rules.find((rule)=>rule.oneOf!==undefined);
if(oneOfRule){
oneOfRule.oneOf.unshift(sassRules);
}else{
config.module.rules.push(sassRules);
}
return config;
};
}
module.exports = createRewireSass;<file_sep># Tabs
《深入React技术栈》第一章随书源码
| a0816aa2b3bf504b3992aca63892448bc2055269 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | zhihongzhong/Tabs | e7b492d260863d169c693f6ca97709c78242b67b | 64fd7b0d12749e13e127cf074bb320f2820a8c54 |
refs/heads/main | <repo_name>krisp3t/tictactoe<file_sep>/src/app/text.js
const text = {
setup: {
currentLang: {
en: "Language",
de: "Sprache",
sl: "Jezik",
hr: "Jezik",
sr: "Језик",
},
darkMode: {
en: "Dark Mode",
de: "Dunkelmodus",
sl: "Temni način",
hr: "Tamni način",
sr: "Тамни режим",
},
player: {
en: "Player",
de: "Spieler",
sl: "Igralec",
hr: "Igrač",
sr: "Играч",
},
name: {
en: "Name",
de: "Name",
sl: "Ime",
hr: "Ime",
sr: "Име",
},
startGameButton: {
en: "Start game",
de: "Spiel beginnen",
sl: "Začni igro",
hr: "Započni igru",
sr: "Започни игру",
},
warning: {
en: "The colors shouldn't match!",
de: "Die Farben dürfen nicht übereinstimmen!",
sl: "Barvi se ne smeta ujemati!",
hr: "Boje se ne smiju podudarati!",
sr: "Боје се не смеју подударати!",
},
},
game: {
wins: {
en: "wins",
de: "Siege",
sl: "zmag",
hr: "pobjeda",
sr: "победа",
},
},
gameEnd: {
win: {
en: `wins`,
de: `gewinnt`,
sl: `je zmagal`,
hr: `je pobijedio`,
sr: `је победио`,
},
draw: {
en: "It's a draw!",
de: "Es steht unentschieden!",
sl: "Neodločeno je!",
hr: "Neriješeno je!",
sr: "Нерешено је!",
},
restartButton: {
en: "New game",
de: "<NAME>",
sl: "Nova igra",
hr: "Nova igra",
sr: "Нова игра",
},
},
};
module.exports = text; // eslint-disable-line
<file_sep>/webpack.dev.js
const path = require("path");
const common = require("./webpack.common");
const { merge } = require("webpack-merge");
const ESLintPlugin = require("eslint-webpack-plugin");
module.exports = merge(common, {
mode: "development",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js",
},
plugins: [
new ESLintPlugin({
failOnError: false,
}),
],
module: {
rules: [
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: ["postcss-preset-env"],
},
},
},
{
loader: "sass-loader",
},
],
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: ["postcss-preset-env"],
},
},
},
],
},
],
},
});
<file_sep>/src/vendor.js
// Import SVG
function requireAll(r) {
r.keys().forEach(r);
}
requireAll(require.context("./assets/", true, /\.svg$/)); // eslint-disable-line
import "./vendor.scss";
import { Dropdown } from "bootstrap"; // eslint-disable-line
<file_sep>/src/app/twemoji.js
import twemoji from "twemoji";
twemoji.parse(document.body);
<file_sep>/src/index.js
import "./main.scss";
import "./app/twemoji.js";
import "./app/app.js";
| c1b680cca097f3b768c9e7fd1a01319a482e3da8 | [
"JavaScript"
] | 5 | JavaScript | krisp3t/tictactoe | 617415089ab66b44515a3815e893912c083fe2b2 | 9d77ed4479d6241eb03759635cdc1a5a340f8cc4 |
refs/heads/master | <file_sep>from torch.utils.data import Dataset, DataLoader
import pandas as pd
import os
from PIL import Image
from torchvision import transforms
import numpy as np
import torch
def moments_category_dict(category_file_name):
lines = [line.strip() for line in open(category_file_name).readlines()]
moments_label_dict = {}
index = 0
for line in lines:
category_name = line
moments_label_dict[category_name] = index
index+=1
return moments_label_dict
class MomentsDataset(Dataset):
def __init__(self, mode, feature_data_dir, name_data_dir, category_dict, csv_file, transform=None):
self.mode = mode
self.feature_data_dir = feature_data_dir
self.name_data_dir = name_data_dir
self.dataset = pd.read_csv(csv_file)
self.category_dict = category_dict
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
feature_file = os.path.join(self.feature_data_dir, self.dataset['Feature'][idx])
if self.mode == 'train':
name_file = os.path.join(self.name_data_dir, self.dataset['Feature'][idx].replace("names", "features"))
elif self.mode == 'test':
name_file = os.path.join(self.name_data_dir, self.dataset['Feature'][idx].replace("features", "name"))
else:
raise Exception("no such mode exist, only train or test mode")
feature_per_video = np.load(feature_file)
name_per_video = np.load(name_file)
label_per_video = self.category_dict[name_file.split('/')[-2]]
sample = {'feature': feature_per_video, 'label': label_per_video}
return sample, name_per_video.tolist()
def get_loader(feature_data_dir, name_data_dir, category_dict, csv_file, batch_size, mode='train', dataset='moments'):
"""Build and return data loader."""
shuffle = True if mode == 'train' else False
if dataset == 'moments':
dataset = MomentsDataset(mode, feature_data_dir, name_data_dir, category_dict, csv_file)
data_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=shuffle, num_workers=8)
return data_loader
if __name__ == '__main__':
label_dict = moments_category_dict("./feature_list/category_moment.txt")
val_feature_dir = "/media/lili/fce9875a-a5c8-4c35-8f60-db60be29ea5d/extracted_features_moments_raw/feature_val"
val_name_dir = "/media/lili/fce9875a-a5c8-4c35-8f60-db60be29ea5d/extracted_features_moments_raw/name_val"
val_csv_file = "./feature_list/feature_val_list.csv"
val_batch_size = 10
val_data_loader = get_loader(feature_data_dir = val_feature_dir,
name_data_dir = val_name_dir,
category_dict = label_dict,
csv_file = val_csv_file,
batch_size = val_batch_size,
mode = 'test',
dataset='moments')
for i, (sample, batch_name) in enumerate(val_data_loader):
batch_feature = sample['feature']
batch_label = sample['label']
print("batch_feature.shape: ", batch_feature.shape)
print("batch_label.shape: ", batch_label.shape)
print("batch_name: ", batch_name)
break
train_feature_dir = "/media/lili/f9020c94-3607-46d2-bac8-696f0d445708/extracted_features_moments_raw/training_features"
train_name_dir = "/media/lili/f9020c94-3607-46d2-bac8-696f0d445708/extracted_features_moments_raw/training_names"
train_csv_file = "./feature_list/feature_train_list.csv"
train_batch_size = 16
train_data_loader = get_loader(feature_data_dir = train_feature_dir,
name_data_dir = train_name_dir,
category_dict = label_dict,
csv_file = train_csv_file,
batch_size = train_batch_size,
mode = 'train',
dataset='moments')
for i, (sample, batch_name) in enumerate(train_data_loader):
batch_feature = sample['feature']
batch_label = sample['label']
print("batch_feature.shape: ", batch_feature.shape)
print("batch_label.shape: ", batch_label.shape)
print("batch_name: ", batch_name)
break
<file_sep>"""
make feature and name list txt file for the moments data loader
Author: <NAME> (<EMAIL>)
Date: August 25, 2018
"""
import numpy as np
import os
feature_dir = "/media/lili/f9020c94-3607-46d2-bac8-696f0d445708/extracted_features_moments_raw/training_features"
txt_file = open("feature_train_list.txt", mode='a')
txt_file.write("Feature"+"\n")
for subdir in sorted(os.listdir(feature_dir)):
print("subdir :", subdir)
for video in sorted(os.listdir(os.path.join(feature_dir, subdir))):
if '.npy' in video:
print("video: ", video)
feature_name = os.path.join(subdir, video)
print("feature_name: ", feature_name)
txt_file.write(feature_name+"\n")
| 01aaa3c289a85203ab914d97cefaad6b46152331 | [
"Python"
] | 2 | Python | LiliMeng/spatial_temporal_att_moments | e978e7850a5e7ccf9829b88bdff77f797d98c6ba | a83ebf7388b8fa30492789d799c35b1133bdc03e |
refs/heads/master | <repo_name>suzhihui/Trade<file_sep>/Models/ProjectModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ZCZJ.Trade.Web.Models
{
public class ProjectModel
{
public List<DAL.ZC_project> List { get; set; }
public string PageHtml { get; set; }
}
}<file_sep>/Controllers/ProjectController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ZCZJ.Trade.Web.Controllers
{
public class ProjectController : Controller
{
// GET: Project
public ActionResult Index(string projectname, int? state, string amounts, string area)
{
var model = new ZCZJ.Trade.Web.Models.ProjectModel();
int nowPage = 1;
int pageSize = 8;
int total = 0;
int t = state.HasValue ? 0 : state.Value;
model.List = BLL.ZcProject.ZcProjectManager.CreateInstance().ProjectNewList(projectname, t, amounts, area, pageSize, nowPage, ref total);
int pageCount = Common.PageCount.GetPageCount(pageSize, total);
if (pageCount > 1)
{
model.PageHtml = Common.PageHelper.GetPageNumbersForAjax(nowPage, pageCount, 4);
}
return View(model);
}
public ActionResult Detail()
{
return View();
}
}
}<file_sep>/Controllers/SpecialController.cs
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZCZJ.Trade.Web.Models;
using System.Transactions;
namespace ZCZJ.Trade.Web.Controllers
{
public class SpecialController : Controller
{
// GET: Special
public ActionResult Index()
{
return View();
}
#region 站岗宝专题
public ActionResult StandGuardBao()
{
ViewBag.Time = DateTime.Now;
var model = new StandGuardModel();
model.IsDayBuy = false;
ViewBag.show = false;
string userid = ZCZJ.Share.SessionManager.Instance.UserID;
var standBao = BLL.FlowFinancing.ZC_FlowFinancingManager.CreateInstance().Query();
if (standBao == null)
{
standBao = new DAL.ZC_FlowFinancing();
model.IsDayBuy = true;
}
model.PayAmount = standBao.Amount - standBao.CurrentAmount > 0 ? standBao.Amount - standBao.CurrentAmount : 0;
if (model.PayAmount == 0)
{
model.IsDayBuy = true;
}
if (!string.IsNullOrEmpty(userid))
{
if (standBao != null)
{
model.info = standBao;
model.Amount = ZCZJ.Share.UserFundsShare.GetCurrentUserAccount().AvailableBalance;//当前用户余额
var standAmount = BLL.FlowFinancing.ZC_FlowFinancingOrderManager.CreateInstance().GetUserTodayPayAmount(int.Parse(ZCZJ.Share.SessionManager.Instance.UserID)); //当日最大的购买金额
model.CurrentAmount = standAmount;
//model.PayAmount = model.info.Amount - model.info.CurrentAmount > 0 ? model.info.Amount - model.info.CurrentAmount : 0;
if (standBao.CurrentAmount >= standBao.Amount || standBao.EndTime < DateTime.Now)
{
model.IsDayBuy = true;
}
var endTime = DateTime.Now.Hour;
if (endTime >= 11 && endTime < 23)
{
ViewBag.show = true;
}
}
}
return View(model);
}
public JsonResult CheckStandGuard()
{
var endTime = DateTime.Now.Hour;
if (endTime >= 23 || endTime < 11)
{
return Json("购买时间为上午11点到晚上23点!!!", JsonRequestBehavior.AllowGet);
}
return Json("", JsonRequestBehavior.AllowGet);
}
public JsonResult MaxBuy()
{
decimal Balance = ZCZJ.Share.UserFundsShare.GetCurrentUserAccount().AvailableBalance;
string userid = ZCZJ.Share.SessionManager.Instance.UserID;
var standBao = BLL.FlowFinancing.ZC_FlowFinancingManager.CreateInstance().Query();
if (standBao == null)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
var standAmount = ZCZJ.Share.UserFundsShare.GetFlowFinancingAccount().AvailableBalance; //站岗投资额
var dayAmount = BLL.FlowFinancing.ZC_FlowFinancingOrderManager.CreateInstance().GetUserTodayPayAmount(int.Parse(userid));//当前用户当天投资金额
var payAmount = standBao.Amount - standBao.CurrentAmount; //剩余可购余额
var maxAmount = 100000 - standAmount;//累计最大的投资金额100000
var maxDayAmount = 20000 - dayAmount; //当日最大的投资金额20000
if (maxAmount <= 0 || maxDayAmount <= 0)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
if (Balance > payAmount) //转入金额和可购余额比较25000 30000
{
Balance = payAmount; //取可购余额
if (Balance > maxDayAmount) //大于的话就去达日最大的投资额 并且累计最的金额大于转入金额
{
Balance = maxDayAmount;
if (Balance > maxAmount) //与累计金额比较 如果大于最大累计金额 就去最大累计金额
{
Balance = maxAmount;
}
}
}
else
{
if (Balance > maxDayAmount) //大于的话就去达日最大的投资额 并且累计最的金额大于转入金额
{
Balance = maxDayAmount;
if (Balance > maxAmount) //与累计金额比较 如果大于最大累计金额 就去最大累计金额
{
Balance = maxAmount;
}
}
}
return Json(Balance, JsonRequestBehavior.AllowGet);
}
public JsonResult Buy()
{
var amount = Request["amount"] ?? "";
var pwd = Request["pwd"] ?? "";
var endTime = DateTime.Now.Hour;
if (endTime >= 23 || endTime < 11)
{
return Json(new { msg = "购买时间为上午11点到晚上23点!!!", state = "no" }, JsonRequestBehavior.AllowGet);
}
if (amount != "" && Common.RegExp.IsMoney(amount))
{
var standBao = BLL.FlowFinancing.ZC_FlowFinancingManager.CreateInstance().Query();
if (standBao == null)
{
return Json(new { msg = "项目已过期", state = "no" }, JsonRequestBehavior.AllowGet);
}
var userAmount = ZCZJ.Share.UserFundsShare.GetCurrentUserAccount().AvailableBalance;//帐号余额
var standAmount = ZCZJ.Share.UserFundsShare.GetFlowFinancingAccount().AvailableBalance;//站岗投资额
var payAmount = standBao.Amount - standBao.CurrentAmount; //可购余额
decimal maxAmount = decimal.Parse(amount) + standAmount; //累计最大投资额
var dayAmount = BLL.FlowFinancing.ZC_FlowFinancingOrderManager.CreateInstance().GetUserTodayPayAmount(int.Parse(ZCZJ.Share.SessionManager.Instance.UserID));//当前用户当天投资金额
string result = string.Empty;
decimal maxDayAmount = decimal.Parse(amount) + dayAmount;//当日用户最大的投资额
if (maxDayAmount > 20000)
{
return Json(new { msg = "每人每天限额2万", state = "no" });
}
if (maxAmount > 100000)
{
return Json(new { msg = "每人最大投资金额为10万", state = "no" });
}
if (decimal.Parse(amount) <= 0)
{
return Json(new { msg = "输入金额必须大于零", state = "no" });
}
if (decimal.Parse(amount) > userAmount)
{
return Json(new { msg = "余额不够,请充值", state = "no" });
}
if (decimal.Parse(amount) > payAmount)
{
return Json(new { msg = "超出可购金额,请重新输入", state = "no" });
}
var info = BLL.ZcProject.ZC_PayPasswordManager.CreateInstance().CheckPayPwd(int.Parse(ZCZJ.Share.SessionManager.Instance.UserID), Common.Utils.MD5(Common.Utils.MD5(pwd.Trim())));
if (info)
{
standBao.CurrentAmount += decimal.Parse(amount);
var istrue = BLL.FlowFinancing.ZC_FlowFinancingManager.CreateInstance().Edit(standBao);
if (istrue)
{
using (TransactionScope ts = new TransactionScope())
{
ZCZJ.Share.UserFundsShare.UserFlowFinancingOperation(int.Parse(ZCZJ.Share.SessionManager.Instance.UserID), decimal.Parse(amount), (int)ZCZJ.Share.FinancingType.转入, standBao.ID,1);
ZCZJ.Share.UserFundsShare.UserAccountOperation(int.Parse(ZCZJ.Share.SessionManager.Instance.UserID), decimal.Parse(amount), (int)ZCZJ.Share.FundType.转出到活期宝, null);
BLL.FlowFinancing.ZC_FlowFinancingOrderManager.CreateInstance().Add(new ZC_FlowFinancingOrder { Amount = decimal.Parse(amount), ID = standBao.ID, UserID = int.Parse(ZCZJ.Share.SessionManager.Instance.UserID), PostDate = DateTime.Now });
ts.Complete();
}
}
return Json(new { msg = "", state = "yes" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { msg = "支付密码错误", state = "no" }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { msg = "输入金额错误", state = "no" }, JsonRequestBehavior.AllowGet);
}
}
public JsonResult checkLogin()
{
string userid = ZCZJ.Share.SessionManager.Instance.UserID;
if (userid == "")
{
return Json(new { msg = "你还没有登录", state = "noLogin" }, JsonRequestBehavior.AllowGet);
}
var endTime = DateTime.Now.Hour;
if (endTime >= 23 || endTime < 11)
{
return Json(new { msg = "购买时间为上午11点到晚上23点!!!", state = "timeout" }, JsonRequestBehavior.AllowGet);
}
var Isok = ZCZJ.Share.AuthenticationHelper.CheckIsAuthentication();
if (!Isok)
{
return Json(new { msg = "请先认证投资人", state = "noauth" }, JsonRequestBehavior.AllowGet);
}
return Json(new { state = "yes" }, JsonRequestBehavior.AllowGet);
}
#endregion
#region 质押宝专题
public ActionResult PledgeBao()
{
return View();
}
#endregion
}
}<file_sep>/Models/StandGuardModel.cs
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ZCZJ.Trade.Web.Models
{
public class StandGuardModel
{
public ZC_FlowFinancing info { get; set; }
/// <summary>
/// 帐号余额
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// 可购余额
/// </summary>
public decimal PayAmount { get; set; }
public decimal CurrentAmount { get; set; }
/// <summary>
/// 是否已经购买完
/// </summary>
public bool IsDayBuy { get; set; }
}
}<file_sep>/Controllers/PassportController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ZCZJ.Trade.Web.Controllers
{
public class PassportController : Controller
{
// GET: Passport
public ActionResult Index()
{
return View();
}
#region 登录页面
public ActionResult Login()
{
return View();
}
#endregion
}
} | edb9b909cb28b0cd59f4029b03c0c532b2b1e938 | [
"C#"
] | 5 | C# | suzhihui/Trade | 03d09fd01c0021b3e9e8cc648f0d52b330a33ff9 | 87a91a6b253876c57695420c2f0e21a797d69568 |
refs/heads/master | <file_sep># React-redux vanilla template.
This project was bootstrapped with "Create React App". This code base is made to fast-forward the intermidiate setup process while starting new project.
The following are configured and ready to use. Run `npm install`.
1) Redux - Make reducers in `./src/reducers/`;
2) React Router
3) SASS support
### Available scripts:
`npm start`
`npm test`
`npm run build`
`npm run eject`
<file_sep>import React, { Component } from 'react';
const LandingPage = ()=>{
return(
<div>
I am supposed to be landing page.
</div>
)
}
export default LandingPage;
<file_sep>import React, { Component } from 'react';
const SomePage = ()=>{
return(
<div>
I am a sample page.
</div>
)
}
export default SomePage;
| 0a16c69705c3591e517d21ae73901d0e5ec4ba1d | [
"Markdown",
"JavaScript"
] | 3 | Markdown | urbanpiper/up-react-vanilla | 7bec6e3aa18bb6b64323000334fe09bc4ed0dc14 | c01bf387e6662b712760c4525f3613d621b402b9 |
refs/heads/master | <file_sep><?php use_helper('a') ?>
<?php if ($editable): ?>
<?php include_partial('a/simpleEditWithVariants', array('pageid' => $pageid, 'name' => $name, 'permid' => $permid, 'slot' => $slot)) ?>
<?php endif ?>
<?php $report = $sf_data->getRaw('report'); ?>
<ol>
<?php $arrRows = array(); ?>
<?php if(isset($report->rows) AND is_array($report->rows)): ?>
<?Php $arrRows = $report->rows; ?>
<?php else: ?>
<?php echo __('No response from Google Analytics, please try again later'); ?>
<?php endif; ?>
<?php foreach($arrRows as $key=>$value): ?>
<li>
<a href="<?php echo $value[1] ?>"><?php echo $value[0] ?></a>: <?php echo $value[2] ?>
</li>
<?php endforeach; ?>
</ol><file_sep>siGoogleAnalyticsReportingPlugin
================================
Screencast on how it works: http://www.youtube.com/watch?v=KOVSGft26yg
Done with screenr.com, a wonderful online screencast tool
Used to display web stats from an associated Google Analytics account, in the [Apostrophe CMS](http://apostrophenow.org)
All reports are cached, and updated daily.
Available Report Slots
----------------------
* siGaTopContentSlots -- displays the top _n_ hits on the site, and the hit count in an ordered list
Installation
------------
1. download to plugins directory or preferably use svn externals (I think this is possible with gitHub)
2. add your google analytics credential to app.yml, they should look something like this:
<pre><code>
a:
gareports:
username: <EMAIL>
password: <PASSWORD>
profile: profile_id_starts_with_ga:
key: looong_api_key
</code></pre>
3. rebuild your classes from the command line:
./symfony doctrine:build --all-classes
4. add plugin to config/ProjectConfiguration.class.php
5. add module(s) to settings.yml to enable them
6. add slot to app.yml under "slot_types:"
7. optionally add slot to standard area
8. clear cache: ./symfony cc
9. make sure the slot is included in an area
10. try it out
Finding your google info:
-------------------------
* username & password: you can use your administrator login, however it would be better to create a subordinate account that has read only access so you don't share your admin account with everyone with code access
* profileId:
1. log into your analytics account, and choose the site you need stats for
2. the profile id is the 6 digit integer after the p
3. add it to the app.yml starting with "ga:", for example ga:123456
* Api Key: login to google, and goto https://code.google.com/apis/console this will allow you to get your full quota from the API and for google to contact you if there are any problems
<file_sep><?php
class siGaTopContentSlotEditForm extends BaseForm
{
// Ensures unique IDs throughout the page
protected $id;
public function __construct($id, $defaults = array(), $options = array(), $CSRFSecret = null)
{
$this->id = $id;
parent::__construct($defaults, $options, $CSRFSecret);
}
public function configure()
{
// ADD YOUR FIELDS HERE
// A simple example: a slot with a single 'text' field with a maximum length of 100 characters
$this->setWidgets(array('limit' => new sfWidgetFormInput(array('default' => 10, 'label' => 'Length of List'))));
$this->setValidators(array('limit' => new sfValidatorInteger(array('required' => false, 'max' => 99, 'min' => 1))));
// Ensures unique IDs throughout the page. Hyphen between slot and form to please our CSS
$this->widgetSchema->setNameFormat('slot-form-' . $this->id . '[%s]');
// You don't have to use our form formatter, but it makes things nice
$this->widgetSchema->setFormFormatterName('aAdmin');
}
}
<file_sep><?php
class siGaTopContentSlotComponents extends aSlotComponents
{
public function executeEditView()
{
// Must be at the start of both view components
$this->setup();
// Careful, don't clobber a form object provided to us with validation errors
// from an earlier pass
if (!isset($this->form))
{
$this->form = new siGaTopContentSlotEditForm($this->id, $this->slot->getArrayValue());
}
}
public function executeNormalView()
{
$this->setup();
$this->values = $this->slot->getArrayValue();
$limit = 10;
if(isset($this->values['limit'])){
$limit = $this->values['limit'];
}
//$this->report = $this->getTopContent(array('limit'=>$limit));
// use the report type + limit value as a key, and only update once a day
$this->report = $this->fetchCached('topContent'.$limit, $options=array('limit'=>$limit), $interval=86400);
}
private function getTopContent($options){
if(!isset($options['limit']) OR !is_numeric($options['limit'])){
throw new sfException('A limit of type integer is required');
}
$arrGaReportsSettings = sfConfig::get('app_a_gareports', false);
if(!isset($arrGaReportsSettings['username'])){
die('Google Analytics username is missing');
}
if(!isset($arrGaReportsSettings['password'])){
die('Google Analytics password is missing ');
}
if(!isset($arrGaReportsSettings['profile'])){
die('Google Analytics profile is missing ');
}
if(!isset($arrGaReportsSettings['key'])){
die('Google Analytics API Key is missing ');
}
try {
// create an instance of the GoogleAnalytics class using your own Google {email} and {password}
// todo pull all config data from app.yml
$ga = new GoogleAnalytics($arrGaReportsSettings['username'],$arrGaReportsSettings['password']);
// set the Google Analytics profile you want to access - format is 'ga:123456';
$ga->setProfile($arrGaReportsSettings['profile']);
$ga->setKey($arrGaReportsSettings['key']);
// set the date range we want for the report - format is YYYY-MM-DD
// todo: have this adjustable from the slot edit view
$dateFormat = 'Y-m-d';
$startDate = date($dateFormat, strtotime('-1 month'));
$endDate = date($dateFormat, time());
$ga->setDateRange($startDate,$endDate);
// get the report for date and country filtered by Australia, showing pageviews and visits
$report = $ga->getReport(
array('dimensions'=>urlencode('ga:pagetitle,ga:pagePath'),
'metrics'=>urlencode('ga:pageviews'),
'sort'=>'-ga:pageviews',
'max-results' => $options['limit']
),
$returnJson = TRUE
);
} catch (Exception $e) {
$report = 'Error: ' . $e->getMessage();
}
return $report;
}
/**
* Lovingly ripped off from P'unk Ave's aFeed plugin, and moved from model controller
* @param mixed $url
* @param mixed $interval
* @return mixed
*/
private function fetchCached($key, $options, $interval = 300)
{
$cache = aCacheTools::get('feed');
$feed = $cache->get($key, false);
if ($feed === 'invalid')
{
return false;
}
else
{
if ($feed !== false)
{
// sfFeed is designed to serialize well
$feed = unserialize($feed);
}
}
if (!$feed)
{
try
{
// We now always use the fopen adapter and specify a time limit, which is configurable.
// Francois' comments about fopen being slow are probably dated, the stream wrappers are
// quite good in modern PHP and in any case Apostrophe uses them consistently elsewhere
// $options = array('adapter' => 'sfFopenAdapter', 'adapter_options' => array('timeout' => sfConfig::get('app_a_feed_timeout', 30)));
// $feed = sfFeedPeer::createFromWeb($url, $options);
$feed = $this->getTopContent($options);
$cache->set($key, serialize($feed), $interval);
}
catch (Exception $e)
{
// Cache the fact that the feed is invalid for 60 seconds so we don't
// beat the daylights out of a dead feed
$cache->set($key, 'invalid', 60);
return false;
}
}
return $feed;
}
}
| c86243d360c6545c9994299256064a216a22048a | [
"Markdown",
"PHP"
] | 4 | PHP | rhspeer/siGoogleAnalyticsReportingPlugin | 80f982eecbfe48d6ebf3d3f79f6efb6a1264572c | 855232b64f1b964c886f2e09566b473fdffeb340 |
refs/heads/master | <repo_name>anaeinteractive/logics<file_sep>/src/selectors.ts
import { createSelector, Selector } from "reselect";
import {isArray, isFunction} from "util";
import {GetByKey, Hashmap} from "./types";
export type SelectorCreator = (getSelector: GetByKey<SelectorCreator>) => any;
export type AnySelector = Selector<any, any>;
export function parseSelectors(selectors: Hashmap<any>, rootPath: string) {
const selectorCreators: Hashmap<SelectorCreator> = {};
if (selectors) {
Object.keys(selectors).forEach((selectorName) => {
selectorCreators[selectorName] = makeSelectorCreator(selectors[selectorName], rootPath);
});
}
return selectorCreators;
}
type statePicker = (localState: any, state: any, rootPath: string) => ((state: any) => any);
export function makeSelectorCreator(arg: string|string[]|statePicker, rootPath: string): SelectorCreator {
if (typeof arg === "string") {
const pathArray = arg.split(".");
const fullPath = rootPath.split(".").concat(pathArray.slice(pathArray[0] === "@state" ? 1 : 0));
return () => (state: any) => fullPath.reduce((o: any, k: string) => o[k], state);
} else if (isArray(arg)) {
const len = arg.length;
return (getSelector: GetByKey<AnySelector>) => {
const args: any[] = arg.map((part: any, i: number) => {
if (i < len - 1) { return getSelector(part); }
return part;
});
return createSelector.apply(null, args);
};
} else if (isFunction(arg)) {
return () => (state: any) => {
const localState = rootPath.split(".").reduce((o: any, k: string) => o[k], state);
return arg(localState, state, rootPath);
};
} else {
throw new TypeError("supplied argument must be either a string or an array");
}
}
export function makeSelectors(selectorCreators: Hashmap<SelectorCreator>) {
const selectors: Hashmap<AnySelector> = {};
const getSelector: GetByKey<AnySelector> = (path: string): any => {
const selector = path.split(".").reduce((o: any, k: string) => {
if (o === undefined || o[k] === undefined) { return; } // TODO check if need throw
return o[k];
}, selectors);
if (!selector) {
const selectorCreator = selectorCreators[path];
if (!selectorCreator) {
throw new Error(`selector creator "${path}" not found`);
}
return registerSelector(selectorCreator, path);
}
return selector;
};
const registerSelector = (selectorCreator: SelectorCreator, path: string) => {
const selector = selectorCreator(getSelector);
selectors[path] = selector;
return selector;
};
Object.keys(selectorCreators).forEach((path) => {
const selectorCreator = selectorCreators[path];
registerSelector(selectorCreator, path);
});
return selectors;
}
export function makePropsFromSelectors(selectors: Hashmap<any>, state: any, props?: any) {
const newProps: any = {};
Object.keys(selectors).forEach((path: string) => {
const pathArray = path.split(".");
if (path[0][0] === "_") { return; }
const len = pathArray.length;
let pointer = newProps;
for (let i = 0; i < len; i++) {
const part = pathArray[i];
if (i === len - 1) {
pointer[part] = selectors[path](state, props);
} else {
pointer[part] = pointer[part] || {};
pointer = pointer[part];
}
}
});
return newProps;
}
<file_sep>/src/store.ts
import {
applyMiddleware, combineReducers, compose,
createStore as createReduxStore, DeepPartial, Middleware,
Reducer, Store, StoreCreator, StoreEnhancer,
} from "redux";
import createSagaMiddleware, { Effect, Task } from "redux-saga";
import {call, cancel} from "redux-saga/effects";
import {Logic, makeGetProps} from "./logic";
import {Hashmap} from "./types";
const windowIfDefined = typeof window === "undefined" ? null : window as any;
const composeEnhancers = windowIfDefined.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export interface StoreConfig {
state?: DeepPartial<{}>;
reducers?: {[name: string]: any};
middlewares?: Middleware[];
enhancers?: StoreEnhancer[];
}
export interface LogicsStore extends Store {
injectReducers: (reducers: {[name: string]: Reducer}) => void;
removeReducers: (reducers: string[]) => void;
registerLogic: (logic: Logic) => LogicRegistryEntry;
dropLogic: (logic: Logic) => void;
getLogic: (logicName: string) => LogicRegistryEntry|undefined;
}
export function reducerInjector(reduxCreateStore: StoreCreator): StoreCreator {
const reducers: Hashmap<Reducer> = {};
return (reducer: Reducer, preloadedState: any, enhancer?: StoreEnhancer) => {
const store = reduxCreateStore(reducer, preloadedState, enhancer);
(store as LogicsStore).injectReducers = (newReducers: Hashmap<Reducer>) => {
Object.keys(newReducers).forEach((r) => {
if (reducers[r]) {
throw new Error(`cannot inject reducer: a reducer with name "${r}" already exists`);
}
reducers[r] = newReducers[r];
});
store.replaceReducer(combineReducers(reducers));
store.dispatch({type: ""});
};
(store as LogicsStore).removeReducers = (names: string[]) => {
names.forEach((name) => delete reducers[name]);
store.replaceReducer(combineReducers(reducers));
store.dispatch({type: ""});
};
return store;
};
}
export interface LogicRegistry {
[path: string]: LogicRegistryEntry;
}
export interface LogicRegistryEntry {
logic: Logic;
getProps: (props?: any) => any;
watchers: Task[];
}
function createLogicRegistry(store: LogicsStore, runSaga: ((saga: any) => any)) {
const logics: LogicRegistry = {};
const register = (logic: Logic) => {
const entry = logics[logic.name];
if (entry) {
throw new Error(`cannot register logic : a logic named "${logic.name}" is already registred`);
} else {
const getProps = makeGetProps(logic, store);
const watchers = logic.watchers.map(runSaga);
logics[logic.name] = {logic, getProps, watchers};
if (logic.reducer) {
store.injectReducers({[logic.name]: logic.reducer});
}
return logics[logic.name];
}
};
const drop = (logic: Logic) => {
const entry = logics[logic.name];
if (entry) {
runSaga(function *() {
yield entry.watchers.map((task) => cancel(task));
yield call(store.removeReducers, [logic.name]);
});
} else {
throw Error(`cannot drop unregisterd logic "${logic.name}"`);
}
};
const get = (logicName: string) => logics[logicName];
return {register, drop, get};
}
export function createStore(config: StoreConfig = {}): LogicsStore {
const initialState = config.state || {};
const middlewares = config.middlewares || [];
const sagaMiddleware = createSagaMiddleware();
middlewares.push(sagaMiddleware);
const enhancers = [applyMiddleware(...middlewares), reducerInjector, ...(config.enhancers || [])];
const storeEnhancer: StoreEnhancer = composeEnhancers(...enhancers);
const rootReducer: Reducer = (state: {[key: string]: any} = {}) => state;
const store = createReduxStore(rootReducer, initialState, storeEnhancer) as LogicsStore;
if (config.reducers) { store.injectReducers(config.reducers); }
const logicRegistry = createLogicRegistry(store, sagaMiddleware.run);
store.registerLogic = logicRegistry.register;
store.dropLogic = logicRegistry.drop;
store.getLogic = logicRegistry.get;
return store;
}
<file_sep>/src/react.ts
import {
ComponentClass,
ComponentElement,
Context,
default as React,
ReactElement,
ReactNode,
StatelessComponent,
} from "react";
import {Unsubscribe} from "redux";
import {getStore} from ".";
import {createLogic, LogicDescriptor} from "./logic";
import {LogicRegistryEntry, LogicsStore} from "./store";
interface LogicProviderProps {
store?: LogicsStore;
logic: LogicDescriptor|((options: any) => LogicDescriptor);
name?: string;
children?: ReactNode[];
}
interface ILogicProvider {
(props: LogicProviderProps): ComponentElement<LogicsWrapperProps, LogicsWrapper>;
connect: (logicPath?: ((props: any) => string)|string) => (
ConnectedComponent: ComponentClass|StatelessComponent) => (
props: any) => ReactElement<any>;
}
export function createLogicProvider(): ILogicProvider {
const cache: {
descriptor?: LogicDescriptor;
name?: string;
entry?: LogicRegistryEntry;
} = {};
let context: Context<any>;
const LogicProvider = ({
store = getStore(),
logic: logicDesc,
name,
children,
}: LogicProviderProps) => {
if (!name) {
throw new Error("connot provide logic without a name");
}
if (logicDesc !== cache.descriptor || name !== cache.name) {
cache.name = name;
cache.descriptor = logicDesc;
if (cache.entry) {
store.dropLogic(cache.entry.logic);
}
const entry = store.getLogic(name);
if (entry) {
throw new Error(`a logic with name "${name}" is already registered`);
}
cache.entry = store.registerLogic(createLogic(logicDesc)(name));
}
const {logic, getProps} = cache.entry as LogicRegistryEntry;
const dropLogic = () => store.dropLogic(logic);
const subscribe = store.subscribe;
context = React.createContext(getProps());
return React.createElement(LogicsWrapper, {subscribe, dropLogic, getProps, context}, children);
};
(LogicProvider as ILogicProvider).connect = (logicPath: ((props: any) => string)|string = "") => {
return (ConnectedComponent: ComponentClass|StatelessComponent) => {
return ({children, ...props}: { children?: ReactNode; props?: any; }) => {
const {Consumer} = context;
const propsPath: string = typeof logicPath === "function" ? logicPath(props) : logicPath;
return React.createElement(Consumer, null, (logicProps: any) => {
const localProps = propsPath.split(".").reduce((o, k) => o[k], logicProps) || logicProps;
return React.createElement(ConnectedComponent, {...props, ...localProps}, children);
});
};
};
};
return LogicProvider as ILogicProvider;
}
interface LogicsWrapperProps {
subscribe: (listener: () => void) => Unsubscribe;
dropLogic: () => void;
getProps: () => any;
context: Context<any>;
children?: ReactNode[];
}
class LogicsWrapper extends React.Component<LogicsWrapperProps> {
private unsubscribe?: () => void;
public render() {
const value = this.props.getProps();
return React.createElement(this.props.context.Provider, {value}, this.props.children);
}
public handleChange() {
this.forceUpdate();
}
public componentDidMount() {
this.unsubscribe = this.props.subscribe(this.handleChange.bind(this));
}
public componentWillUnmount() {
if (this.unsubscribe) { this.unsubscribe(); }
this.props.dropLogic();
}
}
<file_sep>/src/logic.test.ts
import {createLogic} from "./logic";
describe("createLogic", () => {
test("returns result", () => {
const logicName = "test";
const logic = createLogic({})(logicName);
expect(logic).toHaveProperty("actions");
expect(logic).toHaveProperty("reducer");
});
});
<file_sep>/src/helpers.ts
import {Hashmap} from "./types";
export const isPlainObject = (o: any) => (typeof o === "object" && o !== null && !Array.isArray(o));
export function setPath(o: Hashmap<any>, path: string|string[], value: any) {
let pointer = o;
const pathParts = Array.isArray(path) ? path : path.split(".");
const depth = pathParts.length - 1;
pathParts.forEach((part, idx) => {
if (idx === depth ) {
pointer[part] = value;
} else {
pointer[part] = pointer[part] || {};
pointer = pointer[part];
}
});
return o;
}
export function getPath(o: Hashmap<any>, path: string|string[]) {
const pathParts = Array.isArray(path) ? path : path.split(".");
return pathParts.reduce((ptr, k) => ptr[k], o);
}
<file_sep>/src/actions.ts
import {AnyAction, Dispatch} from "redux";
import {ForkEffect, takeEvery, takeLatest} from "redux-saga/effects";
import {isArray, isFunction, isObject} from "util";
import {getPath, setPath} from "./helpers";
import {Hashmap} from "./types";
export function parseActions(actions: Hashmap<any>, rootPath: string) {
const actionCreators: Hashmap<ActionCreator> = {};
const reducerHandlers: Hashmap<ReducerHandler> = {};
const watcherCreators: any[] = [];
const actionTypes: string[] = [];
Object.keys(actions).forEach((actionName) => {
if (!actionName.match("^[a-zA-Z_]*$")) {
throw new Error(`invalid logic: "${actionName}" is not a valid action name`);
}
if (isObject(actions[actionName]) && !isArray(actions[actionName])) {
// defining combo (action creator + handler)
const combo = actions[actionName] as HandlerCreatorCombo;
// defining action creator
const type: string = makeActionType(rootPath, actionName);
const result = parseCombo(combo, type, actionName);
if (result.actionCreator) {
actionCreators[actionName] = result.actionCreator;
}
if (result.reducerHandler) {
reducerHandlers[type] = result.reducerHandler;
}
if (result.watcherCreator) {
watcherCreators.push(result.watcherCreator);
}
if (!actionTypes.includes(type)) { actionTypes.push(type); }
} else if (isFunction(actions[actionName])) {
// defining a handler for the reducer;
const type = makeActionType(...rootPath.split("."), actionName);
reducerHandlers[type] = actions[actionName] as ReducerHandler;
if (!actionTypes.includes(type)) { actionTypes.push(type); }
} else if (isArray(actions[actionName])) {
// defining an action creator
const [actionType, payloadCreator] = actions[actionName] as [string, PayloadCreator];
const actionCreator = makeActionCreator(actionType, payloadCreator);
actionCreators[actionName] = actionCreator;
} else if (typeof actions[actionName] === "string") {
// defining an action creator alias
// TODO
console.warn("action creator alias not yet implemented");
} else {
throw new Error(`invalid logic: actions entry cannot be a ${typeof actions[actionName]}`);
}
});
return {actionCreators, reducerHandlers, watcherCreators, actionTypes};
}
export function parseHandlers(handlers: Hashmap<any>, rootPath: string) {
const reducerHandlers: Hashmap<ReducerHandler> = {};
const watcherCreators: any[] = [];
const actionTypes: string[] = [];
Object.keys(handlers).forEach((key) => {
// defining a handler
let type: string;
if (key.match("^[.]{3}")) {
// defining type from action path
const actionPath = key.substr(3);
if (!actionPath.match("[a-zA-Z_[.]]*")) {
throw new Error(`invalid logic: invalid action path "${actionPath}"`);
}
// defining action type from path
// const shift = actionPath.split(".").length - 1;
// type = makeActionType(...rootPath.split(".").slice(0, -shift), actionPath);
type = makeActionType(...rootPath.split(".").slice(0, 1), actionPath);
} else {
// key is directly an action type;
type = key;
if (!actionTypes.includes(type)) { actionTypes.push(type); }
}
if (typeof handlers[key] === "function") {
// defining reducer handler
const handler = handlers[key] as ReducerHandler;
reducerHandlers[type] = handler;
} else if (isObject(handlers[key]) && !isArray(handlers[key])) {
// defining watcher or reducer handler
const combo = handlers[key] as HandlerCreatorCombo;
// cannot define an action creator here
if (combo.payload !== undefined) {
throw new Error(`invalid logic: "${key}" cannot define an action creator`);
}
const result = parseCombo(combo, type);
if (result.reducerHandler) {
reducerHandlers[type] = result.reducerHandler;
}
if (result.watcherCreator) {
watcherCreators.push(result.watcherCreator);
}
} else {
throw new Error(`invalid logic: handler for "${key} must a be either a function or an object`);
}
});
return {reducerHandlers, watcherCreators, actionTypes};
}
type WatcherTaker = (type: string, actions: any) => () => IterableIterator<ForkEffect>;
export type ActionWatcher = () => IterableIterator<ForkEffect>;
export type WatcherCreator = (actions: any) => ActionWatcher;
type ReducerHandler = (state: any, payload: any, error: any) => any;
export type PayloadCreator = (...args: any[]) => any;
export interface HandlerCreatorCombo { name?: string; payload: any; take?: string; handler: any; }
interface ParseComboResult {
actionCreator?: ActionCreator;
reducerHandler?: ReducerHandler;
watcherCreator?: WatcherCreator;
}
function parseCombo(combo: HandlerCreatorCombo, type: string, name?: string) {
const {payload, take, handler} = combo;
const result: ParseComboResult = {};
if (name && payload !== undefined) {
const actionCreator = makeActionCreator(type, payload);
result.actionCreator = actionCreator;
}
// define action handler
if (!isFunction(handler)) {
throw new Error(`invalid logic: handler for "${type}" must be a function`);
}
if (take) {
// handler is a saga
if (!handler) {
throw new Error(`invalid logic: missing handler for "${type}" action watcher`);
}
result.watcherCreator = makeWatcherCreator(type, take, handler);
} else {
// handler is a reducer
result.reducerHandler = handler;
}
return result;
}
function makeWatcherCreator(type: string, take: string|WatcherTaker, handler: GeneratorFunction): WatcherCreator {
if (typeof take === "function") {
return (actions: any) => take(type, actions);
} else if (take === "every") {
return (actions: any) => function* watch() {
yield takeEvery(type, handler, actions);
};
} else if (take === "latest") {
return (actions: any) => function* watch() {
yield takeLatest(type, handler, actions);
};
} else {
throw new Error(`invalid logic: wrong \"take\" value for action type "${type}"`);
}
}
export type ActionCreator = (...args: any[]) => AnyAction;
export function makeActionCreator(type: string, payloadCreator?: any): ActionCreator {
const actionCreator: ActionCreator = (...args: any[]) => {
const action: AnyAction = {type};
if (payloadCreator === undefined) { return action; }
if (typeof payloadCreator === "function") {
const data = payloadCreator(...args);
if (isObject(data) && !isArray(data) && data.payload !== undefined) {
action.payload = data.payload;
} else {
action.payload = data;
}
} else if ((payloadCreator instanceof Error || payloadCreator instanceof TypeError)) {
action.payload = {message: payloadCreator.message};
action.error = true;
} else if (payloadCreator !== null) {
throw new Error("invalid payload creator: it must be either a function, an error or a null");
}
return action;
};
actionCreator.toString = () => type;
return actionCreator;
}
export function makeActionType(...args: string[]) {
return args.join(".").split(".").join("__").toUpperCase();
}
export function makeActions(actionCreators: Hashmap<any>, actionTypes?: Hashmap<string>) {
const actions: any = {};
Object.keys(actionCreators).forEach((logicPath: string) => {
const logicActionCreators = actionCreators[logicPath];
Object.keys(logicActionCreators).forEach((actionPath: string) => {
const fullPath = logicPath.split(".").slice(1).concat(actionPath.split("."));
const createAction = logicActionCreators[actionPath];
if (actionTypes && !actionTypes[createAction.toString()]) {
throw new Error(`"${createAction.toString()}" is not a valid action type`);
}
setPath(actions, fullPath, logicActionCreators[actionPath]);
});
});
if (actionTypes) {
actions._types = actionTypes;
}
return actions;
}
<file_sep>/README.md
# Logics
## What Is Logics?
Logics is a library for defining and organizing the state of an application and the logic to manage it in the form of composable logics. It is built has a thin layer on top of [Redux](https://github.com/reduxjs/redux), [Redux-Saga](https://github.com/redux-saga/redux-saga) and [Reselect](https://github.com/reduxjs/reselect).
## How Does It Work?
Working with Redux usually implies having to define action types, action creators, and reducers in different files. Other files defining sagas and selectors also probably have to be added. This tends to make the code verbous and can lead to a certain complexity.
Instead Logics defines the logic of an app in self contained and composable "logics":
```js
const counterLogic = {
state: {
count: 0,
step: 1,
},
actions: {
decrement: {
payload: (step) => step,
handler: (state, step) => ({...state, count: state.count - step})
},
increment: {
payload: (step) => step,
handler: (state, step) => ({...state, count: state.count + step})
},
},
selectors: {
count: "@state.count"
},
};
```
## Getting Started
### Installation
npm install logics
### Defining Logics
```js
// /logics/display.js
export default {
state { // define the default state
message: "",
status: "",
},
actions: {
set: { // define an action
payload: (message, status) => ({message, status}), // function to build the payload of this action (for action creator)
handler: (state, {message, status=""}) => ({...state, message, status}) // reducer to handle this action
},
clear: { // define an other action
payload: null, // null means that the action will have no payload,
handler: () => ({message: "", status: ""})
},
},
};
```
```js
// /logics/counter.js
export default ({defaultStep=1}) => { // define a configurable logic: (options) => logic
state: {
count: 0,
step: defaultStep,
},
actions: {
decrement: {
payload: (step) => step,
handler: (state, step) => ({...state, count: state.count - step})
},
increment: {
payload: (step) => step,
handler: (state, step) => ({...state, count: state.count + step})
},
setStep: {
payload: (value) => value,
handler: (state, value) => ({...state, step: value})
},
},
selectors: {
count: "@state.count",
},
};
```
```js
// /logics/main.js
import api from "../api"; // import an hypothetic API
import {call, put} from "logics/effects";
import displayLogic from "./display-logic";
import counterLogic from "./counter-logic";
export default = {
__display: displayLogic, // use displayLogic as sub-logic
__counter: { // use counterLogic as sub-logic
logic: counterLogic(5), // logic will is merged to be extended
actions: {
saveCount: {
payload: (state) => state.count,
take: "latest", // take parameter indicates that hadler defines a saga
handler: function* (actions, {payload}) {
try {
yield put(actions.display.set("saving count..."));
yield call(api.saveCount(payload));
yield put(actions.display.set("count saved", "success"));
} catch (e) {
yield put(actions.display.set("error saving count", "error"));
}
}
},
},
};
```
### Using Logics With React
```jsx
// /components/LogicProvider.js
import {createLogicProvider} from "logics/react";
export default createLogicProvider();
```
```jsx
// /components/counter.jsx
import React from "react";
import {LogicProvider} from "./LogicProvider";
const Counter = ({count, step, actions}) => {
const increment = () => actions.increment(step);
const decrement = () => actions.decrement(step);
const updateStep = (e) => {
const value = parseInt(e.currentTarget.value, 10);
actions.setStep(value);
};
const saveCount = () => actions.saveCount(count)
return (
<div>
<button onClick={decrement}>-</button> | {count} | <button onClick={increment}>+</button><br/>
<br/>
<span>step: </span><input type="text" value={step} onChange={updateStep}/><br/>
<br/>
<button conClick={saveCount}>Save</button>
</div>
);
};
export default LogicProvider.connect("counter")(Counter);
```
```jsx
// /components/display.jsx
import React from "react";
import {LogicProvider} from "./LogicProvider";
export Display = (props) => {
const {message, status} = props["@state"];
return (
<div class={status}>{message}</div>
);
};
export defaut LogicProvider.connect("display")(Display);
```
```jsx
// /app.jsx
import React from "react";
import ReactDOM from "react-dom";
import {LogicProvider} from "./LogicProvider";
import Counter from "./components/counter";
import Display from "./components/display";
import mainLogic from "./logics/main";
const App = () => {
const {getContext} = LogicProvider;
return (
<LogicProvider logic={mainLogic} name="app">
<Display />
<br/>
<Counter />
</LogicProvider>
);
};
ReactDOM.render(React.createElement(App), document.getElementById("app"));
```
## Licence
The MIT License
Copyright (c) 2018 ANAE INTERACTIVE<file_sep>/src/logic.ts
import {combineReducers, Reducer} from "redux";
import {isArray, isObject} from "util";
import {
ActionCreator,
ActionWatcher,
HandlerCreatorCombo,
makeActions,
parseActions,
parseHandlers,
PayloadCreator,
WatcherCreator,
} from "./actions";
import {isPlainObject, setPath} from "./helpers";
import {
AnySelector,
makePropsFromSelectors,
makeSelectorCreator,
makeSelectors,
parseSelectors,
SelectorCreator,
} from "./selectors";
import {LogicsStore} from "./store";
import {Hashmap} from "./types";
export interface LogicDescriptor {
state?: any;
private?: boolean;
selectors?: {
[selectorKey: string]: string|any[]|(() => any);
};
actions?: {
[actionKey: string]: [string, PayloadCreator]|HandlerCreatorCombo|string;
};
actionTypes?: string[];
[namespaceKey: string]: any;
}
export type LogicDescriptorFactory = (options: {[opt: string]: any}) => Logic;
interface SubLogic {
actionCreators: Hashmap<ActionCreator>;
// selectors: Hashmap<AnySelector>;
}
export type LogicFactory = (name: string) => Logic;
export interface Logic {
readonly name: string;
readonly actions: Hashmap<string>;
readonly watchers: ActionWatcher[];
readonly reducer: Reducer;
readonly selectors: Hashmap<AnySelector>;
readonly actionCreators: Hashmap<Hashmap<ActionCreator>>;
// readonly logics: Hashmap<SubLogic>;
}
export interface LogicParsingResult {
actionTypes: string[];
selectorCreators: Hashmap<SelectorCreator>;
actionCreators: Hashmap<Hashmap<ActionCreator>>;
watcherCreators: WatcherCreator[];
reducer: Reducer;
// logics: Hashmap<SubLogic>;
}
export function createLogic(descriptor: LogicDescriptor|((o: any) => LogicDescriptor), options: Hashmap<any> = {}) {
let logic: Logic;
return (name: string) => {
if (logic && logic.name === name) { return logic; }
descriptor = (typeof descriptor === "function") ? descriptor(options) : descriptor;
const {reducer, ...result} = parseLogicDescriptor(descriptor, name);
const selectors = makeSelectors(result.selectorCreators);
const actionCreators = result.actionCreators;
const actionTypes = result.actionTypes.reduce((o: any, type: string) => { o[type] = type; return o; }, {});
const actions = makeActions(actionCreators, actionTypes);
const watchers = result.watcherCreators.map((wc: WatcherCreator) => wc(actions));
logic = { name, actions, watchers, reducer, selectors, actionCreators };
return logic;
};
}
function parseLogicDescriptor(logic: LogicDescriptor, rootPath: string = "logic"): LogicParsingResult {
if (rootPath === "") { throw new Error("rootPath cannot be empty"); }
const result: any = {}; // TODO define result type
const logicBase: LogicDescriptor = logic.logic || {};
// define initial state
const initialState: any = logic.state || logicBase.state;
// define action types
const actionTypes: string[] = logicBase.actionTypes || [];
(logic.actionTypes || []).forEach((type: string) => {
if (!actionTypes.includes(type)) { actionTypes.push(type); }
});
// parse "selectors" entry
const selectorCreators: Hashmap<SelectorCreator> = {};
if (logic.selectors || logicBase.selectors) {
const selectors = Object.assign({}, logicBase.selectors, logic.selectors);
Object.assign(selectorCreators, parseSelectors(selectors, rootPath));
} else {
// make selector creator for the whole state if no selectors are defined
if (logic.state && !(logic.private || logic.logic && logic.logic.private)) {
// const logicName = rootPath.split(".").pop() as string;
selectorCreators["@state"] = makeSelectorCreator("@state", rootPath);
}
}
const reducers: Hashmap<any> = {};
const actionCreators: Hashmap<Hashmap<ActionCreator>> = {};
const watcherCreators: WatcherCreator[] = [];
const reducerHandlers: Hashmap<Reducer> = {};
// parse "actions entry"
if (logic.actions || logicBase.actions) {
const actions = Object.assign({}, logicBase.actions, logic.actions);
const res = parseActions(actions, rootPath);
Object.assign(actionCreators, {[rootPath]: res.actionCreators});
Object.assign(reducerHandlers, res.reducerHandlers);
watcherCreators.push(...res.watcherCreators);
res.actionTypes.forEach((type: string) => {
if (!actionTypes.includes(type)) { actionTypes.push(type); }
});
// if (Object.keys(res.reducerHandlers).length > 0) {
// result.reducer = makeReducer(res.reducerHandlers, initialState);
// }
}
// parse "handlers entry"
if (logic.handlers || logicBase.handlers) {
const handlers = Object.assign({}, logicBase.handlers, logic.handlers);
const res = parseHandlers(handlers, rootPath);
Object.assign(reducerHandlers, res.reducerHandlers);
watcherCreators.push(...res.watcherCreators);
res.actionTypes.forEach((type: string) => {
if (!actionTypes.includes(type)) { actionTypes.push(type); }
});
}
if (Object.keys(reducerHandlers).length > 0) {
result.reducer = makeReducer(reducerHandlers, initialState);
}
// parse sub logics
Object.keys(logic).forEach((key: string) => {
if (key[0] !== "_") { return; }
if (isArray(logic[key]) || !isObject(logic[key])) {
throw new Error("invalid logic: sub-logic must be a plain object");
}
if (initialState !== undefined) {
throw new Error("invalid logic: cannot define a sub-logic inside a sub-state");
}
if (key.match("^__")) {
// defining a sub-namespace;
const subName = key.substr(2);
const logicPath = rootPath + "." + subName;
const subResult = parseLogicDescriptor(logic[key], logicPath);
subResult.actionTypes.forEach((type: string) => {
if (!actionTypes.includes(type)) { actionTypes.push(type); }
});
watcherCreators.push(...subResult.watcherCreators);
if (subResult.reducer) { reducers[subName] = subResult.reducer; }
// add selector for sublogic in current logic
const subSelectorCreators = subResult.selectorCreators;
Object.keys(subSelectorCreators).forEach((subPath) => {
const subSelectorCreator = subSelectorCreators[subPath];
const p = subName + "." + subPath;
selectorCreators[p] = subSelectorCreator;
});
// put action creators is sub-namespace
Object.assign(actionCreators, subResult.actionCreators);
} else {
// defining a sub-state;
const subName = key.substr(1);
const subLogic = logic[key];
const logicPath = rootPath + "." + subName;
const subResult = parseLogicDescriptor(subLogic, logicPath);
subResult.actionTypes.forEach((type: string) => {
if (!actionTypes.includes(type)) { actionTypes.push(type); }
});
watcherCreators.push(...subResult.watcherCreators);
if (subResult.reducer) { reducers[subName] = subResult.reducer; }
// add selector for sublogic in current logic
const subSelectorCreators = subResult.selectorCreators;
const subState = subLogic.state || subLogic.logic && subLogic.logic.state;
// const prvt = subLogic.private || subLogic.logic && subLogic.logic.private;
// if (subState && !prvt && Object.keys(subSelectorCreators).length === 0) {
// // make selector creator for the whole state if no selectors are defined
// selectorCreators[subName] = makeSelectorCreator("@state", rootPath + "." + subName);
// } else {
// Object.keys(subSelectorCreators).forEach((subPath) => {
// const selectorCreator = subSelectorCreators[subPath];
// selectorCreators[subName + "." + subPath] = selectorCreator;
// });
// }
Object.keys(subSelectorCreators).forEach((subPath) => {
const selectorCreator = subSelectorCreators[subPath];
if (subPath === "@state") {
selectorCreators[subName] = selectorCreator;
} else {
selectorCreators[subName + "." + subPath] = selectorCreator;
}
});
// merge action creators
const subActionCreators = subResult.actionCreators[logicPath];
Object.keys(subActionCreators).reduce((o: any, k: string) => {
o[subName + "." + k] = subActionCreators[k];
return o;
}, actionCreators[rootPath]);
}
});
if (Object.keys(reducers).length > 0) {
result.reducer = combineReducers(reducers);
}
result.actionTypes = actionTypes;
result.actionCreators = actionCreators;
result.selectorCreators = selectorCreators;
result.watcherCreators = watcherCreators;
return result as LogicParsingResult;
}
function makeReducer(handlers: Hashmap<any>, initialState: any) {
if (initialState === undefined) {
throw new Error("invalid logic: cannot define a reducer without an initial state");
}
return (state: any = initialState, action: any) => {
const handle = handlers[action.type];
if (!handle) { return state; }
const payload = action.payload === undefined ? action : action.payload;
return handle(state, payload, action.error);
};
}
export function makeGetProps(logic: Logic, store: LogicsStore) {
const logicActions: any = {};
Object.keys(logic.actionCreators).forEach((logicPath: string) => {
const actions = logic.actionCreators[logicPath];
if (!actions) { return; }
const actionTree = {};
Object.keys(actions).forEach((actionPath) => {
const dispatch = (...args: any[]) => store.dispatch(actions[actionPath](...args));
return setPath(actionTree, "actions." + actionPath, dispatch);
});
const subPath = logicPath.split(".").slice(1);
if (subPath.length === 0) {
Object.assign(logicActions, actionTree);
} else {
setPath(logicActions, subPath, actionTree);
}
});
return (props: Hashmap<any> = {}) => {
const state = store.getState();
const logicProps: Hashmap<any> = {...props, ...makePropsFromSelectors(logic.selectors, state)};
return deepMerge(logicProps, logicActions);
};
}
function deepMerge(o1: any, o2: any) {
const o = {...o1};
Object.keys(o2).forEach((k) => {
const value = o2[k];
if (isPlainObject(o2[k])) {
o[k] = isPlainObject(o[k]) ? o[k] : {};
o[k] = deepMerge(o[k], o2[k]);
} else {
o[k] = o2[k];
}
});
return o;
}
<file_sep>/src/index.ts
import {createLogic} from "./logic";
import {createStore, LogicsStore} from "./store";
export {createLogic};
export {createStore};
let store: LogicsStore;
export function getStore() {
store = store || createStore();
return store;
}
export default {
createLogic,
createStore,
getStore,
};
| f69ee41820fc332405254d056f71995fbfd5022d | [
"Markdown",
"TypeScript"
] | 9 | TypeScript | anaeinteractive/logics | 35f771ca82fbb1192b2ecded3d8004d1ce51c3cb | 3b418ed70a44bef664cc5f9d8fb17bc5a5c3f151 |
refs/heads/master | <repo_name>DrydenLinden/Csc-Project<file_sep>/sat2sud.py
import re
import sys
import os
def sat2sud (bubble):
try:
file = open(bubble[1],'r')
intake = file.read()
intake = intake[3:]
file.close()
except:
print("error opening txt file.")
Matrix = [[0 for z in range(9)] for y in range(9)]
for line in intake.split(" "):
if(int(line) == 0):
break
if (line.find('-', 0) == -1):
Matrix[int(line[0])-1][int(line[1]) -1] = int(line[2])
s = ""
for c in range(9):
for q in range (9):
s = s + str(Matrix[q][c])
s = s + "\n"
print(s)
bubble = sys.argv
sat2sud(bubble)
<file_sep>/sat2sud729.py
import re
import sys
import os
def sat2sud (bubble):
try:
file = open(bubble[1],'r')
intake = file.read()
intake = intake[3:]
file.close()
except:
print("error opening txt file.")
Matrix = [[0 for z in range(9)] for y in range(9)]
for line in intake.split(" "):
if(int(line) == 0):
break
if (line.find('-', 0) == -1):
c = int(line)
if(c <= 9):
Matrix[0][0]= c
if(c <= 81):
p = c/9
d = c-(p*9)
Matrix[0][p] = d
else:
p = c/81
d = c - (p*81)
e = d/9
f = d - (e*9)
Matrix[p][e] = f
s = ""
for c in range(9):
for q in range (9):
s = s + str(Matrix[q][c])
s = s + "\n"
print(s)
bubble = sys.argv
sat2sud(bubble)<file_sep>/README.md
Sud2SAT
=============
Created By
-------------
<NAME> V00849440
<NAME> V00839944
<NAME> V00844643
Divyapreet Chawla V00862263
Introduction
------------
The Files Sat2sud729 and sud2sat729 are the minimalencided versions.
while sat2sud and sud2sat are extended versions
The Program Sud2Sat inclosed is designed to take a unsolved suduko puzzle of the form
000001000
100020040
200030060
000000000
000000000
000000000
000000000
000000000
000000000
or of the form
000001000100020040200030060000000000000000000000000000000000000000000000000000000
Where the zeros or other non-numeric characters represent unknown values ranging from 1-9.
The program will then take the text and convert it into a cnf format with the form 123 where the 1 correspods to row the 2 corresponds to col and 3 is the value.
This cnf format will then be passed to a miniSAT solver to be solved and the output of that will be parsed and put into the form listed above.
Requirments
------------
The operation of this program requires the miniSAT SATsolver to be installed in the same directory as the python file.
Librarys
---------
The Program uses the OS , sys and re.
How To Run
----------
python sud2sat.py \<inputfile\>
python sat2sud.py CNF.txt
<file_sep>/SATsolver.py
#Initial File
'''
Sudo Code For project:
function From_puzzle_to_cnf(stdin){
Read Input From Stdin
if (no input throw error){
}
// Load input into something and ignore newlines
/*
we intiat are data structure whatever it it to have all spots be wild cards then as we find non wild cards
we change the appropriate items in are datastructure to not include the new value ie tables stars like this:
000000000
000000000
000000000
000000000
000000000
000000000
000000000
000000000
000000000
then after find a 2 in the input at the 1,2 position
we mark the 1,2 position as not everythiong except 2
020000000
000000000
000000000
000000000
000000000
000000000
000000000
000000000
000000000
and we mark the first row and second column plus the 3x3 grid as not 2
*/
// a possible datastructure could be a 3d array 3x3x9 where possible values are stored in the 9 length array
while (more chars/ints){
for the 9 ints/chars {
IF (wildcard){
continue
}
else (not wild card){
remove item from possible values of col
remove item from possible values of row
remove item from possible values of 3x3
}//else
read next int/ char
} // for
}// while
// after done reading input into datastructure we have a function/method evalute are structure and spit it out in normal form
output = Some_func(datastructure );
return output//Print?
}
some_func(structure){
// convert from are datasctructure to the cnf form
for i<9 {
for i<9{
while more pssible values
string clause += cur.pos + all values possible
print
//state that all possible values would conflict with all values in the row, col and 3x3
while more row
string clauserow = '-' + cur.pos + '-' + current row positon + '0'
print
while more col
string clausecol = '-' + cur.pos + '-' + current column positon + '0'
print
while more 9x9
string claus9 = '-' + cur.pos + '-' + current 9 positon + '0'
print
}// col
}// row
}
function convertfromcnftopuzzle(stdin){
table sudoku[][]
Start by reading the cnf into stdin
read first line
x = lines from it
for y:x
if (y contains - )
continue
else if(number of spaces > 1 )
continue
else
z = y.split('')
table[z[0][z[1] = z[3]
}
'''
<file_sep>/sud2sat.py
import sys
import os
import re
def grid(s,x,t, y, value):
for i in range(s,x):
for j in range(t,y):
puzzle[i][j][value] = 0
def mark(value, x, y):
for k in range(9):
puzzle[x][k][value] = 0
puzzle[k][y][value] = 0
if(x < 3):
if(y < 3):
grid(0,3,0,3, value)
if(y < 6):
grid(0,3,3,6, value)
else:
grid(0,3,6,9, value)
if(x < 6):
if(y < 3):
grid(3,6,0,3, value)
if(y < 6):
grid(3,6,3,6, value)
else:
grid(3,6,6,9, value)
else:
if(y < 3):
grid(6,9,0,3, value)
if(y < 6):
grid(6,9,3,6, value)
else:
grid(6,9,6,9, value)
def CNFpos(x, y, z):
sa = ""
for p in range(10):
if(p > 0):
for i in range(p+1, 10):
sa = sa +"-"+str(x+1)+str(y+1)+str(p)+" -"+str(x+1)+str(y+1)+str(i)+" 0\n"
return(sa);
def CNFrow(x, y, value):
sr = ""
for t in range(1,10):
if(t != y+1):
sr = sr + "-"+str(x+1)+str(y+1)+str(value)+" -"+str(x+1)+str(t)+str(value)+" 0\n"
return sr
def CNFcol(x, y, value):
sc = ""
for c in range(1,10):
if(c != x+1):
sc = sc + "-"+str(x+1)+str(y+1)+str(value)+" -"+str(c)+str(y+1)+str(value)+" 0\n"
return sc
def CNFbox(x, y, value):
if(x < 3):
if(y < 3):
return(grid1(1,4,1,4,x,y, value))
if(y < 6):
return(grid1(1,4,4,7,x,y, value))
else:
return(grid1(1,4,7,10,x,y, value))
if(x < 6):
if(y < 3):
return(grid1(4,7,1,4,x,y, value))
if(y < 6):
return(grid1(4,7,4,7,x,y, value))
else:
return(grid1(4,7,7,10,x,y, value))
else:
if(y < 3):
return(grid1(7,10,1,4,x,y, value))
if(y < 6):
return(grid1(7,10,4,7,x,y, value))
else:
return(grid1(7,10,7,10,x,y, value))
return
def grid1(s1,f1,s2,f2,x,y,value):
sg = ""
for i in range(s1,f1):
for j in range(s2,f2):
if(i != x+1 and j != y+1):
sg = sg+ "-"+str(x+1)+str(y+1)+str(value)+" -"+str(i)+str(j)+str(value)+" 0\n"
return sg
def check(str):
if str == '0':
return False
if str == '*':
return False
if str == '.':
return False
if str == '?':
return False
return True
x = sys.argv
count = 0
try:
file = open(x[1],'r')
x = file.read().split('\n')
file.close()
except:
print("error opening txt file.")
if(len(x[0]) == 0):
print("No Input Provided.")
exit()
if(len(x) == 9):
lines = x
else:
lines = re.findall('.........?', x[0])
puzzle = [[[ 1 for col in range(10)]for col in range(10)]for col in range(10)]
def sud2sat():
count = 0
for x in range(9):
number = re.findall('.', lines[x])
for y in range(9):
if(check(number[y])):
i = int(number[y])
puzzle[x][y][0] = i;
mark(i,x,y)
else:
count = count + 1
puzzle[x][y][0] = 0;
try:
file = open('CNF.txt', 'w')
file.write("p cnf 17577 729 \n")
except:
print("error opening txt file.")
for x in range(9):
for y in range(9):
so = ""
for z in range(10):
if(z == 0 and puzzle[x][y][z] != 0):
so = str(x+1)+str(y+1)+str(puzzle[x][y][z])
so = so + " 0\n"
count = count + 1
break;
elif(z == 9):
if(puzzle[x][y][z] == 1):
so = so + str((x+1))+str(y+1)+str(z)
so = so + " 0\n"
else:
so = so +str(x+1)+str(y+1)+str(z)
so = so + " 0\n"
elif(z > 0):
if(puzzle[x][y][z] == 1):
so = so + str((x+1))+str(y+1)+str(z)
so = so + " "
else:
so = so + str(x+1)+str(y+1)+str(z)
so = so + " "
file.write(so)
file.write(CNFpos(x,y,z))
## write now it says it can be 1 or 2 or 3 .. etc now I need to say that
## for each row, column and box, if its 111 then nothing in row box or column can be
## if its 112 nothing in that row, box, or columns could be etc.
for p in range(10):
if(p > 0 ):
file.write(CNFrow(x,y,p))
# mark all things in xyp row can't be p
file.write(CNFcol(x,y,p))
# mark all things in xyp col can't be p
file.write(CNFbox(x,y,p))
# mark all things in xyp box can't be p
file.close()
cmd = 'minisat CNF.txt SatOutput.txt'
os.system(cmd)
sud2sat()
| b3b5c153f33ebd3014b8ac8ec6fb305cb8bb73c9 | [
"Markdown",
"Python"
] | 5 | Python | DrydenLinden/Csc-Project | 617c6aa0c9c87ad2503f589ad7eaf7f245f86448 | 96b2024a8c94b7d8048592691cbbf39d90266d88 |
refs/heads/main | <file_sep>/**
* @file Scheduler.hpp
*
* @author <NAME>
* Contact: <EMAIL>
*
*/
#ifndef Scheduler_hpp
#define Scheduler_hpp
#include "Process.hpp"
class Scheduler{
Process *soq;
Process *eoq;
string schedule_name;
int arrival_time;
int _size, _capacity;
int wt_total;
float quantum;
public:
Scheduler(int, string);
~Scheduler();
void add(int, string);
string drop();
int capacity() const {return _capacity;}
int size() const {return _size;}
bool empty() const {return _size == 0;};
bool full() const {return _size == _capacity;}
void print();
};
#endif<file_sep>/**
* @file main .cpp
*
* @author <NAME>
* Contact: <EMAIL>
*
*/
#include "include/Process.hpp"
#include "include/Scheduler.hpp"
#include "include/Dataloader.hpp"
#include <random>
#include <iostream>
using namespace std;
int main(){
int p_count = 500;
// Random seed
srand(time(NULL));
Dataloader datapack;
vector<string> data = datapack.getData();
// Creating a new schedule
Scheduler my_pc(p_count, "Sessión Android.");
try{
for(int i = 0; i < p_count; i++){
my_pc.add((rand() % 1000 + 1), data[rand() % data.size() + 1]);
}
}catch(const char* e){
cout << e << endl;
}
my_pc.print();
cout << data[4] << endl;
return 0;
}<file_sep>g++ -o robin.out main.cpp src/Scheduler.cpp src/Dataloader.cpp
<file_sep>/**
* @file Datalaoder.cpp
*
* @author <NAME>
* Contact: <EMAIL>
*
*/
#include <iostream>
#include "../include/Dataloader.hpp"
#include <fstream>
#include <vector>
#include <assert.h>
#include <iterator>
#include <iomanip>
using namespace std;
Dataloader::Dataloader(){}
vector<string> Dataloader::getData(){
string filename = "datapack/googleplaystore.txt";
ifstream file(filename);
assert(file);
vector<string> fileContents;
copy(istream_iterator<string>(file), istream_iterator<string>(),back_inserter(fileContents));
return fileContents;
}<file_sep>/**
* @file Dataloader.cpp
*
* @author <NAME>
* Contact: <EMAIL>
*
*/
#ifndef Dataloader_hpp
#define Dataloader_hpp
#include <vector>
using namespace std;
class Dataloader{
vector<string> data;
public:
Dataloader();
vector<string> getData();
};
#endif<file_sep>/**
* @file Process.cpp
*
* @author <NAME>
* Contact: <EMAIL>
*
*/
#ifndef Node_hpp
#define Node_hpp
#include <string>
using namespace std;
class Process{
// You could also add different data information as: PID, directions, etc.
int priority;
int burst_time;
string process_name;
Process *p;
public:
Process(int _p, string _pn): burst_time(_p), process_name(_pn), p(nullptr){}
int getBurstTime() const {return burst_time;}
string getProcessName() const {return process_name;}
Process *next() {return p;}
void next(Process *q) {p = q;}
};
#endif <file_sep>/**
* @file Scheduler.cpp
*
* @author <NAME>
* Contact: <EMAIL>
*
*/
#include "../include/Process.hpp"
#include "../include/Scheduler.hpp"
#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <chrono>
#include <thread>
using namespace std;
Scheduler::Scheduler(int c, string sn): _capacity(c), schedule_name(sn){
_size = 0;
arrival_time = 0;
eoq = NULL;
soq = NULL;
}
// Destructor
Scheduler::~Scheduler(){
while(!empty()){
drop();
}
}
// Enqueue
void Scheduler::add(int x, string pn){
if(full()){
cout << "Queue overflow!" << endl;
throw("Message");
}else{
Process *tmp = new Process(x, pn);
tmp->next(NULL);
if(size() == 0){
eoq = tmp;
soq = tmp;
}else{
eoq->next(tmp);
eoq = tmp;
}
// cout << "in: " << eoq->getProcessName() <<" - "<<eoq->getBurstTime() << endl;
_size++;
}
}
// Dequeue
string Scheduler::drop(){
if(empty()){
cout << "Queue underflow!" << endl;
return "-1";
}else{
if(size() == 1){
string tmp_data = soq->getProcessName();
delete soq;
soq = NULL;
eoq = NULL;
_size = 0;
return tmp_data;
}else{
string tmp_data = soq->getProcessName();
Process *tmp = soq;
soq = soq->next();
delete tmp;
_size--;
return tmp_data;
}
}
}
void Scheduler::print(){
int p_aux = 0;
if(!empty()){
system("clear");
Process *soq_copy = soq;
cout << "\033[1;32m"<< schedule_name << "\033[0m" << endl;
cout.width(15);
cout << left << "Burst time |" << setw(2) << "Process name" << endl;
while(soq_copy != NULL){
cout.width(15);
cout << left << soq_copy->getBurstTime() << soq_copy->getProcessName() << endl;
p_aux++;
wt_total = wt_total + soq_copy->getBurstTime();
soq_copy = soq_copy->next();
}
cout << "Process count: " << size() << endl;
cout << "Quantum: " << wt_total / (float) size() << endl;
cout << "Total waiting time: " << wt_total << endl;
}
} | 99621d2a086e9a8ab9f8221e14158ba775facc00 | [
"C++",
"Shell"
] | 7 | C++ | evilelliot/Scheduling-Round-Robin | 95fa7e990dae4fa17bb478baeb79c4e4ad043716 | 2d09f1933ce135c5b093139cf0a076ed82e26cce |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import {ReportService} from '../services/report.service';
@Component({
selector: 'app-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css']
})
export class FiltersComponent implements OnInit {
fromDate: string;
toDate: string;
filterBtns: {name: string, active: boolean}[] = [
{name: 'All Time', active: true},
{name: 'Yesterday', active: false},
{name: 'Last 7 Days', active: false},
{name: 'Last 30 Days', active: false},
{name: 'Last 6 Months', active: false},
];
// Current active filter, initial set to 'All Time'
activeButton = this.filterBtns[0];
constructor(private reportService: ReportService) { }
ngOnInit() {
this.reportService._filterDatesListener.subscribe((data: any) => {
this.fromDate = data.fromDate;
this.toDate = data.toDate;
});
}
/**
* Set current active button to false to remove highlight
* Set button clicked to active to apply highlight
* @param {number} index - the index of the button clicked
*/
onFilterBtnClick(index: number) {
// If same active button is clicked do nothing
if (this.activeButton === this.filterBtns[index]) {
return;
}
this.activeButton.active = false;
this.filterBtns[index].active = true;
this.activeButton = this.filterBtns[index];
this.reportService.getFilteredReports(this.activeButton.name);
}
/**
* Reset active to all time
* Clear date filter
*/
onClearBtnClick() {
this.activeButton.active = false;
this.filterBtns[0].active = true;
this.activeButton = this.filterBtns[0];
// Clear date inputs
this.clearDates();
// Reset reports to all time
this.reportService.getFilteredReports();
}
/**
* Reset date inputs to undefined
*/
clearDates() {
this.toDate = this.fromDate = undefined;
}
onToDateChange() {
if (this.fromDate === undefined || this.toDate === undefined) {
return;
}
const filter = `${this.reformatDateForDisplay(this.fromDate)} to ${this.reformatDateForDisplay(this.toDate)}`;
this.reportService.getFilteredReports(filter, this.fromDate, this.toDate);
}
/**
* Reformat date to MM-DD-YYYY to match mockup
* @param date - the date to reformat
* @returns {string} - the formatted ate string
*/
reformatDateForDisplay(date: string) {
const splitDate = date.split('-');
splitDate.push(splitDate.shift());
return splitDate.join('-');
}
}
<file_sep>import { Injectable } from '@angular/core';
import {Report} from '../models/report';
import {HttpClient} from '@angular/common/http';
import {Subject} from 'rxjs';
@Injectable()
export class ReportService {
filter = 'All Time';
reports: Report[] = [
{
title: 'Members',
filter: this.filter,
number: null
},
{
title: 'Licensed Users',
filter: this.filter,
number: null
},
{
title: 'Inactive Users',
filter: this.filter,
number: null
},
{
title: 'Deleted Boards',
filter: this.filter,
number: null
},
{
title: 'Active Boards',
filter: this.filter,
number: null
},
{
title: 'Archived Boards',
filter: this.filter,
number: null
},
];
_reportsChangeListener = new Subject();
_filterDatesListener = new Subject();
constructor(private http: HttpClient) { }
/**
* Initial API call to get default All Time Reports
* @returns {Observable<Object>}
*/
getAllTimeReports() {
const baseUrl = 'https://www.gcumedia.com/sample-data/api/reporting/activeMemberCount-licensedMemberCount-inactiveMemberCount-deletedBoardCount-activeBoardCount-archivedBoardCount';
return this.http.get(baseUrl);
}
/**
* Make API call to get filtered report data
* @returns {Observable<Object>} - the http response
*/
getFilteredReports(filter = 'All Time', from = '', to = '') {
let baseUrl = 'https://www.gcumedia.com/sample-data/api/reporting/activeMemberCount-licensedMemberCount-inactiveMemberCount-deletedBoardCount-activeBoardCount-archivedBoardCount';
const date = new Date();
const month = `0${date.getMonth() + 1}`.slice(-2);
const day = `0${date.getDate()}`.slice(-2);
let today = `${date.getFullYear()}-${month}-${day}`;
// Reset reports to show loading message
this._reportsChangeListener.next([]);
// Get URL based on filter selected
if (from !== '' && to !== '') {
baseUrl += `/start/${from}/end/${to}`;
today = to;
} else if (filter === 'Yesterday') {
from = this.getFilterDates(1);
baseUrl += `/start/${from}/end/${today}`;
} else if (filter === 'Last 7 Days') {
from = this.getFilterDates(7);
baseUrl += `/start/${from}/end/${today}`;
} else if (filter === 'Last 30 Days') {
from = this.getFilterDates(30);
baseUrl += `/start/${from}/end/${today}`;
} else if (filter === 'Last 6 Months') {
from = this.getFilterDates(this.getLastSixMonthsDays());
}
this.http.get(baseUrl).subscribe((data: any) => {
// Get values from API call
const reportValues = Object.values(data);
// Iterate over reports and change numbers with API data
this.reports.forEach((report, i) => {
report.number = +reportValues[i]; // Convert string value to number
report.filter = filter;
});
// Update report change
this._reportsChangeListener.next(this.reports);
this._filterDatesListener.next({toDate: today, fromDate: from});
});
}
/**
* Function taken from stack overflow https://stackoverflow.com/questions/19910161/javascript-calculating-date-from-today-date-to-7-days-before
* @param numberOfDays - the days to subtract
* @returns {string} - the formatted date string for the API call
*/
getFilterDates(numberOfDays) {
const date = new Date();
const last = new Date(date.getTime() - (numberOfDays * 24 * 60 * 60 * 1000));
const day = `0${last.getDate()}`.slice(-2);
const month = `0${last.getMonth() + 1}`.slice(-2);
const year = last.getFullYear();
return `${year}-${month}-${day}`;
}
/**
* Get number of days from a month
* Taken from stack overflow https://stackoverflow.com/questions/13146418/find-all-the-days-in-a-month-with-date-object
* @param {Number} month
* @param {*} year
*/
getDaysInMonth(month, year) {
const date = new Date(year, month, 1);
const days = [];
while (date.getMonth() === month) {
days.push(new Date(date));
date.setDate(date.getDate() + 1);
}
return days;
}
/**
* Get total number of days from past 6 months
* @returns {number} - the total number of days
*/
getLastSixMonthsDays() {
const date = new Date();
const currMonth = date.getMonth();
let totalDays = 0;
/**
* This needs to be fixed to get past six months
* It works at the moment because we are in the 6th month currently
*/
for (let i = 0; i <= currMonth; i++) {
totalDays += this.getDaysInMonth(i, 2018).length;
}
return totalDays;
}
getActivityLog() {
return this.http.get('https://www.gcumedia.com/sample-data/api/reporting/actionCounts');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {Report} from '../models/report';
import {ReportService} from '../services/report.service';
@Component({
selector: 'app-reports',
templateUrl: './reports.component.html',
styleUrls: ['./reports.component.css']
})
export class ReportsComponent implements OnInit {
reports: Report[] = [];
constructor(private reportService: ReportService) { }
ngOnInit() {
// Subscribe to API data
this.reportService.getAllTimeReports().subscribe((data: any) => {
// Get values from API call
const reportValues = Object.values(data);
// Iterate over reports and change numbers with API data
this.reportService.reports.forEach((report, i) => {
report.number = +reportValues[i]; // Convert string value to number
report.filter = 'All Time';
this.reports = this.reportService.reports;
});
});
// Listen for changes
this.reportService._reportsChangeListener.subscribe((data: any) => {
this.reports = data;
});
}
}
<file_sep>export class Report {
title: string;
filter: string;
number: number;
}
<file_sep># Trello Activity Report
## Technologies
| Name | Link | Description |
| ------- | -------- | ----------- |
| Angular | <https://angular.io/> | JavaScript front-end framework |
| Bootstrap 4 | <https://getbootstrap.com/> | CSS Framework |
| ng-bootstrap | <https://ng-bootstrap.github.io/> | Angular-specific bootstrap components (See note below) |
### About ng-bootstrap
Ng-bootstrap allows the use of Bootstrap components with Angular. Many of the CSS components, such as drop downs and date pickers, rely on under lying technologies like jQuery to perform their actions. Direct DOM manipulation is discouraged with Angular, but by using **ng-boostrap** these features are re-worked to do things the Angular way, but functionally work the same way as the original Bootstrap components.
See the [ng-bootstrap install page](https://ng-bootstrap.github.io/#/getting-started) for instructions on how to install with an Angular application.
---
Link to basic prototype: <https://xmtrinidad.github.io/TrelloActivityReport/>
### Bugs and Questions
* **Bug**: Clicking clear filter always fetches 'All Time' data
* **Bug**: When dates are selected then cleared, 'All Time' data is fetched but filter type on cards isn't updated
* **Bug**: Clear filter click doesn't hide 'To' date placeholder
* **Bug**: Last six months function needs to be fixed
* **Question**: How do I get the 'Activity Log' data based on date?
* **Question**: Is there a similar date API call for 'Activity Log' data?
* **Question**: Are all 'Activity Log' types represented in the API call? If so, under what properties from the API call are they listed?
<file_sep>import { Component, OnInit } from '@angular/core';
import {ReportService} from '../services/report.service';
@Component({
selector: 'app-activity',
templateUrl: './activity.component.html',
styleUrls: ['./activity.component.css']
})
export class ActivityComponent implements OnInit {
tableData: {name: string, number: number}[] = [];
constructor(private reportService: ReportService) { }
ngOnInit() {
this.reportService.getActivityLog().subscribe((data: any) => {
const table: {name: string, number: number}[] = [
{name: 'Comments', number: data.actionCounts.commentCard},
{name: 'Cards Created', number: data.actionCounts.createCard},
{name: 'Cards Moved', number: data.actionCounts.moveCardFromBoard},
{name: 'Cards Duplicated', number: data.actionCounts.copyCard},
{name: 'Cards Archived', number: 731},
{name: 'Cards Deleted', number: data.actionCounts.deleteCard},
{name: 'Lists Created', number: data.actionCounts.createList},
{name: 'Lists Moved', number: data.actionCounts.moveListFromBoard},
{name: 'Lists Duplicated', number: 192},
{name: 'Lists Archived', number: 221},
{name: 'Lists Deleted', number: 58},
{name: 'Unique Labels', number: 38},
];
this.tableData = table;
});
}
}
| 92895f3a6257dfca9a48562eb8bb44efb5e9d988 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | xmtrinidad/TrelloActivityReport | d3c657f0e080ccf57678fc69f244f03edf27a614 | 5bd790e05587d4df22d15484f3d1a4afde9aaea7 |
refs/heads/master | <file_sep>package com.example.user.testmelli;
/**
* Created by User on 26.03.2018.
*/
public class Test {
}
| d3a887882f6bcd219e74a32156abd8a9e00b4d5a | [
"Java"
] | 1 | Java | MelliSt/TestMelli | a2d2996a0c2aba052ae19175b862bcfb8dc26ffc | 73290fbff10076b1044d8315a9ef74b62b29786f |
refs/heads/master | <repo_name>YasminTeles/CodeSmell<file_sep>/CodeSmell/DataClass.py
## Problem
class ColorSpec:
def __init(self, color_of_product_to_find):
self._color_of_product_to_find = color_of_product_to_find
def get_color_of_product_to_find(self):
return self._color_of_product_to_find
## Solution
class ColorSpec:
def __init__(self, color_of_product_to_find):
self._color_of_product_to_find = color_of_product_to_find
def get_color_of_product_to_find(self):
return self._color_of_product_to_find
def is_satisfied_by(self, product):
return product.get_color() is self._color_of_product_to_find
<file_sep>/CodeSmell/DataClumps.py
## Problem
import math
def calculateRectangleArea(width, length):
return width * length
def calculateRectanglePerimeter(width, length):
return 2 * (width + length)
def calculateRectangleDiagonal(width, length):
return math.sqrt(width ** 2 + length ** 2)
## Solution
class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
def perimeter(self):
return 2 * (self.width + self.length)
def diagonal(self):
return math.sqrt(self.width ** 2 + self.length ** 2)
<file_sep>/CodeSmell/DeadCode.py
## Problem 1
def unusedVariable():
x = 5 * 5
return 5 * 5
## Problem 2
def flow(x):
while(x > 0):
if(x == 10):
break
x -= 1
x += 1
return x
## Problem 3
def doWork():
print("Hello, I'm doing work.")
def main():
print("Hello, I'm fine.")
if __name__ == '__main__':
main()
<file_sep>/README.md
# CodeSmell
Some examples of code smell and refactoring
<file_sep>/CodeSmell/DuplicatedCode.py
## Subtle Duplication
import StringIO
# Compare the toPlainTextString member function in the FormTag class with that of the LinkTag class.
class FormTag(Node):
def toPlainTextString(self):
outstr = StringIO.StringIO()
for stringNode in self.allNodes:
outstr.write(stringNode.getText())
return outstr.getvalue()
class LinkTag(Node):
def toPlainTextString(self):
output = StringIO.StringIO()
for stringNode in self.linkData:
output.write(stringNode.getText())
return output.getvalue()
## Blatant Duplication
class Row(Widget):
def collectChildren(self, result):
for child in self.children:
if child.isVisible():
result.add(self.children)
child.collectChildren(result)
class Column(Widget):
def collectChildren(self, result):
for child in self.children:
if child.isVisible():
result.add(self.children)
child.collectChildren(result)
<file_sep>/CodeSmell/LongParameterList.py
## Problem
class OwnershipTest:
def createUserInGroup(self):
groupManager = GroupManager()
group = groupManager.create(TEST_GROUP, False, GroupProfile.UNLIMITED_LICENSES, "", GroupProfile.ONE_YEAR, None)
user = userManager.create(USER_NAME, group, USER_NAME, "joshua", USER_NAME, LANGUAGE, False, False, datetime.date.today(), "blah", datetime.date.today())
<file_sep>/Refactoring/DecomposeConditional.py
## Problem
if date.before(SUMMER_START) or date.after(SUMMER_END):
charge = quantity * winterRate + winterServiceCharge
else:
charge = quantity * summerRate
## Solution
if isSummer(date):
charge = summerCharge(quantity)
else:
charge = winterCharge(quantity)<file_sep>/CodeSmell/PrimitiveObsession.py
## Problem
phoneNumber = "5551230004"
print "Our support line in North America is (" + \
phoneNumber[0:3] + \
") " + \
phoneNumber[3:6] + \
"-" + \
phoneNumber[6:10]
## Solution
phone_number = Phone("5551230004");
print "Our support line in North America is " + phone_number.to_formatted_string()
class Phone:
def __init__(self, unformatted_number):
self._unformatted_number = unformatted_number
def _get_area_code(self):
return self._unformatted_number[0:3]
def _get_prefix(self):
return self._unformatted_number[3:6]
def _get_number(self):
return self._unformatted_number[6:10]
def to_formatted_string(self):
return "(" + self.get_area_code() + ") " + self.get_prefix() + "-" + self.get_number()<file_sep>/CodeSmell/LazyClass.py
## Problem
class Employee:
def __init__(self):
self._jobsCompleted = 0
self._jobsSkipped = 0
def jobsCompletedCount(self):
return self._jobsCompleted
def jobsSkippedCount(self):
return self.jobsSkippedCount
def performJob(self, job):
if job in self._responsibilities():
self._jobsCompleted += 1
else:
self._jobsSkipped += 1
@abstractmethod
def _responsibilities(self):
pass
## Lazy Class
class Programmer(Employee):
def _responsibilities(self):
return [Job.PROGRAM, Job.TEST, Job.INTEGRATE, Job.DESIGN]
## Lazy Class
class Manager(Employee):
def _responsibilities(self):
return [Job.MANAGE, Job.MARKET, Job.SELL]
## Solution
class Employee:
def __init__(self, jobs):
self._jobsCompleted = 0
self._jobsSkipped = 0
self._jobs = jobs
def jobsCompletedCount(self):
return self._jobsCompleted
def jobsSkippedCount(self):
return self.jobsSkippedCount
def performJob(self, job):
if job in self.responsibilities():
self._jobsCompleted += 1
else:
self._jobsSkipped += 1
def responsibilities(self):
return self._jobs
<file_sep>/CodeSmell/TemporaryField.py
## Problem
class PhoneAccount:
def __init__(self, includedMinutes):
self._excessMinutesCharge = 0.0
self._includedMinutes = includedMinutes
def computeBill(self):
excessMinutes = self._minutesUsed - self._includedMinutes
if excessMinutes >= 1:
self._excessMinutesCharge = excessMinutes * excessMinuteRate
bill += self._excessMinutesCharge
return bill
def chargeForExcessMinutes(self):
self.computeBill()
return self._excessMinutesCharge
## Solution
class PhoneAccount:
def __init__(self, includedMinutes):
self._includedMinutes = includedMinutes
def computeBill(self):
bill += self._chargeForExcessMinutes()
return bill
def chargeForExcessMinutes(self):
excessMinutes = self._minutesUsed - self._includedMinutes
if excessMinutes < 1:
return 0.0
return excessMinutes * self._excessMinuteRate<file_sep>/CodeSmell/LongMethod.py
## Problem
def to_xml(self, result):
result.append("<")
result.append(self._name)
result.append(self._attributes)
result.append(">")
for node in self.children():
node._to_string_helper(result)
if self._value is not "":
result.append(self._value)
result.append("</")
result.append(self._name)
result.append(">")
## Solution
def to_xml(self, result):
self._write_open_tag_to(result)
self._write_children_to(result)
self._write_value_to(result)
self._write_end_tag_to(result)
def _write_open_tag_to(self, result):
result.append("<")
result.append(self._name)
result.append(self._attributes)
result.append(">")
def _write_children_to(self,result):
for node in self.children():
node._to_string_helper(result)
def _write_value_to(self, result):
if self._value is not "":
result.append(self._value)
def _write_end_tag_to(self, result):
result.append("</")
result.append(self._name)
result.append(">")
<file_sep>/Refactoring/ExtractMethod.py
## Problem: Print details
def printOwing(self, amount):
self.printBanner()
# print details
print("name: ", self._name)
print("amount: ", amount)
def printLateNotice(self, amount):
self.printBanner()
self.printLateNoticeHeader()
# print details
print("name: ", self._name)
print("amount: ", amount)
## Solution
def printOwing(self, amount):
self.printBanner()
self.printDetails(amount)
def printLateNotice(self, amount):
self.printBanner()
self.printLateNoticeHeader()
self.printDetails(amount)
def printDetails(self, amount):
print("name: ", self._name)
print("amount: ", amount) | 342d522100de8a0c5ee3b947dbfabdc74bd90e6f | [
"Markdown",
"Python"
] | 12 | Python | YasminTeles/CodeSmell | f62d0df3ae1de3c3dcf877d5de7aca7c47a21abb | 7bf10576f672d4d359c609ff0fb9a992de3f8d87 |
refs/heads/master | <file_sep><< set headObj=[
[
{name:"学校概况",href:"http://www.ncepu.edu.cn/xxgk/xxjj/index.htm"},
{name:"院系设置",href:"faculty_settings.html"},
{name:"机构设置",href:"institutional_settings.html"}
],
[
{name:"师资队伍",href:"http://192.168.127.12/rshch/webpages/default.aspx"},
{name:"国际交流",href:"http://icd.ncepu.edu.cn/"},
{name:"招生就业",href:"recurit_and_employment.html"}
],
[
{name:"文献资料",href:"http://202.206.214.254/"},
{name:"邮件系统",href:"http://email.ncepubd.edu.cn/cgi-bin/index.cgi"},
{name:"English",href:"http://english.ncepu.edu.cn/"}
]
]
>>
<< set rightObj=[
{name:"新闻中心",href:"http://news.ncepu.edu.cn/",classname:"u-icon-nav-blue"},
{name:"华电大讲堂",href:"http://172.16.58.3/LH/",classname:"u-icon-nav-blue"},
{name:"青年之声",href:"http://qnzs.youth.cn/2016jyj/",classname:"u-icon-nav-blue"},
{name:"OA系统",href:"http://192.168.127.12/OA/Default.MSPX",classname:"u-icon-nav-blue"},
{name:"教务信息",href:"http://5172.16.17.32/jiaowuchu/",classname:"u-icon-nav-blue"},
{name:"仿真教学",href:"http://172.16.58.3/syjx/default.html",classname:"u-icon-nav-blue"},
{name:"人才招聘",href:"http://202.206.208.65/zhaopin.aspx",classname:"u-icon-nav-blue"},
{name:"精品课堂",href:"http://202.206.208.43/ECWeb/notice.htm",classname:"u-icon-nav-blue"},
{name:"科技学院",href:"http://www.hdky.edu.cn/",classname:"u-icon-nav-blue"}
]
>>
<< set friendObj=[
{name:"大学主页",href:"http://www.ncepubbs.cn/",classname:"link"},
{name:"缘路有你",href:"http://www.ncepubbs.cn/",classname:"link"},
{name:"网络服务",href:"http://202.206.208.58/wlzx/Second.aspx?id1=103&id2=104",classname:"link"},
{name:"VOD点播",href:"http://202.206.223.102/",classname:"link"}
]
>><file_sep>/*window.data={
name:"dai",
type:"email",
value:"<EMAIL>"
}*/
// Vue.config.delimiters = ['${', '}'];
new Vue({
el:"#test",
data:{
dai:"adai",
value:"email",
number:"email"
}
})
console.log(0)<file_sep>var express = require('express');
var router = express.Router();
var user=require("../public/test.json")
var user1=require("../public/test1.json")
//var user2=require("../routes/controller.js")
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', user);
});
router.get('/index1', function(req, res, next) {
res.render('index1', user1);
});
/*router.get('/index1', function(req, res, next) {
res.render('index1', {});
});*/
module.exports = router;
<file_sep>router.get('/index1', function(req, res, next) {
res.render('index1', user1);
});
<% from "json.html" import obj %> | f2ee276b5dbee675e0dc8b92fc4ccea52967d420 | [
"JavaScript",
"HTML"
] | 4 | HTML | daihaiqing/myapp | 80fc7af4beca4c2b75b2a36877a88b2010a25c62 | cbbe56cc6a2426923040479fdeebbad3c16fd48c |
refs/heads/main | <repo_name>baomengli/Front-end-learning<file_sep>/puzzle8/puzzle8.js
var puzblk = 3;
var ran = [1, 2, 3, 4, 5, 6, 7, 8]
var eptblk = -1;
var divwd = $('#a').width();
var left = [];
var right = [];
var topp = [];
var bottom = [];
var mid = [];
var $divs;
var clknum = -1;
function randomorder(n) {//生成随机序列
var j = 0;
for (i = 9; i < n * n; i++) {
var ran = [1, 2, 3, 4, 5, 6, 7, 8];
ran.push(i);
ran.length++;
j++;
}
document.getElementById('pp').innerHTML = ran;
document.getElementById('ppp').innerHTML = ran.length + "aa" + j;
console.log(ran);
return ran;
}
$('#reset').click(function () {//重置函数 添加n*n个div
var num = document.getElementById("setnum").value;
var num2 = num - 1 + 1;
var ran = [];
if (num == '') num2 = 3;
console.log("num2:" + num2);
console.log(typeof (num));
console.log(typeof (num2));
if (num2 < 10 && num2 >= 2) {
puzblk = num2;
var divs = "";
$('#a').empty();
for (var i = 0; i < num2 * num2; i++) {
divs = divs + '<div></div>';
ran.push(i);
}
$blk = $(divs);//加上n*n个div
for (i = 0; i < ran.length; i++) {
var random_index = Math.floor(Math.random() * ran.length);//产生一个在0到数组长度之间的随机数
//经典的临时变量交换
var t = ran[i];
ran[i] = ran[random_index];
ran[random_index] = t;
}
$('#a').append($blk);
$('#a>div').css({
'width': divwd / num2,
'height': divwd / num2,
'border': 'black 1px solid',
});
var bdpx = divwd + 2 * num2;
bdpx = bdpx + 'px';
$('#a').css({
'height': bdpx,
'width': bdpx,
});
$('#a>div').each(function (index, element) {
if (ran[index]) {
$(element).text(ran[index]);
$(element).attr('class', 'numblk');
}
else {
eptblk = index;
$(element).attr('class', 'eptblk');
}
});
$divs = $('#a>div');
console.log("空格序号:" + eptblk);
}
else {
alert("输入错误");
return;
}
});
$('#a').on('click', $('.numblk'), function (e) {
var x = e.pageX
var y = e.pageY;
var atop = $('#a').offset().top;//'#a'据页面顶点的上、左边距
var aleft = $('#a').offset().left;
var divwd = $($divs[0]).width() + 2;//一个数字方块的宽、高
var xn = Math.floor((x - aleft - 5) / divwd);
var yn = Math.floor((y - atop - 5) / divwd);
clknum = yn * puzblk + xn;
console.log('clknum:', clknum);
$.windowbox.move(clknum);
});
$(document).on('keydown', function (e) {
console.log(e.keyCode);
switch (e.keyCode) {
case 38: clknum = eptblk + puzblk; break;//按上键
case 40: clknum = eptblk - puzblk; break;//按下键
case 37: clknum = eptblk + 1; break;//按左键
case 39: clknum = eptblk - 1; break;//按右键
case 82: $('#reset').trigger('click'); ; break;
case 83: $('#submit').trigger('click'); ; break;
default: break;
}
$.windowbox.move(clknum);
});
$.windowbox = {
move: function (clknum) {
var n = puzblk;
var clkable = [];
if (parseInt(eptblk / n)) clkable.push(eptblk - n);
if (parseInt(eptblk / n) != n - 1) clkable.push(eptblk + n);
if ((eptblk % n) != 0) clkable.push(eptblk - 1);
if ((eptblk % n) != n - 1) clkable.push(eptblk + 1);
console.log('可供点击clkable:', clkable);
if (clkable.indexOf(clknum) != -1) {
console.log('点击正确');
t = $($divs[clknum]).text();
$($divs[eptblk]).text(t);
$($divs[clknum]).text('');
$($divs[eptblk]).attr('class', 'numblk');
$($divs[clknum]).attr('class', 'eptblk');
eptblk = clknum;
}
}
}
$('#submit').click(function () {
var t = -1;
for (i = 0; i < puzblk * puzblk - 1; i++) {
if (parseInt($($divs[i]).text()) > t) {
t = parseInt($($divs[i]).text());
}
else {
alert('解答错误!');
return;
}
}
alert('恭喜,解答正确!');
});
$('#reset').click();
<file_sep>/Calculator/calculator.js
var flag = 0;
var fnum = 0, lnum = '';
var mark = 0;
function clearre() {
console.log("clear");
document.getElementById("result").innerHTML = "";
flag = 0;
fnum = 0;
lnum = '';
mark = 0;
}
function percent100() {
var pinner = document.getElementById("result").innerHTML;
if (isNaN(pinner)) document.getElementById("result").innerHTML = "ERROR";
else
{
pinner = pinner * 100;
document.getElementById("result").innerHTML = pinner;
flag = 2;
fnum = 0;
lnum = '';
mark = 0;
}
return;
}
function innum(num) {
console.log("flag=%d",flag);
var pinner = document.getElementById("result").innerHTML;
if(pinner=='ERROR'){
clearre();
document.getElementById("result").innerHTML += num;
return;
}
pinner = pinner + num;
document.getElementById("result").innerHTML = pinner;
if (flag == 1) {
lnum = lnum + num;
console.log("lnum=%s", lnum);
}
if(flag==2){
clearre();
document.getElementById("result").innerHTML += num;
}
}
function operator(operatornum) {
if(document.getElementById("result").innerHTML =='ERROR'){
clearre();
return;
}
if (flag == 0) {
fnum = document.getElementById("result").innerHTML;
mark = operatornum;
switch (operatornum) {
case 1: document.getElementById("result").innerHTML += '+'; break;
case 2: document.getElementById("result").innerHTML += '-'; break;
case 3: document.getElementById("result").innerHTML += 'x'; break;
case 4: document.getElementById("result").innerHTML += '÷'; break;
}
flag = 1;
console.log("fnum=%s,mark=%d", fnum, mark);
}
else {
document.getElementById("result").innerHTML = "ERROR";
flag = 0;
fnum = 0;
lnum = '';
mark = 0;
}
}
function cclt() {
var num1 = num = 0;
if (flag == 1) {
// switch (mark) {
// case 1: num1 = parseFloat(fnum);
// num2 = parseFloat(lnum);
// document.getElementById("result").innerHTML = (num1 + num2).toFixed(10);
// break;
// case 2: document.getElementById("result").innerHTML = (fnum - lnum).toFixed(10); break;
// case 3: document.getElementById("result").innerHTML = (fnum * lnum).toFixed(10); break;
// case 4: document.getElementById("result").innerHTML = (fnum / lnum).toFixed(10); break;
// }
switch (mark) {
case 1: num1 = parseFloat(fnum);
num2 = parseFloat(lnum);
document.getElementById("result").innerHTML = (num1 * 1000 + num2 * 1000) / 1000;
break;
case 2: document.getElementById("result").innerHTML = ((fnum * 1000) - (lnum * 1000)) / 1000; break;
case 3: document.getElementById("result").innerHTML = (fnum * 1000 * lnum ) / 1000; break;
case 4: document.getElementById("result").innerHTML = (fnum * 1000 / lnum ) / 1000; break;
}
flag = 2;
fnum = 0;
lnum = '';
mark = 0;
}
else{
document.getElementById("result").innerHTML = "ERROR";
}
} | 3bb6971cfd8f968719f1da8a78de62815c9ebd77 | [
"JavaScript"
] | 2 | JavaScript | baomengli/Front-end-learning | 43bde67b26aaec889407854ddcfbb3d8aa83cb7e | 8ac8bb26489de1d2169f03ed20faa107b344d9c7 |
refs/heads/master | <file_sep>sprout_base_bash_it_custom_plugin 'bash_it/custom/android_home.bash'
<file_sep>include_recipe 'sprout-android::sdk'
haxm_pkg = node['sprout']['android']['haxm']['package_name']
haxm_dmg_path = node['sprout']['android']['haxm']['dmg_path']
execute 'update-haxm-pkg' do
command 'echo y | android update sdk --no-ui --filter extra-intel-Hardware_Accelerated_Execution_Manager'
user node['current_user']
end
sdk_path_prefix_command = Mixlib::ShellOut.new('brew --prefix android-sdk')
sdk_path_prefix_command.run_command
sdk_path_prefix = sdk_path_prefix_command.stdout.strip
include_recipe 'sprout-base::var_chef_cache'
link "#{Chef::Config[:file_cache_path]}/#{haxm_pkg}.dmg" do
to "#{sdk_path_prefix}/#{haxm_dmg_path}" # Symlink to cache dir so dmg_package can load the file
end
dmg_package haxm_pkg do
source 'http://example.com/' # Hack to keep dmg_package happy. Will not download.
owner node['current_user']
type 'mpkg'
package_id node['sprout']['android']['haxm']['package_id']
checksum node['sprout']['android']['haxm']['checksum']
end
| 72ea31d3b8f3ea13470889f839f969febf67bb63 | [
"Ruby"
] | 2 | Ruby | pivotal-shipio/sprout-android | 196c322790b7be0a78b10bc17744f87d05193e21 | 1bdd067763fb5eae2f31e9dc9d13a318c55f39fd |
refs/heads/master | <file_sep>import time
import smtplib
import requests
import bs4
from url import URLs
listOfUrls = set(URLs)
myDataFile = open('C:\\Users\\Lenovo\\Desktop\\myData.txt')
myEmail = myDataFile.readline().strip()
myPassword = myDataFile.readline().strip()
subscriberEmail = myDataFile.readline().strip()
changePrice = int(myDataFile.readline().strip())
breakTime = int(myDataFile.readline().strip())
def check_the_market():
message = """Subject:Attention It's time to sell or buy \n"""
someChages = False
while True:
for i in listOfUrls:
res = requests.get(i.value)
different = 0
beautifulSoapElement = bs4.BeautifulSoup(res.text, features="html.parser")
changes = beautifulSoapElement.select(
'html > body > div:nth-of-type(2) > div > div > div:nth-of-type(3) > div > div > span:nth-of-type(2)')
different = changes[0].getText()[2:len(changes[0].getText()) - 4]
different = float(different)
print(i.name, different)
if -changePrice >= different or different >= changePrice:
someChages = True
message += f"""\nYour coin which you posses: {i.name}
# change yourself price about: {different}% \n\n"""
print("\n\n\n")
if someChages:
return message
time.sleep(breakTime)
def send_email(message):
smtpObj = smtplib.SMTP('smtp.gmail.com:587')
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(myEmail, myPassword)
smtpObj.sendmail(myEmail, subscriberEmail, message)
{}
smtpObj.close()<file_sep>from enum import Enum
class URLs(Enum):
BITCOIN = "https://coinmarketcap.com/currencies/bitcoin/"
RIPPLE = "https://coinmarketcap.com/currencies/ripple/"
LITECOIN = "https://coinmarketcap.com/currencies/litecoin/"
LISK = "https://coinmarketcap.com/currencies/lisk/"
DOGECOIN = "https://coinmarketcap.com/currencies/dogecoin/"
TRON = "https://coinmarketcap.com/currencies/tron/"
STEEM = "https://coinmarketcap.com/currencies/steem/"
ETHEREUM="https://coinmarketcap.com/currencies/ethereum/"
<file_sep>from tkinter import *
root = Tk()
root.geometry('600x400')
root.title("Coin Market Cap Analizer")
root.iconbitmap(r'icon.ico')
root.mainloop()<file_sep>(during work)
Introduction
The aim of the program is to scan the website: https://coinmarketcap.com/
Every specified period of time we check the fluctuations and if they are greater than selected by you percent, the program will send us an e-mail with an appropriate notification.
How to use:
1.The first step is to download my code.
2.Open the file functions.py and look at the 10 lines. You have to create a new file and paste the path to it in this line.
IMPORTANT!!!
In this file, place the following data in separate information:
-your e-mail
-your password
-e-mail where you want to send information about change price
-level of price change you are interested in (total, positive value)
-time interval between price change checks
I've included some examples of cryptovalutes in the file url.py. If you want to add any cryptocurrency, go to the website https://coinmarketcap.com/, selet cryto which intereting you, click and copy link and paste to file url.py.
Run the program, it will work until you send an e-mail.
--Future plans
Creation of a graphical interface.
<file_sep>import time
from functions import check_the_market, send_email
startTime = time.time()
message = check_the_market()
send_email(message)
stopTime = time.time()
print(stopTime - startTime)
| f27cde708099d2c9504ca836792742d5eb5f43c1 | [
"Markdown",
"Python"
] | 5 | Python | Slawek12Q/CoinMarketCap-Analizer | a242ee0b3f7418cab143e84e318be04c4492be28 | e5c6acafe90710fb95d725e42a0b13787307fe4e |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SpeedometerHandler : MonoBehaviour
{
[SerializeField] List<Sprite> speed = new List<Sprite>();
CarEngine carEngine;
float kmh = 0;
float maxSpeed = 130f;
Image image;
[SerializeField] Text speedText = null;
// Start is called before the first frame update
void Start()
{
carEngine = GetComponentInParent<CarEngine>();
image = GetComponent<Image>();
}
// Update is called once per frame
void Update()
{
kmh = carEngine.Kmph;
UpdateSpeed();
kmh = (int)kmh;
speedText.text = kmh.ToString() + " KMPH";
}
void UpdateSpeed()
{
if (kmh >= maxSpeed)
{
image.sprite = speed[18];
}
else if (kmh >= (maxSpeed / 19) * 18)
{
image.sprite = speed[17];
}
else if (kmh >= (maxSpeed / 19) * 17)
{
image.sprite = speed[16];
}
else if (kmh >= (maxSpeed / 19) * 16)
{
image.sprite = speed[15];
}
else if (kmh >= (maxSpeed / 19) * 15)
{
image.sprite = speed[14];
}
else if (kmh >= (maxSpeed / 19) * 14)
{
image.sprite = speed[13];
}
else if (kmh >= (maxSpeed / 19) * 13)
{
image.sprite = speed[12];
}
else if (kmh >= (maxSpeed / 19) * 12)
{
image.sprite = speed[11];
}
else if (kmh >= (maxSpeed / 19) * 11)
{
image.sprite = speed[10];
}
else if (kmh >= (maxSpeed / 19) * 10)
{
image.sprite = speed[9];
}
else if (kmh >= (maxSpeed / 19) * 9)
{
image.sprite = speed[8];
}
else if (kmh >= (maxSpeed / 19) * 8)
{
image.sprite = speed[7];
}
else if (kmh >= (maxSpeed / 19) * 7)
{
image.sprite = speed[6];
}
else if (kmh >= (maxSpeed / 19) * 6)
{
image.sprite = speed[5];
}
else if (kmh >= (maxSpeed / 19) * 5)
{
image.sprite = speed[4];
}
else if (kmh >= (maxSpeed / 19) * 4)
{
image.sprite = speed[3];
}
else if (kmh >= (maxSpeed / 19) * 3)
{
image.sprite = speed[2];
}
else if (kmh >= (maxSpeed / 19) * 2)
{
image.sprite = speed[1];
}
else if (kmh >= (maxSpeed / 19) * 1)
{
image.sprite = speed[0];
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarSelect : MonoBehaviour
{
int screenIndex = 0;
GameObject[] cars = new GameObject[3];
MenuButtonManager menuButtonManager;
bool hasMoved = false;
// Start is called before the first frame update
void Start()
{
menuButtonManager = GetComponent<MenuButtonManager>();
for (int i = 0; i < 3; i++)
{
cars[i] = transform.GetChild(0).GetChild(i).gameObject;
}
}
// Update is called once per frame
void Update()
{
if(Input.GetAxis("Horizontal") >= 0.75f && !hasMoved)
{
Right();
hasMoved = true;
}
else if(Input.GetAxis("Horizontal") <= -0.75f && !hasMoved)
{
Left();
hasMoved = true;
}
if (hasMoved)
{
if(Input.GetAxis("Horizontal") < 0.3f && Input.GetAxis("Horizontal") > -0.3f)
{
hasMoved = false;
}
}
if (Input.GetAxis("Vertical") >= 0.5f)
{
Select();
}
else if (Input.GetAxis("Vertical") <= -0.5f)
{
Back();
}
}
void Left()
{
if(screenIndex > 0)
{
cars[screenIndex].SetActive(false);
screenIndex -= 1;
cars[screenIndex].SetActive(true);
}
}
void Right()
{
if(screenIndex < 2)
{
cars[screenIndex].SetActive(false);
screenIndex += 1;
cars[screenIndex].SetActive(true);
}
}
void Select()
{
if(screenIndex == 0)
{
menuButtonManager.NextScene();
}
}
void Back()
{
menuButtonManager.PreviousScene();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
CarEngine carMove;
[SerializeField] GameObject pauseObj = null;
Button firstSelect;
bool isPaused = false;
// Start is called before the first frame update
void Start()
{
firstSelect = pauseObj.transform.GetChild(1).GetComponent<Button>();
carMove = GetComponent<CarEngine>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
//pause
if (isPaused)
{
Unpause();
isPaused = false;
}
else
{
Pause();
isPaused = true;
}
}
}
public void LoadFirstScene()
{
SceneManager.LoadScene(0);
}
void Pause()
{
pauseObj.SetActive(true);
firstSelect.Select();
carMove.Pause();
carMove.enabled = false;
}
public void Unpause()
{
pauseObj.SetActive(false);
carMove.enabled = true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PointsHandler : MonoBehaviour
{
[SerializeField] float timeShow = 5f;
float timeCD;
bool showingInfo = false;
[SerializeField] List<GameObject> pointsUI = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (showingInfo)
{
if(timeCD <= 0f)
{
CloseInfo();
}
timeCD -= Time.deltaTime;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Poin"))
{
Debug.Log("Lol");
OpenInfo(other.gameObject.name[0] - '0');
}
}
void CloseInfo()
{
foreach(GameObject g in pointsUI)
{
g.SetActive(false);
}
showingInfo = true;
}
void OpenInfo(int index)
{
pointsUI[index].SetActive(true);
timeCD = timeShow;
showingInfo = true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class TimedUpdate : MonoBehaviour
{
[SerializeField] private float duration;
private float time;
private void Update()
{
time -= Time.deltaTime;
if(time < 0){
time = duration;
timedUpdate();
}
}
protected abstract void timedUpdate();
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FloatingBox : MonoBehaviour
{
Vector3 rotation = new Vector3();
Vector3 position = new Vector3();
Vector3 originalPos = new Vector3();
[SerializeField] float rotateRate = 1f;
[SerializeField] float moveRate = 1f;
[SerializeField] float yPos = 1f;
[SerializeField] float yRange = 1f;
float ySin = 0f;
// Start is called before the first frame update
void Start()
{
originalPos = transform.position;
}
// Update is called once per frame
void Update()
{
Rotate();
//position.Set(0, rotateRate, 0);
yPos += 0.01f;
ySin = Mathf.Sin(yPos * moveRate)/(yRange*3);
position.Set(0, ySin, 0);
transform.Translate(position);
/*if (transform.position.y >= originalPos.y + 10)
{
moveRate *= -1;
}
else if(transform.position.y <= originalPos.y - 10)
{
moveRate *= -1;
}*/
}
void Rotate()
{
rotation.Set(0, rotation.y + rotateRate, 0);
transform.localRotation = Quaternion.Euler(rotation);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarEngine : MonoBehaviour
{
WheelCollider fl, fr, rl, rr;
float gas;
float steer;
[SerializeField] Transform steerObj = null;
Vector3 steerRotation = new Vector3();
[SerializeField] float maxSteerTurn = 90f;
[SerializeField] float turnRate = 0;
[SerializeField] float engineAccel = 450;
[SerializeField] float brakeRate = 0;
[SerializeField] float maxRPM = 500f;
[SerializeField] float minRPM = -200f;
[SerializeField] float kmph = 0f;
float engineTorque = 0;
int gearIndex = 1;
public float Kmph { get => kmph; set => kmph = value; }
// Start is called before the first frame update
void Start()
{
engineTorque = engineAccel;
fl = transform.GetChild(1).GetComponent<WheelCollider>();
fr = transform.GetChild(2).GetComponent<WheelCollider>();
rl = transform.GetChild(3).GetComponent<WheelCollider>();
rr = transform.GetChild(4).GetComponent<WheelCollider>();
}
// Update is called once per frame
void Update()
{
gas = Input.GetAxis("Vertical");
steer = Input.GetAxis("Horizontal");
Kmph = Mathf.Abs(fl.rpm / 3);
steerRotation.Set(0, -steer * maxSteerTurn, 0);
steerObj.localRotation = Quaternion.Euler(steerRotation);
if (Input.GetButtonDown("RB") || Input.GetKeyDown(KeyCode.Q))
{
Shift("Up");
}
else if (Input.GetButtonDown("LB") || Input.GetKeyDown(KeyCode.E))
{
Shift("Down");
}
if(fl.rpm > maxRPM || fl.rpm < minRPM)
{
engineTorque = 10f;
}
else
{
engineTorque = engineAccel;
}
Turn();
if(gas > 0)
{
Gas();
}
else if(gas <= 0)
{
Brake();
}
RotateWheel(fl);
RotateWheel(fr);
RotateWheel(rl);
RotateWheel(rr);
}
public void Pause()
{
fl.motorTorque = 0;
fr.motorTorque = 0;
rr.motorTorque = 0;
rl.motorTorque = 0;
Brake();
}
void Gas()
{
fl.brakeTorque = 0;
fr.brakeTorque = 0;
rl.brakeTorque = 0;
rr.brakeTorque = 0;
fl.motorTorque = engineTorque * gas * gearIndex;
fr.motorTorque = engineTorque * gas * gearIndex;
rr.motorTorque = engineTorque * gas * gearIndex;
rl.motorTorque = engineTorque * gas * gearIndex;
}
void Brake()
{
fl.brakeTorque = brakeRate + (brakeRate * (gas * -1));
fr.brakeTorque = brakeRate + (brakeRate * (gas * -1));
rl.brakeTorque = brakeRate + (brakeRate * (gas * -1));
rr.brakeTorque = brakeRate + (brakeRate * (gas * -1));
}
void Turn()
{
fl.steerAngle = turnRate * steer;
fr.steerAngle = turnRate * steer;
}
void RotateWheel(WheelCollider wheel)
{
Quaternion q;
Vector3 p;
wheel.GetWorldPose(out p, out q);
// assume that the only child of the wheelcollider is the wheel shape
Transform shapeTransform = wheel.transform.GetChild(0);
shapeTransform.position = p;
shapeTransform.rotation = q;
}
void Shift(string state)
{
if(state == "Up")
{
gearIndex = 1;
}
else if(state == "Down")
{
gearIndex = -1;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarMove : MonoBehaviour
{
float gas = 0f;
float steer = 0f;
Animator animator = null;
Transform steeringWheel = null;
[SerializeField] float maxSteerTurn = 90f;
Vector3 steerRotation = new Vector3();
// Start is called before the first frame update
void Start()
{
//GetComponentInParent<PlayerController>().AssignCarMove(this);
steeringWheel = transform.GetChild(1).GetChild(0).GetComponent<Transform>();
animator = GetComponent<Animator>();
animator.speed = 1f;
}
// Update is called once per frame
void Update()
{
gas = Input.GetAxis("Vertical");
steer = Input.GetAxis("Horizontal");
animator.SetFloat("Speed", gas);
steerRotation.Set(0, -steer * maxSteerTurn, 0);
steeringWheel.localRotation = Quaternion.Euler(steerRotation);
}
public void Pause()
{
animator.SetFloat("Speed", 0);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class DirectionSignal : TimedUpdate
{
[SerializeField]
private GameObject[] objs;
protected override void timedUpdate()
{
foreach(var obj in objs)
{
obj.SetActive(!obj.activeInHierarchy);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HmdCalibrator : MonoBehaviour
{
Vector3 offsetPos = new Vector3();
Quaternion offsetRot = new Quaternion();
Transform child;
// Start is called before the first frame update
void Start()
{
Calibrate();
}
public void Calibrate()
{
child = transform.GetChild(0).GetChild(1);
offsetRot.Set(0, child.rotation.y, 0, 1);
transform.rotation = offsetRot;
offsetPos = child.position - transform.position;
transform.position -= offsetPos;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
Button[] buttons;
bool selected = false;
public void Selected()
{
print("Selected");
selected = true;
}
public void Deselected()
{
selected = false;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetAxis("Vertical") >= 0.5f)
{
if(selected)
Select();
}
else if (Input.GetAxis("Vertical") <= -0.5f)
{
Exit();
}
}
void Select()
{
ExecuteEvents.Execute(gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerDownHandler);
}
void Exit()
{
Application.Quit();
}
}
| ada043ae2451c57441a9ae436bd66fdd6f6230a7 | [
"C#"
] | 11 | C# | peculiarnewbie/VRLowoIreng | f3b90197b06583a79ced309d53ed2f35527190e7 | 7a368c78568426ec46f31064f88a250ea3c20987 |
refs/heads/main | <repo_name>bluerainmango/nextjs-typescript<file_sep>/framework/shopify/utils/fetch-api.ts
// import axios from "axios";
import { ApiFetcherOptions, ApiFetcherResults } from "@common/types/api";
// Promise<FetcherResult<T>>: return promise type
const fetchApi = async <T>({
url,
query,
}: ApiFetcherOptions): Promise<ApiFetcherResults<T>> => {
// const url = "http://localhost:4000/graphql";
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
}),
});
const { data, errors } = await res.json();
if (errors) {
throw new Error(errors[0].message ?? errors.message);
}
return { data };
};
export default fetchApi;
// const fetchApi = async ({ query }: FetcherParams) => {
// try {
// const url = "http://localhost:4000/graphql";
// const res = await axios.post(url, {
// query,
// });
// return res;
// } catch (err) {
// throw new Error(
// err.response.data.errors[0]?.message || err.response.data.errors.message
// );
// }
// };
<file_sep>/framework/shopify/utils/normalize.ts
import { ImageEdge, MoneyV2, Product as ShopifyProduct } from "../schema";
import { Product } from "@common/types/product";
// 인자로 들어온 객체에서 edges prop만 빼는데, 이 prop의 type은 ImageEdge[] 다.(ImageEdge가 모인 arr)
const normalizeProductImages = ({ edges }: { edges: ImageEdge[] }) =>
// node 객체를 destructurizing to {originalSrc: url, ...rest}
edges.map(({ node: { originalSrc: url, ...rest } }) => ({
url: `/images/${url}`,
...rest,
})); //! correct
// function normalizeProductImages({edges: ImageEdge[]}) {} //! type 지정하는 법에서 error
const normalizeProductPrice = ({ currencyCode, amount }: MoneyV2) => ({
value: +amount,
currencyCode,
});
// Normalize raw product data into data that is easy to use
export function normalizeProduct(productNode: ShopifyProduct): Product {
const {
id,
title: name,
handle,
vendor,
description,
images: imageConnection,
priceRange,
...rest
} = productNode;
const product = {
id,
name,
vendor,
description,
path: `/${handle}`,
slug: handle.replace(/^\/+\/+$/g, ""), // remove slash /
images: normalizeProductImages(imageConnection),
price: normalizeProductPrice(priceRange.minVariantPrice),
...rest,
};
return product;
}
<file_sep>/postcss.config.js
//! just for testing with postcss-cli script to build compiled css file. (npm run build:css)
// module.exports = {
// plugins: [require("tailwindcss"), require("autoprefixer")],
// };
// 각 플러그인에 option 넣을 필요없다면 아래 [] 형식도 가능. 위가 아닌 아래처럼 해야 build 가능
module.exports = {
plugins: ["tailwindcss", "postcss-nesting", "autoprefixer"],
};
// module.exports = {
// plugins: {
// tailwindcss: {},
// autoprefixer: {},
// },
// }
<file_sep>/framework/shopify/product/get-all-products.ts
//* Utils > index.ts
import { normalizeProduct, getAllProductsQuery } from "../utils";
//* GraphQL Query. Shopify Schema for type definition
import { ProductConnection } from "../schema";
//* Universal Types cross all platforms including Shopify
import { Product } from "@common/types/product";
import { ApiConfig } from "@common/types/api";
// Import Shopify's product schema so that inside props can be chained and used in 'getAllProducts' func.
type ReturnType = {
products: ProductConnection;
};
// any type of array is returned as a result of promise
const getAllProducts = async (config: ApiConfig): Promise<Product[]> => {
const { data } = await config.fetch<ReturnType>({
url: config.apiUrl,
query: getAllProductsQuery,
});
//* Normalize products: [{product1}, {product2}...]
// Changing fetched data directory to utilize in our app
// product: alias to change prop name 'node' to something else
// if null or undefined returned, change it to []
const products =
data.products.edges.map(({ node: product }) => normalizeProduct(product)) ??
[];
// normalize and return new data
return products;
};
export default getAllProducts;
<file_sep>/framework/common/config.js
const path = require("path");
const fs = require("fs");
const merge = require("deepmerge");
const prettier = require("prettier");
// frameworks to choose
const ALLOWED_FW = ["shopify", "bigcommerce", "shopify_local"]; // shopify_local: our fake shopify server
const FALLBACK_FW = "shopify";
// Import the designated framework's config and merge with common config & set tsconfig.json
exports.withFrameworkConfig = function (defaultConfig = {}) {
let framework = defaultConfig?.framework?.name; // shopify, bigcommerce ... or undefined
if (!framework) {
throw new Error(
"The api framework is missing, please add a valid provider."
);
}
if (!ALLOWED_FW.includes(framework)) {
throw new Error(
`The api framework: ${framework} cannot be found, please use one of ${ALLOWED_FW.join(
", "
)}`
);
}
if (framework === "shopify_local") {
framework = FALLBACK_FW; // shopify
}
const frameworkNextConfig = require(path.join(
"../",
framework,
"next.config.js"
));
// 가장 바깥 폴더의 next.config.js 내 해당 함수의 인자로 들어온 defaultConfig obj 내용과 shopify, bigcommer 등 폴더 내 next.config.js 파일을 deep merge
const newMergedNextConfig = merge(defaultConfig, frameworkNextConfig);
console.log("😜 Merged next.js config.js:", newMergedNextConfig);
//! 1. tsconfig.json 설정
//"@framework":["framework/shopify"]를 "@framework":[`framework/${framework 이름 아무거나}`]로 바꾸고 tsconfig.json 파일 새로 덮어쓰기
const tsPath = path.join(process.cwd(), "tsconfig.json");
const tsConfig = require(tsPath);
tsConfig.compilerOptions.paths["@framework"] = [`framework/${framework}`];
tsConfig.compilerOptions.paths["@framework/*"] = [`framework/${framework}/*`];
// tsconfig.json 파일 덮어쓰기. 포맷이 이상하면 json 에러떠서 prettier.format()으로 정렬. 안해도 상관은 없음.
fs.writeFileSync(
tsPath,
prettier.format(JSON.stringify(tsConfig), { parser: "json" })
);
// fs.writeFileSync(tsPath, JSON.stringify(tsConfig, null, 2));
//! 2. next.config.js 설정하기 위한 new merged config 반환
return newMergedNextConfig;
};
// module.exports = {withFrameworkConfig};
<file_sep>/playground.ts
// type strData = string
// interface Person{
// name: strData
// age: number
// }
class Person {
name: string;
age?: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
// interface functionFormat {
// (person: {name: string, age: number}): string // 마지막 :string은 return 값의 type
// }
type functionFormat = (person: { name: string; age?: number }) => string;
//type aliases
// to describe function types
// type Person = {
// name: string,
// age: number
// }
export default function play() {
console.log("hello world");
const personObj = {
name: "Emily",
age: 27,
};
const logPersonInfo2: functionFormat = (person) => {
const info = `name: ${person.name} age: ${person.age}`;
console.log(info);
return info;
};
// function logPersonInfo2(person: Person): string{
// const info = `name: ${person.name} age: ${person.age}`
// console.log(info)
// return info
// }
// logPersonInfo2(personObj)
logPersonInfo2(new Person("emily", 22));
// let test = "implicitly defined as string"
// test = 12
// const names: Array<string> = ["emily", "andy"];
const names: string[] = ["emily", "andy"];
const numbers: Array<number> = [1, 2, 3, 4, 5];
const random = Math.random() > 0.5 ? "Hello" : [1, 2];
// Narrowing : type에 따라 달리 process
// if(typeof random ==="string"){
// const upper = random.toUpperCase();
// }else{
// console.log(random)
// }
// console.log(random.toUppercase())
}
// Extending interface
interface Human {
name: string;
age: number;
}
interface BusinessHuman extends Human {
salary: number;
}
interface AcademicHuman extends Human {
publications: string[];
}
type Car = {
name: string;
};
type RaceCar = {
speed: number;
} & Car & { mileage: number };
type CityCar = {
space: string;
} & Car;
type AllCar = RaceCar | CityCar;
export function printHuman() {
const schoolGraduate: AcademicHuman = {
name: "emily",
age: 22,
publications: ["haha"],
};
function logHuman(human: Human) {}
// No error on more data
logHuman(schoolGraduate);
function logCar(car: AllCar) {
console.log(car.name);
// Type Casting
console.log((car as CityCar).space);
console.log((<CityCar>car).space);
}
logCar({ name: "fast car", space: "big" });
}
interface Family {
name: string;
}
interface Family {
members: string[];
}
// How to define Obj type as param
function printInfo(someObj: object) {} // value is any type
// function printInfo(someObj: { [key: string]: any }) { } // value is any type
// function printInfo(someObj: { [key: string]: string }) { } // value is string type
// function printInfo(someObj: { [key: string]: string | number | boolean }) { } // value is string || number || boolean
printInfo({});
type Noop = () => any;
type Noop2 = () => void;
function iterate(items: Array<Car>) {
items.forEach((item) => {
console.log(item);
});
}
//! Custom generic type for class
// <T> 안에 각 instance 별 다른 type를 그때마다 넣어줄 수 있다.
// T 대신 아무 문자와도 되는데 <T> 가 convention
class Logger<T> {
log(items: T[], cb: (item: T) => void) {
items.forEach((item) => {
cb(item);
});
}
}
const logger1 = new Logger<string>();
const strings = ["hhh", "aa", "ddd"];
logger1.log(strings, (str) => {
console.log(str);
});
const logger2 = new Logger<number>();
const numbers = [12, 421, 22];
logger2.log(numbers, (num) => {
console.log(num);
});
//! Generic Extends
// interface는 필수로 가져야할 property(+ type)를 명시
interface AI {
model: string;
}
// 해당 interface를 설치한 class는 꼭 interface 내 모든 property를 초기값과 함께 가지고 있어야 함
class StudentAI implements AI {
model = ""; // 초기값 넣어줌
}
type DNA = {
model: string;
age: number;
};
// <T extends AI> 의미: 최소 AI 인터페이스의 property를 지닌 class를 Instance의 init 값으로 추가해라.
class Logger2<T extends AI = StudentAI> {
log(items: T[], cb: (item: T) => void) {
items.forEach((item) => console.log(item));
}
}
// const loggerAI = new Logger2<StudentAI>();
const loggerAI = new Logger2();
const ais = [{ model: "st-1" }, { model: "st-2" }];
loggerAI.log(ais, (ai) => console.log(ai));
interface Life {
name: string;
}
interface Animal extends Life {
age: number;
}
interface Alien extends Life {
age: number;
magic: string;
}
type Dog<T extends Life = Life> = {
data: T;
breed: string;
};
function logDog(info: Dog<Alien>) {
console.log(info.data.magic);
}
type ET<T extends any = Alien> = T extends Alien
? {
age: number;
magin: string;
face: string;
}
: string;
//! Single from array
function logET(info: ET<Alien>) {
console.log(info);
}
interface Flower {
name: string;
}
type SingleType<T> = T extends any[] ? T[number] : T;
//의미: 입력 값(T)이 array 형태이면 array[x] 해서 el 값 반환 or 입력 값. [number] 는 index type이 num이라는 뜻.
function playSingleType() {
type Type1 = SingleType<string[]>; // [ str1, str2... ] 에서 값 하나 반환
type Type2 = SingleType<number[]>; // [ num1, num2... ] 에서 값 하나 반환
type Type3 = SingleType<Flower>; // 그냥 Flower 반환
}
//! Array types 정의하기
type CustomArray<T> = {
[index: number]: T; // array index와 single el 값 type 명시
};
function playCustomArr() {
const items: CustomArray<string> = ["1", "2", "3"];
const items2: CustomArray<number> = [1, 2, 3];
}
//! Object types 정의하기
type CustomObject = {
[key: string]: string | number | CustomArray<any>;
};
type CustomObject2<T = string | number | Person> = {
[key: string]: T;
};
function playObj() {
const person: CustomObject = {
name: "asd",
};
const person2: CustomObject2<string> = {
name: "dd",
};
}
//! Function types 정의하기
function logger(...args: any[]) {
return "hello";
}
const KinaLogger: typeof logger = (name: string, age: number) => "Hi!";
const info = {
name: "emily",
age: 22,
};
//! Infer R
type ReturnType<T> = T extends () => infer R ? R : number;
// 의미: RreturnType< > 에 param를 가지지 않는 함수 타입이 지정되면, 해당 함수의 return과 같은 형식의 type(or property)를, 아니면 number
function logger3() {
return {
name: "hh",
};
}
const loggerReturn: ReturnType<typeof logger3> = { name: "emily" };
//! keyof type
interface Keys {
name: string;
age: number;
}
const keyofInfo: keyof Keys = "name";
//! Multiple param
type Multiple<FP = string, SP = number, RT = string> = (
param1: FP,
param2: SP
) => RT;
const superLog: Multiple<string, number, string> = (name, age) => {
return "Hello";
};
const powerLog: Multiple = (brand, age) => brand + age;
//! Promise function 을 type 화하기
type Greeting = { message: string };
// type : 프로미스를 반환하는 함수를 T인자로 받으면 그 프로미스안 result라는 이름의 data를 반환해라
type InferGetData<T> = T extends () => Promise<{ result: infer Data }>
? Data
: never;
const getData = async () => {
const greeting: Greeting = { message: "hi" };
return {
result: {
greeting,
data: {
name: "emily",
age: 22,
},
},
};
};
// getData의 프로미스 결과값 내 result 데이터 출력 함수
// 인자로 getData의 반환값과 같은 형식의 result obj가 필요하다
function printGreeting(result: InferGetData<typeof getData>) {
console.log(result.greeting);
}
(async () => {
const data = await getData();
printGreeting(data.result);
})();
| e1c901871bc9766d595e5eed56eaffb64963c27d | [
"JavaScript",
"TypeScript"
] | 6 | TypeScript | bluerainmango/nextjs-typescript | 3f4fba060613b2c24e59107f713203071bafc485 | d1449570e1f15f15b3f2268b6a8b1174ba55a701 |
refs/heads/master | <file_sep>var nombre = document.getElementById('nombre')
var edad = document.getElementById('edad')
function cantante(){
var name = prompt("Nombre dell personaje")
nombre.textContent = name
var age = prompt("Edad del personaje")
edad.innerText = age
} | e890b37f2aaf72050e148216814bdb1fdf70b0e3 | [
"JavaScript"
] | 1 | JavaScript | esrojas27/SegudaTereaBictia | 8b459cc694ec618004d5f7269d4d3417daa5bf22 | 6ba1aab172b9bb0549bf428e8483a674d423f1ac |
refs/heads/main | <repo_name>SEOP-YOON/Baek<file_sep>/1932.cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int dp[501][501];
int test_case;
int i, j;
int sum = 0;
cin >> test_case;
for (i = 1; i <= test_case; i++)
{
for (j = 1; j <= i; j++)
{
cin >> dp[i][j];
}
}
for (i = 2; i <= test_case; i++)
{
for (j = 1; j <= i; j++)
{
if (j == 1)
{
dp[i][j] = dp[i][j] + dp[i - 1][j];
}
else if (j == i)
{
dp[i][j] = dp[i][j] + dp[i - 1][j - 1];
}
else
{
dp[i][j] = max(dp[i][j] + dp[i - 1][j], dp[i][j] + dp[i - 1][j - 1]);
}
}
}
for (i = 1; i <= test_case; i++)
{
sum = max(sum, dp[test_case][i]);
}
cout << sum << endl;
}<file_sep>/1697.cpp
#include <iostream>
#include <queue>
using namespace std;
//BFS 문제
int main()
{
queue<int> q;
int visited[100001] = { 0 };
int N, K;
cin >> N >> K;
q.push(N);
visited[N] = 1;
while (!q.empty())
{
int p = q.front();
q.pop();
if (p == K)
{
visited[K] = visited[K] - 1;
break;
}
// 현재 위치에서 -1 했을경우에 방문하지 않았으면 p-1로 이동한후 index증가
if (p - 1 >= 0 && visited[p-1] == 0)
{
visited[p-1] = visited[p] +1;
q.push(p - 1);
}
// 현재 위치에서 +1 했을경우에 방문하지 않았으면 p+1로 이동한후 index증가
if (p + 1 <= 100000 && visited[p+1] == 0)
{
visited[p + 1] = visited[p] + 1;
q.push(p + 1);
}
// 현재 위치에서 *2 했을경우에 방문하지 않았으면 p*2로 이동한후 index증가
if(p*2 <=100000 && visited[p*2] == 0)
{
visited[p * 2] = visited[p] + 1;
q.push(p * 2);
}
//방문 했던 곳을 애초에 손해발생
}
cout << visited[K] << endl;
}<file_sep>/1149-2.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int arr[1001][3];
int dp[1001][3] = { 0 };
int test_case;
cin >> test_case;
for (int i = 0; i < test_case; i++)
{
for (int j = 0; j < 3; j++)
cin >> arr[i][j];
}
dp[0][0] = arr[0][0];
dp[0][1] = arr[0][1];
dp[0][2] = arr[0][2];
for (int i = 1; i < test_case; i++)
{
dp[i][0] += min(dp[i-1][1], dp[i-1][2]) + arr[i][0];
dp[i][1] += min(dp[i - 1][0],dp[i - 1][2]) + arr[i][1];
dp[i][2] += min(dp[i - 1][0], dp[i - 1][1]) + arr[i][2];
}
int sum = min(dp[test_case - 1][2], min(dp[test_case - 1][0], dp[test_case - 1][1]));
cout << sum << endl;
}<file_sep>/1500.cpp
#include <iostream>
#include <queue>
using namespace std;
int main()
{
long long S, K;
long long num1,num2;
long long sum=1;
long long temp1, temp2 = 0;
queue<long long> q;
cin >> S >> K;
num1 = S / K;
num2 = S % K;
for (int i = 0; i < K; i++)
{
q.push(num1);
}
for (int j = 0; j < num2; j++)
{
temp1 = q.front() + 1;
q.push(temp1);
q.pop();
}
int t_size = q.size();
for (int z = 0; z < t_size; z++)
{
temp2 = q.front();
sum = sum * temp2;
q.pop();
}
cout << sum << endl;
} | e13a6e75d63411eb8243a232d263882ba761f26c | [
"C++"
] | 4 | C++ | SEOP-YOON/Baek | ac7970649df47777c111c81f2218c3c355e2b9fb | c00776d7d779b03f70eb28937ce6330648e0fc73 |
refs/heads/main | <repo_name>syonaneeraj/PSY6422-Major-Project<file_sep>/README.md
# PSY6422-Major-Project
Data Visualisation project
This is a README file describing the folders available on this repository
This github repository folder contains the following:
1. fried food.R - The R script consisting of the raw code
2. Fried food.Rmd - This RMarkdown folder contains the markdown script for the visualisation code
3. Fried food consumption.csv is the excel sheet that contains the dataset derived from Kaggle
4. Fried food.pdf consists of the pdf output of the markdown code
5. Visualisation-project.html - contains the html output for the markdown code
6. Fried_food.docx - contains the word doc output for the markdown code
7. Rplotdiseases - is the output graph for the code which compares the fried food consumption per week to diseases observed
8. Rplotraces - is the output graph for the code which compares the fried food consumption per week observed in different racial groups
<file_sep>/fried food.R
setwd("C:/Users/<NAME>/Desktop") #setting working directory
#load all the necessary libraries
library(here)
library(tidyverse)
library(knitr)
#load the data
Data <- read.csv(here("Data", "Fried food.csv")) #loaded the data
View(Data)
head(Data)
# Wrangling the data by removing rows and columns not needed
Data <- Data[-c(1),]
Data <- Data%>% select(-P)
Data <- Data[-c(1),]
names(Data)
#Renaming columns for convenience
Data2 <- Data%>%
rename(serving_0 = None..n.15.166.,serving_1 = X.1.serving.week..n.38.482.,serving_2 = X1.2.servings.week..n.33.210.,serving_3 = X3.6.servings.week..n.15.480.,serving_max = â..1.serving.day..n.4628.)
names(Data2)
#slice the dataframe into subsets
dfrace <- Data2 %>% slice_head(n = 5)
df_diseases <- Data2 %>% slice(39:41)
#creating matrix out of the subsets of data
as.matrix.data.frame(dfrace)
dfrace[,-1]
mytable1 = as.matrix(dfrace[,-1])
#using the barplot function to plot the matrix
barplot1 <- barplot(mytable1,
xlab="servings per week",
ylab= "Fried food consumption",
legend.text = dfrace$Factors,
col = c("burlywood1","coral1","brown","darksalmon","gold"),
args.legend = list(x = "bottomright",inset = c(- 0.05, 1)))
#To save the graph, we use
ggsave("barplot1.png")
#same as above for the diseases subset
as.matrix.data.frame(df_diseases)
df_diseases[,-1]
mytable2 = as.matrix(df_diseases[,-1])
barplot2 <- barplot(mytable2,
xlab = "servings per week",
ylab = "Fried food consumption",
legend.text=df_diseases$Factors,
col=c("bisque1","darksalmon","coral1"),
args.legend = list(x = "topright",inset = c(- 0.48, 0)))
ggsave("barplot2.png")
<file_sep>/Fried_food.Rmd
---
title: "Fried food consumption in demographic groups"
author: "<NAME>"
date: "26/05/2021"
output:
html_document:
df_print: paged
word_document: default
pdf_document: default
---
<font size="6"> ***Data Origins*** </font>
The data was collected from online open sources and can be viewed [here](https://www.kaggle.com/jleibow27/fried-food-consumption-and-mortality).
The full dataset records the consumption of fried food in different demographic groups based on the number of servings consumed during a week.
<font size="6"> ***Research Question*** </font>
Fried food consumption was tracked in women from the US, belonging to different demographic groups. Here, we analyze the trend of number of *fried food servings* consumed along the week within different groups.
This could point out the cultural norms and habits as followed within them.
Comparing them to the trend observed in baseline disorders would provide insight into how the consumption affects different groups.
However, it is important to note that the baseline disorders observed are not correlated to the trend in racial groups so we cannot conclude how the consumption in different groups would directly lead to disorders.
1. Set working directory and load all the necessary libraries
```{r warning=FALSE,include=FALSE}
setwd("C:/Users/Sy<NAME>/Desktop")
```
```{r echo=FALSE}
library(here)
library(tidyverse)
library(knitr)
```
2. Once the libraries are ready, we load the data and view it for clarity.
```{r warning=FALSE}
Data <- read.csv(here("PSY6422_Major Project", "Fried food consumption.csv"))
Data #loaded the data
View(Data)
head(Data)
```
3. We clean the data in order to use it efficiently. The P values are not necessary, neither is the age at baseline as they are not relevant to our objective.
```{r}
Data <- Data[-c(1),]
Data <- Data%>% select(-P)
Data <- Data[-c(1),]
names(Data)
```
4. For convenience, we rename the columns to more accessible names as follows :
```{r warning=FALSE,include=FALSE}
Data2 <- Data%>%
rename(serving_0 = None..n.15.166.,serving_1 = X.1.serving.week..n.38.482.,serving_2 = X1.2.servings.week..n.33.210.,serving_3 = X3.6.servings.week..n.15.480.,serving_max = â..1.serving.day..n.4628.)
```
where,
**serving_0 = 0 servings per week**
**serving_1 = 0 to 1 servings per week**
**serving_2 = 1 to 2 servings per week**
**serving_3 = 3 to 6 servings per week**
**serving_max = more than 1 serving per day**
```{r}
names(Data2)
```
5. Next, we must create subsets of the data that we do require. There are two groups that we need:
A. Fried food in racial groups (Rows 1 to 5)
B. Disorders observed (Rows 39 to 41)
```{r}
dfrace <- Data2 %>% slice_head(n = 5)
df_diseases <- Data2 %>% slice(39:41)
```
```{r}
as.matrix.data.frame(dfrace)
dfrace[,-1]
mytable1 = as.matrix(dfrace[,-1])
```
<font size="4"> ***Visualization 01*** </font>
```{r}
barplot1 <- barplot(mytable1,
xlab = "servings per week",
ylab = "Fried food consumption",
legend.text=dfrace$Factors,
col=c("burlywood1","coral1","brown","darksalmon","gold"),
args.legend = list(x = "bottomright",inset = c(- 0.48, 0)))
ggsave("barplot1.png")
```
We follow the same routine for the graph plotting the disorders:
```{r}
as.matrix.data.frame(df_diseases)
df_diseases[,-1]
mytable2 = as.matrix(df_diseases[,-1])
```
<font size="4"> ***Visualization 02*** </font>
```{r}
barplot2 <- barplot(mytable2,
xlab = "servings per week",
ylab = "Fried food consumption",
legend.text=df_diseases$Factors,
col=c("bisque1","darksalmon","coral1"),
args.legend = list(x = "topright",xpd=TRUE,inset = c(- 0.48, 0)))
ggsave("barplot2.png")
```
To save the file, we used the ggsave function above.
<font size="6"> ***Summary*** </font>
Through the visualization performed above, we can conclude that White women consume the highest level of fried food, followed by Black and Hispanic women. The rest of the data present accounts for others and missing data
We can also conclude that baseline diabetes is most common among women consuming fried food followed by cardiovascular disorders and finally cancer.
<font size="6"> ***Caveats*** </font>
A. The dataset was present in wider format and was hard to process considering it was spread along columns
B. The values were present in percentages and made it extremely hard to manipulate the data as the number of participants for each group was different and a standard formula using the mutate function was hard to achieve.
<font size="6"> ***References*** </font>
<NAME>. (2018). [__*Data visualisation: a practical introduction.*__](https://socviz.co/)Princeton University Press.
[*_Association of fried food consumption with all cause, cardiovascular, and cancer mortality_*](https://www.bmj.com/content/364/bmj.k5420)
| 8ff3ce0989acdd607c30a8189c721a58d641dbea | [
"Markdown",
"R",
"RMarkdown"
] | 3 | Markdown | syonaneeraj/PSY6422-Major-Project | 659e35567818f69a3b537e40793ec1d5a2e9860a | f5bf268b23f4cd521178cbcf698d3ceb95b8025c |
refs/heads/master | <file_sep>'use strict';
/**
* @ngdoc function
* @name serviceSchedulingApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the serviceSchedulingApp
*/
angular.module('serviceSchedulingApp')
.controller('MainCtrl', ["$scope", "$firebaseArray", function ($scope, $firebaseArray) {
var ref = new Firebase("https://blinding-inferno-2443.firebaseio.com/");
//$scope.tasks = $firebaseArray(ref.child('tasks'));
$scope.workers = $firebaseArray(ref.child('users/workers/').orderByChild("uid"));
$scope.sortableOptions = {
cursor: "move",
connectWith: ".sortable-container",
placeholder: "sortable-placeholder"
};
var hidePopover = function() {
$('.popover').each(function () {
//Set the state of the popover in the scope to reflect this
var elementScope = angular.element(this).scope().$parent;
elementScope.isOpen = false;
//Remove the popover element from the DOM
$(this).remove();
});
};
$scope.editTask = function(task) {
if (!$scope.editingTask) {
$scope.editingTask = task;
task.editing = 1;
$scope.workers.$save($scope.workers.$getRecord(task.worker));
//$scope.editingTask.editing = 1;
$scope.editPopover.name = task.name;
$scope.editPopover.address = task.address;
$scope.editPopover.description = task.description;
//$firebaseArray(ref.child('users').child('workers').child(task.worker).child(task.section)).$save(task);
};
}
$scope.cancelEdit = function() {
var task = $scope.editingTask;
task.editing = 0;
$scope.workers.$save($scope.workers.$getRecord(task.worker));
$scope.editingTask = null;
hidePopover();
}
$scope.saveEdit = function() {
var task = $scope.editingTask;
task.name = $scope.editPopover.name;
task.address = $scope.editPopover.address;
task.description = $scope.editPopover.description;
task.editing = 0;
$scope.workers.$save($scope.workers.$getRecord(task.worker));
//$scope.workers.$save($scope.editPopover.worker);
//$firebaseArray(ref.child('users').child('workers').child(task.worker).child(task.section)).$save(task);
$scope.editingTask = null;
hidePopover();
}
$scope.addTask = function(worker, section) {
if (!$scope.editingTask) {
$scope.editingTask = true;
$scope.addPopover.worker = $scope.workers.$keyAt(worker);
$scope.addPopover.section = section;
};
}
$scope.cancelAdd = function() {
$scope.editingTask = null;
$scope.addPopover.name = '';
$scope.addPopover.address = '';
$scope.addPopover.description = '';
hidePopover();
}
$scope.saveAdd = function() {
var order = 0;
$firebaseArray(ref.child('users/workers').child($scope.addPopover.worker).child($scope.addPopover.section))
.$add({
order: order,
worker: $scope.addPopover.worker,
section: $scope.addPopover.section,
name: $scope.addPopover.name,
address: $scope.addPopover.address,
description: $scope.addPopover.description
});
$scope.editingTask = null;
$scope.addPopover.name = '';
$scope.addPopover.address = '';
$scope.addPopover.description = '';
hidePopover();
}
$scope.editPopover = {
editTemplateUrl: 'template/popover-edit-card.html',
name: '',
address: '',
description: ''
};
$scope.addPopover = {
addTemplateUrl: 'template/popover-add-card.html',
worker: '',
section: 'morning',
name: '',
address: '',
description: ''
};
}]);
| eb600006a1495653245c2facb8d6fe1bc3e796d8 | [
"JavaScript"
] | 1 | JavaScript | sunsq1991/service_scheduling | 8d7f00d98d8ca196df7eab4aa478a3189af37863 | 624d34a0d5330a43a80aab0e07a5fe3073677f6a |
refs/heads/master | <repo_name>mc2squared/tmux-mpd<file_sep>/README.md
# tmux-mpd
🎵 A dead simple script for MPD status in your tmux bar
## Requirements
The requirements are nothing you shouldn't already have - bash, sed, grep, cut, tr, and mpc - chances are if you're on any modern Linux distribution, you'll only need to install mpc to get this functioning.
## Installation and Usage
Move the bash script to your path, make sure it's executable (`chmod +x tmux-mpd`) and congratulations - you've got the module installed.
For usage in tmux, it's as simple as adding `#(tmux-mpd)` to your status bar lines in your tmux config. Make sure there's no detatched sessions running (aka "restart" tmux), and you've got your tunes in every window pane you go to!
## Side Note
Yes, I know this is janky - I built it to work for me, not to be the prettiest piece of shell script I've ever wrote. The semicolon parsing is for Mopidy-spotify support when a track has multiple artists, but if you're just using traditional MPD/Mopidy with local files exclusively, it'll likely just be redundant parsing.
<file_sep>/tmux-mpd
#!/bin/sh
while true; do
echo "Playing: $(mpc | grep - | tr ';' '+' | sed 's/+/ + /g') - $(mpc | grep % | sed 's/ /_/g' | cut -d_ -f2 | sed 's/repeat/ /g' | sed 's/off/ /g' | sed 's/on/ /g' | sed 's/ :/ /g' | awk 'NF > 0')"
sleep 1
done
| 4cec6c860d6628cf5c1a688478035eeca490832b | [
"Markdown",
"Shell"
] | 2 | Markdown | mc2squared/tmux-mpd | 93edfa683bb9ffad943dc838b506200bfd18a436 | 1b380884fb0d249549495c101a061f317eccc206 |
refs/heads/master | <repo_name>precagno/product_services<file_sep>/src/main/java/com/precagno/product/services/product_services/product/dao/ProductDAO.java
package com.precagno.product.services.product_services.product.dao;
import com.precagno.product.services.product_services.product.dto.Product;
public interface ProductDAO {
void create(Product product);
Product read(int id);
void update(Product product);
void delete(int id);
} | 82a2f6b337b3fba6f5a9a1198c5e8ceac9833163 | [
"Java"
] | 1 | Java | precagno/product_services | bc45cdfaedf3ef26e8d12d29070b7f9f55fa82f9 | fa7a34666731be9696f892e70882460a27002c9f |
refs/heads/master | <file_sep>install.packages("tidyverse")
install.packages("rmarkdown")
install.packages("esquisse")
install.packages("feather")
install.packages("knitr")
<file_sep># r-binder
R kernel for Data Gymnasia courses
[](https://mybinder.org/v2/gh/data-gymnasia/r-binder/master)
| 1d7ef2bedd4eff07cf71b377d3d8c17443548258 | [
"Markdown",
"R"
] | 2 | R | data-gymnasia/r-binder | 0762eb77e5b9715b5fb2e0a6866b2a2b85aad2fd | f3bf249ff69e345764480f09b5ffda3596c7565b |
refs/heads/master | <repo_name>QzhouZ/vue-ssr-demo<file_sep>/README.md
## 解决问题
- 【手机端首屏渲染问题】
- 【SEO解决搜索引擎抓取问题】
- 【提高页面渲染性能】
## 项目结构
````bash
├── README.md
├── build
│ ├── setup-dev-server.js
│ ├── vue-loader.config.js
│ ├── webpack.base.config.js
│ ├── webpack.client.config.js
│ └── webpack.server.config.js
├── package.json
├── config
├── server.js
└── src
├── App.vue
├── app.js
├── assets
│ ├── img
│ └── less
├── components
├── entry-client.js
├── entry-server.js
├── index.template.html
├── 404.template.html
├── 500.template.html
├── util
├── router
├── store
│ ├── actions.js
│ ├── getters.js
│ ├── index.js
│ ├── mutationtypes.js
│ └── state.js
└── views
````
#### 目录说明
- build 存放构建用的配置文件
- config 存放整个项目的配置文件
- api 存放接口管理文件
- assets 存放静态资源,包括图片、样式
- components 存放公共组件
- router 存放路由配置文件
- views 存放页面模块文件
- store 存放状态管理文件
- util 存放工具类文件
- app.js 是项目入口文件
- App.vue 是项目入口文件
- entry-client和entry-server分别是客户端入口文件和服务端的入口文件
- index.template.html 项目模版
- 404.template.html 页面404模版
- 500.template.html 页面500模版
- server.js 服务端启动服务的入口文件
## 运行 Demo 示例项目
进入项目 执行以下命令
```bash
// 安装 NPM 包
npm install
```
```bash
// dev模式下启动服务
npm run dev
```
```bash
// 打包命令
npm run build
```
```bash
// production模式下启动服务
npm run start
```
npm run dev 启动服务路径http://localhost:8080
<file_sep>/src/util/seo-tdk.js
import tdkConfig from 'rootconfig/tdk.js'
// tdk keywors and description
function getTDK (vm) {
const { tdk } = vm.$options
if (tdk) {
return typeof tdk === 'function'
? tdk.call(vm)
: tdk
}
}
const serverTDKMixin = {
created () {
let tdk = getTDK(this)
if (tdk) {
tdk = Object.assign(tdkConfig, tdk)
this.$ssrContext.tdk = tdk
}
}
}
const clientTDKMixin = {
mounted () {
let tdk = getTDK(this)
if (tdk) {
tdk = Object.assign(tdkConfig, tdk)
document.title = `${tdk.title}`
document.querySelector(`meta[name=keywords]`).content = tdk.keywords
document.querySelector(`meta[name=description]`).content = tdk.description
}
}
}
export default process.env.VUE_ENV === 'server'
? serverTDKMixin
: clientTDKMixin
<file_sep>/src/store/actions.js
import { fetchDeptList } from '@/api'
export default {
fetchItem ({ commit }, pageIndex = 1) {
return fetchDeptList({
pageIndex: pageIndex
}).then(res => {
commit('SET_LIST_DATA', res)
})
}
}
<file_sep>/src/api/index.js
import axios from 'axios'
var api = axios
api.defaults.headers.common['Accept'] = 'application/json'
api.defaults.headers.common['Content-Type'] = 'application/json'
export const fetchDeptList = (param) => {
return api.get('https://wy.guahao.com/json/consult/expert', {
params: param
}).then(res => {
return res.data
}).catch(e => {
throw e
})
}
<file_sep>/config/tdk.js
module.exports = {
title: '微医',
keywords: '挂号网,微医,互联网医院,预约挂号,网上预约,网上挂号,网上预约挂号,在线问诊,在线咨询,健康资讯,医院挂号,医院预约,专家门诊',
description: '微医集团(原挂号网),互联网医院国家试点平台,聚合了全国1900家重点医院,6700位学科带头人,20万副主任以上的医师,提供预约挂号,预约专家门诊,在线诊疗,电子处方,在线配药全方位服务。找大专家,上微医。'
}
| c6ca57024359dc948b85544ee984d8b45571e613 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | QzhouZ/vue-ssr-demo | e48e881adbd44ecd73fd4c7852fadb301b6ed481 | 00f43d1250acd7e299d65f431eb55788b3ba9e57 |
refs/heads/master | <file_sep>package DAL;
import java.util.List;
import Metier.I_Produit;
public class ProduitDAO_XMLAdap implements I_ProduitDAO{
private ProduitDAO_XML dao = new ProduitDAO_XML();
private static ProduitDAO_XMLAdap instance = new ProduitDAO_XMLAdap();
@Override
public boolean create(I_Produit produit) {
return dao.creer(produit);
}
@Override
public boolean update(I_Produit produit) {
return dao.maj(produit);
}
@Override
public boolean delete(I_Produit produit) {
return dao.supprimer(produit);
}
@Override
public I_Produit read(String nom) {
return dao.lire(nom);
}
@Override
public List<I_Produit> readAll() {
return dao.lireTous();
}
public static ProduitDAO_XMLAdap getInstance(){
return instance;
}
}
<file_sep>package Metier;
import java.text.DecimalFormat;
public class Produit implements I_Produit{
private int quantiteStock;
private String nom;
private double prixUnitaireHT;
private static float tauxTVA = 0.2f;
public Produit(String nom, double prix, int qte){
this.nom = nom.trim().replace('\t', ' ');
this.prixUnitaireHT = prix;
this.quantiteStock = qte;
}
@Override
public boolean ajouter(int qteAchetee) {
this.quantiteStock += qteAchetee;
return true;
}
@Override
public boolean enlever(int qteVendue) {
this.quantiteStock -= qteVendue;
return false;
}
@Override
public String getNom() {
return this.nom;
}
@Override
public int getQuantite() {
return this.quantiteStock;
}
@Override
public double getPrixUnitaireHT() {
return this.prixUnitaireHT;
}
@Override
public double getPrixUnitaireTTC() {
return this.prixUnitaireHT*(1+tauxTVA);
}
@Override
public double getPrixStockTTC() {
return this.prixUnitaireHT * this.quantiteStock * (1+tauxTVA);
}
public String toString(){
DecimalFormat df = new DecimalFormat("0.00");
return this.nom + " - prix HT : " + df.format(this.prixUnitaireHT) + " € - prix TTC : " + df.format(this.getPrixUnitaireTTC()) + " € - quantité en stock : " + this.quantiteStock;
}
}
<file_sep>package DAL;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import Metier.I_Produit;
import Metier.ProduitFactory;
public class ProduitDAORelationnel implements I_ProduitDAO {
private Connection cn;
private PreparedStatement ps;
private ResultSet rs;
private static ProduitDAORelationnel instance = new ProduitDAORelationnel();
private ProduitDAORelationnel(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
this.cn = DriverManager.getConnection("jdbc:oracle:thin:@gloin:1521:iut", "fernandeza", "aulas");
} catch (ClassNotFoundException e) {
System.out.println("Driver introuvable");
e.printStackTrace();
} catch (SQLException e) {
this.deconnexion();
e.printStackTrace();
}
}
public boolean create(I_Produit p){
try {
ps = cn.prepareStatement("{call newProduit(?,?,?)}");
ps.setString(1, p.getNom());
ps.setDouble(2, p.getPrixUnitaireHT());
ps.setInt(3, p.getQuantite());
ps.execute();
return true;
} catch (SQLException e) {
System.out.println("Erreur création produit");
return false;
}
}
public boolean delete(I_Produit p){
try {
ps = cn.prepareStatement("delete from Produits where nomProduit = ?");
ps.setString(1, p.getNom());
return ps.execute();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public I_Produit read(String nom){
try {
ps = cn.prepareStatement("select * from Produits where nomProduit = ? ");
ps.setString(1, nom);
rs = ps.executeQuery();
return ProduitFactory.createProduit(rs.getString(1), rs.getDouble(2), rs.getInt(3));
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public boolean update(I_Produit p ){
return true;
}
// public boolean deleteAll(){
// try {
// ps = cn.prepareStatement("delete from Produits");
// return ps.execute();
// } catch (SQLException e) {
// e.printStackTrace();
// return false;
// }
// }
public static ProduitDAORelationnel getInstance(){
return instance;
}
public void deconnexion(){
try {
this.cn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public List<I_Produit> readAll() {
try {
List<I_Produit> list = new ArrayList<I_Produit>();
ps = cn.prepareStatement("select * from Produits");
rs = ps.executeQuery();
while(rs.next()){
list.add(ProduitFactory.createProduit(rs.getString(2), rs.getDouble(3), rs.getInt(4)));
}
return list;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
| 34ee93f56344660e22d5105848480be88ddbb79e | [
"Java"
] | 3 | Java | fernandezadrian/projetUML | a069569937822350eba09cdd3f23130f4365005b | 1a04115311d70d52d269ee49882b061a1f5f5f30 |
refs/heads/master | <repo_name>BohdanKadenskyi/goit-js-hw-01<file_sep>/task2/task2.js
const total = 100; //(количество товаров на складе)
const ordered = 50; // (единиц товара в заказе).
let message;
if (total < ordered) {
message = 'На складе недостаточно товаров!';
} else {
message = 'Заказ оформлен, с вами свяжется менеджер';
}
console.log(message);
{
const ordered = 20;
if (total < ordered) {
message = 'На складе недостаточно товаров!';
} else {
message = 'Заказ оформлен, с вами свяжется менеджер';
}
console.log(message);
}
{
const ordered = 80;
if (total < ordered) {
message = 'На складе недостаточно товаров!';
} else {
message = 'Заказ оформлен, с вами свяжется менеджер';
}
console.log(message);
}
{
const ordered = 130;
if (total < ordered) {
message = 'На складе недостаточно товаров!';
} else {
message = 'Заказ оформлен, с вами свяжется менеджер';
}
console.log(message);
}
<file_sep>/task5/task5.js
const userInput = prompt('Оформить доставку товара к себе в страну');
let credits;
if (userInput === null) {
console.log('Отмена');
}
const countryName = userInput.toLowerCase();
switch (countryName) {
case 'китай':
credits = 100;
console.log(
`Доставка в ${
countryName[0].toUpperCase() + countryName.substring(1)
} будет стоить ${credits} кредитов.`,
);
break;
case 'чили':
credits = 250;
console.log(
`Доставка в ${
countryName[0].toUpperCase() + countryName.substring(1)
} будет стоить ${credits} кредитов.`,
);
break;
case 'австралия':
credits = 170;
console.log(
`Доставка в ${
countryName[0].toUpperCase() + countryName.substring(1)
} будет стоить ${credits} кредитов.`,
);
break;
case 'индия':
credits = 80;
console.log(
`Доставка в ${
countryName[0].toUpperCase() + countryName.substring(1)
} будет стоить ${credits} кредитов.`,
);
break;
case 'ямайка':
credits = 120;
console.log(
`Доставка в ${
countryName[0].toUpperCase() + countryName.substring(1)
} будет стоить ${credits} кредитов.`,
);
break;
default:
alert('В вашей стране доставка не доступна');
}
<file_sep>/task4/task4.js
let input = prompt('Какое количество дроидов желаите преобрести?');
const credits = 23580;
let pricePerDroid = 3000;
const totalPrice = input * pricePerDroid;
if (input === null) {
console.log(alert('Отменено пользователем!'));
} else {
input = Number(input);
const notNumber = Number.isNaN(input);
if (notNumber) {
console.log(alert('Было введено не число, попробуйте еще раз'));
} else {
prompt('Общая сумма', totalPrice);
}
if (totalPrice > credits) {
alert('Недостаточно средств на счету!');
} else if (totalPrice - credits) {
console.log(
`Вы купили ${input} дроидов, на счету осталось ${
credits - totalPrice
} кредитов.`,
);
alert(
`Вы купили ${input} дроидов, на счету осталось ${
credits - totalPrice
} кредитов.`,
);
}
}
| 601d958f62489726860bb3c6649c1094a18e93c5 | [
"JavaScript"
] | 3 | JavaScript | BohdanKadenskyi/goit-js-hw-01 | e0913e9ca9e9fe3e8649feb63c8bd0f4975cded5 | b0e5e600adf90785c8cfcdab6bf68717a7bc7d97 |
refs/heads/master | <file_sep>import java.util.Scanner;
public class Hadanka {
public static void main(String args[]){
int randomNumber = (int) (Math.random() * 100) + 1;
boolean hasWon = false;
System.out.println("Náhodně jsem vybral číslo mezi 1 a 100");
System.out.println("Zkus ho uhádnout..");
Scanner scanner = new Scanner(System.in);
for (int i = 10; i > 0; i--) {
System.out.println("Máš "+ i + " pokusů. Hádej: ");
int guess = scanner.nextInt();
System.out.println("Tvůj tip byl: " +guess);
// System.out.println("You picked "+guess);
if (randomNumber > guess) {
System.out.println("Je to větší než " + guess + ".");
}
else if (randomNumber < guess) {
System.out.println("Je to menší než " + guess + ".");
} else {
hasWon = true;
break;
}
}
if(hasWon){
System.out.println("SPRAVNE...VYHRAVAS!!!");
}else{
System.out.println("Už nemáš další pokusy. Ale zkus novou hru :-)");
System.out.println("Číslo bylo: " + randomNumber);
};
}
}
| 9307b100574e47e631aa1b94052e8ff39fcbb638 | [
"Java"
] | 1 | Java | EKrejci/NumberGame | 9fa8c3ac96e48547513992fea7a15203e22c5e98 | 0d8dbe76de63e0d0ad241c870f4778bd93b971e6 |
refs/heads/main | <file_sep>import { Specification } from '@modules/cars/infra/typeorm/entities/Specification';
import { SpecificationsRepository } from '@modules/cars/infra/typeorm/repositories/SpecificationsRepository';
class ListSpecificationsUseCase {
constructor(private specificationRepository: SpecificationsRepository) {}
async execute(): Promise<Specification[]> {
const all = await this.specificationRepository.list();
return all;
}
}
export { ListSpecificationsUseCase };
<file_sep>// import { SpecificationsRepository } from '../../repositories/implementations/SpecificationsRepository';
// import { ListSpecificationController } from './listSpecificationsController';
// import { ListSpecificationsUseCase } from './ListSpecificationUseCase';
// const specificationsRepository = SpecificationsRepository.getInstance();
// const listSpecificationUseCase = new ListSpecificationsUseCase(
// specificationsRepository
// );
// const listSpecificationController = new ListSpecificationController(
// listSpecificationUseCase
// );
// export { listSpecificationController };
| 253f657bad28a8d05be215cbec74063c3712bfcf | [
"TypeScript"
] | 2 | TypeScript | rsjayme/igniteRentalx | c559254b550804b26f4175ceb923d769f99eaebb | f29a03df2d8b22f76bac5e320a18dc5840b5bdd2 |
refs/heads/master | <file_sep>const express = require('express');
const app = express();
app.use('/', express.static(__dirname + '/public'));
app.listen(8000, function(){
console.log("[Sortable] Server is now running on port 8000");
});<file_sep>function Data(_data){
this.init(_data);
// clone ... for filtered data
this.current = this.safeClone();
// event emit
this.dispatcher = d3.dispatch("sort", "highlight", "mouseover", "mouseout", "filter", "reset");
this.on = (...args) => this.dispatcher.on(...args);
this.call = (event, ...args) => this.dispatcher.call(event, this, ...args);
// default sort method
this.sort = this.sortParallel;
}
Data.prototype.el = {};
Data.prototype.init = function(data){
var newFormat = {};
// pick headers from first record
var headers = {};
var headerIds = {};
d3.keys(data[0]).forEach(function(name, col){
// header's format
headers[name] = {
col: col,
name: name,
order: null, // sort order status
isNumericData: name !== "name",
weight: 1,
width: 0,
x: 0
};
headerIds[name] = col;
newFormat[name] = [];
});
data.forEach(function(d, row){
// cell's format
d3.keys(d).forEach(function(name){
var header = headers[name];
d[name] = {
name: name,
header: header,
row: row,
col: header.col,
value: header.isNumericData ? +d[name] : d[name],
visible: true,
active: false,
color: null
};
newFormat[name].push(d[name]);
});
});
this.headers = d3.values(headers);
this.origin = d3.values(newFormat);
}
Data.prototype.safeClone = function(initialCallback){
if(initialCallback) return this.origin.map(column => column.map(d => initialCallback(d)));
return this.origin.map(column => column.map(d => d));
}
Data.prototype.reset = function(){
this.current = this.safeClone(d => {
d.visible = true;
d.active = false;
d.color = null;
return d;
});
this.highlights = {};
this.colors = this.colorsOrigin.map(d => d);
this.headers.forEach(header => {
header.order = null;
});
this.call("reset");
}
Data.prototype.ascend = function(a, b){
return a.value > b.value ? 1 : a.value < b.value ? -1 : a.row > b.row ? 1 : -1;
}
Data.prototype.descend = function(a, b){
return a.value < b.value ? 1 : a.value > b.value ? -1 : a.row < b.row ? 1 : -1;
}
Data.prototype.sortRelative = function(header, order){
var targetCol = this.origin[header.col];
this.current = this.current.map(function(column){
return column.sort(function(a, b){
return order(targetCol[a.row], targetCol[b.row]);
});
});
this.headers.forEach(function(header){
header.order = null;
});
header.order = order;
this.call("sort", this.sortRelative, header, order);
}
Data.prototype.sortParallel = function(header, order){
this.current[header.col].sort(order);
header.order = order;
this.call("sort", this.sortParallel, header, order);
}
Data.prototype.colorsOrigin = d3.schemeCategory10.map(function(d){ return d; });
Data.prototype.colors = d3.schemeCategory10.map(function(d){ return d; });
Data.prototype.colorIndex = 0;
Data.prototype.highlights = {};
Data.prototype.highlight = function(row){
if(this.highlights[row]){
this.colors.unshift(this.highlights[row]);
this.highlights[row] = null;
}else{
if(this.colors.length === 0) return alert("선택할 수 있는 최대치를 초과하였습니다!! (최대 10개)");
this.highlights[row] = this.colors.shift();
}
this.current.forEach((column) => {
column.forEach((d) => {
if(d.row === row) d.color = this.highlights[row];
});
});
this.call("highlight", row, this.highlights[row]);
}
Data.prototype.mouseover = function(row, focused){
this.call("mouseover", row);
}
Data.prototype.mouseout = function(row){
this.call("mouseout", row);
}
Data.prototype.filter = function(rows){
var r = {};
rows.forEach(function(row){ r[row] = true; });
this.current.forEach((column) => {
column.forEach((d) => {
d.visible = !(d.row in r);
});
});
this.call("filter", rows);
}<file_sep>function Table(options){
var bindto = options.bindto;
var data = options.data;
var width = options.width || 960;
var height = options.height || 540;
this.el.root = d3.select(bindto).append("svg");
this.data = data;
this._width = width;
this._height = height;
this.cellHeight = 20;
this.el.columns = this.el.root.append("g")
.selectAll("g")
.data(this.data.current)
.enter().append("g");
this.el.cells = this.el.columns
.selectAll("g")
.data(function(d){ return d; })
.enter().append("g")
.on("mouseover", (d) => {
this.data.mouseover(d.row);
})
.on("mouseout", (d) => {
this.data.mouseout(d.row);
})
.on("click", (d) => {
this.data.highlight(d.row);
});
this.el.cells.append("rect")
.attr("height", this.cellHeight);
this.el.cells.append("text");
this.updateSize();
this.updateCells();
this.data.on("sort.table", (...args) => this.onSort(...args));
this.data.on("highlight.table", (...args) => this.onHighlight(...args));
this.data.on("mouseover.table", (...args) => this.onMouseOver(...args));
this.data.on("mouseout.table", (...args) => this.onMouseOut(...args));
this.data.on("filter.table", (...args) => this.onFilter(...args));
this.data.on("reset.table", (...args) => this.onReset(...args));
}
Table.prototype.el = {};
Table.prototype.width = function(width){
if(width){
this._width = width;
this.updateSize();
}
else return this._width;
}
Table.prototype.height = function(height){
if(height){
this._height = height;
this.updateSize();
}
else return this._height;
}
Table.prototype.updateCells = function(){
this.updateSize();
this.el.cells
.attr("class", function(d){ return "cell cell-col-" + d.col + " cell-row-" + d.row; })
.each(function(d){
var cell = d3.select(this)
.attr("class", function(d){ return "cell cell-col-" + d.col + " cell-row-" + d.row + (d.color ? " cell-active" : ""); });
cell.select("rect").style("fill", function(d){ return d.color; });
cell.select("text").text(function(d){ return d.value; });
});
}
Table.prototype.updateSize = function(){
var width = this._width, height = this._height;
if(width === undefined || height === undefined) return;
this.el.root
.attr("width", width)
.attr("height", height);
this.el.cells.selectAll("rect")
.attr("width", function(d){ return d.header.width; });
this.el.cells.selectAll("text")
.attr("x", function(d){ return d.header.width / 2; })
.attr("y", this.cellHeight / 2);
var cellHeight = this.cellHeight;
var finalHeight;
this.el.columns
.each(function(column){
var nestedHeight = 0;
d3.select(this).selectAll("g")
.each(function(d){
var cell = d3.select(this);
cell.style("display", d.visible ? null : "none");
if(d.visible){
cell.attr("transform", "translate(" + d.header.x + "," + nestedHeight + ")");
nestedHeight += cellHeight;
}
});
finalHeight = nestedHeight;
});
this.el.root
.attr("height", finalHeight);
}
Table.prototype.onSort = function(sort, header, order){
this.el.columns.data(this.data.current);
this.el.cells.data(function(d){ return d; });
this.updateCells();
}
Table.prototype.onHighlight = function(row, color){
this.el.cells.filter(".cell-row-" + row)
.classed("cell-active", !!color)
.selectAll("rect")
.style("fill", color);
}
Table.prototype.onMouseOver = function(row){
this.el.cells.filter(".cell-row-" + row)
.classed("cell-hover", true);
}
Table.prototype.onMouseOut = function(row){
this.el.cells.filter(".cell-row-" + row)
.classed("cell-hover", false);
}
Table.prototype.onFilter = function(rows){
this.updateCells();
}
Table.prototype.onReset = function(){
this.el.cells
.classed("cell-active", false)
.selectAll("rect")
.style("fill", null);
this.el.columns.data(this.data.current);
this.el.cells.data(function(d){ return d; });
this.updateCells();
}<file_sep># Sortable
Parallel table with parallel coordinates

| 4a26497c18173ece8d1c50c119c49880e2c46053 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | solo5star/Sortable | 5d20b31b86033e955b25147370f36f742ec353b8 | 1fc0d905509ecbe4d33922816a00090d08d4f545 |
refs/heads/main | <repo_name>Barzabel/hexlet_pytest<file_sep>/tests/test_example.py
from hexlet_pytest.example import reverse
from hexlet_pytest.stack import Stack
import pytest
def test_revers():
assert reverse('hexlet') == 'telxeh'
def test_reverse_for_empty_string():
assert reverse('') == ''
# пример модульного тестирования
# 1 Тестируем основную функциональность (пример стек)
def test_stack():
stack = Stack()
stack.push('one')
stack.push('two')
assert stack.pop() == 'two'
assert stack.pop() == 'one'
# 2 Тестируем дополнительную функциональность
def test_emptiness():
stack = Stack()
assert not stack
stack.push('one')
assert bool(stack) # not not stack
stack.pop()
assert not stack
# Пограничные случаи (попытка взять элемент из пустого стека)
def test_pop_with_empty_stack():
stack = Stack()
with pytest.raises(IndexError):
stack.pop()<file_sep>/hexlet_pytest/stack.py
class Node:
def __init__(self,val):
self.value = val
self.prev = None
class Stack:
def __init__(self):
self.stack = None
self.count = 0
def __bool__(self):
try:
self.peek()
except IndexError:
return False
else:
return True
def size(self):
return self.count
def pop(self):
if self.size() == 0:
raise IndexError('stakc is empty')
res = self.stack.value
self.stack = self.stack.prev
self.count = self.count - 1
return res
def push(self, value):
NewNode = Node(value)
NewNode.prev = self.stack
self.stack = NewNode
self.count = self.count + 1
def peek(self):
if self.size()== 0:
raise IndexError('stakc is empty') # если стек пустой
res = self.stack.value
return res | 1d5092d06ff4b573bc59e1a0cd979e0df41dd69d | [
"Python"
] | 2 | Python | Barzabel/hexlet_pytest | 085d9724de7933912553d7b5137767df4b7a675a | ded3b60de63ac4b23bdaf830694024df7ee91a1c |
refs/heads/master | <file_sep># Galactica
3D Android Game
Galactica is a mobile game application based on Android operating system built using only OpenGl and Java. The main idea and topic behind the game is that invaders from outer space attack Earth and the user is the sole person capable of fending off the evil forces. The art style is a little retro when it comes to the GUI and the font used. The idea is to create an 8-bit themed game with a fancy graphical user interface with textured and lighted models. The user interacts with the game by tilting the phone in order to move the user controlled objects and by touching on the screen to fire up different events such as: firing missiles, pausing/ resuming or even terminating the game. Given the fact that the game is a single-level game where the main focus is to score as many points as possible Galactica can be classified as a first-person shooter arcade game. <file_sep>package com.shehi.regi.androidinvaders;
import com.shehi.regi.framework.Game;
import com.shehi.regi.framework.Input;
import com.shehi.regi.framework.gl.Camera2D;
import com.shehi.regi.framework.gl.GLScreen;
import com.shehi.regi.framework.gl.SpriteBatcher;
import com.shehi.regi.framework.math.OverlapTester;
import com.shehi.regi.framework.math.Rectangle;
import com.shehi.regi.framework.math.Vector2;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
public class HelpScreen extends GLScreen {
Camera2D guiCam;
SpriteBatcher batcher;
Rectangle backBounds;
Rectangle nextBounds;
Vector2 touchPoint;
String textString;
String textString1;
String textString2;
String textString3;
public HelpScreen(Game game) {
super(game);
guiCam = new Camera2D(glGraphics, 480, 320);
backBounds = new Rectangle(0, 0, 64, 64);
nextBounds = new Rectangle(416, 0, 64, 64);
touchPoint = new Vector2();
batcher = new SpriteBatcher(glGraphics, 100);
textString = "1. Tilt the phone to move";
textString1 = "the ship left/right";
textString2 = "2. Make a full trip side to";
textString3 = "side to score 10 points";
}
@Override
public void update(float deltaTime) {
List<Input.TouchEvent> events = game.getInput().getTouchEvents();
int len = events.size();
for (int i = 0; i < len; i++) {
Input.TouchEvent event = events.get(i);
if (event.type != Input.TouchEvent.TOUCH_UP)
continue;
guiCam.touchToWorld(touchPoint.set(event.x, event.y));
if (OverlapTester.pointInRectangle(backBounds, touchPoint)) {
game.setScreen(new MainMenuScreen(game));
Assets.playSound(Assets.clickSound);
return;
}
if (OverlapTester.pointInRectangle(nextBounds, touchPoint)) {
game.setScreen(new HelpScreen2(game));
Assets.playSound(Assets.clickSound);
return;
}
}
}
@Override
public void present(float deltaTime) {
GL10 gl = glGraphics.getGL();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
guiCam.setViewportAndMatrices();
gl.glEnable(GL10.GL_TEXTURE_2D);
batcher.beginBatch(Assets.background);
batcher.drawSprite(240, 160, 480, 320, Assets.backgroundRegion);
batcher.endBatch();
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
batcher.beginBatch(Assets.items);
Assets.font.drawText(batcher, textString, 30, 240);
Assets.font.drawText(batcher, textString1, 100, 240 - 30);
Assets.font.drawText(batcher, textString2, 30, 240 - 30 - 70);
Assets.font.drawText(batcher, textString3, 80, 240 - 30 - 70 - 30);
batcher.drawSprite(32, 32, 64, 64, Assets.leftRegion);
batcher.drawSprite(480 - 32, 32, -64, 64, Assets.leftRegion);
batcher.endBatch();
gl.glDisable(GL10.GL_BLEND);
}
@Override
public void resume() {
}
@Override
public void pause() {
}
@Override
public void dispose() {
}
}
<file_sep>package com.shehi.regi.androidinvaders;
import com.shehi.regi.framework.DynamicGameObject3D;
public class Ship extends DynamicGameObject3D {
static float SHIP_VELOCITY = 20f;
static int SHIP_ALIVE = 0;
static int SHIP_EXPLODING = 1;
static float SHIP_EXPLOSION_TIME = 1.6f;
static float SHIP_RADIUS = 0.5f;
int lives;
int state;
public float stateTime = 0;
public static int score;
boolean already_touched = true;
boolean touchright = false;
boolean touchleft = true;
public Ship(float x, float y, float z) {
super(x, y, z, SHIP_RADIUS);
lives = 3;
state = SHIP_ALIVE;
score = 0;
}
public void update(float deltaTime, float accelY) {
if (state == SHIP_ALIVE) {
velocity.set(accelY / 10 * SHIP_VELOCITY, 0, 0);
position.add(velocity.x * deltaTime, 0, 0);
if (position.x < World.WORLD_MIN_X)
position.x = World.WORLD_MIN_X;
if (position.x > World.WORLD_MAX_X)
position.x = World.WORLD_MAX_X;
bounds.center.set(position);
} else {
if (stateTime >= SHIP_EXPLOSION_TIME) {
lives--;
stateTime = 0;
state = SHIP_ALIVE;
}
}
stateTime += deltaTime;
}
public void kill() {
state = SHIP_EXPLODING;
stateTime = 0;
velocity.x = 0;
}
}
<file_sep>package com.shehi.regi.androidinvaders;
import com.shehi.regi.framework.DynamicGameObject3D;
import java.util.Random;
public class Invader extends DynamicGameObject3D {
static final int INVADER_ALIVE = 0;
static final int INVADER_DEAD = 1;
static final float INVADER_RADIUS = 0.75f;
int state = INVADER_ALIVE;
float stateTime = 0;
Random rand;
public Invader(float x, float y, float z) {
super(x, y, z, INVADER_RADIUS);
velocity.z = (int) (Math.random() * 7 + 5);
rand = new Random();
}
public void update(float deltaTime) {
if (state == INVADER_ALIVE) {
position.z += velocity.z * deltaTime;
bounds.center.set(position);
if (position.z > World.WORLD_MAX_Z) {
position.set((float) Math.random() * World.WORLD_MAX_X, 0, World.WORLD_MIN_Z);
velocity.z = (int) (Math.random() * 7 + 5);
}
}
stateTime += deltaTime;
}
}
<file_sep>package com.shehi.regi.androidinvaders;
import com.shehi.regi.framework.Music;
import com.shehi.regi.framework.Sound;
import com.shehi.regi.framework.gl.Animation;
import com.shehi.regi.framework.gl.Font;
import com.shehi.regi.framework.gl.ObjLoader;
import com.shehi.regi.framework.gl.Texture;
import com.shehi.regi.framework.gl.TextureRegion;
import com.shehi.regi.framework.gl.Vertices3;
import com.shehi.regi.framework.impl.GLGame;
public class Assets {
public static Texture background;
public static TextureRegion backgroundRegion;
public static Texture items;
public static TextureRegion logoRegion;
public static TextureRegion menuRegion;
public static TextureRegion gameOverRegion;
public static TextureRegion highScoresRegion;
public static TextureRegion pauseRegion;
public static TextureRegion settingsRegion;
public static TextureRegion touchRegion;
public static TextureRegion accelRegion;
public static TextureRegion touchEnabledRegion;
public static TextureRegion accelEnabledRegion;
public static TextureRegion soundRegion;
public static TextureRegion soundEnabledRegion;
public static TextureRegion leftRegion;
public static TextureRegion rightRegion;
public static TextureRegion fireRegion;
public static TextureRegion pauseButtonRegion;
public static Font font;
public static Texture explosionTexture;
public static Animation explosionAnim;
public static Vertices3 shipModel;
public static Texture shipTexture;
public static Vertices3 coinModel;
public static Texture coinTexture;
public static Vertices3 invaderModel;
public static Texture invaderTexture;
public static Vertices3 shotModel;
public static Vertices3 shieldModel;
public static Music music;
public static Sound clickSound;
public static Sound explosionSound;
public static Sound shotSound;
public static Sound coinSound;
public static Sound laserSound;
public static Sound hithitSound;
public static void load(GLGame game) {
background = new Texture(game, "background.jpg", true);
backgroundRegion = new TextureRegion(background, 0, 0, 480, 320);
items = new Texture(game, "items.png", true);
logoRegion = new TextureRegion(items, 0, 192, 512, 96);
menuRegion = new TextureRegion(items, 64, 352, 448, 160);
gameOverRegion = new TextureRegion(items, 224, 128, 128, 64);
pauseRegion = new TextureRegion(items, 0, 128, 160, 64);
highScoresRegion = new TextureRegion(Assets.items, 64, 288, 288, 32);
settingsRegion = new TextureRegion(items, 256, 416, 224, 32);
touchRegion = new TextureRegion(items, 0, 384, 64, 64);
accelRegion = new TextureRegion(items, 64, 384, 64, 64);
touchEnabledRegion = new TextureRegion(items, 0, 448, 64, 64);
accelEnabledRegion = new TextureRegion(items, 64, 448, 64, 64);
soundRegion = new TextureRegion(items, 0, 288, 64, 64);
soundEnabledRegion = new TextureRegion(items, 0, 352, 64, 64);
leftRegion = new TextureRegion(items, 0, 0, 64, 64);
rightRegion = new TextureRegion(items, 64, 0, 64, 64);
fireRegion = new TextureRegion(items, 128, 0, 64, 64);
pauseButtonRegion = new TextureRegion(items, 0, 64, 64, 64);
font = new Font(items, 224, 0, 16, 16, 20);
explosionTexture = new Texture(game, "explode.png", true);
TextureRegion[] keyFrames = new TextureRegion[16];
int frame = 0;
for (int y = 0; y < 256; y += 64) {
for (int x = 0; x < 256; x += 64) {
keyFrames[frame++] = new TextureRegion(explosionTexture, x, y, 64, 64);
}
}
explosionAnim = new Animation(0.1f, keyFrames);
shipTexture = new Texture(game, "ship.png", true);
shipModel = ObjLoader.load(game, "ship.obj");
invaderTexture = new Texture(game, "invader.png", true);
invaderModel = ObjLoader.load(game, "invader.obj");
shieldModel = ObjLoader.load(game, "shield.obj");
shotModel = ObjLoader.load(game, "shot.obj");
coinTexture = new Texture(game, "coins.png", true);
coinModel = ObjLoader.load(game, "coins.obj");
music = game.getAudio().newMusic("music.mp3");
music.setLooping(true);
music.setVolume(0.5f);
if (Settings.soundEnabled)
music.play();
clickSound = game.getAudio().newSound("click.ogg");
coinSound = game.getAudio().newSound("coin.ogg");
explosionSound = game.getAudio().newSound("explosion.ogg");
shotSound = game.getAudio().newSound("shot.ogg");
laserSound = game.getAudio().newSound("laser.ogg");
hithitSound = game.getAudio().newSound("hithit.ogg");
}
public static void reload() {
background.reload();
items.reload();
explosionTexture.reload();
shipTexture.reload();
invaderTexture.reload();
coinTexture.reload();
if (Settings.soundEnabled)
music.play();
}
public static void playSound(Sound sound) {
if (Settings.soundEnabled)
sound.play(1);
}
}
| 9367407e72ec9f96163999be8a9c60c6645d3642 | [
"Markdown",
"Java"
] | 5 | Markdown | RegiShehi/Galactica | c39276eeea81316a867d5c3aa3eac93306cede7b | 2ed599bc8f212e7a27ade484b6f3f2bd5a521e1f |
refs/heads/master | <file_sep>pro xxf,help=help
;+
; NAME:
; XXF
;
; ====================
; Syntax: xxf,help=help
; ====================
;
; xxf Renaming of SHOW procedure plus displaying line flags
; --
;
;-
; V5.1 July 2008
; V6.0 June 2009
; tmb/dsb fixed for elegance
; V7.0 03may2013 tvw - added /help, !debug
;-
;
if keyword_set(help) then begin & get_help,'xxf' & return & endif
erase
show
flags
;
return
end
<file_sep>;===============================================================
; Batch script to translate Trey's code into TMBIDL structure
;===============================================================
; use !rec and !blkrec structures to make the translation
; !blkrec flagis initialized to zero
;
!rec=!blkrec ; make sure that !rec is initialized
;
; pass the intensities
;
npts=n_vel
!rec.s_pts=npts
!rec.data[0:npts-1]=spect
!rec.ytype=byte('TB')
;
; pack info on the model parameters
;
sname=' '
gname,lgal,bgal,src=sname
!rec.source=byte(sname)
!rec.vel=0.
!rec.pol_id=byte(' H I')
;
; Annotate based on properties of the model
;
percc=textoidl(' cm^{-3}')
kms=textoidl(' km s^{-1}')
maxr=textoidl('R_{max}')
tspin=textoidl('T_{s}')
sigma=textoidl('\sigma')
;
test=n_elements(model)
if test eq 1 then begin & den=denlos[0] & temp=tlos[0] & disp=siglos[0] & endif
if test ge 2 then begin & den=model[1] & temp=model[0] & disp=model[2] & endif
;
label='n='+fstring(den,'(f3.1)')+' '
label=label+tspin+'='+fstring(temp,'(f4.0)')+' '
label=label+sigma+'='+fstring(disp,'(f3.0)')+' '
label=strmid(label,0,32)
;
!rec.line_id=byte(label)
;
mtype=' '
sdisk=' ExpDisk'
sclouds=' Clouds'
sspiral=' Spiral'
sdispgrad='DispGrad'
if KeyWord_Set(expdisk) then mtype=mtype+sdisk
if ~KeyWord_Set(noclouds) then mtype=mtype+sclouds
if KeyWord_Set(smodel) then mtype=mtype+sspiral
;!rec.scan_type=byte(mtype)
!rec.date=byte(mtype)
;
label=maxr+'='+fstring(rmax,'(f3.0)')+' '
label=label+'dx='+fstring(dx,'(f5.3)')+' '
if KeyWord_Set(dispgrad) then label=label+sdispgrad
label=strmid(label,0,32)
!rec.observer=byte(label)
;
; deal with the frequency axis
;
!rec.rest_freq=1420.4058d+6
!rec.sky_freq =1420.4058d+6
!rec.ref_ch=!rec.s_pts/2.d
df=(double(dv)/!light_c)*!rec.rest_freq
!rec.delta_x=-df
;
; This stuff to keep code from bombing with zero divides
;
!rec.tsys=1.
!rec.tcal=1.
;
; copy !rec to !b[0]
;
!b[0]=!rec
;
<file_sep>pro close_archive,help=help
;+
; NAME:
; CLOSE_ARCHIVE
;
; close_archive Closes the currently open ARCHIVE file
; =============
; Syntax: close_archive,help=help
; ===============================
;-
; V5.0 July 2007
; V7.0 3may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'close_archive' & return & endif
;
close,!archiveunit
;
return
end
<file_sep>pro srcvlon,help=help
;+
; NAME:
; SRCVLON
;
; =========================
; Syntax: srcvlon,help=help
; =========================
;
;; srcvlon Turn the source velocity flag line ON.
; --------
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'srcvlon' & return & endif
;
!srcvl=1
;
return
end
<file_sep>pro tmbsave,help=help
;+
; NAME:
; TMBSAVE
;
; =========================
; Syntax: tmbsave,help=help
; =========================
;
; tmbsave SAVES all system + local variables and user defined procedures and
; ------- functions in !save_idl_state and !save_idl_procs files, respectively
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
if keyword_set(help) then begin & get_help,'tmbsave' & return & endif
;
save, /all, filename=!save_idl_state ; system and local variables
;
save, /routines, filename=!save_idl_procs ; user defined procedures and functions
;
return
end
<file_sep># generateContCat.py - generate continuum catalog
#
# Usage:
#
# > python generateContCat.py <catalog name>
#
def generateContCat(proj='hii'):
# set the output file
outfile = 'source_catalog'
fout = open(outfile, 'w')
print " "
print "Reading data from proj :", proj
print " "
# define project and catalog lists
if proj == 'hii':
path = '/home/groups/3helium/GBT/hii/obs/'
infile = ['fluxcal.cat', 'pointing.cat', 'final_18-30_good.cat', 'final_50-65_good.cat', 'reobserve_30-50.cat', 'reobserve_30-50_continuum.cat', 'far_arm_nvss.cat', 'far_arm_2nd_tier.cat', 'cross_cal.cat', 'final_30-65.cat', 'final_18-30_fainter.cat']
elif proj == 'te':
path = '/home/groups/3helium/GBT/te/obs/'
infile = ['fluxcal.cat', 'pointing.cat', 'FC72.cat', 'S83.cat', 'R97.cat', 'R96.cat', 'EC.cat', 'OG.cat', 'FJL96.cat', 'FJL89.cat', 'QRBBW06.cat', 'glimpse.cat']
elif proj == 'he3':
path = '/home/groups/3helium/GBT/he3/obs/'
infile = ['fluxcal.cat', 'pointing.cat', 'pne.cat', 'hii.cat']
elif proj == 'cii':
path = '/home/groups/3helium/GBT/cii/obs/'
infile = ['fluxcal.cat', 'pointing.cat', 'hii.cat']
else:
print 'No valid projects. Use: hii, te, he3, cii.'
return
# write out header
fout.write("CONTINUUM SOURCE CATALOG for HII Region Survey ==============\n")
fout.write("NOVEMBER 2008\n")
fout.write(" \n")
# loop through catalog list
for icat in range(len(infile)):
lines = open(path+infile[icat], 'r').readlines()
print 'Processing catalog: ', infile[icat]
# loop through each catalog
start = 0
for i in range(len(lines)):
# get the line for each table
x = lines[i].split()
# read sources
if start == 1:
# if no elements (e.g., blank line) break out of loop
if len(x) == 0:
break
source = x[0]
# check that this is not a comment statement
if (source[0] + source[1]) != '##':
# remove comments from source names
if source[0] == '#':
source = source[1:]
ra = x[1].split(':')
dec = x[2].split(':')
# output info
fout.write("%-12s %-2s %-2s %-7s %-3s %-2s %-6s %-5s\n" % (source, ra[0], ra[1], ra[2], dec[0], dec[1], dec[2], epoch))
# check for the epoch
if x[0] == 'COORDMODE' or x[0] == 'coordmode':
epoch = x[2]
# check when to begin reading sources
if x[0] == 'HEAD' or x[0] == 'head':
start = 1
fout.close()
if __name__=="__main__":
import sys
import pdb
generateContCat(str(sys.argv[1]).strip())
<file_sep>PRO Killwin,help=help
;+
; NAME:
; KILLWIN
;
; =========================
; Syntax: killwin,help=help
; =========================
;
; killwin Kill off all the windows.
; -------
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'killwin' & return & endif
While !D.Window NE -1 DO WDelete, !D.Window
END
<file_sep>pro zlon,help=help
;+
; NAME:
; ZLON
;
; ======================
; Syntax: zlon,help=help
; ======================
;
; zlon Turn the zero line ON: !zline=1
; ----
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'zlon' & return & endif
;
!zline=1
;
return
end
<file_sep>pro setid,id,help=help
;+
; NAME:
; SETID
;
; ==================================
; Syntax: setid, 'line_id',help=help
; ==================================
;
; setid Sets line ID for a SELECT search of ONLINE/OFFLINE data.
; ----- if id value not passed, prompts for string.
; Syntax: setid,"rx1.2" <-- must pass a string "*" is wildcard
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
;
if keyword_set(help) then begin & get_help,'setid' & return & endif
;
if n_params() eq 0 then begin
print,'no quotes needed; <CR> means wildcard'
print
id=' '
read,id,prompt='Input line ID: '
endif
;
!id=strtrim(id,2)
if !id eq "" or !id eq " " then !id='*'
;
print,'Line ID for searches is: ' + !id
;
return
end
<file_sep>pro srcvl,ch,help=help
;+
; NAME:
; SRCVL
;
; ================================================
; Syntax: srcvl, sourc_velocity_position,help=help
; ================================================
;
;
; srcvl Plots vertical flag at specified source velocity
; ----- ch= position of flag. Must be in current x-axis units.
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
compile_opt idl2 ; all integers are 32bit longwords by default
@CT_IN
;
if n_params() eq 0 or keyword_set(help) then begin & get_help,'srcvl' & return & endif
;
case !clr of
1: clr=!cyan
else: clr=!d.name eq 'PS' ? !black : !white
endcase
;
get_clr,clr
;
; get data ranges
;
xmin = !x.crange[0]
xmax = !x.crange[1]
ymin = !y.crange[0]
ymax = !y.crange[1]
xrange = xmax-xmin
yrange = ymax-ymin
yincr=0.025*yrange
;
vel=!b[0].vel & cvel='Vsrc'
plots,vel,ymin
plots,vel,ymax+yincr,/continue,color=clr
; cvel=cvel+fstring(vel,'(f5.2)')
xyouts,vel,ymax+yincr+yincr/5,cvel,/data,alignment=0.5,color=clr
;
@CT_OUT
return
end
<file_sep>pro srcvloff,help=help
;+
; NAME:
; SRCVLOFF
;
; ==========================
; Syntax: srcvloff,help=help
; ==========================
;
; srcvloff Turn the source velocity flag line OFF.
; --------
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'srcvloff' & return & endif
;
!srcvl=0
;
return
end
<file_sep>pro zloff,help=help
;+
; NAME:
; ZLOFF
;
; =======================
; Syntax: zloff,help=help
; =======================
;
; zloff Turn the zero line OFF: !zline=0
; -----
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'zloff' & return & endif
;
!zline=0
;
return
end
<file_sep>pro nroff,help=help
;+
; NAME:
; NROFF
;
; =======================
; Syntax: nroff,help=help
; =======================
;
; nroff Turn flag OFF for showing BMARK regions (NREGIONS).
; ----
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'nroff' & return & endif
;
!bmark=0
;
return
end
<file_sep>pro spiderclean,help=help,no_baseline=no_baseline,cuttoff=cutoff
;+
; NAME:
; spiderclean
;
; ========================================================
; Syntax: spiderclean,help=help,/no_baseline,cutoff=cutoff
; ========================================================
;
; spiderclean procedure to
; ----------- fit nregions, baseline, and gaussian to spider scan
; data
;
; ** requires stack to be filled with (L+R) *_AVG data
; puts new ns starting at !lastns
;
; KEYWORDS:
; HELP - get syntax help
; NO_BASELINE - don't fit baseline
; CUTOFF - cutoff range (default [0,15,575,588])
;
; MODIFICATION HISTORY:
;
; V1.0 TVW 18june2012
; 02july2012 - shows image and contours
; dsb 15oct2012 - remove datapath from cmapvgps (i.e., use default)
; modify to use dsb version of bb
; dsb 19nov2012 - change edge cuttoff range
; dsb 20nov2012 - add keyword for cutoff range
; add setx before baseline fit
; allow user to redo gg
;-
on_error,2 ; on error return to top level
compile_opt idl2 ; compile with long integers
;
if keyword_set(help) then begin
get_help,'spiderclean'
return
endif
if (n_elements(cutoff) eq 0) then cutoff=[0,15,575,588]
;
acount=!acount
stack=!astack
;
;
for i=0,acount-1 do begin
getns,stack[i]
;
cmapvgps,!b[0].l_gal,!b[0].b_gal,size=80.,/peak,/spider,length=80.
;
type=string(!b[0].scan_type)
;
cans='n'
while cans eq 'n' do begin
getns,stack[i]
chan
; cut off edges
zero,cutoff[0],cutoff[1],/no_ask
zero,cutoff[2],cutoff[3],/no_ask
case type of
"RA_AVG" : raxx
"CC_AVG" : raxx
"DEC_AVG" : decx
"CW_AVG" : decx
endcase
print, 'Set the x-axis with the cursor'
freexy & xx & setx
xx
;
ymax=max(!b[0].data[0:588])
;print,"max in data is ",ymax
ymax+=0.1*ymax
;print,"Ymax is ",ymax
ymin=min(!b[0].data[0:588])
ymin-=0.1*ymax
;print,"Ymin is ",ymin
sety,ymin,ymax
;setx,16,max(!xx)-16
nroff
xx
if ~keyword_set(no_baseline) then begin
;read,num,prompt="How many regions?"
;nrset,num
read,num,prompt="How many baseline parameters?"
bb,num
nron
chan
; cut off edges
zero,cutoff[0],cutoff[1],/no_ask
zero,cutoff[2],cutoff[3],/no_ask
case type of
"RA_AVG" : raxx
"CC_AVG" : raxx
"DEC_AVG" : decx
"CW_AVG" : decx
endcase
freexy
xx
print,'Ok? (y/n/q)'
pause,cans,ians
!b[0].scan_type=bytarr(32)
!b[0].scan_type=byte(strmid(type,0,3)+" B G")
if cans eq 'q' then return
endif else begin
cans='y'
!b[0].scan_type=bytarr(32)
!b[0].scan_type=byte(strmid(type,0,3)+" G")
nrset,1,[0,0]
endelse
endwhile
;
nron
gans='n'
while gans eq 'n' do begin
xx
gg,1
print,'Ok? (y/n/q)'
xx & g & read,gans
if gans eq 'q' then return
endwhile
;
nsoff
history
putns,!lastns+1
nson
;
++!lastns
endfor
;
return
end
<file_sep>pro tp,help=help
;+
; NAME:
; TP
;
; ====================
; Syntax: tp,help=help
; ====================
;
; tp Toggle !tp on to select total power mode.
; --
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
if keyword_set(help) then begin & get_help,'tp' & return & endif
;
!tp=1
;
return
end
<file_sep>pro xx,pause=pause,charsize=charsize,help=help
;+
; NAME:
; XX
;
; ==================================================
; SYNTAX: xx,pause=pause,charsize=charsize,help=help
; ==================================================
;
; xx Renaming of SHOW procedure
; --
;
; KEYWORDS:
; charsize - charsize for plotting stuff
; default is 2.0
;
; pause - if set pause after plot
;
;-
; V5.0 July 2007
; 12aug08 tmb added /pause feature
; tvw 30jul2012 - added charsize keyword
;
; V7.0 03may2013 tvw - added /help, !debug
;
;-
if keyword_set(help) then begin & get_help,'xx' & return & endif
;
erase
show,charsize=charsize
;
if Keyword_Set(pause) then pause
;
return
end
<file_sep>pro hline,val,color=color,no_value=no_value,help=help
;+
; NAME:
; HLINE
;
; ======================================================================
; Syntax: hline, y_value_to_draw,color=color,no_value=no_value,help=help
; ======================================================================
;
; hline Draw horizontal line at specific y-axis value 'y_value_to_draw'
; ----- no_value flag supresses plotting the value
;-
; V5.0 July 2007
;
; V6.1 March 2010 tmb seamless PS handling and value flag for plot
;
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
compile_opt idl2 ; all integers are 32bit longwords by default
@CT_IN
;
if n_params() eq 0 or keyword_set(help) then begin & get_help,'hline' & return & endif
;
if ~Keyword_Set(color) then color=!magenta
case !clr of
1: clr=color
else: clr=!d.name eq 'PS' ? !black : !white
endcase
;get_clr,clr
;
; get data ranges
;
xmin = !x.crange[0] & xmax = !x.crange[1]
ymin = !y.crange[0] & ymax = !y.crange[1]
xrange = xmax-xmin & yrange = ymax-ymin
xincr=0.02*xrange
;
plots,xmin,val
;
case Keyword_Set(no_value) of
0:begin
plots,xmax+xincr,val,/continue,color=clr
xyouts,xmax+xincr,val,fstring(val,'(f6.2)'),/data,color=clr
end
else:plots,xmax,val,/continue,color=clr
endcase
;
@CT_OUT
return
end
<file_sep>pro lastxy,help=help
;+
; NAME:
; LASTXY
;
; ========================
; Syntax: lastxy,help=help
; ========================
;
; lastxy Restore x and y-axis ranges to previous values.
; ------
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
if keyword_set(help) then begin & get_help,'lastxy' & return & endif
;
!x.range=!last_x
!y.range=!last_y
;
return
end
<file_sep>;============================================================
; BATCH SCRIPT TO CONFIGURE TMBIDL CONTINUUM DATA FOR COOKING
;============================================================
;
debugon ; <== just in case something goes wrong
cont ; <== make sure you are in continuum mode
offline
list,0,9 ; <== show a full Peak/Focus cycle of data
cget,5
elxx ; <== this is an elevation scan
freex
nrset,2,[-342.,-96.,57.,347.]
bbb,/no
mk
scaley
xx
zline
flag,0.
<file_sep>pro lasty,help=help
;+
; NAME:
; LASTY
;
; =======================
; Syntax: lasty,help=help
; =======================
;
; lasty Restore y-axis range to value set at last SETY.
; -----
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
if keyword_set(help) then begin & get_help,'lasty' & return & endif
;
!y.range=!last_y
;
return
end
<file_sep>;================================================================
; BATCH SCRIPT TO CONFIGURE TMBIDL SPECTRAL LINE DATA FOR COOKING
;================================================================
;
debugon ; <== just in case something goes wrong
line ; <== make sure you are in spectral line mode
online
setsrc,'W3'
settype,'ON'
setid,'rx2'
clrstk
select
tellstk
cat
avgstk
dcsub
nrset,4,[1510.,1815.,1962.,2096.,2286.,2322.,2456.,2986.]
nron
setx,1800,2500
mk
bbb,5,/no
scaley
xx
zline
rrlflag
<file_sep>pro disp,n,m,help=help
;+
; NAME:
; DISP
;
; disp DISPlay: SHOW buffer n and RESHOW buffer m
; ---- Default is SHOW !b[0] and RESHOW !b[1]
;
; ======================================================
; Syntax: disp, buffer_#_SHOW, buffer_#_RESHOW,help=help
; ======================================================
;
; V5.0 July 2007
; V7.0 3may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
if keyword_set(help) then begin & get_help,'disp' & return & endif
;
if n_params() eq 0 then begin & n=0 & m=1 & endif &
;
copy,n,0
SHOW
copy,m,0
RESHOW
copy,9,0 ; put last SHOW buffer 9 into buffer 0
;
return
end
<file_sep>pro getoff,rec,help=help
;+
; NAME:
; GETOFF
;
; =======================================
; Syntax: getoff, rec_#,help=help
; =======================================
;
; getoff Copy rec_# into buffer !b[0] and !b[6]
; ------ This is assumed to be an OFF scan in TP mode.
;-
; V5.0 July 2007
; V7.0 3may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'getoff' & return & endif
;
get,rec
copy,0,6 ; copy OFFinto buffer 6
!tsys = !b[0].tsys
!time = !b[0].tintg
;
return
end
<file_sep>pro lastx,help=help
;+
; NAME:
; LASTX
;
; =======================
; Syntax: lastx,help=help
; =======================
;
; lastx Restore x-axis range to value set at last SETX.
; -----
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
if keyword_set(help) then begin & get_help,'lastx' & return & endif
;
!x.range=!last_x
;
return
end
<file_sep>pro tmbrestore,help=help
;+
; NAME:
; TMBRESTORE
;
; ============================
; Syntax: tmbrestore,help=help
; ============================
;
; tmbrestore RESTORES all system + local variables and
; ---------- user defined procedures + functions from
; !save_idl_state and !save_idl_procs files,
; respectively
;-
; V7.0 03may2013 tvw - added /help, !debug
;-
;
on_error,!debug ? 0 : 2
if keyword_set(help) then begin & get_help,'tmbrestore' & return & endif
;
restore, filename=!save_idl_state ; system and local variables
;
restore, filename=!save_idl_procs ; user defined procedures and functions
;
return
end
<file_sep>pro ggg,help=help
;+
; NAME:
; GGG
;
; =======================================
; Syntax: ggg,help=help
; =======================================
; ggg 'G' procedure with explicit i/o i.e. forces !flag on
; --- MUST have baseline removed. Needs initial guesses for the fit.
; Returns the fits no matter what state !flag is in.
;-
; V5.0 July 2007
; V7.0 3may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'ggg' & return & endif
;
flag=!flag
flagon
;
g
;
!flag=flag
;
return
end
<file_sep>pro nron,help=help
;+
; NAME:
; NRON
;
; ======================
; Syntax: nron,help=help
; ======================
;
; nron Turn flag ON for showing BMARK regions (NREGIONS)
; ----
;-
; V5.0 July 2007
; V7.0 03may2013 tvw - added /help, !debug
;-
if keyword_set(help) then begin & get_help,'nron' & return & endif
;
!bmark=1
;
return
end
| 7a7a0d05906de343ada3aa23a7223bb8d38c2c36 | [
"Python",
"INI"
] | 27 | INI | tvwenger/tmbidl | 7a2e53f103877bb8f0e6f2f6211c660395ed85fb | bed3146857b3d27d25c132319b381099b27b46ae |
refs/heads/master | <file_sep>require_relative 'QuestionsDatabase'
class Replies
attr_accessor :id, :subject_in_question, :parent_reply, :author_id, :body
def self.all
data = QuestionsDBConnection.instance.execute("SELECT * FROM replies")
data.map { |datum| Replies.new(datum) }
end
def self.find_by_id(id)
reply = QuestionsDBConnection.instance.execute(<<-SQL, id)
SELECT
*
FROM
replies
WHERE
id = ?
SQL
return nil if reply.empty?
Replies.new(reply.first)
end
def self.find_by_user_id(user_id) #returns replies to user_id regardless of questions
reply = QuestionsDBConnection.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
replies
WHERE
author_id = ?
SQL
return nil if reply.empty?
Replies.new(reply.first)
end
def self.find_by_question_id(question_id)
reply = QuestionsDBConnection.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
replies
WHERE
subject_in_question = ?
SQL
return nil if reply.empty?
reply.map {|hash| Replies.new(hash)}
end
def initialize(options)
@id = options['id']
@subject_in_question = options['subject_in_question']
@parent_reply = options['parent_reply']
@author_id = options['author_id']
@body = options['body']
end
def author #return array of authors
author = QuestionsDBConnection.instance.execute(<<-SQL, author_id)
SELECT
*
FROM
users
WHERE
id = ?
SQL
return nil if author.empty?
author.map {|hash| Users.new(hash)}
end
def question
question = QuestionsDBConnection.instance.execute(<<-SQL, subject_in_question)
SELECT
*
FROM
questions
WHERE
id = ?
SQL
return nil if question.empty?
question.map {|hash| Questions.new(hash)}
end
def parent_reply # fix this
return nil if self.parent_reply.nil?
parent = QuestionsDBConnection.instance.execute(<<-SQL, parent_reply)
SELECT
*
FROM
replies
WHERE
id = ?
SQL
return nil if parent.empty?
parent.map {|hash| Replies.new(hash)}
end
def child_replies
child = QuestionsDBConnection.instance.execute(<<-SQL, id)
SELECT
*
FROM
replies
WHERE
parent_reply = ?
SQL
return nil if child.empty?
child.map {|hash| Replies.new(hash)}
end
end
<file_sep>require_relative 'QuestionsDatabase'
class QuestionsLikes
attr_accessor :id, :question_liked, :liked_by_user
def self.all
data = QuestionsDBConnection.instance.execute("SELECT * FROM questions_likes")
data.map { |datum| QuestionsLikes.new(datum) }
end
def self.find_by_id(id)
question_like = QuestionsDBConnection.instance.execute(<<-SQL, id)
SELECT
*
FROM
questions_likes
WHERE
id = ?
SQL
return nil if question_like.empty?
QuestionsLikes.new(question_like.first)
end
def initialize(options)
@id = options['id']
@question_liked = options['question_liked']
@liked_by_user = options['liked_by_user']
end
end
<file_sep>require_relative 'QuestionsDatabase'
class Users
attr_accessor :id, :fname, :lname
def self.all
data = QuestionsDBConnection.instance.execute("SELECT * FROM users")
data.map { |datum| Users.new(datum) }
end
def self.find_by_id(id)
user = QuestionsDBConnection.instance.execute(<<-SQL, id)
SELECT
*
FROM
users
WHERE
id = ?
SQL
#returns an empty array if the input ID isn't included in the database
return nil if user.empty?
# user is an array of one hash with user information. must unzip the array to access the hash
Users.new(user.first)
end
def self.find_by_name(fname, lname)
user = QuestionsDBConnection.instance.execute(<<-SQL, fname, lname)
SELECT
*
FROM
users
WHERE
fname = ? AND lname = ?
SQL
#returns an empty array if the input ID isn't included in the database
return nil if user.empty?
# user is an array of one hash with user information. must unzip the array to access the hash
Users.new(user.first)
end
def initialize(options)
@id = options['id']
@fname = options['fname']
@lname = options['lname']
end
def authored_questions
Questions.find_by_author_id(self.id)
end
def author_replies
Replies.find_by_user_id(self.id)
end
end
<file_sep>require_relative 'QuestionsDatabase'
class Questions
attr_accessor :id, :title, :body, :author_id
def self.all
data = QuestionsDBConnection.instance.execute("SELECT * FROM questions")
data.map { |datum| Questions.new(datum) }
end
def self.find_by_id(id)
question = QuestionsDBConnection.instance.execute(<<-SQL, id)
SELECT
*
FROM
questions
WHERE
id = ?
SQL
#returns an empty array if the input ID isn't included in the database
return nil if question.empty?
# user is an array of one hash with user information. must unzip the array to access the hash
Questions.new(question.first)
end
def self.find_by_author_id(author_id)
question = QuestionsDBConnection.instance.execute(<<-SQL, author_id)
SELECT
*
FROM
questions
WHERE
author_id = ?
SQL
return nil if question.empty?
Questions.new(question.first)
end
def initialize(options)
@id = options['id']
@title = options['title']
@body = options['body']
@author_id = options['author_id']
end
def author
author = QuestionsDBConnection.instance.execute(<<-SQL, author_id)
SELECT
*
FROM
users
WHERE
id = ?
SQL
author.map {|user_hash| Users.new(user_hash)}
end
def replies
Replies.find_by_question_id(id)
end
end
<file_sep>DROP TABLE IF EXISTS users;
CREATE TABLE users (
id INTEGER PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL
);
-- ==================================
DROP TABLE IF EXISTS questions;
CREATE TABLE questions (
id INTEGER PRIMARY KEY,
title VARCHAR(255) ,
body TEXT,
author_id VARCHAR(255),
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- ==================================
DROP TABLE IF EXISTS question_follows;
CREATE TABLE question_follows (
id INTEGER PRIMARY KEY,
user_id INTEGER,
question_id INTEGER,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (question_id) REFERENCES questions(id)
);
-- ==================================
DROP TABLE IF EXISTS replies;
CREATE TABLE replies (
id INTEGER PRIMARY KEY,
subject_in_question INTEGER NOT NULL,
parent_reply INTEGER,
author_id INTEGER NOT NULL,
body TEXT NOT NULL,
FOREIGN KEY (author_id) REFERENCES users(id),
FOREIGN KEY (subject_in_question) REFERENCES questions(id),
FOREIGN KEY (parent_reply) REFERENCES replies(id)
);
-- ==================================
DROP TABLE IF EXISTS questions_likes;
CREATE TABLE questions_likes (
id INTEGER PRIMARY KEY,
question_liked INTEGER,
liked_by_user INTEGER,
FOREIGN KEY (question_liked) REFERENCES questions(id),
FOREIGN KEY (liked_by_user) REFERENCES users(id)
);
-- ==================================
INSERT INTO
users(fname, lname)
VALUES
('Cherry', 'Lam'),
('Janet', 'Lee'),
('Jane', 'Doe'),
('John', 'Doe');
INSERT INTO
questions(title, body, author_id)
VALUES
('App Academy', 'How to succeed?', (SELECT id FROM users WHERE fname = 'Cherry' AND lname = 'Lam')),
('Hack Reactor', 'What is your name?', (SELECT id FROM users WHERE fname = 'Janet' AND lname = 'Lee'));
INSERT INTO
question_follows(user_id, question_id)
VALUES
((SELECT id FROM users WHERE fname = 'Jane'), (SELECT id FROM questions WHERE title = 'App Academy')),
((SELECT id FROM users WHERE fname = 'John'), (SELECT id FROM questions WHERE title = 'Hack Reactor'));
INSERT INTO
-- #replies, questions_like
replies(subject_in_question, parent_reply, author_id, body)
VALUES
((SELECT id FROM questions WHERE id = 1), NULL, (SELECT id FROM users WHERE fname = 'Jane'),'Sleep alot!'),
((SELECT id FROM questions WHERE id = 2), NULL, (SELECT id FROM users WHERE fname = 'John'),'DJ jazzy'),
((SELECT id FROM questions WHERE id = 1), 1, (SELECT id FROM users WHERE fname = 'Jane'),'Study');
-- (SELECT id FROM replies WHERE body = 'Sleep alot!')
INSERT INTO
questions_likes(question_liked, liked_by_user)
VALUES
((SELECT id FROM questions WHERE body = 'How to succeed?'), (SELECT id FROM users WHERE fname = 'Janet' AND lname = 'Lee')),
((SELECT id FROM questions WHERE body = 'What is your name?'), (SELECT id FROM users WHERE fname = 'Cherry' AND lname = 'Lam'));
| 1db4327b278f52796eaec1b67ebfeafbb4c948fa | [
"SQL",
"Ruby"
] | 5 | Ruby | greenteamuimui/users-followers-sql | a01cff9a2df91a8501eec462d76048091429979a | 9b458d6ec17d198bb0aaeaeb28db50c612ba77e3 |
refs/heads/master | <file_sep>library(tidyverse); library(rvest)
library(png)
library(gganimate)
#Get Sea Ice data from NASA ----
url <- "https://climate.nasa.gov/system/internal_resources/details/original/1270_minimum_extents_and_area_north_SBA_reg_20171001_2_.txt"
nasa.seaice <- read_table2(url,skip = 3)
nasa.seaice1 <- nasa.seaice %>%
select(Year = YR, Ice_Extent = ICE) %>%
filter(Year >= 1980) %>%
mutate(Ice_Extent_Perc = Ice_Extent / first(Ice_Extent))
#Polar Bear Image ----
pb.pic.raw <- readPNG("data/PolarBear.png")
pb.pic <- pb.pic.raw[,,4] %>%
as.data.frame() %>%
mutate(y = n()-row_number()) %>%
gather(x, value, 1:(ncol(.)-1)) %>%
mutate(x = as.numeric(str_remove_all(x, "V"))) %>%
filter(value > 0) %>%
#Rescale to 50% of coords
group_by(x = x %/% 4, y = y %/% 4) %>%
summarize(value = max(value)) %>%
ungroup() %>%
mutate(cluster = kmeans(.[, c(1:2)], 100)$cluster)
pb.pic %>% ggplot(aes(x=x,y=y)) +
geom_raster() +
coord_fixed()
#PLot it -----
pb.slices <- sample(1:100, 100, replace = FALSE)
pb.data <- nasa.seaice1 %>%
mutate(plot = map(Ice_Extent_Perc, function(comp){
# keep_k <- pb.slices[1:round(comp*100)]
keep_k <- 1:round(comp*100)
return(pb.pic %>% filter(cluster %in% keep_k))
})) %>%
unnest(plot)
trex.labels <- trex.specimens %>%
mutate(label_p = paste0(round(comp), "%"),
label_d = paste0("Discovered: ", Discovered, "\n",
Location))
pb.data %>%
filter(Year %in% seq(1980, 2017, by = 5)) %>%
ggplot(aes(x=x, y=y, fill = Ice_Extent_Perc)) +
geom_raster() +
scale_fill_gradient(low = "#ff4040", high = "#00436b") +
# scale_fill_manual(values = c("#2dd49c", "#ff4040", "#5384ff", "#ff25ab", "#ff6141", "#ff9e53")) +
coord_fixed() +
# geom_text(data = trex.labels, aes(label = label_p),
# x = 30, y = 30, size = 5,
# color = "#00436b", fontface = "bold") +
# geom_text(data = trex.labels, aes(label = label_d),
# x = 400, y = 40, size = 3) +
facet_wrap(~Year, ncol = 4) +
labs(title = "Arctic sea ice minimum by year",
subtitle = "% of 1980 levels",
caption = paste0("Data: https://climate.nasa.gov/vital-signs/arctic-sea-ice/\n",
"Image: phylopic.org\n",
"<NAME> .com")) +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
strip.background = element_rect(fill = "#00436b"),
strip.text = element_text(color = "white", face = "bold"),
plot.background = element_rect(fill = "#fcedcc"),
plot.title = element_text(size = 20, face = "bold"),
plot.subtitle = element_text(size = 16),
panel.background = element_rect(fill = "#fcedcc"),
legend.position = "bottom"
)
pb.data %>%
filter(Year %in% seq(1980, 2017, by = 5)) %>%
ggplot(aes(x=x, y=y)) +
geom_raster() +
# scale_fill_gradient(low = "#ff4040", high = "#00436b") +
coord_fixed() +
# geom_text(label = '{frame_state}',
# x = 30, y = 30, size = 5,
# color = "#00436b", fontface = "bold") +
# geom_text(data = trex.labels, aes(label = label_d),
# x = 400, y = 40, size = 3) +
# facet_wrap(~Year, ncol = 8) +
labs(title = "Arctic sea ice minimum by year",
subtitle = "% of 1980 levels",
caption = paste0("Data: https://climate.nasa.gov/vital-signs/arctic-sea-ice/\n",
"Image: phylopic.org\n",
"<NAME>e .com")) +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
strip.background = element_rect(fill = "#00436b"),
strip.text = element_text(color = "white", face = "bold"),
plot.background = element_rect(fill = "#fcedcc"),
plot.title = element_text(size = 20, face = "bold"),
plot.subtitle = element_text(size = 16),
panel.background = element_rect(fill = "#fcedcc"),
legend.position = "bottom"
) +
transition_states(
Year, 0.1, 3
) <file_sep>library(tidyverse)
library(rvest)
nhl_cols <- read_csv("data/NHLTeamColors.csv")
url <- "https://www.hockey-reference.com/leagues/NHL_2019_skaters.html"
nhl_stats <- read_html(url) %>%
html_nodes(xpath = '//*[@id="stats"]') %>%
html_table()
nhl_stats_df <- nhl_stats[[1]]
names(nhl_stats_df) <- trimws(paste(names(nhl_stats_df), as.character(nhl_stats_df[1, ])))
nhl_stats_df <- nhl_stats_df[-1, ]
names(nhl_stats_df)
pbx <- nhl_stats_df %>%
filter(!(Tm %in% c("TOT", "Tm"))) %>%
left_join(nhl_cols %>%
select(Tm = Team, Conference, Division, Col1, Col2) %>%
group_by(Conference) %>%
mutate(team_index = row_number()) %>%
ungroup()) %>%
mutate(Tm = factor(Tm)) %>%
select(Player, Tm, GP = `GP`, Points = `Scoring PTS`, PIM = `PIM`, TOI = `Ice Time TOI`,
Conference, Division, Col1, Col2, team_index) %>%
mutate_at(vars(GP, Points, PIM, TOI), as.numeric) %>%
mutate(PIM_TOI = PIM / TOI)
#Draw my own!
pbx_plot <- pbx %>%
group_by(Tm, Division, Col1, Col2) %>%
nest() %>%
mutate(PIM_qt = map(data, ~quantile(.x$PIM, probs = c(0, 0.1, 0.25, .5, 0.75, 0.9, 1)))) %>%
unnest(PIM_qt) %>%
group_by(Tm) %>%
mutate(Qnt = paste0("Q", row_number())) %>%
ungroup() %>%
spread(Qnt, PIM_qt) %>%
group_by(Division) %>%
mutate( x_base = row_number()) %>%
ungroup() %>%
#Num of 0 minute PIM
left_join(
pbx %>%
group_by(Tm) %>%
summarize(PIM_0 = sum(PIM == 0),
PIM_2sd = sum(PIM >= (mean(PIM) + 1.5*sd(PIM))))
) %>%
mutate(Division = fct_relevel(Division, "Metropolitan", "Atlantic", "Pacific", "Central"))
pbx_legend <- pbx_plot %>%
filter(Tm == "WPG") %>%
gather(metric, yy, starts_with("Q")) %>%
mutate(
label = case_when(
metric == "Q4" ~ "Median PIM",
metric == "Q3" ~ "40%",
metric == "Q5" ~ "60%",
metric == "Q2" ~ "25% PIM",
metric == "Q6" ~ "75% PIM"
),
col = case_when(
metric == "Q4" ~ "#FF0000",
metric %in% c("Q3", "Q5") ~ "#0000FF",
TRUE ~ "black"
),
x_jit = case_when(
metric == "Q4" ~ -1/3,
metric %in% c("Q3", "Q5") ~ -1/3,
TRUE ~ 1/4
),
x_jit = x_jit + x_base
) %>%
drop_na(label)
pbx_plot %>%
ggplot(aes(x= x_base, y = Q4, group = Tm)) +
#Rink
geom_rect(aes(xmin = x_base-1/3, xmax = x_base+1/3, ymin = Q2, ymax = Q6),
fill = "white", color = "black") +
#Median
geom_segment(aes(x = x_base-1/3, xend = x_base+1/3, y = Q4, yend = Q4),
size = 1.5, color = "#FF0000") +
#25/75
geom_segment(aes(x = x_base-1/3, xend = x_base+1/3, y = Q3, yend = Q3),
size = 1.2, color = "#0000FF") +
geom_segment(aes(x = x_base-1/3, xend = x_base+1/3, y = Q5, yend = Q5),
size = 1.2, color = "#0000FF") +
#Logo
geom_point(aes(color = Col2, size = PIM_2sd*2)) +
geom_point(aes(color = Col1, size = PIM_2sd)) +
scale_size_continuous(range = c(3, 8), guide = FALSE) +
# geom_point(aes(color = Col2), size = 10) +
# geom_point(aes(color = Col1), size = 7) +
scale_color_identity() +
#Team name
geom_label(aes(x = x_base, y = Q6, label = Tm, fill = Col2), color = "white",
hjust = 0.5, vjust = 0.5, nudge_y = 8, fontface = "bold", size = 3) +
scale_fill_identity() +
#Fake legend
geom_segment(
data = pbx_legend,
aes(x = x_base + 1/3 + 0.1, xend = x_jit + .9, y = yy, yend = yy, color = col),
size = 1
) +
geom_label(
data = pbx_legend,
aes(x = x_jit+1, y = yy, label = label, color = col),
hjust = 0,size = 3
) +
#Rest of plot
coord_cartesian(ylim = c(-5, max(pbx_plot$Q6+10)), xlim = c(2/3, 8.9)) +
facet_grid(Division ~ ., scales = "free_x") +
labs(
title = "Penalty Boxplots - NHL player time in penalty box",
subtitle = paste("Player penalty minutes by team, 2018-2019 season through", format.Date(Sys.Date(), format = "%B %d, %Y")),
caption = "Size of middle circle proportional to # of players with PIM >1.5 st dev from mean.
Data: https://www.hockey-reference.com
@ <NAME> .com",
x = NULL,
y = "Penalty Minutes"
) +
theme_minimal()+
theme(
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.text.y = element_text(color = "black"),
strip.background = element_rect(fill = "#00436b"),
strip.text = element_text(color = "white", face = "bold"),
plot.background = element_rect(fill = "#fcedcc"),
panel.grid.major.y = element_line(color = "#ebdcbb"),
panel.grid.minor.y = element_blank(),
panel.grid.major.x = element_blank()
)
ggsave("Output/PenaltyBoxPlots.png", device = "png",
width = 6.6, height = 5.6, units = "in")
<file_sep>####
# Random turkey facts
####
library(tidyverse); library(rvest);
library(png)
#Text wrapping function ---
wrapper <- function(x, ...) {paste(strwrap(x, ...), collapse = "\n")}
#Turkey facts! ----
url <- "http://extension.illinois.edu/turkey/turkey_facts.cfm"
trk.raw <- read_html(url) %>%
html_nodes("li") %>%
html_text() %>%
str_remove_all("\\t|\\n|\\r")
trk.fact <- trk.raw[nchar(trk.raw) > 15][7:82]
#Turkey PNG ----
process_png <- function(pic, scale=2){
dat <- pic[,,4] %>%
as.data.frame() %>%
mutate(y = n()-row_number()) %>%
gather(x, value, 1:(ncol(.)-1)) %>%
mutate(x = as.numeric(str_remove_all(x, "V"))) %>%
filter(value > 0) %>%
#Rescale to 50% of coords
group_by(x = x %/% scale, y = y %/% scale) %>%
summarize(value = max(value)) %>%
ungroup() %>%
#Make 100 chunks
mutate(cluster = kmeans(.[, c(1:2)], 100)$cluster) %>%
arrange(x, desc(y))
dat.cluster.i <- unique(dat$cluster)
dat2 <- dat %>%
rowwise() %>%
mutate(cluster_i = which(cluster == dat.cluster.i)) %>%
ungroup()
return(dat2)
}
process_png_y <- function(pic, feet=6){
dat <- pic[,,4] %>%
as.data.frame() %>%
mutate(y = n()-row_number()) %>%
gather(x, value, 1:(ncol(.)-1)) %>%
mutate(x = as.numeric(str_remove_all(x, "V"))) %>%
filter(value > 0)
xscale <- (max(dat$y)/max(dat$x))^(-1)
dat2 <- dat %>%
#Rescale to 1ft == 50px
mutate(ys = floor(y/max(y)*feet*50), xs = floor(x/max(x)*feet*50*xscale)) %>%
group_by(x = xs, y = ys) %>%
summarize(value = max(value)) %>%
ungroup() %>%
#Make 100 chunks
mutate(cluster = kmeans(.[, c(1:2)], 100)$cluster) %>%
arrange(x, desc(y))
dat.cluster.i <- unique(dat2$cluster)
dat3 <- dat2 %>%
rowwise() %>%
mutate(cluster_i = which(cluster == dat.cluster.i)) %>%
ungroup()
return(dat2)
}
trk1.pic <- readPNG("data/Meleagris.png") %>% process_png()
trk2.pic <- readPNG("data/Turkey2.png") %>% process_png()
# Universals ----
chart_footer <- paste0("Turkey Triva: http://extension.illinois.edu/turkey/turkey_facts.cfm\n",
"@ Ryan Timpe .com")
chart_footer_bonus <- paste0("Turkey Triva
@ Ryan Timpe .com")
#Colors
trk.col.orange <- c("#ff6141")
trk.col.red <- c("#8B0000", "#ff4040")
trk.col.gold <- c("#D4AF37", "#CFB53B", "#C5B358")
trk.col.blue <- c("#00436b")
trk.col.ltblue <- c("#5384ff")
trk.col.bkgrnd <- c("#fcedcc")
trk.colors <- c(trk.col.orange, trk.col.blue, trk.col.gold[1], trk.col.red[1])
trk.colors2 <- c(trk.col.orange, trk.col.blue, trk.col.gold[1], trk.col.red[1], "#5384ff", "#ff25ab")
#Chart theme
trk_chart_theme <- theme(
panel.grid = element_blank(),
strip.background = element_rect(fill = "#00436b"),
strip.text = element_text(color = "white", face = "bold"),
plot.background = element_rect(fill = "#fcedcc"),
plot.title = element_text(size = 14, face = "bold"),
plot.subtitle = element_text(size = 10),
plot.caption = element_text(size = 8),
panel.background = element_rect(fill = "#fcedcc"),
legend.position = "bottom"
)
NULL #Just so RStudio stops opening plot 14
# Fact 14 Whole vs product ----
fact.index <- 14
fact <- trk.fact[fact.index]
"Turkey hens are usually sold as whole birds.
Toms are processed into turkey sausage, turkey franks, tenderloins, cutlets and deli meats."
f14 <- tibble::tribble(
~Turkey, ~Channel, ~Amount,
"Hens (female)", "Whole bird", 100,
"Toms (male)", "Sausage", 20,
"Toms (male)", "Franks", 20,
"Toms (male)", "Tenderloins", 20,
"Toms (male)", "Cutlets", 20,
"Toms (male)", "Deli meat", 20
) %>%
uncount(Amount) %>%
group_by(Turkey) %>%
mutate(cluster_i = row_number()) %>%
ungroup() %>%
right_join(trk1.pic %>% mutate(Turkey = "Hens (female)") %>%
bind_rows(trk1.pic %>% mutate(Turkey = "Toms (male)")))
f14 %>%
ggplot(aes(x=x, y=y, fill = Channel)) +
geom_raster() +
scale_fill_manual(name = "Product", values = trk.colors2) +
coord_fixed() +
facet_wrap(.~Turkey) +
geom_text(data = tibble(Turkey = c("Toms (male)","Hens (female)"),
symb = c("\u2642", "\u2640"),
Channel = NA),
aes(label = symb),
x = 180, y = 200, size = 15, fontface = "bold",
color = trk.col.blue) +
labs(title = "U.S. Turkey consumption, by final product",
subtitle = wrapper(fact, 90),
caption = chart_footer) +
guides(fill = guide_legend(nrow=2))+
theme_minimal() +
trk_chart_theme +
theme(
axis.text = element_blank(),
axis.title = element_blank()
)
ggsave("Output/Turkey/1_ConsumptionBySex.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact 14a NGrams ----
library(jsonlite)
#Data manuallly copied out of Google NGram source
#https://books.google.com/ngrams/graph?content=turkey+burger%2Cturkey+sausage%2Cturkey+tenderloin%2Cturkey+cutlet%2Cturkey+leg&year_start=1960&year_end=2008&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cturkey%20burger%3B%2Cc0%3B.t1%3B%2Cturkey%20sausage%3B%2Cc0%3B.t1%3B%2Cturkey%20tenderloin%3B%2Cc0%3B.t1%3B%2Cturkey%20cutlet%3B%2Cc0%3B.t1%3B%2Cturkey%20leg%3B%2Cc0
f14a <- read_json("data/Turkey/ngrams.json", simplifyVector = TRUE) %>%
unnest(timeseries) %>%
rename(value = timeseries) %>%
group_by(ngram) %>%
mutate(Year = row_number() + 1959) %>%
mutate(norm = value / value[which(Year == 1980)]* 100) %>%
ungroup() %>%
filter(Year >= 1980)
f14a %>%
ggplot(aes(x=as.factor(Year), y=value, group = ngram)) +
geom_line(aes(color = ngram), size = 2) +
scale_color_manual(values = trk.colors2, name = "Ngram") +
labs(title = "Turkey product popularity, 1980-2008, Google Ngrams",
subtitle = "Turkey sausuge popularity peaked in 1996; turkey burgers are still on the up.",
caption = paste0("Data: https://books.google.com/ngrams/\n", chart_footer_bonus),
y = "Percent usage") +
guides(color = guide_legend(nrow=2))+
theme_minimal() +
trk_chart_theme +
theme(
axis.text.y = element_text(size = 12, face = 'bold', color = "black"),
axis.title.y = element_text(size = 12, face = 'bold', color = "black"),
axis.text.x = element_text(size = 12, face = 'bold', color = "black",
angle = 90, hjust = 1),
axis.title.x = element_blank(),
axis.line.x = element_line(color = "black")
)
ggsave("Output/Turkey/1a_ConsumptionByTime.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact 15 Channel ----
fact.index <- 15
fact <- trk.fact[fact.index]
"In 2011, 47.4% of turkeys were sold to grocery stores and other retail outlets,
30% sold in commodity outlets, 15.5% sold to foodservice outlets and 6.2% were exported."
f15 <- tibble::tribble(
~Channel, ~Amount,
"Grocery Stores & Retail", 48,
"Commodity outlets", 30,
"Foodservice outlets", 16,
"Exported", 6
) %>%
uncount(Amount) %>%
mutate(cluster = row_number()) %>%
right_join(trk2.pic)
f15 %>%
ggplot(aes(x=x/2, y=y/2, fill = Channel)) +
geom_raster() +
scale_fill_manual(values = trk.colors) +
coord_fixed() +
# geom_text(aes(label = paste0("Fact #", fact.index)),
# x = 220, y = 20, size = 5, color = trk.col.blue) +
labs(title = "U.S. Turkey production, by final destination",
subtitle = wrapper(fact, 70),
caption = chart_footer) +
guides(fill = guide_legend(nrow=2))+
theme_minimal() +
trk_chart_theme +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
plot.title = element_text(size = 14, face="bold"),
plot.subtitle = element_text(hjust = 0),
legend.text = element_text(size=10),
legend.title = element_text(size=10),
plot.margin = margin(t = 2, r = 60, b = 2, l = 60, unit = "pt")
)
ggsave("Output/Turkey/2_ProductionByDestination.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact 19 ----
fact.index <- 19
fact <- trk.fact[fact.index]
fact <- "A 15lb turkey is 70% white meat by volume, but white meat is only 67% of the calories."
#Calories
158*70 / (158*70 + 183*30)
f19 <- tibble::tribble(
~`Meat Type`, ~Amount, ~Metric,
"Dark meat (183 cal / serving)", 30, "Volume",
"White meat (158 cal / serving)", 70, "Volume",
"Dark meat (183 cal / serving)", 33, "Calories",
"White meat (158 cal / serving)", 67, "Calories"
) %>%
uncount(Amount) %>%
group_by(Metric) %>%
mutate(cluster_i = row_number()) %>%
ungroup() %>%
right_join(trk2.pic ) %>%
mutate(Metric = fct_relevel(Metric, "Volume", "Calories"))
f19 %>%
ggplot(aes(x=x, y=y, fill = `Meat Type`)) +
geom_raster() +
scale_fill_manual(values = c(trk.col.red[1], trk.col.gold[1])) +
coord_fixed() +
geom_text(data = tibble(Metric = c("Volume", "Calories"),
Label = paste(c("70%", "67%"), "\nwhite meat"),
`Meat Type` = NA),
aes(label = Label),
x = 170, y = 150, size = 6, fontface="bold", color = trk.col.blue) +
facet_grid(.~Metric) +
guides(fill = guide_legend(nrow=2))+
labs(title = "Whole turkey composition, by meat type",
subtitle = wrapper(fact, 90),
caption = chart_footer) +
theme_minimal() +
trk_chart_theme +
theme(
axis.text = element_blank(),
axis.title = element_blank()
)
ggsave("Output/Turkey/3_CompositionByMeat.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact stuffing ----
f99 <- tribble(
~Recipe, ~Turkey, ~Stuffing, ~URL,
"<NAME>", 11, 4, "https://www.foodnetwork.com/recipes/alton-brown/turkey-with-stuffing-recipe-3381360",
"Taste of Home", 15, 12, "https://www.tasteofhome.com/recipes/classic-stuffed-turkey/",
"Farmhouse Herbed", 12, 9, "https://www.epicurious.com/recipes/food/views/farmhouse-herbed-stuffing-240446",
"Pillsburty", 16, 10, "https://www.pillsbury.com/recipes/roast-turkey-with-stuffing/3dd04532-f8a3-4338-a523-080fe7b30314",
"<NAME>", 20, 12, "https://www.marthastewart.com/317812/turkey-with-stuffing",
"<NAME>", 16, 9, "https://www.bettycrocker.com/recipes/easy-turkey-stuffing/380d2532-b381-4336-8f18-f74469f17cd0",
"Real Simple", 11, 6, "https://www.myrecipes.com/recipe/roast-turkey-with-sage-stuffing-gravy",
"Food & Wine", 19, 20, "https://www.foodandwine.com/recipes/roasted-turkey-with-italian-sausage-stuffing",
"BBC", 11, 1.5, "https://www.bbc.com/food/recipes/perfect_roast_turkey_72482",
"Kraft", 10, 2, "https://www.kraftrecipes.com/recipe/054214/roast-turkey-sausage-stuffing",
"Bon Appetit", 18, 8, "https://www.bonappetit.com/recipe/roast-turkey-with-cornbread-sausage-stuffing",
"<NAME>", 14, 9, "https://andrewzimmern.com/2012/11/16/perfect-thanksgiving-turkey-stuffing-gravy/",
"Cooking Channel", 15, 7, "https://www.cookingchanneltv.com/recipes/turkey-and-stuffing-2012777",
"NYTimes", 15, 8, "https://cooking.nytimes.com/recipes/231-roast-turkey-with-bread-stuffing",
"<NAME>", 18.5, 6, "https://cooking.nytimes.com/recipes/185-roast-stuffed-turkey"
)
f99 %>%
ggplot(aes(x=Turkey, y=Stuffing))+
geom_point(size = 4, color = trk.col.ltblue, shape = 18)+
geom_smooth(size = 2, color = trk.col.blue, fill = trk.col.gold[1],
method = "lm", formula = y ~ x + 0) +
geom_text(label = "Online recipes", y =8.5, x= 13, angle = 15, size = 6, color = trk.col.blue) +
geom_label(label = "0.56 cups stuffing /\nlb turkey", y =3, x= 17, size = 5,
fill = trk.col.blue, color = "white") +
geom_label(label = "0.75 cups stuffing /\nlb turkey", y =18, x= 12, size = 5,
fill = trk.col.red[1], color = "white") +
geom_text(label = "Conventional Wisdom", y =11, x= 13, angle = 17, size = 6, color = trk.col.red[1]) +
geom_segment(x=10, y=7.5, xend=20, yend=15,
size = 2, color = trk.col.red[1]) +
scale_x_continuous(breaks = seq(10, 20, 2)) +
labs(title = "Stuffing required by Turkey weight,\nconventional knowledge vs online recipes",
subtitle = "Conventional wisdom suggests 3/4 cups per pound of turkey,\nwhile 15 online recipes call for an average of a little more than half a cup.",
caption = paste0("Data collected from various online recipes\n", chart_footer_bonus),
x = "Turkey Weight (lbs)",
y = "Stuffing amount (cups)") +
theme_minimal() +
trk_chart_theme +
theme(
axis.text.y = element_text(size = 12, face = 'bold', color = "black"),
axis.title = element_text(size = 12, face = 'bold', color = "black"),
axis.text.x = element_text(size = 12, face = 'bold', color = "black",
angle = 90, hjust = 1),
axis.line = element_line(color = "black"),
panel.grid = element_line(color = "#cccccc"),
plot.margin = margin(t = 2, r = 50, b = 2, l = 20, unit = "pt")
)
ggsave("Output/Turkey/4_StuffingBySize.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact 63 feathers ----
fact.index <- 63
fact <- trk.fact[fact.index]
"Turkeys will have 3,500 feathers at maturity."
library(emoGG)
emoji_search("turkey")
f63 <- trk2.pic %>%
mutate(cluster2 = kmeans(.[,1:2], 700)$cluster) %>%
group_by(cluster2) %>%
sample_n(1) %>%
ungroup()
f63 %>%
ggplot(aes(x=x, y=y)) +
geom_emoji(emoji="1f983") +
# geom_point( color = trk.col.red[1], size = 3, alpha = 0.5, shape = 18) +
coord_fixed() +
# geom_text(aes(paste0("Fact #", fact.index)),
# x = 220, y = 20, size = 5, color = trk.col.blue) +
labs(title = wrapper(fact, 90),
subtitle = "Each turkey emoji is 50 feathers",
caption = chart_footer) +
guides(fill = guide_legend(nrow=2))+
theme_minimal() +
trk_chart_theme +
theme(
axis.text = element_blank(),
axis.title = element_blank()
)
ggsave("Output/Turkey/5_TurkeyFeathers.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact 48 Speed ----
fact.index <- 48
fact <- paste(trk.fact[fact.index], trk.fact[45])
"Wild turkeys can fly for short distances up to 55 mph and can run 20 mph."
f48 <- tribble(
~Method, ~Speed, ~Label,
"Flying", 55, "55 mph",
"Running", 20, "20 mph",
"Caged", 1, "#buyorganic"
) %>%
mutate(Method = fct_relevel(Method, "Caged", "Running", "Flying"))
f48 %>%
ggplot(aes(x = Method, y = Speed, fill = Method)) +
geom_col(width = 0.5) +
scale_fill_manual(values = c("Flying" = trk.col.ltblue, "Running" = trk.col.gold[1],
"Caged" = trk.col.red[2])) +
geom_text(aes(label = Label), hjust = 0, nudge_y = 1, size = 6) +
coord_flip() +
scale_y_continuous(limits = c(0, 70)) +
labs(title = "Turkey speed, by mobility method",
subtitle = wrapper(fact, 76),
caption = paste0("Images: phylopic.org\n", chart_footer)) +
theme_minimal() +
trk_chart_theme +
theme(
axis.text.y = element_text(size = 12, face = 'bold', color = "black"),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 12, face = 'bold', color = "black"),
axis.title.x = element_text(size = 14, face = "bold"),
axis.line.x = element_line(color = "black"),
legend.position = "none"
)
ggsave("Output/Turkey/6_TurkeyMoblity.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact Poop ----
fact <- "You can identify a turkey's gender by the shape of its droppings."
emoji_search("turkey") #1f983
emoji_search("poop") #1f4a9
fpp <- read_csv("data/Turkey/TurkeyPoop.csv") %>%
group_by(Sex) %>%
mutate(y = n()-row_number()) %>%
ungroup() %>%
gather(x, value, `1`:`10`) %>%
mutate(x = as.numeric(x)) %>%
mutate(emoji = case_when(
value == 1 & (x+y)%%2 == 0 ~ "1f4a9",
value == 1 & (x+y)%%2 == 1 ~ "1f983"
)) %>%
filter(!is.na(emoji)) %>%
mutate(Sex = ifelse(Sex == "Male", "Toms (male)", "Hens (female)"))
fpp %>%
filter(emoji == "1f4a9") %>%
ggplot(aes(x=x, y=y)) +
geom_emoji(emoji="1f4a9", size = .08) +
geom_emoji(data = fpp %>% filter(emoji == "1f983"), emoji="1f983", size = .08) +
coord_fixed() +
facet_grid(.~Sex) +
labs(title = wrapper(fact, 90),
subtitle = "Female turkey poop has a 'J' shape, while male droppings are spiral.",
caption = chart_footer_bonus) +
guides(fill = guide_legend(nrow=2))+
theme_minimal() +
trk_chart_theme +
theme(
axis.text = element_blank(),
axis.title = element_blank()
)
ggsave("Output/Turkey/7_TurkeyPoop.png", device = "png",
width = 6, height = 5.6, units = "in")
# Fact 27 - Evolution ----
fact.index <- 27
fact <- trk.fact[fact.index]
#Hmmm probably 11
fact <- "Turkeys lived eleven million years ago."
f27 <- tribble(
~Animal, ~mya,
"Archaeopteryx", 1500,
"Tyrannosaurus rex", 680,
"Turkey", 110,
"You", 0
)
f27 %>%
ggplot(aes(x=mya)) +
coord_fixed() +
scale_x_reverse(name = "Millions of Year ago",
breaks = c(f27$mya), labels = f27$mya/10) +
scale_y_continuous(limits = c(0, 300)) +
geom_raster(data = readPNG("data/Homo.png") %>% process_png(4),
aes(x=x-50, y=y), fill = trk.col.blue[1]) +
geom_raster(data = readPNG("data/Meleagris.png") %>% process_png(6),
aes(x=x+100, y=y), fill = trk.col.gold[1]) +
geom_raster(data = readPNG("data/Tyrannosaurus.png") %>% process_png(2),
aes(x=x+450, y=y), fill = trk.col.red[1]) +
geom_raster(data = readPNG("data/Archaeopteryx.png") %>% process_png(6),
aes(x=x+1450, y=y), fill = trk.col.orange[1]) +
geom_text(aes(label = "The earliest birds"),
x = -1500, y = 150,
size = 5, color = trk.col.orange[1]) +
geom_text(aes(label = "T. rex"),
x = -680, y = 250,
size = 5, color = trk.col.red[1]) +
geom_text(aes(label = "Turkeys\nevolved"),
x = -120, y = 150,
size = 5, color = trk.col.gold[1]) +
labs(title = wrapper(fact, 90),
subtitle = "T.rex couldn't celebrate Thanksgiving with turkey, but they had plenty of other options.",
caption = paste0("Images: phylopic.org\n", chart_footer_bonus)) +
guides(fill = guide_legend(nrow=2))+
theme_minimal() +
trk_chart_theme +
theme(
axis.text.y = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 12, face = 'bold', color = "black"),
axis.title.x = element_text(size = 14, face = "bold"),
axis.line.x = element_line(color = "black"),
panel.border = element_blank(),
panel.background = element_blank()
)
ggsave("Output/Turkey/8_Evolution.png", device = "png",
width = 8, height = 3.5, units = "in")
# Fact B1 - Jurassic Park Velociraptor ----
fact <- "Actual velociraptors were the size of turkeys"
fb1 <- tribble(
~Source, ~Animal, ~Height,
"Human size", "Homo", 6,
"Jurassic Park", "Velociraptor", 4.75,
"Turkey-size", "Meleagris", 2.5,
"Turkey-size", "Velociraptor", 2
) %>%
mutate(Pic = purrr::map2(Animal, Height, function(ani, hght){
readPNG(paste0("data/", ani, ".png")) %>%
process_png_y(hght)
})) %>%
unnest(Pic) %>%
group_by(Source, Animal) %>%
mutate(x = ifelse(Animal == "Velociraptor", -x, x),
x = ifelse(Source == "Turkey-size", x + floor(median(x)/4), x)) %>%
ungroup()
fb1 %>%
ggplot(aes(x=x, y=y, fill = Source)) +
geom_raster() +
scale_fill_manual(values = c("Human size" = trk.col.blue, "Turkey-size" = trk.col.gold[2],
"Jurassic Park" = trk.col.red[1])) +
scale_y_continuous(name = "Height (Ft)", breaks = seq(50, 300, by=50), labels = 1:6) +
coord_fixed() +
# geom_text(aes(label = paste0("Fact #", fact.index)),
# x = 220, y = 20, size = 5, color = trk.col.blue) +
labs(title = fact,
subtitle = wrapper("Hollywood took some liberties with human-sized velociraptors in Jurassic Park...
and they plucked off the feathers.", 85),
caption = paste0("Images: phylopic.org\n", chart_footer_bonus)) +
theme_minimal() +
trk_chart_theme +
theme(
axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.text.y = element_text(size = 12, face = 'bold'),
axis.title.y = element_text(size = 14, face = "bold")
)
ggsave("Output/Turkey/9_JurassicPark.png", device = "png",
width = 6, height = 4, units = "in")
<file_sep>####
#Quick t-rex chart for Phylopic
####
library(tidyverse); library(rvest)
library(png)
#Phylopid Budget ----
phylo.budget <- tribble(
~Expense, ~PerMil,
"Web Hosting\n4.3%", 43,
"Development\n51.1%", 511,
"Migration\n2.9%", 29,
"Quality Assurance\n2.9%", 29,
"Manufacturing\n14.2%", 142,
"Shipping & Handling\n20.6%", 206,
"Crowdfunding\n4%", 40
)
phylo.budget2 <- phylo.budget%>%
uncount(PerMil) %>%
mutate(cluster_i = row_number())
#Get TRex pic ----
trex.pic.raw <- readPNG("data/Tyrannosaurus.png")
trex.pic <- trex.pic.raw[,,4] %>%
as.data.frame() %>%
mutate(y = n()-row_number()) %>%
gather(x, value, 1:(ncol(.)-1)) %>%
mutate(x = as.numeric(str_remove_all(x, "V"))) %>%
filter(value > 0) %>%
#Rescale to 50% of coords
group_by(x = x %/% 2, y = y %/% 2) %>%
summarize(value = max(value)) %>%
ungroup() %>%
mutate(cluster = kmeans(.[, c(1:2)], 1000)$cluster) %>%
arrange(x, desc(y))
trex.pic.cluster.i <- unique(trex.pic$cluster)
trex.pic2 <- trex.pic %>%
rowwise() %>%
mutate(cluster_i = which(cluster == trex.pic.cluster.i)) %>%
ungroup() %>%
right_join(phylo.budget2) %>%
mutate(Expense = fct_relevel(Expense, unique(Expense)))
trex.pic2 %>%
ggplot(aes(x=x, y=y, fill = Expense)) +
geom_raster() +
scale_fill_manual(values = c("#ff4040", "#2dd49c", "#D4AF37", "#ff25ab", "#5384ff", "#ff6141", "#ff9e53")) +
coord_fixed() +
labs(title = "PhyloPic 2.0 Projected Budget",
subtitle = "https://www.indiegogo.com/projects/phylopic-2-0-free-silhouettes-of-all-life-forms/") +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
strip.background = element_rect(fill = "#00436b"),
strip.text = element_text(color = "white", face = "bold"),
plot.background = element_rect(fill = "#fcedcc"),
plot.title = element_text(size = 16, face = "bold"),
plot.subtitle = element_text(size = 11),
panel.background = element_rect(fill = "#fcedcc"),
legend.position = "bottom",
legend.title = element_text(size = 11, face ="bold"),
legend.text = element_text(size = 10)
)
ggsave("TRexPhylo.png", device = "png")
<file_sep>library(tidyverse); library(rvest)
library(png)
#Get Specimen table from Wikipedia ----
wiki <- read_html("https://en.wikipedia.org/wiki/Specimens_of_Tyrannosaurus")
trex.specimens <- wiki %>%
html_node("table") %>%
html_table() %>%
#Clean up % columns'
mutate(comp = str_replace_all(`%`,"<", ""),
comp = as.numeric(ifelse(nchar(comp) > 2,
(as.numeric(substr(comp, 1, 2)) + as.numeric(substr(comp, 4, 5)))/2,
comp))) %>%
top_n(12, comp) %>%
#Clean name
rename(Name = `Name(Spec #)`) %>%
mutate(Name = str_remove(Name, "\n"),
Name = str_replace(Name, "\\(", " \n\\("),
Name = factor(Name, levels = Name))
#Get TRex pic ----
trex.pic.raw <- readPNG("data/Tyrannosaurus.png")
trex.pic <- trex.pic.raw[,,4] %>%
as.data.frame() %>%
mutate(y = n()-row_number()) %>%
gather(x, value, 1:(ncol(.)-1)) %>%
mutate(x = as.numeric(str_remove_all(x, "V"))) %>%
filter(value > 0) %>%
#Rescale to 50% of coords
group_by(x = x %/% 2, y = y %/% 2) %>%
summarize(value = max(value)) %>%
ungroup()
# Plot the Rexes ----
#Hacking K-means clustering to approximate slices
trex.pic2 <- trex.pic %>%
mutate(cluster = kmeans(.[, c(1:2)], 100)$cluster)
trex.data <- trex.specimens %>%
mutate(plot = map(comp, function(comp){
keep_k <- sample(1:100, comp)
return(trex.pic2 %>% filter(cluster %in% keep_k))
})) %>%
unnest(plot)
trex.labels <- trex.specimens %>%
mutate(label_p = paste0(round(comp), "%"),
label_d = paste0("Discovered: ", Discovered, "\n",
Location))
trex.data %>%
ggplot(aes(x=x, y=y, fill = Formation)) +
geom_raster() +
scale_fill_manual(values = c("#2dd49c", "#ff4040", "#5384ff", "#ff25ab", "#ff6141", "#ff9e53")) +
coord_fixed() +
geom_text(data = trex.labels, aes(label = label_p),
x = 30, y = 30, size = 5,
color = "#00436b", fontface = "bold") +
geom_text(data = trex.labels, aes(label = label_d),
x = 400, y = 40, size = 3) +
facet_wrap(~Name, ncol = 3) +
labs(title = "Tyrannosaurus rex fossils, % of skeleton discovered",
subtitle = "Sorted by date discovered, colored by geological formation discovered",
caption = paste0("Data: https://en.wikipedia.org/wiki/Specimens_of_Tyrannosaurus\n",
"Image: phylopic.org\n",
"<NAME> .com")) +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
strip.background = element_rect(fill = "#00436b"),
strip.text = element_text(color = "white", face = "bold"),
plot.background = element_rect(fill = "#fcedcc"),
plot.title = element_text(size = 20, face = "bold"),
plot.subtitle = element_text(size = 16),
panel.background = element_rect(fill = "#fcedcc"),
legend.position = "bottom"
)
#Addendum ---
# Got a bunch of complaints about Trix... and I like Tristan
add.specimens <- tibble::tribble(
~Name, ~Discovered, ~Formation, ~Location, ~comp,
"Trix", 2013, "Hell Creek Formation", "Montana", 77,
"Tristan \n(MB.R.91216)", 2010, "Hell Creek Formation", "Carter County, Montana", 57
)
add.data <- add.specimens %>%
mutate(plot = map(comp, function(comp){
keep_k <- sample(1:100, comp)
return(trex.pic2 %>% filter(cluster %in% keep_k))
})) %>%
unnest(plot)
add.labels <- add.specimens %>%
mutate(label_p = paste0(round(comp), "%"),
label_d = paste0("Discovered: ", Discovered, "\n",
Location))
add.data %>%
ggplot(aes(x=x, y=y, fill = Formation)) +
geom_raster() +
scale_fill_manual(values = "#ff4040") +
coord_fixed() +
geom_text(data = add.labels, aes(label = label_p),
x = 30, y = 30, size = 5,
color = "#00436b", fontface = "bold") +
geom_text(data = add.labels, aes(label = label_d),
x = 400, y = 40, size = 4) +
facet_wrap(~Name, ncol = 2) +
labs(title = "Addendum: Tyrannosaurus rex fossils, % of skeleton discovered",
subtitle = "Sorted by date discovered, colored by geological formation discovered",
caption = paste0("Data: https://en.wikipedia.org/wiki/Specimens_of_Tyrannosaurus\n",
"Image: phylopic.org\n",
"<NAME>e .com")) +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
strip.background = element_rect(fill = "#00436b"),
strip.text = element_text(color = "white", face = "bold"),
plot.background = element_rect(fill = "#fcedcc"),
plot.title = element_text(size = 20, face = "bold"),
plot.subtitle = element_text(size = 16),
panel.background = element_rect(fill = "#fcedcc"),
legend.position = "bottom"
)
| 80e8841bd2baa7a22e2ee8ac8a4c060096e77f25 | [
"R"
] | 5 | R | ryantimpe/ChartOfTheDay | d08460a7c98f5856e03d43b30b2f7992b7ae2180 | 03254b513d34bdc789fdac54aa6947b12a50101c |
refs/heads/master | <file_sep>class Program
{
public static void Main()
{
int x = 1;
int y = 2;
Console.WriteLine($"Hello World {x + y}");
}
}
| d29ebfb069971b2170bfc8e3a7a73987f124db66 | [
"C#"
] | 1 | C# | Mercurial/sagemode1 | abd7c69918471bebb9b50e804ff05956efd6bca1 | 0251a5635f8b9446e38deac184354279213568fe |
refs/heads/master | <file_sep>require('chai').should();
var FizzBuzz = require("../lib/fizzbuzz.js")
describe('FizzBuzz', function(){
it('should exist', function(){
FizzBuzz.should.be;
});
it("should return Fizz when input mod 3 == 0", function(){
FizzBuzz(3).should.equal('Fizz');
FizzBuzz(6).should.equal('Fizz');
});
it("should return Buzz when input mod 5 == 0", function(){
FizzBuzz(5).should.equal('Buzz');
FizzBuzz(10).should.equal('Buzz');
});
it("should return Fizz Buzz when input mod 5 == 0 and input mod 3 == 0", function(){
FizzBuzz(15).should.equal('Fizz Buzz');
});
it("should return input in all other cases", function(){
FizzBuzz(2).should.equal(2);
FizzBuzz(7).should.equal(7);
});
});<file_sep>// display temperature (ajax call)
// display update button
// when user clicks on button widget should update temperature
describe("TempWidget", function(){
var $parent, widget;
beforeEach(function(){
jasmine.Ajax.install();
$parent = $('<div class="test-parent"></div>').appendTo('body');
widget = new TempWidget($parent);
});
afterEach(function(){
$parent.remove();
jasmine.Ajax.uninstall();
});
it('tempWidget should exist', function(){
expect(TempWidget).toBeDefined();
});
it("should create div element with class .temp-widget", function(){
fakeAjax(22);
widget.render();
expect($("div.temp-widget").size()).toEqual(1);
});
var fakeAjax = function(tempValue){
var fakeSuccess = {
'status': 200,
'content-type' : 'application/json',
'responseText' : JSON.stringify({"temperature" : tempValue})
}
jasmine.Ajax.requests.mostRecent().respondWith(fakeSuccess);
};
describe("when widget is initialized", function(){
it("should fetch temperature from server", function(){
expect(jasmine.Ajax.requests.mostRecent().url).toEqual("/api/temperature");
});
});
it('should display temperature in div with class .temp-value', function(){
fakeAjax(22);
widget.render();
expect($("div.temp-value").text()).toEqual("22 C");
});
it("when user clicks on button widhet should be updated", function(){
fakeAjax(22);
widget.render();
expect($("div.temp-value").text()).toEqual("22 C");
$parent.find("button.update").click();
fakeAjax(5);
expect($("div.temp-value").text()).toEqual("5 C");
});
});<file_sep>function StringCalc(input){
if(!input || input === '')
return 0;
var regexpResult = input.match(/^\/\/(.*)\n(.*)$/);
if(!!regexpResult)
{
var customDelimiter = regexpResult[1];
input = regexpResult[2];
input = input.replace(customDelimiter, ',');
}
input = input.replace('\n',',')
var array = input.split(',');
var sum = 0;
for(var i = 0; i< array.length; i++){
sum +=(+array[i]);
}
return sum;
}
module.exports = StringCalc;<file_sep> /* brackets-xunit: includes=../lib/StringCalc.js */
describe("String calculator", function(){
if(require !== undefined)
var StringCalc = require("../lib/StringCalc.js");
it("should exist", function(){
expect(StringCalc).toBeTruthy();
});
it("should return some value", function(){
expect(StringCalc()).toBeDefined();
});
describe("when input is empty string", function(){
it("should return 0", function(){
expect(StringCalc('')).toEqual(0);
});
});
describe("when input is a value as string", function(){
it("should return same value as number", function(){
expect(StringCalc('5')).toEqual(5);
expect(StringCalc('4')).toEqual(4);
expect(StringCalc('-4')).toEqual(-4);
expect(StringCalc('0')).toEqual(0);
});
});
describe("when input is a pair of values with ',' as delimiter", function(){
it("should return sum of them", function(){
expect(StringCalc('1,2')).toEqual(3);
expect(StringCalc('3,4')).toEqual(7);
expect(StringCalc('-3,-4')).toEqual(-7);
expect(StringCalc('-3,4')).toEqual(1);
});
});
describe("when number is unlimited number of values with ',' as delimiter",function(){
it("should return a sum of them", function(){
expect(StringCalc('1,2,3,4,5,6,7,8,9')).toEqual(45);
expect(StringCalc('-1,-2,-3,-4,-5,-6,-7,-8,-9')).toEqual(-45);
});
});
describe("when delimiter is '\\n'", function(){
it("should work", function(){
expect(StringCalc("1\n2")).toEqual(3);
});
});
describe("when custome delimiter is set by //[delimiter]\\n", function(){
it("should work", function(){
expect(StringCalc("//;\n1;2")).toEqual(3);
expect(StringCalc("//;;\n1;;2")).toEqual(3);
});
});
}); | 3db671c47982101411546de4d8ffebe2e9f2aee3 | [
"JavaScript"
] | 4 | JavaScript | curlydevil/JS-TDD | 619246976c622b7123fc9193551dc2b67c31ad56 | baa92c54716dd954e6d22a3c53faa1ede5146745 |
refs/heads/master | <file_sep>//#include<iostream>
//#include"Particle.h"
//#include<fstream>
//#include<algorithm>
//#include"Rod.h"
//using namespace std;
//
//#define N 50000000
//
//const unsigned dim =12;
//
//Particle<dim> a[N];
//
//bool at_zero_point(Particle<dim> &a)
//{
// return a.get_position() == Particle<dim>().get_position();
//}
//
//void dimension_move()
//{
//
// ofstream out("C:\\Users\\10069\\Desktop\\dim=12.txt");
// out << '{';
// for (int i = 0; true; i++)
// {
// for (int j = 0; j < N; j++)
// {
// a[j].move(ON_GRID);
// }
// if (i % 2 != 0)
// {
// auto temp = count_if(begin(a), end(a), at_zero_point);
// cout << temp << endl;
// out << temp << ',';
// if (temp<20)
// {
// break;
// }
// }
// }
// out.close();
// system("pause");
//}<file_sep>#include"RandomJS.h"
#include<iostream>
#include<fstream>
#include <iomanip>//目的为高精度输出
#include<cmath>
using namespace std;
using namespace randomjs;//使用自己random库的命名空间
int main()
{
ofstream out2("C:\\Users\\10069\\Desktop\\result2.txt");
ofstream out5("C:\\Users\\10069\\Desktop\\result5.txt");
ofstream out10("C:\\Users\\10069\\Desktop\\result10.txt");
clock_t startTime, endTime;
startTime = clock();
out2 << setprecision(10);
for (int i = 0; i < 1000000; i++)
{
double x1 = RandomFibonacci() + 3;
double x2 = asin(RandomSchrage() * 2 - 1)/5;
double x3 = acos(RandomFibonacci() * 2 - 1) / 5+3;
double x4 = acos(RandomFibonacci() * 2 - 1) / 2 + 2;
double x5 = -0.1*log(RandomSchrage());
double x6 = RandomFibonacci() + 6;
double x7 = asin(RandomSchrage() * 2 - 1) / 5+10;
double x8 = acos(RandomFibonacci() * 2 - 1) / 5 + 3+2;
double x9 = x4 = acos(RandomFibonacci() * 2 - 1) *2 + 2;
double x0 = 0.2*log(RandomSchrage());
out2 << x1 + x2 << ' ';
out5 << x1 + x2 + x3 + x4 + x5 << endl;
double temp = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x0;
out10 << temp << endl;
}
out2.close();
out5.close();
out10.close();
endTime = clock();//计时结束
cout << "The run time is: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
getchar();
}<file_sep>#ifndef RANDOMNUMBERJS //DB is short for my name <NAME>
#define RANDOMNUMBERJS
namespace randomjs //防止日后调库的命名冲突
{
double RandomSchrage();
double RandomFibonacci();
void SetSeed(int seed);
}
#endif // !RANDOMJS
<file_sep>#include<iostream>
#include"Particle.h"
#include"Vector.h"
#include<GL/glut.h>
using namespace std;
#include"Animation.h"
#define dim 2
#define NUM 100000
#define MAPSIZE 1024
Particle<dim> p[NUM];
void cleanup() {}
int calc_offset(int x,int y)
{
int center = (MAPSIZE + 1)*MAPSIZE / 2;
if (x<-MAPSIZE / 2 || y<-MAPSIZE / 2 || x>MAPSIZE / 2 || y>MAPSIZE / 2)
{
cerr << "Out of bound!" << endl;
return center;
}
else
{
return center + x + y * MAPSIZE;
}
}
//
//}
//
//void generate_frame(DataBlock *d, int ticks)
//{
//
// CPUAnimBitmap *map = d->bitmap;
// auto ptr = map->get_ptr();
// for (int i = 0; i < NUM; i++)
// {
// int offset = calc_offset(p[i][0], p[i][1]);
// ptr[offset * 4 + 0] = 0;
// ptr[offset * 4 + 1] = 0;
// ptr[offset * 4 + 2] = 0;
// ptr[offset * 4 + 3] = 0;
// p[i].move(ON_GRID);
// }
//
// for (int i = 0; i < NUM; i++)
// {
// int offset = calc_offset(p[i][0], p[i][1]);
//
// int center = calc_offset(0, 0);
//
// ptr[center * 4 + 0] = 255;
// ptr[center * 4 + 1] = 0;
// ptr[center * 4 + 2] = 255;
// ptr[center * 4 + 3] = 1;
//
//
// ptr[offset * 4 + 0] = 255;
// ptr[offset * 4 + 1] = 255;
// ptr[offset * 4 + 2] = 255;
// ptr[offset * 4 + 3] = 1;
// }
//
//}
//
//void run_show()
//{
// DataBlock data;
// CPUAnimBitmap bitmap(MAPSIZE, MAPSIZE, &data);
// data.bitmap = &bitmap;
//
// bitmap.anim_and_exit((void(*)(void*, int))generate_frame, (void(*)(void*))cleanup);
//}
<file_sep>#pragma once
#include<GL/glut.h>
struct CPUAnimBitmap;
struct CPUAnimBitmap {
unsigned char *pixels;
int width, height;
void *dataBlock;
void(*fAnim)(void*, int);
void(*animExit)(void*);
void(*clickDrag)(void*, int, int, int, int);
int dragStartX, dragStartY;
CPUAnimBitmap(int w, int h, void *d = NULL) {
width = w;
height = h;
pixels = new unsigned char[width * height * 4];
dataBlock = d;
clickDrag = NULL;
}
~CPUAnimBitmap() {
delete[] pixels;
}
unsigned char* get_ptr(void) const { return pixels; }
long image_size(void) const { return width * height * 4; }
void click_drag(void(*f)(void*, int, int, int, int)) {
clickDrag = f;
}
void anim_and_exit(void(*f)(void*, int), void(*e)(void*)) {
CPUAnimBitmap** bitmap = get_bitmap_ptr();
*bitmap = this;
fAnim = f;
animExit = e;
// a bug in the Windows GLUT implementation prevents us from
// passing zero arguments to glutInit()
int c = 1;
char* dummy = nullptr;
glutInit(&c, &dummy);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(width, height);
glutCreateWindow("bitmap");
glutKeyboardFunc(Key);
glutDisplayFunc(Draw);
if (clickDrag != NULL)
glutMouseFunc(mouse_func);
glutIdleFunc(idle_func);
glutMainLoop();
}
// static method used for glut callbacks
static CPUAnimBitmap** get_bitmap_ptr(void) {
static CPUAnimBitmap* gBitmap;
return &gBitmap;
}
// static method used for glut callbacks
static void mouse_func(int button, int state,
int mx, int my) {
if (button == GLUT_LEFT_BUTTON) {
CPUAnimBitmap* bitmap = *(get_bitmap_ptr());
if (state == GLUT_DOWN) {
bitmap->dragStartX = mx;
bitmap->dragStartY = my;
}
else if (state == GLUT_UP) {
bitmap->clickDrag(bitmap->dataBlock,
bitmap->dragStartX,
bitmap->dragStartY,
mx, my);
}
}
}
// static method used for glut callbacks
static void idle_func(void) {
static int ticks = 1;
CPUAnimBitmap* bitmap = *(get_bitmap_ptr());
bitmap->fAnim(bitmap->dataBlock, ticks++);
glutPostRedisplay();
}
// static method used for glut callbacks
static void Key(unsigned char key, int x, int y) {
switch (key) {
case 27:
CPUAnimBitmap* bitmap = *(get_bitmap_ptr());
bitmap->animExit(bitmap->dataBlock);
//delete bitmap;
exit(0);
}
}
// static method used for glut callbacks
static void Draw(void) {
CPUAnimBitmap* bitmap = *(get_bitmap_ptr());
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glDrawPixels(bitmap->width, bitmap->height, GL_RGBA, GL_UNSIGNED_BYTE, bitmap->pixels);
glutSwapBuffers();
}
};<file_sep>#ifndef SAMPLINGJS
#define SAMPLINGJS
namespace randomjs
{
void BallSurface(double &x, double&y, double&z, double func() = RandomSchrage);
bool BallSurfaceMarsaglia(double &x, double &y, double &z);
}
#endif // !SAMPLINGJS
<file_sep>#pragma once
#include<initializer_list>
#include<cmath>
#include"RandomJS.h"
#include<iostream>
using namespace randomjs;
using std::initializer_list;
using std::ostream;
using std::cout;
#define EPSILON 1E-9
template<unsigned dimension>
class Vector;
template<unsigned dimension>
Vector<dimension> operator*(const Vector<dimension>&r, double lambda);
template<unsigned dimension>
Vector<dimension> operator+(const Vector<dimension>&l, const Vector<dimension>&r);
template<unsigned dimension>
Vector<dimension> operator-(const Vector<dimension>&l, const Vector<dimension>&r);
template<unsigned dimension>
Vector<dimension> operator/(const Vector<dimension>&r, double lambda);
template<unsigned dimension>
bool operator==(const Vector<dimension>&l, const Vector<dimension>&r);
template<unsigned dimension>
class Vector
{
friend void swap(Vector<dimension>&l, Vector<dimension>&r)//交换并赋值的写法,保证自赋值安全,同时按版本区分拷贝和移动构造函数
{
auto p = l.coordinates;
l.coordinates = r.coordinates;
r.coordinates = p;
}
public:
//拷贝控制
Vector()
{
coordinates = new double[dimension]();
}
Vector(initializer_list<double> list)
{
coordinates = new double[dimension]();
for (int i = 0; i < dimension; i++)
{
if (i<list.size())
{
coordinates[i] = *(list.begin() + i);
}
else
{
coordinates[i] = 0;
}
}
}
Vector(const Vector &vec)
{
coordinates = new double[dimension];
for (int i = 0; i < dimension; i++)
{
coordinates[i] = vec[i];
}
}
Vector operator= (Vector in)
{
Vector temp(in);
swap(*this, in);
return *this;
}
Vector(Vector&& rvec)
{
coordinates = rvec.coordinates;
rvec.coordinates = nullptr;
}
~Vector()
{
delete[] coordinates;
coordinates = nullptr;
}
//拷贝控制结束
//算符重载
Vector<dimension>& operator*=(double lambda)
{
*this = *this *lambda;
return *this;
}
Vector<dimension>& operator+=(const Vector<dimension>&r)
{
*this = *this + r;
return *this;
}
Vector<dimension>& operator-=(const Vector<dimension>&r)
{
*this = *this - r;
return *this;
}
Vector<dimension>& operator/=(double lambda)
{
*this = *this / lambda;
return *this;
}
//算符重载结束
double& operator[](int i)
{
return get_cor(i);
}
double operator[](int i) const
{
return get_cor(i);
}
double length() const
{
double result = 0;
for (int i = 0; i < dimension; i++)
{
result += coordinates[i] * coordinates[i];
}
return sqrt(result);
}
void print(ostream &out = cout) const
{
for (int i = 0; i < dimension; i++)
{
out << coordinates[i] << ' ';
}
cout << std::endl;
}
protected:
double *coordinates;
//const版本和非const版本
double get_cor(int i) const
{
try
{
if (i > dimension)
{
throw std::out_of_range("Try to get a coordinate more than dimension");
}
}
catch (const std::out_of_range& e)
{
std::cerr << e.what() << std::endl;
return 0;
}
return coordinates[i];
}
double& get_cor(int i)//非const版本返回引用,以改变值
{
try
{
if (i > dimension)
{
throw std::out_of_range("Try to get a coordinate more than dimension");
}
}
catch (const std::out_of_range& e)
{
std::cerr << e.what() << std::endl;
}
return coordinates[i];
}
};
//将二元运算符写在外面以备可能的类型转换
template<unsigned dimension>
double distance(const Vector<dimension>&l, const Vector<dimension>&r)
{
return (l - r).length();
}
template<unsigned dimension>
Vector<dimension> operator+(const Vector<dimension>&l, const Vector<dimension>&r)
{
Vector<dimension> result;
for (int i = 0; i < dimension; i++)
{
result[i] = l[i] + r[i];
}
return result;
}
template<unsigned dimension>
Vector<dimension> operator-(const Vector<dimension>&r)
{
Vector<dimension> result;
for (int i = 0; i < dimension; i++)
{
result[i] = -r[i];
}
return result;
}
template<unsigned dimension>
Vector<dimension> operator-(const Vector<dimension>&l,const Vector<dimension>&r)
{
return l + (-r);
}
template<unsigned dimension>
Vector<dimension> operator*(double lambda,const Vector<dimension>&r)
{
Vector<dimension> result;
for (int i = 0; i < dimension; i++)
{
result[i] = lambda * r[i];
}
return result;
}
template<unsigned dimension>
Vector<dimension> operator*(const Vector<dimension>&r,double lambda)
{
return lambda * r;
}
template<unsigned dimension>
Vector<dimension> operator/(const Vector<dimension>&r, double lambda)
{
return (1.0 / lambda) * r;
}
template<unsigned dimension>
inline bool operator==(const Vector<dimension>& l, const Vector<dimension>& r)//此处优化的效果是十分明显的
{
for (int i = 0; i < dimension; i++)
{
auto temp = l[i] - r[i];
if (( temp>0 ? temp : -temp) > EPSILON)
{
return false;
}
}
return true;
//for (int i = 0; i < dimension; i++)
//{
// if (l[i]!=r[i])
// {
// return false;
// }
//}
//return true;
}
template<unsigned dimension>
Vector<dimension> operator*(const Vector<dimension>&l, const Vector<dimension>&r)
{
return l + (-r);
}
template<unsigned dimension>
double operator*(const Vector<dimension>&l, const Vector<dimension>&r)
{
double result = 0;
for (int i = 0; i < dimension; i++)
{
result += l[i] + r[i];
}
return result;
}
//extern Vector<3> cross(const Vector<3>&l, const Vector<3>&r)
//{
// return Vector<3>({ l[1] * r[2] - l[2] * r[1], l[2] * r[3] - l[3] * r[2], l[3] * r[1] - l[1] * r[3] });
//}
template<unsigned dim>
Vector<dim> RandomVectorOnBall(double length = 1)
{
Vector<dim> temp;
for (int i = 0; i < dim; i++)
{
temp[i] = RandomGauss();
}
temp /= temp.length();
return temp * length;
}
template<unsigned dim>
Vector<dim> RandomVectorOnGridBall(double length = 1)//在格点球上均匀分布的矢量
{
Vector<dim> temp = RandomVectorOnBall<dim>(length);
for (int i = 0; i < dim; i++)
{
temp[i] = int(temp[i] + 0.4999);
}
return temp;
}<file_sep>#ifndef __BOOK_H__
#define __BOOK_H__
#include <stdio.h>
#include <stdlib.h> // 自己加的
#include "cuda_runtime.h" // 自己加的
#include "device_launch_parameters.h"
static void HandleError(cudaError_t err, const char *file, int line)//定义报错函数,通过传入的返回值和文件名、行号来提示信息
{
if (err != cudaSuccess)
{
printf("%s in %s at line %d\n", cudaGetErrorString(err), file, line);
exit(EXIT_FAILURE);
}
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))// 将报错函数包装为宏,自动填塞文件名和行号
#define HANDLE_NULL( a )/* 空指针报错函数,代码中malloc失败时报错 */ \
{ \
if (a == NULL) \
{ \
printf( "Host memory failed in %s at line %d\n", __FILE__, __LINE__ );\
exit(EXIT_FAILURE); \
} \
}
template< typename T >// 泛型交换(全书都没用到?)
void swap(T& a, T& b)
{
T t = a;
a = b;
b = t;
}
void* big_random_block(int size)//在主机中生成随机数组,无符号字符型
{
unsigned char *data = (unsigned char*)malloc(size);
HANDLE_NULL(data);
for (int i = 0; i < size; data[i] = rand(), i++);
return data;
}
int* big_random_block_int(int size)//在主机中生成随机数组,整型
{
int *data = (int*)malloc(size * sizeof(int));
HANDLE_NULL(data);
for (int i = 0; i < size; data[i] = rand(), i++);
return data;
}
// 公用设备函数
__device__ unsigned char value(float n1, float n2, int hue)
{
if (hue > 360)
hue -= 360;
else if (hue < 0)
hue += 360;
if (hue < 60)
return (unsigned char)(255 * (n1 + (n2 - n1)*hue / 60));
if (hue < 180)
return (unsigned char)(255 * n2);
if (hue < 240)
return (unsigned char)(255 * (n1 + (n2 - n1)*(240 - hue) / 60));
return (unsigned char)(255 * n1);
}
__global__ void float_to_color(unsigned char *optr, const float *outSrc)
{
int x = threadIdx.x + blockIdx.x * blockDim.x;
int y = threadIdx.y + blockIdx.y * blockDim.y;
int offset = x + y * blockDim.x * gridDim.x;
float l = outSrc[offset];
float s = 1;
int h = (180 + (int)(360.0f * outSrc[offset])) % 360;
float m1, m2;
if (l <= 0.5f)
m2 = l * (1 + s);
else
m2 = l + s - l * s;
m1 = 2 * l - m2;
optr[offset * 4 + 0] = value(m1, m2, h + 120);
optr[offset * 4 + 1] = value(m1, m2, h);
optr[offset * 4 + 2] = value(m1, m2, h - 120);
optr[offset * 4 + 3] = 255;
}
__global__ void float_to_color(uchar4 *optr, const float *outSrc)
{
int x = threadIdx.x + blockIdx.x * blockDim.x;
int y = threadIdx.y + blockIdx.y * blockDim.y;
int offset = x + y * blockDim.x * gridDim.x;
float l = outSrc[offset];
float s = 1;
int h = (180 + (int)(360.0f * outSrc[offset])) % 360;
float m1, m2;
if (l <= 0.5f)
m2 = l * (1 + s);
else
m2 = l + s - l * s;
m1 = 2 * l - m2;
optr[offset].x = value(m1, m2, h + 120);
optr[offset].y = value(m1, m2, h);
optr[offset].z = value(m1, m2, h - 120);
optr[offset].w = 255;
}
// 有关线程的设置
#if _WIN32
//Windows threads.
#include <windows.h>
typedef HANDLE CUTThread;// 统一包装
typedef unsigned (WINAPI *CUT_THREADROUTINE)(void *);
#define CUT_THREADPROC unsigned WINAPI
#define CUT_THREADEND return 0
#else
//POSIX threads.
#include <pthread.h>
typedef pthread_t CUTThread;
typedef void *(*CUT_THREADROUTINE)(void *);
#define CUT_THREADPROC void
#define CUT_THREADEND
#endif
// 线程的创造,单线程结束,单线程销毁和多线程等待
CUTThread start_thread(CUT_THREADROUTINE, void *data);
void end_thread(CUTThread thread);
void destroy_thread(CUTThread thread);
void wait_for_threads(const CUTThread *threads, int num);
#if _WIN32
CUTThread start_thread(CUT_THREADROUTINE func, void *data)
{
return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, data, 0, NULL);
}
void end_thread(CUTThread thread)
{
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);
}
void destroy_thread(CUTThread thread)
{
TerminateThread(thread, 0);
CloseHandle(thread);
}
void wait_for_threads(const CUTThread * threads, int num) {
WaitForMultipleObjects(num, threads, true, INFINITE);
for (int i = 0; i < num; i++)
CloseHandle(threads[i]);
}
#else
CUTThread start_thread(CUT_THREADROUTINE func, void * data)
{
pthread_t thread;
pthread_create(&thread, NULL, func, data);
return thread;
}
void end_thread(CUTThread thread)
{
pthread_join(thread, NULL);
}
void destroy_thread(CUTThread thread)
{
pthread_cancel(thread);
}
void wait_for_threads(const CUTThread * threads, int num)
{
for (int i = 0; i < num; i++)
end_thread(threads[i]);
}
#endif
#endif // __BOOK_H__<file_sep>#include"RandomJS.h"
#include<initializer_list>
#include<list>
#include<vector>
#include"Bound.h"
using namespace randomjs;
#include<cmath>
#define PI 3.1415926535
//此处用C++语法多一点是希望写出真正有复用价值的代码,并没有调用C++的库来实现核心功能
double MonteCarloIntegrate(double func(std::vector<double>&), std::initializer_list<Bound> list, int cycle)
{
int dim = list.size();
double volume = 1;
for (auto c:list)
{
volume *= (c.upper - c.lower);
}
double result = 0;
int N = cycle;
for (int i = 0; i < N; i++)
{
std::vector<double> xs;
for (int i = 0; i < dim; i++)
{
auto ptr = list.begin() + i;
xs.push_back(RandomSchrage()*(ptr->upper - ptr->lower));
}
result += func(xs);
}
return result * volume / N;
}
<file_sep>#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
#define precision 1E-10;
#define PI 3.14159265358
#define divide 4192
#define saving 1024
#define lambdamax 4192
#define dlambda (lambdamax / divide)
double arr[divide*saving];
void calc(int times = 1000000)
{
for (int i =999; i < 1001; i++)
{
for (int j = 0; j < saving; j++)
{
arr[i*saving + (j + 1) % saving] = i*sin(arr[i*saving + j % saving] * PI);
}
cout << i << endl;
}
}
int main()
{
for (int i = 0; i < divide*saving; i++)
{
arr[i] = 100.0;
}
calc();
double result = 0;
cout << setprecision(9);
for (int i = 1000 * saving; i < 1001 * saving; i++)
{
cout << arr[i] << endl;
}
system("pause");
}<file_sep># Computing-Physics
### 第一章——随机数
第一章的课程主要会介绍随机数和随机抽样的算法。那么在完成作业的同时我希望能够实现能够复用的经过检验的随机数库。<file_sep>#include<iostream>
#include<fstream>
#include<iomanip>
#include<vector>
#include<cmath>
#include"Bound.h"
using namespace std;
double MonteCarloIntegrate(double func(std::vector<double>&), std::initializer_list<Bound> list, int cycle=1e5);//参数分别为传入的函数,边界,循环次数
double f(vector<double> &vec)//这样的写法比较丑陋,但目前还没有想到很好的解决办法,主要是可变长参数传递会难以生成随机数
{
return sqrt(vec[0] + sqrt(vec[0]));
}
double g(vector<double> &vec)//使用vector传参是不得已的,希望能有更加自然的写法
{
double temp = 6;
for (auto c : vec)
{
temp -= c * c;
}
return temp;
}
int main()
{
ofstream out(".//result2.txt");
clock_t startTime, endTime;
startTime = clock();
cout << setprecision(9);//设置输出精度
cout << MonteCarloIntegrate(f, { Bound(0, 2) },10e4) << endl;
cout << MonteCarloIntegrate(g, { Bound(0,0.9),Bound(0,0.8),Bound(0,0.9),Bound(0,2),Bound(0,1.3) },1e4) << endl;
endTime = clock();
cout << "The run time is: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
out.close();
system("pause");
}<file_sep>#include"Particle.h"
#include"Vector.h"
#include<vector>
#include<utility>
#include<algorithm>
#include<GL/glut.h>
#include"Animation.h"
#include<fstream>
#include<cmath>
#include"RandomJS.h"
using randomjs::RandomSchrage;
#define MAPSIZE 1024
using namespace std;
struct DataBlock
{
CPUAnimBitmap *bitmap;
};
void cleanup();
int calc_offset(int x, int y);
vector<Particle<2>> vec(1, Particle<2>({ 0,0 }));
vector<Particle<2>>::iterator iter = vec.begin();
Particle<2> now({ 1,1 });
const int particles_per_frame = 50;
ofstream out("C:\\Users\\10069\\Desktop\\fractal.txt");
void generate_frame(DataBlock *d, int ticks)
{
CPUAnimBitmap *map = d->bitmap;
int i = 0;
while (i < particles_per_frame)
{
Particle<2> temp = now;
if (find(vec.begin(), vec.end(), now.move()) != vec.end()&&RandomSchrage()<1.1)//如果粒子黏附到了已有体系上
{
vec.push_back(temp);
//查找最远点的次数要减少以提高性能!
iter = max_element(vec.begin(), vec.end(),
[](Particle<2> &a, Particle<2> &b)->bool {return a.get_position().length() < b.get_position().length(); });//找到离原点最远的粒子的位置
now = RandomVectorOnGridBall<2>(iter->get_position().length());
double circle_size = iter->get_position().length()*iter->get_position().length();
out << vec.size() << ' ' << circle_size <<' '<< log(vec.size()) / log((double)circle_size) << endl;
cout << vec.size() << ' ' << circle_size << ' ' << log(vec.size()) / log((double)circle_size) << endl;
i++;
}
if (now.get_position().length() > (iter->get_position().length() + 15))//如果跑太远了就重置
{
now = RandomVectorOnGridBall<2>(iter->get_position().length());
}
}
auto ptr = map->get_ptr();
for (int i = 0; i < vec.size(); i++)
{
int offset = calc_offset(vec[i].get_position()[0], vec[i].get_position()[1]);
ptr[offset * 4 + 0] = 255;
ptr[offset * 4 + 1] = 255;
ptr[offset * 4 + 2] = 255;
ptr[offset * 4 + 3] = 1;
}
}
int main()
{
DataBlock data;
CPUAnimBitmap bitmap(MAPSIZE, MAPSIZE, &data);
data.bitmap = &bitmap;
bitmap.anim_and_exit((void(*)(void*, int))generate_frame, (void(*)(void*))cleanup);
system("pause");
}<file_sep>#ifndef RANDOMNUMBERJS //DB is short for my name <NAME>
#define RANDOMNUMBERJS
namespace randomjs //防止日后调库的命名冲突
{
double RandomSchrage();
double RandomFibonacci();
double RandomGauss(double mu = 0, double sigma = 1);
double RandomExp();
double RandomLorentz();
double RandomCos();
void SetSeed(int seed);
}
#endif // !RANDOMJS
<file_sep>#include<cmath>
#include"RandomNumberJS.h"
#include "SamplingJS.h"
namespace randomjs {
constexpr double PI = 3.1415926535;
void BallSurface(double &x, double&y, double&z, double func())
{
double phi = func() * 2 * PI;
double theta = acos(1 - 2 * func());
x = sin(theta)*cos(phi);
y = sin(theta)*sin(phi);
z = cos(theta);
}
bool BallSurfaceMarsaglia(double &x,double &y,double &z) //通过返回值来判断抽样是否成功!
{
double u = 2 * RandomSchrage() - 1, v = 2 * RandomFibonacci() - 1;
if (u*u + v * v > 1)
{
return false;
}
double temp = sqrt(1 - u * u - v * v);
x = 2 * u*temp;
y = 2 * v*temp;
z = 1 - 2 * (u*u + v * v);
return true;
}
double DirectSampling(double inversedFunc(double))
{
return inversedFunc(RandomSchrage());
}
double RejectionSampling(double func(double), double sample(double), double compare(double))
{
double x = sample(RandomSchrage());
while (compare(x)*RandomFibonacci() > func(x))
{
x = sample(RandomSchrage());
}
return x;
}
}<file_sep>#include<ctime>
#include<vector>//用来保存在Fibonacci数列中的预先项
#include "RandomNumberJS.h"
namespace randomjs //防止日后调库的命名冲突
{
//*********************以下部分都是在生成随机数***************************
constexpr int m = 2147483647;
constexpr int a = 16807;
constexpr int b = 0;
constexpr int q = m / a;
constexpr int r = m % a;
static int seed = int(time(NULL)) % m > 0 ? int(time(NULL)) % m : int(time(NULL)) % m + m;
int RandomSchrageInt()//Schrage算法的int版本
{
int temp = a * (seed%q) - r * (seed / q);//通过公式使得运算中每一项都安全
seed = temp > 0 ? temp : temp + m;
return seed;
}
double RandomSchrage()
{
int temp = a * (seed%q) - r * (seed / q);//通过公式使得运算中每一项都安全
seed = temp >= 0 ? temp : temp + m;
return seed / double(m);
}
constexpr int p_fib = 97;
constexpr int q_fib = 33;
constexpr int size = p_fib > q_fib ? p_fib : q_fib;
int arr[size];
static int head = 0, tail = (p_fib - q_fib) % size;
static bool init = false;
double RandomFibonacci()
{
if (!init)//利用Schrage算法来进行初始化
{
for (int i = 0; i < size; i++)
{
arr[i] = RandomSchrageInt();
}
init = true;
}
int temp = arr[head] ^ arr[tail] % m;
temp = temp < 0 ? temp + m : temp;
arr[head] = temp;
head = (head + 1) % size;
tail = (tail + 1) % size;
return temp / double(m);
}
double CosRandom()
{
double x = 2 * RandomFibonacci() - 1;
double y = 2 * RandomFibonacci() - 1;
while (x*x + y * y > 1.0)
{
x = 2 * RandomFibonacci() - 1;
y = 2 * RandomFibonacci() - 1;
}
return x;
}
double RandomGauss(double mu, double sigma)
{
return sigma * sqrt(-2 * log(RandomSchrage()))*CosRandom() + mu;
}
void SetSeed(int in)
{
seed = in;
}
//*********************以上部分都是在生成随机数***************************
}<file_sep>#ifndef BOUND
#define BOUND
struct Bound
{
Bound(double l, double u) :lower(l), upper(u) {}
double upper;
double lower;
};
#endif // !BOUND<file_sep>//#include"RandomJS.h"
//#include<iostream>
//#include<fstream>
//#include <iomanip>//目的为高精度输出
//
//#define PI 3.1415926535
//
//#define LENGTH (3013-2900+2)
//int numberOfParticles[LENGTH];//该数组第一个元素(下标为0)储存总粒子数量
//double frequence[LENGTH - 1];
//double max = 0;//记录频率的最大值,便于之后的舍选法使用
//
//using namespace std;
//using namespace randomjs;//使用自己random库的命名空间
//
//double inverse(double in)
//{
// int i = 0;
// while (in > frequence[i])
// {
// i++;
// }
// return i + 2900;
//}
//
//int main()
//{
// clock_t startTime, endTime;
// startTime = clock();
// ifstream in("C:\\Users\\10069\\Desktop\\data.TXT");
// ofstream direct_out(".\\direct.txt");
// ofstream rejection_out(".\\rejection.txt");
// int energy;
// int i = 1;
// while (in >> energy)
// {
// in >> numberOfParticles[i++];
// }
// for (int i = 1; i < LENGTH; i++)
// {
// numberOfParticles[0] += numberOfParticles[i];
// }
//
// //以下是为了建立频率和粒子数目的函数
// frequence[0] = numberOfParticles[1] / (double)(numberOfParticles[0]);
// for (int i = 1; i < LENGTH - 1; i++)
// {
// frequence[i] = frequence[i - 1] + numberOfParticles[i + 1] / double(numberOfParticles[0]);
// if (frequence[i] > max)
// {
// max = frequence[i];
// }
// }
//
// for (int i = 0; i < 1000000; i++)
// {
// direct_out << DirectSampling(inverse) + (RandomFibonacci() - 0.5) * 4 << endl;
// }
//
// for (int i = 0; i < 1000000; i++)
// {
// rejection_out << RejectionSampling([](double x)->double {return double(numberOfParticles[int(x) - 2900 + 1]) / numberOfParticles[0]; }, [](double x)->double {return x * (LENGTH - 1) + 2900; }, [](double x)-> double { return double(max); }) << endl;
// }
//
// direct_out.close();
// rejection_out.close();
// endTime = clock();//计时结束
// cout << "The run time is: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
// getchar();
//}<file_sep>#pragma once
template<unsigned dimension>
class Field
{
public:
Field(double(*f[dimension])())
{
func = f;
}
~Field() = default;
void tick_tock()
{
tick++;
}
double force();
private:
double (*func[dimension])();
double tick;
double density;
};
<file_sep>#pragma once
#include"Field.h"
#include"RandomJS.h"
#include<initializer_list>
#include<iostream>
#include"Vector.h"
using namespace randomjs;
enum MOVE_TYPE
{
ON_GRID, CONTINUOUS_DIRECTION, CONTINUOUS_DISTANCE, CONTINUOUS_ALL
};//四种类型的意义大约写得和丁老师的讲义一样令人易于理解,不需要做任何解释
template<unsigned dimension>
class Particle
{
public:
Particle() = default;//不提供任何构造函数,静待系统合成
Particle(std::initializer_list<double> list) :coordinates(list) {}
Particle(Vector<dimension> &in_vec):coordinates(in_vec) {}
Particle(Vector<dimension> &&in_vec) :coordinates(std::move(in_vec)) {}
Particle& operator= (const Particle& p) { step = p.step; coordinates = p.coordinates; return *this; }
Particle& operator= (const Particle&& p) { step = p.step; coordinates = std::move(p.coordinates); return *this; }
Particle(const Particle& p) :step(p.step), coordinates(p.coordinates) {}
Particle(Particle&& p) :step(p.step), coordinates(std::move(p.coordinates)) {}
~Particle() = default;
Particle& move(MOVE_TYPE type = ON_GRID)//未来有继承此类的考虑
{
double dis = 1.0 / dimension;
int i = 0;
double level = RandomFibonacci();//随机选取一个维度进行行走
double l = step * RandomSchrage();
switch (type)
{
case ON_GRID:
while (i*dis < level)
i++;
if (RandomSchrage() > 0.5)
{
coordinates[i - 1] += step;
}
else
{
coordinates[i - 1] -= step;
}
break;
case CONTINUOUS_DIRECTION:
coordinates += step * RandomVectorOnBall<dimension>()*(2 * RandomSchrage() - 1);
break;
case CONTINUOUS_DISTANCE:
while (i*dis < level)
i++;
if (RandomSchrage() > 0.5)
{
coordinates[i - 1] += l;
}
else
{
coordinates[i - 1] -= l;
}
break;
case CONTINUOUS_ALL:
coordinates += l * RandomVectorOnBall<dimension>()*(2 * RandomSchrage() - 1);
break;
}
return *this;
}
//virtual void move(Field<dimension>&);
double operator[](int i)
{
return coordinates[i];
}
Vector<dimension>& get_position()
{
return coordinates;
}
Vector<dimension> get_position() const
{
return coordinates;
}
bool operator==(const Particle& r)
{
return coordinates == r.coordinates;
}
private:
double step = 1;
Vector<dimension> coordinates;
};
<file_sep>//第三题:尝试抽样一个很奇怪的函数
#include<cstdlib>
#include<iostream>
#include<cmath>
#include"RandomJS.h"
using namespace std;
using namespace randomjs;
#define PI 3.1415926535
double StrangeFunction(double x)
{
if (x<=-1||x>=2)
{
std::cout << "x is out of bound!" << endl;
return 0;
}
else
{
return 1.0 / 2 / PI / pow(2 - x, 5 / 6.0) / pow(x + 1, 1 / 6.0);
}
}
<file_sep>#ifndef SAMPLINGJS
#define SAMPLINGJS
namespace randomjs
{
void BallSurface(double &x, double&y, double&z, double func() = RandomSchrage);
bool BallSurfaceMarsaglia(double &x, double &y, double &z);
double DirectSampling(double inversedFunc(double));//直接抽样方法,需要输入目标分布的累积分布函数的反函数
double RejectionSampling(double func(double), double sample(double), double compare(double));//简单分布的变换抽样和舍选法抽样,输入分别为待抽变量,分布函数,比较函数,比较函数的抽样
}
#endif // !SAMPLINGJS
<file_sep>#pragma once
#include"Particle.h"
template<unsigned dimension>
class Rod
{
public:
Rod(double len=1) :length(len) {}
~Rod() = default;//Vector写得好点这里就可以省事
void move(MOVE_TYPE type=CONTINUOUS_DIRECTION)
{
Particle<dimension> tempa = center.get_position() + 1.0 / 2 * length*direction;
Particle<dimension> tempb = center.get_position() - 1.0 / 2 * length*direction;
tempa.move(type);
tempb.move(type);
direction += tempa.get_position()-(center.get_position() + 1.0 / 2 * length*direction);
direction -= tempb.get_position()-(center.get_position() - 1.0 / 2 * length*direction);
center.get_position() = (tempa.get_position() + tempb.get_position()) / 2;
direction /= direction.length();
direction *= length;
}
Vector<dimension> get_direction()
{
return direction / length;
}
//private:
Particle<dimension> center;
Vector<dimension> direction;
double length = 3;
};
| d6e7523975efb191a58b45d59f18e668930478e9 | [
"Markdown",
"C",
"C++"
] | 23 | C++ | Jerry-Shen0527/Computing-Physics | 7a849c7e5297dc41c64fa79d70a154f5506a15a0 | b2e02745d1644e7cb3b80ec6f871ac5f5596b7ac |
refs/heads/main | <file_sep>#!/usr/bin/env python
import setuptools
import site
import sys
from numpy.distutils.core import setup, Extension
site.ENABLE_USER_SITE = True
setup(
name="mask-generation",
version="0.0.1",
ext_modules=[Extension('pre_processing', sources=['src/mask_interpolation.f90'])],
install_requires=['pyevtk'],
)
<file_sep>=====================
Gallery of examples
=====================
This page contains an overview of the examples contained in the `source code
repository <https://github.com/ly16302/mask/tree/main/docs/examples/>`_.
Example 1: Generate mask file for Lamp
.. figure:: https://github.com/ly16302/mask/blob/main/_static/lamp_3.png
The result of Example 1.
See the `source code of Example 1 <https://github.com/ly16302/mask/tree/main/docs/examples/Lamp_3.py>`_ for more information.
Submodules
----------
examples.Lamp\_3 module
-----------------------
.. automodule:: examples.Lamp_3
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: examples
:members:
:undoc-members:
:show-inheritance:
<file_sep>"""
This example showcases:
- using a points to generate masks
"""
import stltovoxel
from pre_processing import mask
import numpy as np
from pyevtk.hl import gridToVTK
stltovoxel.convert_file('3-lamp.stl','resolution',100,'output.npy') #generate a voxel numpy file
point=np.load("output.npy")
n=5
nxd=15*n
nyd=18*n
nzd=100*n
nxp=nxd+1
nyp=nyd+1
nzp=nzd+1
xp=np.linspace(0,150,nxp)
yp=np.linspace(0,180,nyp)
zp=np.linspace(0,1000,nzp)
mask1=mask.mask_interpolation_non_uniform (point,xp,yp,zp)
gridToVTK("mask1",xp,yp,zp,cellData = {"mask1":mask1})
np.save('result',mask1)
<file_sep># mask-generation
mask generation library for wyvern

[](https://ly16302.github.io/mask/)
[](https://pypi.org/project/mask-generation/)
[](https://pepy.tech/project/mask-generation)
|| **Linux** | **OS X** | **Windows** | **Documentation**|
|:------|:-----|:-----|:-----|:-----|
|**Build**| ✅ | ✅ | ✅ | ✅ |
|**PyPI** | ✅ | ✅ | ✅ | ✅ |

## Dependancies
```bash
pip install pyevtk
pip install git+https://github.com/ly16302/stl-to-voxel.git
```
## Installation
The most recent release can be installed simply by
```bash
pip install mask-generation
```
| b3f88a9af9a48b76d730901112331bf8899654ce | [
"Markdown",
"Python",
"reStructuredText"
] | 4 | Python | ly16302/mask | 3a50258a97b004a9a3ff9a42a13ee2d919bef0a6 | 792b6eddab147d9163962ca10601c81206621c83 |
refs/heads/master | <file_sep>
import pytz
from datetime import datetime
# pip install Zipline if you dont have it
from Zipline.api import order, symbol, record, order_target
from Zipline.algorithm import TradingAlgorithm
from Zipline.utils.factory import load_bars_from_yahoo
import pyexcel
# Load data manually from Yahoo! finance
start = datetime(2011, 1, 1, 0, 0, 0, 0, pytz.utc).date()
end = datetime(2012,1,1,0,0,0,0, pytz.utc).date()
data = load_bars_from_yahoo(stocks=['SPY'], start=start,end=end)
#code
def initialize(context):
context.security = symbol('SPY')
#code
#code
def handle_data(context, data):
MA1 = data[context.security].mavg(50)
MA2 = data[context.security].mavg(100)
date = str(data[context.security].datetime)[:10]
current_price = data[context.security].price
current_positions = context.portfolio.positions[symbol('SPY')].amount
cash = context.portfolio.cash
value = context.portfolio.portfolio_value
current_pnl = context.portfolio.pnl
#MA1 = data[context.security].mavg(50)
#code (this will come under handle_data function only)
if (MA1 > MA2) and current_positions == 0:
number_of_shares = int(cash/current_price)
order(context.security, number_of_shares)
record(date=date,MA1 = MA1, MA2 = MA2, Price=
current_price,status="buy",shares=number_of_shares,PnL=current_pnl,cash=cash,value=value)
elif (MA1 < MA2) and current_positions != 0:
order_target(context.security, 0)
record(date=date,MA1 = MA1, MA2 = MA2, Price= current_price,status="sell",shares="--",PnL=current_pnl,cash=cash,value=value)
else:
record(date=date,MA1 = MA1, MA2 = MA2, Price= current_price,status="--",shares="--",PnL=current_pnl,cash=cash,value=value)
#code
algo_obj = TradingAlgorithm(initialize=initialize,handle_data=handle_data)
perf_manual = algo_obj.run(data)
perf_manual[["MA1","MA2","Price"]].plot()
| 4ebd0268dc7d3f1c5ac634a4d749d9281fb49b09 | [
"Python"
] | 1 | Python | jamesthesnake/PythonFinance | 23315940b01837f4ccf55fe7e933e252497573fe | 1e9e956c052d98affa754b9c753383809c9d5374 |
refs/heads/master | <file_sep>var angular = require('angular');
var ngModule = angular.module('myapp', []);
console.log(ngModule);
console.log('success woohoo');
<file_sep>var gulp = require('gulp');
var gulpWebpack = require('gulp-webpack');
var path = require('path');
var merge = require('merge');
var fs = require('fs-extra');
var argv = require('yargs').argv;
var browserSync = require('browser-sync');
var browserSyncActive = false;
/** default run for building for distribution **/
gulp.task('default', ['copy-index'], function() {
return gulp.src('index.js')
.pipe(gulpWebpack(require('./webpack.config.js')))
.pipe(gulp.dest('dist'))
.pipe(browserSync.reload({stream: true}));
});
/** run and serve the app with a --watch option for development **/
gulp.task('run', function() {
if (!browserSyncActive) {
browserSync.init({
server: 'dist/',
port: 8888
});
browserSyncActive = true;
if (argv.watch) {
gulp.watch('app/**', ['default', browserSync.reload]);
}
}
});
/** 1: clean /dist/ **/
gulp.task('clean', function(done) {
fs.remove(path.join(__dirname, 'dist'), done);
});
/** 2: copy index page as is **/
gulp.task('copy-index', ['clean'], function() {
gulp.src('./app/index.html')
.pipe(gulp.dest('./dist'));
});
/** 3: copy Foundation or other UI library to app; commented out as it is not used **/
// gulp.task('copyUiLib', function() {
// gulp.src('./node_modules/foundation-sites/scss/**')
// .pipe(gulp.dest('./app/lib/ui'));
// });
<file_sep>require('./app/app');
require('./index.scss');<file_sep># angular-webpack-gulp-boilerplate
An easy and quick starter for my personal projects. Uses webpack and gulp for Angular projects. BrowserSync integrated for local development. For quick prototyping, Foundation is included as the default UI library. Simply remove `@import "./app/lib/ui/foundation"` in index.scss to exclude from build if it is not needed.
## Installation
`npm install`
Install all dependancies
##Usage
`gulp`
Build and compile the project with webpack to /dist
`gulp run`
Run the app locally via browserSync
`gulp run --watch`
Run the app locally and watch for code changes in /app. Use for active development
---
[Cheri @cyh.io](http://www.cyh.io/)
<file_sep>var ExtractTextPlugin = require("extract-text-webpack-plugin");
var config = {
resolve: {
packageMains: ['webpack', 'web', 'main']
},
entry: {
index: ['./index.js']
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
publicPath: "/dist/"
},
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader','css-loader!sass-loader')
}
]
},
plugins: [
new ExtractTextPlugin("[name].css")
]
};
module.exports = config; | 08004102934f58462492286b3a15d31ffaca2cac | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | cherihung/angular-webpack-gulp-boilerplate | 3daa1c325eaca86c490a98793655604a60f5c8d8 | 5fdedb745e83d839b512aa7313e485373354cac3 |
refs/heads/master | <file_sep>import React from 'react';
const Intro = (props) => {
const currentDate = () => {
const date = new Date();
return (<p>{date.toDateString()}</p>)
}
return (
<div>
<h2>{props.msg} </h2>
{currentDate()}
</div>
);
}
export default Intro;<file_sep>import React, { Component } from 'react';
import Intro from './Intro/Intro'
import ShowList from './ShowList/ShowList';
import './App.css';
class App extends Component {
state = {
series: [
],
seriesName: "",
isFetching: false
}
// componentDidMount () {
// fetch("http://api.tvmaze.com/search/shows?q=Vikings")
// .then(response => response.json())
// .then(json => this.setState({series:json}))
// }
showSearchHandler = (event) =>{
this.setState ({seriesName:event.target.value, isFetching:true})
fetch(`http://api.tvmaze.com/search/shows?q=${event.target.value}`)
.then(response => response.json())
.then(json => this.setState({series:json, isFetching:false}))
// console.log(event);
// console.log(event.target.value);
}
render() {
const {series, seriesName, isFetching} = this.state;
return (
<div className="App">
<Intro msg= "Welcome to Movie Mart!"/>
<p> The length of the series array - {this.state.series.length}</p>
<input type="Text" value= {seriesName} onChange ={this.showSearchHandler}/>
{
isFetching && <p> Loading ...</p>
}
{
!isFetching && <ShowList showList = {series} seriesname ={seriesName}/>
}
</div>
);
}
}
export default App;
| 3534d1560083639d90d272fb40f0401cb93f1002 | [
"JavaScript"
] | 2 | JavaScript | uday625/Movie-Mart | 8907b7623de4efc670b62b3356ebe607dd413b8b | e671870eee09fb90ff5484f377519c56e6725fc5 |
refs/heads/master | <file_sep>###############################################################################
# Plot #1
# Coursera - Exploratory Data Analysis - Course Project #1
# <NAME>
# 2014-07-12
# Data source : https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
###############################################################################
# Set working directory
setwd("N:/Data Science/04 EDA/cp1")
# Change local regional setting
Sys.setlocale("LC_TIME", "English")
# Import the fle
filename = "household_power_consumption.txt"
data <- read.csv(filename,
sep = ";",
header = TRUE,
skip = 0,
na.strings = "?",
dec = ".")
# Subset the required date
power.cons <- data[data$Date == "1/2/2007" | data$Date == "2/2/2007",]
# Format to DateTime
power.cons$test <- paste(power.cons$Date, power.cons$Time, sep=" ")
power.cons$DateTime <- strptime(power.cons$test, format="%d/%m/%Y %H:%M:%S")
power.cons <- power.cons[-10]
# Construct the plot and save it to a PNG file
png(filename="plot1.png", width=480, height=480)
hist(power.cons$Global_active_power,
col="red",
main="Global Active Power",
xlab="Global Active Power (kilowatts)")
dev.off()
<file_sep>### Coursera - Exploratory Data Analysis
#### Project Course #1
This repository contains the files required for the Course Project #1.
There are four PNG files and four R code files. Each R code file creates a plot saved in a PNG file.
* plot1.png
* plot1.R
* plot2.png
* plot2.R
* plot3.png
* plot3.R
* plot4.png
* plot4.R
Data source : https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
| b005b47b6a5a2640db1c9dcb57e0d4f0badc9a7d | [
"Markdown",
"R"
] | 2 | R | mm14770/EDA_CourseProject1 | 0d389c8685922cc49cb0d310b61d08d64b2d607b | e71dc88eafe8f46b193e6db3a08418c0222c895e |
refs/heads/master | <repo_name>soorichu/geogebra<file_sep>/web/src/main/java/org/geogebra/web/web/gui/layout/panels/ToolbarDockPanelW.java
package org.geogebra.web.web.gui.layout.panels;
import org.geogebra.common.main.App;
import org.geogebra.web.web.gui.layout.DockPanelW;
import org.geogebra.web.web.gui.toolbarpanel.ToolbarPanel;
import com.google.gwt.user.client.ui.Widget;
public class ToolbarDockPanelW extends DockPanelW {
private static final int CLOSING_WIDTH = 86;
private ToolbarPanel toolbar;
public ToolbarDockPanelW(App app1) {
super(
App.VIEW_ALGEBRA, // view id
"ToolbarWindow", // view title phrase
null, // toolbar string
false, // style bar?
2, // menu order
'A' // menu shortcut
);
}
@Override
protected Widget loadComponent() {
toolbar = new ToolbarPanel(app);
return toolbar;
}
@Override
public void onResize() {
if (toolbar.getOffsetWidth() < CLOSING_WIDTH) {
toolbar.close();
} else {
toolbar.open();
}
}
public ToolbarPanel getToolbar() {
return toolbar;
}
}
<file_sep>/desktop/src/main/java/org/geogebra/desktop/geogebra3D/euclidian3D/printer3D/ExportToPrinter3DD.java
package org.geogebra.desktop.geogebra3D.euclidian3D.printer3D;
import java.io.BufferedWriter;
import java.io.IOException;
import org.geogebra.common.geogebra3D.euclidian3D.EuclidianView3D;
import org.geogebra.common.geogebra3D.euclidian3D.openGL.ManagerShadersElementsGlobalBuffer;
import org.geogebra.common.geogebra3D.euclidian3D.printer3D.ExportToPrinter3D;
public class ExportToPrinter3DD extends ExportToPrinter3D {
private BufferedWriter objBufferedWriter;
/**
* start file
*
* @param writer
* file writer
* @param view
* 3D view
* @param manager
* geometries manager
*/
public void startFile(BufferedWriter writer, EuclidianView3D view,
ManagerShadersElementsGlobalBuffer manager) {
objBufferedWriter = writer;
set(view, manager);
}
@Override
protected void printToFile(String s) {
// System.out.print(s);
try {
objBufferedWriter.write(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/common/src/main/java/org/geogebra/common/io/latex/BracketsAdapter.java
package org.geogebra.common.io.latex;
public class BracketsAdapter {
public String transformBrackets(String left, String base, String right) {
if ("[".equals(left) && base.contains("...")) {
String[] parts = base.split(",");
if (parts.length == 1) {
parts = base.split("...");
}
return "(" + parts[0] + "..." + parts[parts.length - 1] + ")";
}
return left + base + right;
}
}
<file_sep>/web/src/main/java/org/geogebra/web/web/euclidian/ContextMenuPopup.java
package org.geogebra.web.web.euclidian;
import org.geogebra.common.awt.GPoint;
import org.geogebra.common.euclidian.EuclidianController;
import org.geogebra.common.euclidian.event.PointerEventType;
import org.geogebra.web.html5.gui.GPopupPanel;
import org.geogebra.web.html5.gui.util.ClickEndHandler;
import org.geogebra.web.html5.gui.util.ClickStartHandler;
import org.geogebra.web.html5.main.AppW;
import org.geogebra.web.web.gui.ContextMenuGeoElementW;
import org.geogebra.web.web.gui.GuiManagerW;
import org.geogebra.web.web.gui.images.AppResources;
import org.geogebra.web.web.gui.images.ImgResourceHelper;
import org.geogebra.web.web.gui.util.MyCJButton;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
public class ContextMenuPopup extends MyCJButton
implements CloseHandler<GPopupPanel> {
private static final int GAP_Y = 5;
private EuclidianController ec;
private GPoint location;
private boolean menuShown = false;
private AppW app;
ContextMenuGeoElementW popup;
public ContextMenuPopup(AppW app) {
super();
this.app = app;
ImgResourceHelper.setIcon(AppResources.INSTANCE.dots(), this);
ec = app.getActiveEuclidianView().getEuclidianController();
location = new GPoint();
updateLocation();
createPopup();
addStyleName("MyCanvasButton-borderless");
}
private void updateLocation() {
int x = getAbsoluteLeft();
int y = getAbsoluteTop() + getOffsetHeight() + GAP_Y;
location.setLocation(x, y);
}
private void createPopup() {
popup = ((GuiManagerW) app.getGuiManager())
.getPopupMenu(ec.getAppSelectedGeos());
popup.getWrappedPopup().getPopupPanel().addCloseHandler(this);
// addClickHandler(this);
ClickStartHandler.init(this, new ClickStartHandler(false, true) {
@Override
public void onClickStart(int x, int y, PointerEventType type) {
showMenu();
}
});
ClickEndHandler.init(this, new ClickEndHandler(false, true) {
@Override
public void onClickEnd(int x, int y, PointerEventType type) {
// only stop
}
});
}
public void showMenu() {
updateLocation();
popup.update();
popup.show(location);
ImgResourceHelper.setIcon(AppResources.INSTANCE.dots_active(), this);
menuShown = true;
}
public void hideMenu() {
menuShown = false;
ImgResourceHelper.setIcon(AppResources.INSTANCE.dots(), this);
}
public void onClose(CloseEvent<GPopupPanel> event) {
hideMenu();
}
public boolean isMenuShown() {
return menuShown;
}
public void close() {
popup.getWrappedPopup().hide();
}
}
| b22f2c2918c9b1e489d18a002fca7bd58c56c1ef | [
"Java"
] | 4 | Java | soorichu/geogebra | 0102351af70949217e884de6866e6a7e57680bc9 | 606ef13fe4f3aab15018178459b1dde160bb6002 |
refs/heads/master | <repo_name>CocoZohan/TipaBrowser_v3<file_sep>/src/com/example/TipaBrowser_v3/WebViewClass.java
package com.example.TipaBrowser_v3;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.app.Activity;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.FileOutputStream;
/**
* Created by Dos on 24.06.2014.
*/
public class WebViewClass extends Activity implements View.OnClickListener {
final String LOG_TAG = "myLogs";
DBControlClass dbControlClass;
MyOnTouchListener touchListener;
WebView webView;
boolean firstPage;
public int sessionNo, urlNo;
AlertDialogClass alertDialogClass;
Button btnGoToMain, btnGoToAllPages;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_layout);
btnGoToAllPages = (Button)findViewById(R.id.buttonGoToUrls);
btnGoToMain = (Button)findViewById(R.id.buttonGoToMain);
btnGoToMain.setOnClickListener(this);
btnGoToAllPages.setOnClickListener(this);
firstPage = true;
dbControlClass = new DBControlClass(this);
alertDialogClass = new AlertDialogClass();
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
Intent intent = getIntent();
Uri data = intent.getData();
String initialPage = intent.getStringExtra("initialUrl");
webView.loadUrl(data.toString());
touchListener = new MyOnTouchListener(this);
webView.setWebViewClient(new MyWebViewClient());
webView.setOnTouchListener(touchListener);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonGoToMain:
onPause();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent.addFlags(intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
break;
case R.id.buttonGoToUrls:
onPause();
alertDialogClass.showDialog(this, dbControlClass.returnUrlInSession(sessionNo));
if(alertDialogClass.itemClicked){
webView.loadUrl(dbControlClass.readUrlFromDB(alertDialogClass.itemNo, sessionNo));
}
}
}
private class MyWebViewClient extends WebViewClient{
@Override
// show the web page in webview but not in web browser
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
}
@Override
public void onPageStarted(WebView view, String url, Bitmap facIcon) {
Log.d(LOG_TAG, url);
if(firstPage) {
sessionNo = dbControlClass.findEmptySession();
urlNo = 0;
dbControlClass.insertSessionIntoDB(sessionNo, url);
firstPage = false;
}
urlNo++;
dbControlClass.insertUrlIntoDB(url, sessionNo, urlNo);
}
}
private class MyOnTouchListener extends OnSwipeTouchListener {
public MyOnTouchListener(Context ctx) {
super(ctx);
}
public void onSwipeRight() {
if(webView.canGoBack()){
webView.goBack();
}
}
public void onSwipeLeft() {
if(webView.canGoForward()){
webView.goForward();
}
}
public void onSwipeBottom() {
//webView.reload();
}
}
}
<file_sep>/src/com/example/TipaBrowser_v3/MainActivity.java
package com.example.TipaBrowser_v3;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener{
/**
* Called when the activity is first created.
*/
Button btnGo;
EditText editTextUrl;
Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextUrl = (EditText)findViewById(R.id.editText);
btnGo = (Button)findViewById(R.id.buttonGo);
btnGo.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String address = "http://" + editTextUrl.getText().toString() + "/";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(address));
intent.putExtra("initialUrl", editTextUrl.getText().toString());
startActivity(intent);
}
}
| 3f16758e6f8fa4af3c330d665ee5ef072ecc29f2 | [
"Java"
] | 2 | Java | CocoZohan/TipaBrowser_v3 | 2810c77903ab2285a68fb0cbfafc85145db457c2 | 60c7e70f710b0657b595de34336921832e5f8f44 |
refs/heads/master | <repo_name>AT-main/Flask_project<file_sep>/README.md
# Flask_project
Website implemented for Heating systems manufacturing company
languages: English, Persian
Technologies used:
Back-end: Python, Flask, request, response
Front-end: HTML5, CSS3, JavaScript
Database: sqlite3
<file_sep>/package_selection.py
from flask import Flask, render_template, request, jsonify, make_response
import sqlite3
import datetime
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "cities.db")
log_path = os.path.join(BASE_DIR, "logfile.txt")
static_path = os.path.join(BASE_DIR, "static")
app = Flask(__name__)
def log_report(*args, **kwargs):
if kwargs.get('value', 0):
with open(log_path, 'w') as f:
f.write('Last run: ' + str(datetime.datetime.now()) + '\n\n')
return
with open(log_path, 'a', encoding='utf8') as log_file:
count = 0
for key, value in kwargs['report_dict'].items():
if type(value) == float:
txt = '{0:^6} >> {1:^8.2f}|'.format(key, value)
else:
txt = '{0:^6} >> {1:^8}|'.format(key, value)
count += 1
if not (count % 4):
txt += '\n\n'
log_file.write(txt)
def replace_values_in_text(text, param_char, param_val):
if text == None:
return
output_text = text
if type(param_val) == str:
output_text = output_text.replace(
' '+param_char, ' '+param_val)
else:
output_text = output_text.replace(
param_char, str(int(float(param_val))))
return output_text
@app.route('/package-form/')
def select_package():
# this line was added only to test make_response functionality
resp = make_response(render_template('package-form.html'))
# resp.set_cookie('UserID', 'No users yet') # cookies can be set using make_response
return resp
@app.route('/index/')
def index_page():
# this line was added only to test make_response functionality
resp = make_response(render_template('index.html'))
# resp.set_cookie('UserID', 'No users yet') # cookies can be set using make_response
return resp
@app.route('/home-fa/')
def home_page_fa():
# this line was added only to test make_response functionality
resp = make_response(render_template('home_fa.html'))
# resp.set_cookie('UserID', 'No users yet') # cookies can be set using make_response
return resp
@app.route('/home-en/')
def home_page_en():
db_connect = sqlite3.connect(db_path)
cursor = db_connect.cursor()
cursor.execute('SELECT * FROM MiscTexts WHERE title=?', ('Intro_en',))
intro = cursor.fetchone()
cursor.close()
return render_template('home_en.html', intro=intro[3])
@app.route('/downloads/')
def downloads_page():
# this line was added only to test make_response functionality
resp = make_response(render_template('downloads_fa.html'))
# resp.set_cookie('UserID', 'No users yet') # cookies can be set using make_response
return resp
@app.route('/products/')
def products_page():
db_connect = sqlite3.connect(db_path)
cursor = db_connect.cursor()
cursor.execute('SELECT * FROM Products')
products = cursor.fetchall()
cursor.close()
columns_lables = ['ردیف', 'محصول', 'شرح', 'تعداد مدلهای ظرفیتی', 'محدوده ظرفیت', 'حداکثر فشار کاری', 'حداکثر دمای کاری',
'تکنیک عملکرد', 'راندمان احتراقی', 'ذخیره آبگرم مصرفی', 'جنس', 'محدوده دمای خط گرمایش از کف']
products.insert(0,columns_lables)
for i in range(1,len(products)):
products[i] = products[i][:12] + (('/static/' + products[i][12]),)
print(products[1][12])
return render_template('products_fa.html', products=products)
@app.route('/articles/')
def articles_page():
db_connect = sqlite3.connect(db_path)
cursor = db_connect.cursor()
cursor.execute('SELECT * FROM Articles')
articles = cursor.fetchall()
cursor.close()
articleArray = []
for article in articles:
articleObj = {}
articleObj['id'] = article[0]
articleObj['title'] = article[1]
articleObj['summary'] = article[2][:1000] + ' ...'
articleArray.append(articleObj)
return render_template('articles_fa.html', articles=articleArray)
@app.route('/recommend-package', methods=['POST', 'GET'])
def recommed_package():
if request.method == 'POST':
form_result = request.form
print(form_result)
db_connect = sqlite3.connect(db_path)
cursor = db_connect.cursor()
cursor.execute('SELECT * FROM Cities WHERE City=?',
(form_result['city'],))
city = cursor.fetchone()
# for c in city:
k5 = city[3]
k6 = city[4]
_city = city[2]
print(_city)
# city.close()
Ans5 = int(form_result['Ans5'])
Ans5_list = [0, 1, 1.3, 1.6, 2, 0.8]
k1 = Ans5_list[Ans5]
Ans7 = int(form_result['Ans7'])
if Ans7 == 4:
n = 0
else:
n = Ans7
Ans8 = int(form_result['Ans8'])
if Ans8 == 1:
k2 = 1
else:
k2 = 0.93
Ans9 = int(form_result['Ans9'])
if Ans9 == 1:
k3 = 1
else:
k3 = 1.15
k4 = 1 + (0.02 * k5)
k7 = 1 + (0.00014 * k6)
Area = abs(int(form_result['area']))
P = int(Area * k1 * k2 * k3 * k4 * 120)
Q = P + int(n * 12023)
R = P + int(n * 8516)
S = P + int(n * 6777)
if P <= 12000:
B = 1.5
else:
B = 0.000122 * P
c_dict = {'CP36': 36, 'CP45': 45, 'CP65': 65,
'CP85': 85, 'CP125': 125, 'CP160': 160, 'CP200': 200}
f_dict = {'28000': 27.5, '32000': 31.5, '36000': 35.5,
'39000': 38, '45000': 44.5, '50000': 49, '54000': 53}
h_dict = {'18': 15, '24': 20, '28': 23.5,
'32': 27, '36': 30.5, '40': 33.5}
if S > 200000:
C = ''
D = 0
else:
for key, value in c_dict.items():
if S <= value * 1000:
C = key
D = value * 1000
break
if S > 53000:
G = ''
else:
for key, value in f_dict.items():
if S <= value * 1000:
G = key
break
E = 0.000128 * k7 * Q
if R > 53000:
F = 0
else:
for key, value in f_dict.items():
if R <= value * 1000:
F = key
break
F1 = 0.000119 * k7 * Q
if P > 33500:
H = ''
else:
for key, value in h_dict.items():
if P <= value * 1000:
H = key
break
if R > 200000:
I = ''
O = 0
else:
for key, value in c_dict.items():
if R <= value * 1000:
I = key
O = value * 1000
break
J = 0.000128 * k7 * R
K = 0.000128 * k7 * S
if Q > 53000:
L = ''
else:
for key, value in f_dict.items():
if Q <= value * 1000:
L = key
break
if P > 53000:
M = ''
else:
for key, value in f_dict.items():
if P <= value * 1000:
M = key
break
Q1 = 0.000119 * k7 * R
T = 0.000119 * k7 * S
if P > 200000:
U = ''
V = 0
Z1 = ''
else:
for key, value in c_dict.items():
if P <= value * 1000:
U = key
V = value * 1000
Z1 = key + '-S'
break
W = 0.000122 * P
X = 0.000128 * k7 * P
Y1 = k7 * S
Y2 = k7 * R
Y3 = k7 * P
Z = 0.000119 * k7 * P
Ans1 = int(form_result['Ans1'])
Ans3 = int(form_result['Ans3'])
Ans4 = int(form_result['Ans4'])
Ans7 = int(form_result['Ans7'])
combi = [Ans4, Ans1, Ans3, Ans7]
print('combination is', combi)
cursor.execute(
'SELECT * FROM Combinations WHERE combi=?', (str(combi),))
combination = cursor.fetchone()
parts = []
parts.append(eval(combination[2]))
parts.append(eval(combination[3]))
parts.append(eval(combination[4]))
report_list = ['Area', '_city',
'Ans1', 'Ans3', 'Ans4', 'Ans5', 'Ans7', 'Ans8', 'Ans9',
'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7',
'P', 'Q', 'R', 'S',
'B', 'C', 'D', 'E', 'F', 'F1', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'O', 'Q1', 'T', 'U', 'V',
'W', 'X', 'Y1', 'Y2', 'Y3', 'Z', 'Z1']
log_report(value='erase')
report_dict = {}
for param in report_list:
report_dict[param] = eval(param)
log_report(report_dict=report_dict)
####################################################################################################
# for loops #
####################################################################################################
result = []
for part in parts:
temp = {}
short_text_list = []
print('>>>>> This part includes: ', part, ' <<<<<')
for text_id in part:
print('text_id is:', text_id)
# db_connect = sqlite3.connect(db_path)
cursor = db_connect.cursor()
cursor.execute(
'SELECT * FROM OutputTexts WHERE id=?', (text_id,))
text = cursor.fetchone()
cursor.close()
content = text[1]
condition = eval(text[2])
params = eval(text[3])
short_text = text[4]
if not (condition):
print('condition for text', text_id,
':<<', text[2], '>> is not met')
continue
output_text = content
for item in params:
# if type(eval(item)) == str:
# output_text = output_text.replace(
# item, eval(item)) + '\n\n\n'
# else:
# output_text = output_text.replace(
# item, str(int(float(eval(item))))) + '\n\n\n'
output_text = replace_values_in_text(
output_text, item, eval(item))
short_text = replace_values_in_text(
short_text, item, eval(item))
temp[text_id] = output_text
if short_text != None:
short_text_list.append(short_text)
result.extend([temp, short_text_list])
print('number of texts', len(result))
return render_template('recommend-package.html', result=result)
else:
return render_template('package-form.html')
"""
----------------------------------------------------------------------------------------------------------------------------
"""
##############################################################################################################################
@app.route('/states/')
def return_states():
db_connect = sqlite3.connect(db_path)
cursor = db_connect.cursor()
cursor.execute('SELECT * FROM States')
states = cursor.fetchall()
cursor.close()
# for state in states:
# print(state[0])
stateArray = []
for state in states:
stateObj = {}
stateObj['id'] = state[0]
stateObj['name'] = state[1]
stateArray.append(stateObj)
states_json = jsonify({'states': stateArray})
return states_json
@app.route('/cities/<province>/')
def return_cities(province):
print('>>> {} <<<'.format(province))
db_connect = sqlite3.connect(db_path)
cursor = db_connect.cursor()
cursor.execute('SELECT * FROM States WHERE id=?', (province,))
state = cursor.fetchone()[1]
cursor.execute('SELECT * FROM Cities WHERE State=? ORDER BY Id', (state,))
cities = cursor.fetchall()
cursor.close()
cityArray = []
for city in cities:
cityObj = {}
cityObj['id'] = city[0]
cityObj['name'] = city[2]
cityArray.append(cityObj)
cities_json = jsonify({'cities': cityArray})
return cities_json
app.add_url_rule('/', '/index/', index_page)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
| a58caa097f49e77840f386cfc1e1e5634f94a151 | [
"Markdown",
"Python"
] | 2 | Markdown | AT-main/Flask_project | f92818f61d1bf47e6efe71eca9fed521491c367a | eb144276533487a9e112bcea9da5061d9d4de57a |
refs/heads/master | <file_sep>
import java.util.Scanner;
public class _11720 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int input = sc.nextInt();
String ss = sc.next();
char a;
int sum=0;
for(int i=0;i<input;i++) {
a = ss.charAt(i);
int temp = (int)a-48;
sum+=temp;
}
System.out.println(sum);
}
}
<file_sep>import java.util.Scanner;
import java.util.Stack;
public class _10828 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < n; i++) {
String temp = sc.next();
switch (temp) {
case "push":
int a = sc.nextInt();
st.push(a);
break;
case "pop":
if (st.empty())
System.out.println(-1);
else
System.out.println(st.pop());
break;
case "size":
System.out.println(st.size());
break;
case "empty":
if (st.empty())
System.out.println(1);
else
System.out.println(0);
break;
case "top":
if (st.empty())
System.out.println(-1);
else
System.out.println(st.peek());
break;
}
}
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
public class _2960 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
boolean[] arr = new boolean[n + 1];
Arrays.fill(arr, true);
int cnt = 0;
boolean check = false;
for (int i = 2; i <= n; i++) {
for (int j = 1; i * j <= n; j++) {
if (arr[i * j]) {
arr[i * j] = false;
cnt++;
if (cnt == k) {
System.out.println(i * j);
check = true;
break;
}
}
}
if (check)
break;
}
}
}
<file_sep>
import java.util.Scanner;
public class _11654 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
int aaa = input.charAt(0);
System.out.println((int)aaa);
}
}
<file_sep>
import java.util.Scanner;
public class _11729 {
static int result=0;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
hanoi(input,1,2,3);
System.out.println(result);
System.out.println(sb);
}
private static void hanoi(int n,int from,int by,int to) {
result++;
if(n==1)
sb.append(from+" "+to+"\n");
else {
hanoi(n-1,from,to,by);
sb.append(from+" "+to+"\n");
hanoi(n-1,by,from,to);
}
}
}
<file_sep>import java.util.Scanner;
public class _9095 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int temp = sc.nextInt();
int[] dp = new int[temp + 1];
if(temp >= 1)
dp[1] = 1;
if(temp>=2)
dp[2] = 2;
if(temp>=3)
dp[3] = 4;
for (int j = 4; j <= temp; j++)
dp[j] = dp[j - 1] + dp[j - 2] + dp[j - 3];
System.out.println(dp[temp]);
}
}
}
<file_sep>
import java.util.Scanner;
public class _2446 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
int temp = 2 * n - 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < temp; j++) {
if (i <= j && j < temp - i) {
System.out.print("*");
if(i==n-1)
continue;
sb.append("*");
}
else {
System.out.print(" ");
sb.append(" ");
}
}
System.out.println();
if(i==n-1) continue;
else
sb.append("\n");
}
sb.reverse();
sb.delete(0, temp);
System.out.println(sb);
/*Scanner sc = new Scanner(System.in);
final int N = sc.nextInt();
for(int i = N-1; i >= 0 ; i--) {
for(int j = 1; j < N-i; j++)
System.out.print(" ");
for(int j = 0; j < i*2+1; j++)
System.out.print("*");
System.out.println();
}
for(int i = 1; i < N ; i++) {
for(int j = 1; j < N-i; j++)
System.out.print(" ");
for(int j = 0; j < i*2+1; j++)
System.out.print("*");
System.out.println();
}*/
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
public class _5576 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr1 = new int[10];
int[] arr2 = new int[10];
for (int i = 0; i < 10; i++)
arr1[i] = sc.nextInt();
for (int i = 0; i < 10; i++)
arr2[i] = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
Arrays.parallelSort(arr1);
Arrays.parallelSort(arr2);
sum1 = arr1[9] + arr1[8] + arr1[7];
sum2 = arr2[9] + arr2[8] + arr2[7];
System.out.println(sum1 + " " + sum2);
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _1012 {
static boolean[][] map;
static int cnt;
static boolean[][] visit;
static int mr[] = { 0, 0, -1, 1 };
static int mc[] = { 1, -1, 0, 0 };
static int m;
static int n;
private static void dfs(int r, int c) {
visit[r][c] = true;
for (int i = 0; i < 4; i++) {
int rtemp = r + mr[i];
int ctemp = c + mc[i];
if (ctemp >= 0 && rtemp >= 0 && ctemp < m && rtemp < n) {
if (map[rtemp][ctemp] == true && !visit[rtemp][ctemp])
dfs(rtemp, ctemp);
}
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
cnt = 0;
st = new StringTokenizer(br.readLine());
m = Integer.parseInt(st.nextToken());
n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
map = new boolean[n][m];
visit = new boolean[n][m];
while (k-- > 0) {
st = new StringTokenizer(br.readLine());
int c = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
map[r][c] = true;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == true && !visit[i][j]) {
cnt++;
dfs(i, j);
}
}
}
System.out.println(cnt);
}
}
}
<file_sep>import java.util.Scanner;
public class _2921 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = 0;
for (int i = 0; i <= n; i++) {
for (int j = i; j <= n; j++)
result = result + i + j;
}
System.out.println(result);
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
public class _2309 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = new int[9];
int sum = 0;
for (int i = 0; i < 9; i++) {
arr[i] = sc.nextInt();
sum += arr[i];
}
Arrays.parallelSort(arr);
int temp;
boolean check = false;
for (int i = 8; i >= 0; i--) {
temp = sum - arr[i];
for (int j = 8; j >= 0; j--) {
if (i == j)
continue;
temp -= arr[j];
if (temp == 100) {
arr[i] = 0;
arr[j] = 0;
check = true;
break;
} else
temp += arr[j];
}
if (check)
break;
}
for (int i = 0; i < 9; i++) {
if (arr[i] != 0) {
System.out.println(arr[i]);
}
}
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class _8979 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] num = new int[n];
int find = 1;
for (int i = 0; i < n; i++) {
String temp = br.readLine();
temp = temp.replaceAll(" ", "");
num[i] = Integer.parseInt(temp);
if (num[i] / 1000 == k)
find = num[i] % 1000;
}
int result = 1;
for (int i = 0; i < n; i++) {
if (num[i] % 1000 > find)
result++;
}
System.out.println(result);
}
}
<file_sep>import java.util.Scanner;
public class _9506 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
int n = scan.nextInt();
if (n == -1)
break;
int[] arr = new int[n];
int sum = 0;
int index = 0;
for (int i = 1; i < n; i++) {
if (n % i == 0) {
arr[index++] = i;
sum += i;
}
}
if (sum != n) {
System.out.println(n + " is NOT perfect.");
continue;
}
System.out.print(n + " = ");
for (int i = 0; i < index; i++) {
if (i == index - 1)
System.out.print(arr[i]);
else
System.out.print(arr[i] + " + ");
}
System.out.println();
}
scan.close();
}
}
<file_sep>import java.util.LinkedList;
import java.util.Scanner;
public class _11866 {
static StringBuilder sb = new StringBuilder();
static int now;
static int size;
static int n;
static int k;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
LinkedList<Integer> list = new LinkedList<>();
for (int i = 1; i <= n; i++)
list.add(i);
now = -1;
int t = 0;
sb.append("<");
while (!list.isEmpty()) {
size = list.size();
findN();
int temp = list.remove(now);
if (t == n - 1)
sb.append(temp);
else
sb.append(temp + ", ");
t++;
now -= 1;
}
sb.append(">");
System.out.println(sb);
}
private static void findN() {
now += k;
if (now > size - 1)
now = now % size;
}
}
<file_sep>
import java.util.Arrays;
import java.util.Scanner;
public class _9020 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
for(int i=0;i<testcase;i++) {
int input = sc.nextInt();
boolean[] arr = new boolean[input+1];
Arrays.fill(arr, true);
arr[1] = false;
for(int j=2;j<input;j++)
for(int k=2;j*k<input;k++)
arr[j*k] = false;
int half = input/2;
int conti=-1;
for(int j=half ; j>=2 ; j--) {
if(arr[j]) {
for(int k = half;k<input;k++) {
if(arr[k] && (j+k)==input) {
System.out.println(j+" "+k);
conti=1;
break;
}
}
if(conti==1) break;
}
}
}
}
}
<file_sep>import java.util.Scanner;
public class _5533 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int[][] arr = new int[N][3];
int[] score = new int[N];
for (int i = 0; i < N; i++) {
arr[i][0] = scan.nextInt();
arr[i][1] = scan.nextInt();
arr[i][2] = scan.nextInt();
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < 3; j++) {
boolean flag = true;
for (int k = 0; k < N; k++) {
if (i == k)
continue;
if (arr[i][j] == arr[k][j]) {
flag = false;
break;
}
}
if (flag)
score[i] += arr[i][j];
}
}
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
scan.close();
}
}
<file_sep>
import java.util.Arrays;
public class _4673 {
public static void main(String[] args) {
boolean[] arr = new boolean[10001];
Arrays.fill(arr, true);
int temp;
for(int i=1; i<=10000 ; i++) {
temp=selfnumber(i);
if(temp>10000) continue;
arr[temp]=false;
}
for(int i=1;i<=10000;i++) {
if(arr[i]==true) {
System.out.println(i);
}
}
}
private static int selfnumber(int i) {
int sum=i;
while(true) {
if(i<10) {
sum+=i;
break;
}
sum = sum+i%10;
i=i/10;
}
return sum;
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _5567 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
int f1, f2, result = 0;
int[][] matrix = new int[n + 1][n + 1];
boolean[] invite = new boolean[n + 1];
StringTokenizer st;
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
f1 = Integer.parseInt(st.nextToken());
f2 = Integer.parseInt(st.nextToken());
matrix[f1][f2] = 1;
matrix[f2][f1] = 1;
}
for (int i = 2; i < n + 1; i++) {
if (matrix[1][i] == 1) {
if (!invite[i]) {
result++;
invite[i] = true;
}
for (int j = 2; j < n + 1; j++) {
if (matrix[i][j] == 1 && !invite[j]) {
result++;
invite[j] = true;
}
}
}
}
System.out.println(result);
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _2783 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
double x = Double.parseDouble(st.nextToken());
double y = Double.parseDouble(st.nextToken());
double min = x/y;
int n = Integer.parseInt(br.readLine());
for(int i=0;i<n;i++) {
st = new StringTokenizer(br.readLine());
double a = Double.parseDouble(st.nextToken());
double b = Double.parseDouble(st.nextToken());
min = Math.min(min, a/b);
}
System.out.println(min*1000);
}
}
<file_sep>import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class _2178 {
static int[][] map;
static int[] row = { 0, 0, 1, -1 };
static int[] col = { 1, -1, 0, 0 };
static boolean[][] visit;
static int n, m;
private static void bfs(int i, int j) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[] { i, j });
while (!q.isEmpty()) {
int location[] = q.poll();
visit[i][j] = true;
for (int dir = 0; dir < 4; dir++) {
int r = location[0] + row[dir];
int c = location[1] + col[dir];
if (r >= 0 && c >= 0 && r < n && c < m) {
if (map[r][c] != 0 && !visit[r][c]) {
q.add(new int[] { r, c });
visit[r][c] = true;
map[r][c] = map[location[0]][location[1]] + 1;
}
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
map = new int[n][m];
visit = new boolean[n][m];
for (int i = 0; i < n; i++) {
String temp = sc.next();
for (int j = 0; j < m; j++) {
map[i][j] = temp.charAt(j) - '0';
}
}
bfs(0, 0);
System.out.println(map[n - 1][m - 1]);
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _9465 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
int[][] arr = new int[3][n + 1];
int[][] dp = new int[3][n + 1];
for (int i = 1; i <= 2; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 1; j <= n; j++)
arr[i][j] = Integer.parseInt(st.nextToken());
}
dp[0][1] = 0;
dp[1][1] = arr[1][1];
dp[2][1] = arr[2][1];
for (int i = 2; i <= n; i++) {
dp[0][i] = Math.max(dp[0][i - 1], Math.max(dp[1][i - 1], dp[2][i - 1]));
dp[1][i] = Math.max(dp[0][i - 1], dp[2][i - 1]) + arr[1][i];
dp[2][i] = Math.max(dp[0][i - 1], dp[1][i - 1]) + arr[2][i];
}
System.out.println(Math.max(dp[0][n], Math.max(dp[1][n], dp[2][n])));
}
}
}
<file_sep>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class _4153 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int temp = 1;
while (temp != 0) {
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
int[] len = {x,y,z};
Arrays.sort(len);
if (x == 0) {
temp = 0;
break;
} else {
if (Math.pow(len[0], 2) + Math.pow(len[1], 2) == Math.pow(len[2], 2))
System.out.println("right");
else
System.out.println("wrong");
}
}
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class _1789 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long n = Long.parseLong(br.readLine());
long cnt = 1;
long sum = 1;
while (n > sum) {
cnt++;
sum += cnt;
}
if (n < sum)
cnt--;
System.out.println(cnt);
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class _9375 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcase = Integer.parseInt(br.readLine());
StringTokenizer st;
for (int i = 0; i < testcase; i++) {
int n = Integer.parseInt(br.readLine());
HashMap<String, Integer> clothes = new HashMap<>();
for (int j = 1; j <= n; j++) {
st = new StringTokenizer(br.readLine());
String name = st.nextToken();
String kind = st.nextToken();
if (clothes.containsKey(kind))
clothes.put(kind, clothes.get(kind) + 1);
else
clothes.put(kind, 1);
}
int result = 1;
for (int temp : clothes.values())
result *= temp + 1;
System.out.println(result - 1);
}
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _2563 {
public static void main(String[] args) throws NumberFormatException, IOException {
boolean[][] arr = new boolean[101][101];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
while (n-- > 0) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
for (int i = a; i < a + 10; i++) {
for (int j = b; j < b + 10; j++) {
if (!arr[i][j])
arr[i][j] = true;
}
}
}
int cnt = 0;
for (int i = 1; i < 101; i++) {
for (int j = 1; j < 101; j++) {
if (arr[i][j])
cnt++;
}
}
System.out.println(cnt);
}
}
<file_sep>import java.util.Scanner;
public class _5585 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int temp = 1000 - n;
int cnt = 0;
while (true) {
int a;
if (temp >= 500) {
cnt += 1;
temp -= 500;
} else if (temp >= 100) {
a = temp / 100;
cnt += a;
temp -= 100 * a;
} else if (temp >= 50) {
a = temp / 50;
cnt += a;
temp -= 50 * a;
} else if (temp >= 10) {
a = temp / 10;
cnt += a;
temp -= 10 * a;
} else if (temp >= 5) {
a = temp / 5;
cnt += a;
temp -= 5 * a;
} else if (temp > 0) {
a = temp / 1;
cnt += a;
temp -= 1 * a;
}
if (temp == 0)
break;
}
System.out.println(cnt);
}
}
<file_sep>
import java.util.Arrays;
import java.util.Scanner;
public class _4948 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
int input = sc.nextInt();
if(input==0) break;
boolean[] arr = new boolean[2*input+1];
Arrays.fill(arr, true);
arr[1] = false; //true면 소수, false면 소수x
for(int i=2 ; i<=2*input;i++)
for(int j=2 ; i*j<=2*input ; j++)
arr[i*j] = false;
int result=0;
for(int i=input+1 ; i <= 2*input ; i++) {
if(arr[i]==true)
result++;
}
System.out.println(result);
}
}
}
<file_sep>import java.util.Scanner;
public class _10886 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int cute = 0;
int notcute = 0;
for (int i = 0; i < n; i++) {
int temp = sc.nextInt();
if (temp == 1)
cute++;
else
notcute++;
}
if (cute > notcute)
System.out.println("Junhee is cute!");
else
System.out.println("Junhee is not cute!");
}
}
<file_sep>
import java.util.Scanner;
public class _2609 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b= sc.nextInt();
int min = Math.min(a, b);
while(min != 1) {
if(a%min==0 && b%min==0) {
break;
}
min--;
}
System.out.println(min);
int max = Math.max(a, b);
min = Math.min(a, b);
int i = 1;
int j=1;
while(true) {
while(max*i >= min*j) {
if(max*i == min*j) {
break;
}
j++;
}
if(max*i == min*j) break;
i++;
}
System.out.println(min*j);
}
}
<file_sep>
import java.util.Scanner;
public class _1157 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
int length = input.length();
int[] al = new int[26];
for(int i=0;i<length;i++) {
char temp = input.charAt(i);
if(temp<97) temp+=32;
al[temp-97]++;
}
int max = -1;
int result=0;
for(int i=0;i<26;i++) {
if(al[i]>max) {
max = al[i];
result=i;
}
}
int temp=0;
for(int a :al) {
if(max ==a) temp++;
}
if(temp==1) {
System.out.println((char)(result+65));
}else {
System.out.println("?");
}
}
}
<file_sep>import java.util.Scanner;
public class _2902 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
System.out.print(input.charAt(0));
for (int i = 1; i < input.length(); i++) {
if (input.charAt(i) == '-') {
System.out.print(input.charAt(i + 1));
}
}
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class _1966 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int testcase = Integer.parseInt(br.readLine());
for (int i = 0; i < testcase; i++) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
Queue<Integer> q = new LinkedList<>();
st = new StringTokenizer(br.readLine());
int[] arr = new int[n];
for (int j = 0; j < n; j++) {
int temp = Integer.parseInt(st.nextToken());
q.add(temp);
arr[j] = temp;
}
Arrays.sort(arr);
int index = n - 1;
int result = 0;
int cnt = 0;
while (true) {
int temp = q.poll();
if (cnt == m) {
temp += 101;
}
cnt++;
if (arr[index] == temp - 101) {
result++;
break;
} else if (arr[index] == temp) {
result++;
index--;
} else {
q.add(temp);
}
}
System.out.println(result);
}
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
public class _2804 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
int n = a.length();
int m = b.length();
char[][] matrix = new char[m][n];
for (int i = 0; i < m; i++)
Arrays.fill(matrix[i], '.');
int[] alphabet = new int[26];
for (int i = 0; i < n; i++)
alphabet[a.charAt(i) - 65]++;
int indexOfb = 0;
int alpha = 0;
for (int i = 0; i < m; i++) {
int temp = b.charAt(i) - 65;
if (alphabet[temp] != 0) {
indexOfb = i;
alpha = temp;
break;
}
}
int indexOfa = 0;
for (int i = 0; i < n; i++) {
matrix[indexOfb][i] = a.charAt(i);
}
for (int i = 0; i < n; i++) {
if (alpha == a.charAt(i) - 65) {
indexOfa = i;
break;
}
}
for (int i = 0; i < m; i++)
matrix[i][indexOfa] = b.charAt(i);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
System.out.print(matrix[i][j]);
System.out.println();
}
}
}
<file_sep>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _15649 {
static int n,m;
static int arr[];
static boolean visit[];
static StringBuilder sb = new StringBuilder();
private static void dfs(int d) {
if(d == m) {
for(int i : arr)
sb.append(i+" ");
sb.append("\n");
return;
}
for(int i = 1 ; i <= n ; i++) {
if(!visit[i]) {
visit[i] = true;
arr[d] = i;
dfs(d+1);
visit[i] = false;
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
arr = new int[m];
visit = new boolean[n+1];
dfs(0);
System.out.println(sb);
}
}
<file_sep>import java.util.Scanner;
public class _5618 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n == 2) {
int a = sc.nextInt();
int b = sc.nextInt();
int min = Math.min(a, b);
for (int i = 1; i <= min; i++) {
if (a % i == 0 && b % i == 0)
System.out.println(i);
}
} else {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int min = Math.min(a, b);
min = Math.min(min, c);
for (int i = 1; i <= min; i++) {
if (a % i == 0 && b % i == 0 && c % i == 0)
System.out.println(i);
}
}
}
}
<file_sep>import java.util.Scanner;
public class _3034 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int w = sc.nextInt();
int h = sc.nextInt();
while (n-- > 0) {
int temp = sc.nextInt();
if (temp * temp <= w * w + h * h)
System.out.println("DA");
else
System.out.println("NE");
}
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class _7576 {
static int r, c;
static int[][] map;
static int[] dx = { 0, 0, -1, 1 };
static int[] dy = { -1, 1, 0, 0 };
static int max = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
c = Integer.parseInt(st.nextToken());
r = Integer.parseInt(st.nextToken());
map = new int[r][c];
Queue<int[]> q = new LinkedList<>();
for (int i = 0; i < r; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < c; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
if (map[i][j] == 1)
q.add(new int[] { i, j });
}
}
}
}
<file_sep>
import java.util.Scanner;
public class _2675 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
for(int i=0 ; i<testcase ; i++) {
int r = sc.nextInt();
String s = sc.next();
int len = s.length();
for(int j=0;j<len;j++) {
char temp = s.charAt(j);
for(int k=0;k<r;k++) {
System.out.print(temp);
}
}
System.out.println();
}
}
}
<file_sep>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class _1009 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a;
int b;
int temp;
for (int i = 0; i < n; i++) {
a = sc.nextInt();
b = sc.nextInt();
temp = a%10;
for (int j = 2; j <= b; j++) {
temp = temp * a;
temp = temp % 10;
}
if (temp == 0)
System.out.println("10");
else
System.out.println(temp);
}
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _2606 {
static int cnt = 0;
static boolean[][] map;
static boolean[] visit;
static int n;
static int m;
private static void dfs(int d) {
visit[d] = true;
for (int i = 1; i <= n; i++) {
if (map[d][i] == true && !visit[i]) {
dfs(i);
cnt++;
}
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
n = Integer.parseInt(br.readLine());
m = Integer.parseInt(br.readLine());
map = new boolean[n + 1][n + 1];
visit = new boolean[n + 1];
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
map[a][b] = true;
map[b][a] = true;
}
dfs(1);
System.out.println(cnt);
}
}
<file_sep>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class _1436 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int num = 666;
int cnt=0;
while(true) {
String temp = Integer.toString(num);
if(temp.contains("666"))
cnt++;
if(cnt == n)
break;
num++;
}
System.out.println(num);
}
}
<file_sep>
import java.util.Scanner;
public class _1676 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int cnt=0;
for(int i=5 ; i<=n ; i*=5) {
cnt += n/i;
}
System.out.println(cnt);
}
}
<file_sep>
import java.util.Scanner;
public class _2231 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int result=0;
int sum=0;
int temp;
for(int i=1 ; i < input ; i++) {
temp=i;
sum=i;
do {
sum+=temp%10;
temp/=10;
}while(temp>0);
if(sum==input) {
result=i;
break;
}
}
System.out.println(result);
}
}
<file_sep>
import java.util.Scanner;
public class _3053 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
System.out.println(r*r*Math.PI);
System.out.println(2*r*r);
}
}
| 2def9fa84cc343e98572af65908f08685c7c061f | [
"Java"
] | 44 | Java | Yongjin9660/baekjoon | 90e1dc6c10da01580e22989263158a2a1b29222a | aaf4839e7a6c83bb070ec7e5698c00d4139c8b21 |
refs/heads/main | <repo_name>ngonimuro/nd064_course_1<file_sep>/exercises/python-helloworld/tables.py
from flask_table import Table, Col, LinkCol
class Results(Table):
model_id = Col('Id', show=False)
model_code = Col('Code')
model_year = Col('Year')
model_name_za = Col('Model')
make_name = Col('Make')
created=Col('Created')
modified=Col('Modified')
edit = LinkCol('Edit', 'edit_view', url_kwargs=dict(id='model_id'))
delete = LinkCol('Delete ', 'delete_user', url_kwargs=dict(id='model_id'))
class BodyType(Table):
body_id = Col('Id', show=False)
body_type = Col('Body')
doors = Col('Doors')
created = Col('Created')
modified = Col('Modified')
edit = LinkCol('Edit','edit_view',url_kwargs=dict(id='body_id'))
delete = LinkCol('Delete','delete_boy',url_kwargs=dict(id='body_id'))<file_sep>/exercises/python-helloworld/main.py
from typing import NoReturn
import pymysql
from app import app
from tables import Results,BodyType
from db_config import mysql
from flask import flash, render_template, request, redirect,jsonify
from werkzeug.security import generate_password_hash, check_password_hash
links=[
{'name': 'Home','url':''},
{'name': 'View Models','url':'/models'},
{'name': 'Create Models','url':'/create'}
]
@app.route('/')
def home():
"""KS Auto Parts Catalog"""
return render_template('home.html',
title="Catalog",
description="Catalog System",
links=links
)
@app.route('/models')
def models():
conn = None
cursor = None
_select = "SELECT main.model_id, main.model_code, main.model_year, main.model_name_za, main.created, main.modified, minor.make_name"
_from = " FROM model AS main"
_join = " INNER JOIN make AS minor ON main.key_make = minor.make_id"
_order = " ORDER BY main.modified desc"
_sql = _select + _from + _join + _order
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute(_sql)
rows = cursor.fetchall()
table = Results(rows)
table.border = True
return render_template('models.html', table=table,links=links,rows=rows)
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/edit/<int:id>')
def edit_view(id):
conn = None
cursor = None
_select = "SELECT main.model_id,main.model_code,main.model_year,main.model_name_za,main.key_make "
_from = " FROM model AS main "
_join = " INNER JOIN make AS minor ON main.key_make = minor.make_id"
_select2 = "SELECT make_id, make_name,make_abbreviation "
_from2 = " FROM make"
_sql = _select + _from + _join
_sql2 = _select2 + _from2
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute(_sql + " WHERE model_id=%s ", id)
model_row = cursor.fetchone()
cursor.execute(_sql2)
make_rows = cursor.fetchall()
if model_row and make_rows:
return render_template('edit.html', model_row=model_row , make_rows = make_rows)
else:
return 'Record #{id} is missing'.format(id=id)
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/new_model')
def add_user_view():
conn = None
cursor = None
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("Select make_id,make_name,make_abbreviation FROM make")
rows = cursor.fetchall()
if rows:
return render_template('add.html',
title="Create New Model",
description="Catalog System add a new model to the system",
field_titles="New Model",
rows=rows)
else:
return 'No Makes have been added to the system yet'
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/add_model', methods=['POST'])
def add_model():
conn = None
cursor = None
try:
_code = request.form['inputModelCode']
_year = request.form['inputModelYear']
_name = request.form['inputModelName']
_make = request.form['inputSelectMake']
# validate the received values
if _code and _year and _name and _make and request.method == 'POST':
#do not save password as a plain text
# _hashed_password = generate_password_hash(_password)
# save edits
sql = "INSERT INTO model( model_code, model_year, model_name_za, key_make) VALUES(%s, %s, %s)"
data = (_code, _year, _name, _make)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
flash('Model added successfully!')
return redirect('/models')
else:
return 'Error while adding model'
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/update', methods=['POST'])
def update_model():
conn = None
cursor = None
try:
_code = request.form['inputModelCode']
_year = request.form['inputModelYear']
_model = request.form['inputModelName']
_id = request.form['id']
_make = request.form['inputSelectMake']
# validate the received values
if _code and _year and _model and _id and _make and request.method == 'POST':
#do not save password as a plain text
# _hashed_password = generate_password_hash(_password)
# print(_hashed_password)
# save edits
sql = "UPDATE model SET model_code=%s, model_year=%s, model_name_za=%s, key_make=%s WHERE model_id=%s"
data = (_code, _year, _model, _make,_id)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
flash("Model {_model} updated successfully!")
return redirect('/models')
else:
return 'Error while updating user'
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/delete/<int:id>')
def delete_user(id):
conn = None
cursor = None
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("DELETE FROM model WHERE model_id=%s", (id,))
conn.commit()
flash('Model deleted successfully!')
return redirect('/models')
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/body')
def vehicle_body():
conn = None
cursor = None
_select = "SELECT body_id, body_type, doors, created, modified"
_from = " FROM body"
_sql = _select + _from
try:
conn=mysql.connect()
cursor = conn.cursor()
cursor.execute(_sql)
body_rows = cursor.fetchall()
table=BodyType(body_rows)
table.border = True
if body_rows:
return render_template('body.html',
title="View Body Types",
description="Catalog System view all vehicle body types defined in the system",
field_titles="New Model",
body_rows=body_rows,
table=table
)
else:
return "No body types have been added to the system yet !"
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.run(host='0.0.0.0')<file_sep>/exercises/python-helloworld/app.py
from flask import Flask,render_template,request
from flask import json
import logging
app = Flask(__name__)
app.debug=True
app.secret_key="secret key"
# @app.route("/status")
# def status_healthcheck():
# result={"result":"OK- healthy"}
# response = app.response_class(json.dumps(result),status=200,mimetype="application/json")
# app.logger.info("Status request successful")
# return response
# @app.route("/metrics")
# def metrics():
# result={
# "status":"success",
# "code":0,
# "data":{
# "UserCount":149,
# "UserCountActive":20
# }
# }
# response = app.response_class(json.dumps(result),status=200,mimetype="application/json")
# app.logger.info("Metrics request successful")
# return response
# @app.route("/catalog")
# def catalog():
# result={"url":"http://192.168.1.116:80/kmsdev/catalog/vehicles/index.php"}
# return app.response_class(json.dumps(result),status=200,mimetype="application/json")
# @app.route("/", methods=['GET','POST'])
# def index():
# app.logger.info("Index request successful")
# return render_template('index.html')
# if __name__ == "__main__":
# logging.basicConfig(filename="app.log",level=logging.DEBUG)
# app.run(host='0.0.0.0')
| 535d3d704402c36eeb5be727aa387725bd0dc523 | [
"Python"
] | 3 | Python | ngonimuro/nd064_course_1 | 4163b4b66874ba693b26a33d24dce86e797ed537 | 4198255c4e7b3da08100104123cbe343b8c14b4b |
refs/heads/master | <repo_name>fredrikjsson/quick-restore<file_sep>/src/targets/mssql/index.js
const path = require('path');
const fs = require('fs');
const { promisify } = require('util');
const MssqlClient = require('./mssqlClient');
const noop = require('../../utils/noop');
const readFileAsync = promisify(fs.readFile);
const baseConfig = {
connection: {
server: '127.0.0.1',
username: '',
password: '',
database: ''
},
script: null
};
class MssqlTarget {
constructor (config, baseDir, logFn) {
this.baseDir = baseDir;
this.config = Object.assign({}, baseConfig, config);
this.log = logFn || noop;
this.sqlClient = new MssqlClient(this.config.connection);
}
async restore (restorePoint) {
await this.sqlClient.init();
try {
await this.runRestore(restorePoint);
await this.sqlClient.close();
} catch (err) {
await this.sqlClient.close();
throw err;
}
}
async runRestore (restorePoint) {
const dbExists = await this.databaseExists(this.config.connection.database);
if (dbExists) {
await this.closeConnections(this.config.connection.database);
}
const targetLocation = await this.getDefaultDataLocation();
const backupFiles = await this.getFilesFromBackup(restorePoint);
await this.restoreDatabase(
this.config.connection.database,
restorePoint,
targetLocation,
backupFiles
);
await this.sqlClient.resetConnection();
await this.runScript();
}
restoreDatabase (database, restorePoint, newLocation, files) {
const bakupBasename = path.basename(restorePoint);
this.log(`Restoring database [${bakupBasename}]`);
const getNewFileLocation = (file, newLocation) =>
`${newLocation}\\${path.basename(file.physicalName)}`;
const moveStatements = files.map(
f => `move '${f.logicalName}' to '${getNewFileLocation(f, newLocation)}'`
);
const restoreDb = `
restore database ${database}
from disk = '${restorePoint}'
with replace,
${moveStatements};
`;
return this.sqlClient.executeSql(restoreDb);
}
async databaseExists (database) {
const selectDb = `
select *
from sys.databases
where [name] = '${database}';
`;
const dbs = await this.sqlClient.executeSql(selectDb);
return !!dbs.rowCount;
}
async closeConnections (database) {
const setDbOffline = `
alter database ${database}
set offline
with rollback immediate;
`;
const setDbOnline = `
alter database ${database}
set online;
`;
await this.sqlClient.executeSql(setDbOffline);
await this.sqlClient.executeSql(setDbOnline);
}
async getFilesFromBackup (restorePoint) {
const selectFileList = `
restore filelistonly
from disk = '${restorePoint}';
`;
const fileList = await this.sqlClient.executeSql(selectFileList);
return fileList.rows.map(fileProps => {
const logicalName = fileProps.find(
prop => prop.metadata.colName === 'LogicalName'
).value;
const physicalName = fileProps.find(
prop => prop.metadata.colName === 'PhysicalName'
).value;
return { logicalName, physicalName };
});
}
async getDefaultDataLocation (database) {
const selectMasterLocation = `
select physical_name
from master.sys.master_files
where database_id = 1
and FILE_ID = 1
`;
const masterFileLocation = await this.sqlClient.executeSql(
selectMasterLocation
);
return path.dirname(masterFileLocation.rows[0][0].value);
}
async readScript (scriptPath) {
try {
return await readFileAsync(scriptPath, {
encoding: 'utf8'
});
} catch (err) {
throw new Error(`Could not load sql script file at ${scriptPath}`);
}
}
async runScript () {
const scriptPath = this.config.script;
if (!scriptPath) {
return;
}
const script = await this.readScript(path.join(this.baseDir, scriptPath));
this.log('Running script');
await this.sqlClient.executeSql(
`use ${this.config.connection.database}; ${script}`
);
}
}
module.exports = MssqlTarget;
<file_sep>/src/targets/mssql/__tests__/__fixtures__/test.sql
update Employees
set FirstName='CHANGED'
where EmployeeID = 2<file_sep>/src/sources/s3/s3Client.js
const S3 = require('aws-sdk/clients/s3');
class S3Client {
constructor (config) {
this.config = config;
this.S3 = new S3({
apiVersion: '2006-03-01',
secretAccessKey: this.config.connection.secretAccessKey,
accessKeyId: this.config.connection.accessKeyId
});
}
getObjectFileStream (key) {
return this.S3
.getObject({ Bucket: this.config.connection.bucket, Key: key })
.createReadStream();
}
listObjects (prefix, continuationToken = null) {
return new Promise((resolve, reject) => {
this.S3.listObjectsV2(
{
Bucket: this.config.connection.bucket,
Prefix: prefix,
ContinuationToken: continuationToken
},
(err, data) => {
if (!err) {
resolve(data);
} else {
reject(err);
}
}
);
});
}
}
module.exports = S3Client;
<file_sep>/README.md
# quick-restore
quick-restore is a cli tool which speeds up the tedious task of restoring backups.
Currently supports:
Sources:
- Local files
- S3
Targets:
- MSSQL
## Install
```
npm install quick-restore -g
```
## Setup workspace
#### Create config file at `<working-dir>/.quick-restore/config.json`
Example:
```json
{
"source": {
"client": "s3",
"connection": {
"secretAccessKey": "1234",
"accessKeyId": "1234",
"bucket": "my-bucket"
},
"prefix": "sqlbackup/"
},
"target": {
"client": "mssql",
"connection": {
"server": "127.0.0.1",
"username": "sa",
"password": "<PASSWORD>",
"database": "northwind"
},
"script": "./scrub.sql"
}
}
```
## Usage
#### Restore configured source
```
quick-restore
```
#### Restore local file
```
quick-restore <filepath>
```<file_sep>/src/sources/s3/__tests__/__mocks__/s3Client.js
const path = require('path');
const AWSMock = require('mock-aws-s3');
const basePath = path.join(__dirname, `../__fixtures__`);
AWSMock.config.basePath = basePath;
class MockS3Client {
constructor (config) {
this.config = config;
this.S3 = AWSMock.S3({
params: { Bucket: 'test-bucket', MaxKeys: 1, Delimiter: '/' }
});
}
getObjectFileStream (key) {
return this.S3
.getObject({ Bucket: this.config.connection.bucket, Key: key })
.createReadStream();
}
listObjects (prefix, continuationToken = null) {
return new Promise((resolve, reject) => {
this.S3.listObjectsV2(
{
Bucket: this.config.connection.bucket,
Prefix: prefix,
ContinuationToken: continuationToken
},
(err, data) => {
if (!err) {
resolve(data);
} else {
reject(err);
}
}
);
});
}
}
module.exports = MockS3Client;
<file_sep>/src/sources/s3/index.js
const fs = require('fs-extra');
const fst = require('fs');
const path = require('path');
const S3Client = require('./s3Client');
const noop = require('../../utils/noop');
const baseConfig = {
connection: {
secretAccessKey: '',
accessKeyId: '',
bucket: ''
},
prefix: ''
};
class S3Source {
constructor (config, baseDir, logFn, S3 = S3Client) {
this.s3 = new S3(config);
this.baseDir = baseDir;
this.cacheDir = path.join(this.baseDir, `/cache/s3`);
this.cacheInfoPath = path.join(this.cacheDir, `/cache.json`);
this.config = Object.assign({}, baseConfig, config);
this.log = logFn || noop;
}
downloadFile (key, file) {
return new Promise((resolve, reject) => {
this.log(`Downloading [${key}]`);
const writeStream = fst.createWriteStream(file);
this.s3
.getObjectFileStream(key)
.pipe(writeStream)
.on('finish', () => resolve(file));
});
}
async createCacheInfo (file, etag) {
try {
await fs.writeJson(this.cacheInfoPath, { file, etag });
} catch (err) {
throw new Error('Could not write cache file');
}
}
async readCacheInfo () {
try {
return await fs.readJson(this.cacheInfoPath);
} catch (err) {
return null;
}
}
async downloadLatestFile () {
const cacheInfo = await this.readCacheInfo();
const latestObject = await this.getLatestObject();
if (!latestObject) {
throw new Error('No matching file on S3');
}
const escapedEtag = latestObject.ETag.replace(/"/g, '');
if (cacheInfo && cacheInfo.etag === escapedEtag) {
this.log(`Using cache [${cacheInfo.file}]`);
return path.join(this.cacheDir, `/${cacheInfo.file}`);
}
const basename = path.basename(latestObject.Key);
const dest = path.join(this.cacheDir, `/${basename}`);
await fs.remove(`${this.cacheDir}/`);
await fs.ensureFile(dest);
await this.downloadFile(latestObject.Key, dest);
await this.createCacheInfo(basename, escapedEtag);
return dest;
}
async getLatestObject () {
const objects = await this.getAllObjects(this.config.prefix);
return this.findLatestObject(objects);
}
async getAllObjects (prefix, continuationToken = null, objects = []) {
const data = await this.s3.listObjects(prefix, continuationToken);
if (data.IsTruncated) {
return this.getAllObjects(
prefix,
data.NextContinuationToken,
objects.concat(data.Contents)
);
} else {
return objects.concat(data.Contents);
}
}
findLatestObject (objects) {
return objects.reduce(
(prev, current) =>
(prev && prev.LastModified > current.LastModified ? prev : current),
null
);
}
}
module.exports = S3Source;
<file_sep>/src/targets/mssql/__tests__/index.js
const MssqlDriver = require('../index');
const path = require('path');
const config = require('./__fixtures__/mssql.json');
const MssqlClient = require('../mssqlClient');
const testFile = path.join(
__dirname,
`./__fixtures__/${config.connection.database}.bak`
);
const basePath = path.join(__dirname, `./__fixtures__`);
const timeout = 20000;
describe('mssql tests', function () {
it('restores db', async () => {
const mssqlClient = new MssqlClient(config.connection);
const mssqlTarget = new MssqlDriver(config, basePath);
await mssqlTarget.restore(testFile);
await mssqlClient.init();
const dbExistsResult = await mssqlClient.executeSql(
`select * from sys.databases
where name = '${config.connection.database}'`
);
mssqlClient.close();
expect(dbExistsResult.rowCount).toBe(1);
}, timeout);
it('overwrites existing db', async () => {
const mssqlClient = new MssqlClient(config.connection);
const mssqlTarget = new MssqlDriver(config, basePath);
await mssqlTarget.restore(testFile);
await mssqlClient.init();
await mssqlClient.executeSql(
`use ${config.connection.database};
update Employees
set FirstName='Hurley'
where EmployeeID = 1`
);
mssqlClient.close();
await mssqlTarget.restore(testFile);
await mssqlClient.init();
const firstNameResult = await mssqlClient.executeSql(
`use ${config.connection.database};
select FirstName
from Employees
where EmployeeID = 1`
);
mssqlClient.close();
expect(firstNameResult.rows[0][0].value).toBe('Nancy');
}, timeout);
it('restores db currently in use', async () => {
const mssqlClient = new MssqlClient(config.connection);
const mssqlTarget = new MssqlDriver(config, basePath);
await mssqlTarget.restore(testFile);
await mssqlClient.init();
await mssqlClient.executeSql(
`use ${config.connection.database};
update Employees
set FirstName='Hurley'
where EmployeeID = 1`
);
await mssqlTarget.restore(testFile);
await mssqlClient.init();
const firstNameResult = await mssqlClient.executeSql(
`use ${config.connection.database};
select FirstName
from Employees
where EmployeeID = 1`
);
mssqlClient.close();
expect(firstNameResult.rows[0][0].value).toBe('Nancy');
}, timeout);
it('runs sql-script', async () => {
const mssqlClient = new MssqlClient(config.connection);
const mssqlTarget = new MssqlDriver(config, basePath);
await mssqlTarget.restore(testFile);
await mssqlClient.init();
const firstNameResult = await mssqlClient.executeSql(
`use ${config.connection.database};
select FirstName
from Employees
where EmployeeID = 2`
);
mssqlClient.close();
expect(firstNameResult.rows[0][0].value).toBe('CHANGED');
}, timeout);
});
<file_sep>/src/index.js
#! /usr/bin/env node
const configReader = require('./utils/configReader');
const logger = require('./utils/logger');
const MssqlTarget = require('./targets/mssql');
const S3Source = require('./sources/s3');
const path = require('path');
const fs = require('fs-extra');
const packageSettings = require('../package');
const baseDir = path.join(process.cwd(), `/.${packageSettings.name}`);
const userArgs = process.argv.slice(2);
const filePath = userArgs[0];
const runWithFile = async (file, target) => {
const fullPath = path.resolve(file);
const fileExists = await fs.pathExists(fullPath);
if (!fileExists) {
throw new Error(`File ${fullPath} not found`);
}
await target.restore(fullPath);
};
const runWithSource = async (source, target) => {
const file = await source.downloadLatestFile();
await target.restore(file);
};
const getTarget = config => {
if (!config.target) {
throw new Error(`No target setting found`);
}
return new MssqlTarget(config.target, baseDir, logger);
};
const getSource = config => {
if (!config.source) {
throw new Error(`No source setting found`);
}
return new S3Source(config.source, baseDir, logger);
};
const restore = async () => {
const config = await configReader.getConfig(baseDir);
const target = getTarget(config);
if (filePath) {
return runWithFile(filePath, target);
} else {
const source = getSource(config);
return runWithSource(source, target);
}
};
restore()
.then(() => {
logger('Done!', '🎉');
})
.catch(err => logger(err, '⚠️'));
| f49e6f1780825a3a01f3b6977c1f35422b821edd | [
"JavaScript",
"SQL",
"Markdown"
] | 8 | JavaScript | fredrikjsson/quick-restore | e28cd2e3bfb71273f6b3ee15e40e2413d899234c | b551e884ab3b8c6ce9d66665db0fb0d1966964b7 |
refs/heads/master | <file_sep>;(function ($, window, undefined) {
var pluginName = 'responsiveSlideshow',
document = window.document,
defaults = {
disableControlelements: false,
autoscrollInterval: 0,
startingPosition: 0,
fadeOutHeadlineOnMouseOver: false,
fadeOutHeadlineAfterTimespan: 0,
direction: 'horizontal',
type: 'slideshow',
elements: 1,
r320: {},
r768: {},
r1024: {},
r1280: {}
},
functionscope = {
position: 0
};
var currentWindowProperties = {
width: $(window).width(),
height: $(window).height()
};
function Plugin(element, options) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.functionscope = $.extend( {}, functionscope);
this.init();
}
Plugin.prototype.init = function () {
var plugin = this;
plugin.functionscope.position = plugin.options.startingPosition;
if(Modernizr.prefixed('transform') == 'MozTransform') {
plugin.functionscope.roundfactor = 10000;
} else {
plugin.functionscope.roundfactor = 1000;
}
plugin.functionscope.stopSlideshow = false;
// Set the default size for elements
initAllElements(plugin);
if(plugin.options.autoscrollInterval > 0) {
initSlideshow(plugin);
}
// Bind eventlisteners
bindEventListeners(plugin);
};
function bindEventListeners(plugin) {
$('button', $(plugin.element)).click(function(e) {
e.preventDefault();
if($(this).hasClass('controlelement') && $(this).hasClass('previous')) {
plugin.functionscope.position = getNextAvailablePosition(plugin, 'previous');
scroll(plugin, plugin.functionscope.position);
} else if($(this).hasClass('controlelement') && $(this).hasClass('next')) {
plugin.functionscope.position = getNextAvailablePosition(plugin, 'next');
scroll(plugin, plugin.functionscope.position);
}
resetAndStartSlideshow(plugin);
});
$('li.controlelement.thumbnail', $(plugin.element)).bind('click.thumbnail', function(e) {
bindThumbnail(plugin, this);
});
if(plugin.options.autoscrollInterval > 0) {
$(plugin.element).mouseover(function(e) {
clearInterval(plugin.functionscope.slideShowInterval);
});
$(plugin.element).mouseout(function(e) {
resetAndStartSlideshow(plugin);
});
}
if(plugin.options.fadeOutHeadlineOnMouseOver) {
plugin.functionscope.headlineRemoved = false;
$('div.viewpoint', plugin.element).bind('mouseover.fadeOutHeadlineOnMouseOver', function(e){
removeHeadline(plugin);
});
}
if(plugin.options.fadeOutHeadlineAfterTimespan > 0) {
setTimeout(function(){
removeHeadline(plugin);
}, plugin.options.fadeOutHeadlineAfterTimespan);
}
$(window).resize(function(e) {
// Has the window width or height really changed? There is a bug on iOS devices, that this event is triggerd when requesting or scrolling the page.
if(currentWindowProperties.width != $(window).width() || currentWindowProperties.height != $(window).height()) {
plugin.functionscope.position = plugin.options.startingPosition;
currentWindowProperties = {
width: $(window).width(),
height: $(window).height()
}
initAllElements(plugin);
}
});
}
function bindThumbnail(plugin, tumbnail) {
if(plugin.functionscope.position != -$(tumbnail).index()) {
plugin.functionscope.position = -$(tumbnail).index();
scroll(plugin, plugin.functionscope.position);
setNeedle(plugin);
resetAndStartSlideshow(plugin);
if(plugin.options.fadeOutHeadlineOnMouseOver) {
removeHeadline(plugin);
}
}
}
function removeHeadline(plugin) {
if($('.overlaylabel', $(plugin.element)).length && !plugin.functionscope.headlineRemoved) {
$('.overlaylabel', $(plugin.element)).animate({'opacity': 0}, 400, function(e) {
$('.overlaylabel', $(plugin.element)).css({'display': 'none'});
plugin.functionscope.headlineRemoved = true;
});
}
}
function initAllElements(plugin) {
getElementSize(plugin);
resetDisplayAndControlElements(plugin);
setPageinationDisplay(plugin);
}
function getElementSize(plugin) {
MQ.addQuery({
context: '320',
callback: function() {
if(plugin.functionscope.currentMedia == '' || plugin.functionscope.currentMedia != 320) {
resetStyles(plugin);
if(!jQuery.isEmptyObject(plugin.options.r320)) {
setElementSize(plugin, plugin.options.r320);
} else {
setElementSize(plugin, plugin.options);
}
plugin.functionscope.currentMedia = 320;
}
}
});
MQ.addQuery({
context: '768',
callback: function() {
if(plugin.functionscope.currentMedia == '' || plugin.functionscope.currentMedia != 768) {
resetStyles(plugin);
if(!jQuery.isEmptyObject(plugin.options.r768)) {
setElementSize(plugin, plugin.options.r768);
} else {
setElementSize(plugin, plugin.options);
}
plugin.functionscope.currentMedia = 768;
}
}
});
MQ.addQuery({
context: '1024',
callback: function() {
if(plugin.functionscope.currentMedia == '' || plugin.functionscope.currentMedia != 1024) {
resetStyles(plugin);
if(!jQuery.isEmptyObject(plugin.options.r1024)) {
setElementSize(plugin, plugin.options.r1024);
} else {
setElementSize(plugin, plugin.options);
}
plugin.functionscope.currentMedia = 1024;
}
}
});
MQ.addQuery({
context: '1280',
callback: function() {
if(plugin.functionscope.currentMedia == '' || plugin.functionscope.currentMedia != 1280) {
resetStyles(plugin);
if(!jQuery.isEmptyObject(plugin.options.r1280)) {
setElementSize(plugin, plugin.options.r1280);
} else {
setElementSize(plugin, plugin.options);
}
plugin.functionscope.currentMedia = 1280;
}
}
});
}
function resetDisplayAndControlElements(plugin) {
setPageinationDisplay(plugin);
setNeedle(plugin);
setControlelements(plugin);
}
function resetStyles(plugin) {
clearTransitionStyles(plugin);
$('div.viewpoint', $(plugin.element)).css({'height': ''});
$('div.viewpoint ul', $(plugin.element)).css({'margin': 0});
$('div.viewpoint ul', $(plugin.element)).width(100 + '%');
$('div.viewpoint ul', $(plugin.element)).height(100 + '%');
$('div.viewpoint ul li', $(plugin.element)).width(100 + '%');
$('div.viewpoint ul li', $(plugin.element)).height(100 + '%');
$('div.viewpoint ul li', $(plugin.element)).css({'position': 'relative', 'z-index': ''});
if(plugin.options.fadeOutHeadlineOnMouseOver) {
$('header h1', $(plugin.element)).css({'display': 'block', 'opacity': 1});
plugin.functionscope.headlineRemoved = false;
}
$(plugin.element).find('.next').removeAttr('disabled');
$(plugin.element).find('.next').removeClass('disabled');
$(plugin.element).find('.previous').removeAttr('disabled');
$(plugin.element).find('.previous').removeClass('disabled');
$(plugin.element).find('.ondisplay').removeClass('ondisplay');
setTimeout(function(){setTransitionStyles(plugin);}, 100);
}
function setTransitionStyles(plugin) {
if(Modernizr.csstransitions) {
$('div.viewpoint ul', $(plugin.element)).css({'-moz-transition': 'margin 0.5s ease 0s'});
$('div.viewpoint ul', $(plugin.element)).css({'-webkit-transition': 'margin 0.5s ease 0s'});
$('div.viewpoint ul', $(plugin.element)).css({'-o-transition': 'margin 0.5s ease 0s'});
$('div.viewpoint ul', $(plugin.element)).css({'transition': 'margin 0.5s ease 0s'});
}
}
function clearTransitionStyles(plugin) {
if(Modernizr.csstransitions) {
$('div.viewpoint ul', $(plugin.element)).css({'-moz-transition': ''});
$('div.viewpoint ul', $(plugin.element)).css({'-webkit-transition': ''});
$('div.viewpoint ul', $(plugin.element)).css({'-o-transition': ''});
$('div.viewpoint ul', $(plugin.element)).css({'transition': ''});
}
}
function setElementSize(plugin, options) {
// Type - List
if(options.type == 'list') {
$('div.viewpoint ul', $(plugin.element)).width(100 + '%');
$('div.viewpoint ul li', $(plugin.element)).width(100 + '%');
disableDragAndDropSwipeEventListener(plugin);
} else {
// Type - Slideshow (Default)
if(options.direction == 'vertical') {
$('div.viewpoint ul', $(plugin.element)).height(($('div.viewpoint ul li', $(plugin.element)).size() * 100) / options.elements + '%');
$('div.viewpoint ul li', $(plugin.element)).height(Math.round((100 / $('div.viewpoint ul li', $(plugin.element)).size() * plugin.functionscope.roundfactor)) / plugin.functionscope.roundfactor + '%');
$('div.viewpoint', $(plugin.element)).height(parseInt($('div.viewpoint ul li', $(plugin.element)).outerHeight()) * options.elements);
plugin.functionscope.currentdirection = 'vertical';
disableDragAndDropSwipeEventListener(plugin);
} else if (!Modernizr.touch && options.direction == 'fade') {
$('div.viewpoint ul li', $(plugin.element)).css({'position': 'absolute'});
$('div.viewpoint ul li', $(plugin.element)).first().css({'z-index': 3});
$('div.viewpoint ul li', $(plugin.element)).first().addClass('ondisplay');
$('.controlpanel', $(plugin.element)).css({'z-index': 98});
$('.alwaysontop', $(plugin.element)).css({'z-index': 98});
plugin.functionscope.currentdirection = 'fade';
disableDragAndDropSwipeEventListener(plugin);
} else {
$('div.viewpoint ul', $(plugin.element)).width(($('div.viewpoint ul li', $(plugin.element)).size() * 100) / options.elements + '%');
$('div.viewpoint ul li', $(plugin.element)).width(Math.round((100 / $('div.viewpoint ul li', $(plugin.element)).size() * plugin.functionscope.roundfactor)) / plugin.functionscope.roundfactor + '%');
plugin.functionscope.currentdirection = 'horizontal';
addDragAndDropSwipeEventListener(plugin, options);
}
plugin.functionscope.elementsinviewpoint = options.elements;
}
}
function resetAndStartSlideshow(plugin) {
if(plugin.options.autoscrollInterval > 0) {
clearInterval(plugin.functionscope.slideShowInterval);
initSlideshow(plugin);
}
}
function initSlideshow(plugin) {
if(!plugin.functionscope.stopSlideshow && plugin.options.autoscrollInterval > 0 && $('div.viewpoint ul li', $(plugin.element)).size() > 1) {
plugin.functionscope.slideShowInterval = setInterval(function() {
plugin.functionscope.position = getNextAvailablePosition(plugin, 'next');
scroll(plugin, plugin.functionscope.position);
}, plugin.options.autoscrollInterval);
}
}
function getNextAvailablePosition(plugin, action){
var childCount = $('div.viewpoint ul li', $(plugin.element)).size();
var position = plugin.functionscope.position;
switch(action) {
case 'previous':
position++;
if(position > 0) {
position = -childCount + 1;
}
break;
case 'next':
position--;
if(-position == childCount / plugin.functionscope.elementsinviewpoint) {
position = 0;
}
break;
}
return position;
}
function scroll(plugin, position){
var newPositionPercent = position * 100 + '%';
switch(plugin.functionscope.currentdirection) {
case 'horizontal':
if(Modernizr.csstransitions) {
$('div.viewpoint ul', $(plugin.element)).css({'margin-left': newPositionPercent});
} else {
$('div.viewpoint ul', $(plugin.element)).animate({'margin-left': newPositionPercent});
}
break;
case 'vertical':
if(Modernizr.csstransitions) {
$('div.viewpoint ul', $(plugin.element)).css({'margin-top': position * $('div.viewpoint', $(plugin.element)).height() + 'px'});
} else {
$('div.viewpoint ul', $(plugin.element)).animate({'margin-top': position * $('div.viewpoint', $(plugin.element)).height() + 'px'});
}
break;
case 'fade':
$('li.controlelement.thumbnail', $(plugin.element)).unbind('click.thumbnail');
$('div.viewpoint ul li:eq(' + -position + ')', $(plugin.element)).css({'z-index': 2});
$('div.viewpoint ul li.ondisplay', $(plugin.element)).animate({'opacity': 0}, 300, function() {
$('div.viewpoint ul li:eq(' + -position + ')', $(plugin.element)).css({'z-index': 3});
$('div.viewpoint ul li.ondisplay', $(plugin.element)).css({'z-index': '', 'opacity': ''});
$('div.viewpoint ul li.ondisplay', $(plugin.element)).removeClass('ondisplay');
$('div.viewpoint ul li:eq(' + -position + ')', $(plugin.element)).addClass('ondisplay');
$('li.controlelement.thumbnail', $(plugin.element)).bind('click.thumbnail', function(e) {
bindThumbnail(plugin, this);
});
});
break;
}
resetDisplayAndControlElements(plugin);
}
function setPageinationDisplay(plugin) {
var cPageination = $(plugin.element).find('div.pageination');
if(cPageination.length){
if(plugin.functionscope.elementsinviewpoint && plugin.functionscope.elementsinviewpoint > 1) {
var pageinationFromCount = -plugin.functionscope.position * plugin.functionscope.elementsinviewpoint + 1;
var pageinationToCount = pageinationFromCount + plugin.functionscope.elementsinviewpoint - 1;
if(pageinationToCount > $('div.viewpoint ul li', $(plugin.element)).size()) {
pageinationToCount = $('div.viewpoint ul li', $(plugin.element)).size();
}
var pageinationDisplay = pageinationFromCount + "-" + pageinationToCount + " von " + $('div.viewpoint ul li', $(plugin.element)).size();
} else {
var pageinationDisplay = -plugin.functionscope.position + 1 + '/' + $('div.viewpoint ul li', $(plugin.element)).size();
}
cPageination.html(pageinationDisplay);
}
}
function setNeedle(plugin) {
var currentTumbnail = $('ul.controlpanel li.controlelement.thumbnail', $(plugin.element)).get(-plugin.functionscope.position);
if($(plugin.element).find('ul.controlpanel li.controlelement.thumbnail').length) {
$('.needle', $(plugin.element)).remove();
$(currentTumbnail).append('<div class="needle"></div>');
}
}
function setControlelements(plugin) {
if(plugin.options.disableControlelements) {
var positionCount = $('div.viewpoint ul li', $(plugin.element)).size() / plugin.functionscope.elementsinviewpoint;
if(-plugin.functionscope.position + 1 >= positionCount) {
$(plugin.element).find('.next').attr('disabled', 'disabled');
$(plugin.element).find('.next').addClass('disabled');
} else if($(plugin.element).find('.next').hasClass('disabled')) {
$(plugin.element).find('.next').removeAttr('disabled');
$(plugin.element).find('.next').removeClass('disabled');
}
if(plugin.functionscope.position == 0) {
$(plugin.element).find('.previous').attr('disabled', 'disabled');
$(plugin.element).find('.previous').addClass('disabled');
}
if(-plugin.functionscope.position == 1) {
$(plugin.element).find('.previous').removeAttr('disabled');
$(plugin.element).find('.previous').removeClass('disabled');
}
}
}
function responsiveSlideshowRefresh(plugin) {
plugin.functionscope.position = plugin.options.startingPosition;
resetStyles(plugin);
switch(plugin.functionscope.currentMedia) {
case 320:
if(!jQuery.isEmptyObject(plugin.options.r320)) {
setElementSize(plugin, plugin.options.r320);
} else {
setElementSize(plugin, plugin.options);
}
break;
case 768:
if(!jQuery.isEmptyObject(plugin.options.r768)) {
setElementSize(plugin, plugin.options.r768);
} else {
setElementSize(plugin, plugin.options);
}
break;
case 1024:
if(!jQuery.isEmptyObject(plugin.options.r1024)) {
setElementSize(plugin, plugin.options.r1024);
} else {
setElementSize(plugin, plugin.options);
}
break;
case 1280:
if(!jQuery.isEmptyObject(plugin.options.r1280)) {
setElementSize(plugin, plugin.options.r1280);
} else {
setElementSize(plugin, plugin.options);
}
break;
}
resetDisplayAndControlElements(plugin);
}
function addDragAndDropSwipeEventListener(plugin, options) {
if(Modernizr.touch) {
$('div.viewpoint, .overlaylabel', plugin.element).swipe({swipeStatus: function(event, phase, direction, distance, status) {
// Stop slideshow while swiping
clearInterval(plugin.functionscope.slideShowInterval);
// Clear all transitionstyles while swiping
clearTransitionStyles(plugin);
// Remove the headline while swiping
if(plugin.options.fadeOutHeadlineOnMouseOver) {
removeHeadline(plugin);
}
// Set desired directions (right now only horizontal swiping is supported)
directionnext = "left";
directionprevious = "right";
// Set boundaries
boundarynext = 0;
boundaryprevious = -$('div.viewpoint ul li', $(plugin.element)).size() + 1;
// Functions to handle the swipes in the desired directions
if(phase == "move" && (direction == directionnext || direction == directionprevious)) {
nextpossibleposition = getNextAvailablePosition(plugin, 'next');
previouspossibleposition = getNextAvailablePosition(plugin, 'previous');
// Calculate the swipeposition and set the new position
swipeposition = ((100 * distance) / $('div.viewpoint ul li', $(plugin.element)).outerWidth()) / options.elements;
// If no more elements are available slow the swipe down to simulate the native ios feeling
if((direction == directionprevious && previouspossibleposition == boundaryprevious) || (direction == directionnext && nextpossibleposition == boundarynext)) {
swipeposition /= 4;
}
if(direction == directionnext) {
newposition = -swipeposition;
} else {
newposition = swipeposition;
}
// Add the current position
newposition += (plugin.functionscope.position * 100);
// Set the new position
$('div.viewpoint ul', $(plugin.element)).css({'margin-left': newposition + "%"});
}
// Functions to handle the scroll to the next position
if((phase == "end" && swipeposition >= 30) || phase == "cancel") {
setTransitionStyles(plugin);
if(direction == directionnext && nextpossibleposition != boundarynext) {
plugin.functionscope.position = nextpossibleposition;
} else if(direction == directionprevious && previouspossibleposition != boundaryprevious) {
plugin.functionscope.position = previouspossibleposition;
}
scroll(plugin, plugin.functionscope.position);
// Restart slideshow
resetAndStartSlideshow(plugin);
}
// Functions to handle the scroll back to the current position
if(phase == "end" && swipeposition < 30) {
setTransitionStyles(plugin);
scroll(plugin, plugin.functionscope.position);
// Restart slideshow
resetAndStartSlideshow(plugin);
}
}, allowPageScroll: "vertical" })
}
}
function disableDragAndDropSwipeEventListener(plugin) {
$('div.viewpoint, .overlaylabel', plugin.element).swipe('destroy');
}
function startSlideshow(plugin) {
plugin.functionscope.stopSlideshow = false;
}
function stopSlideshow(plugin) {
plugin.functionscope.stopSlideshow = true;
}
$.fn.startSlideshow = function () {
return this.each(function () {
startSlideshow($.data(this, 'plugin_' + pluginName));
});
}
$.fn.stopSlideshow = function () {
return this.each(function () {
stopSlideshow($.data(this, 'plugin_' + pluginName));
});
}
$.fn.responsiveSlideshowRefresh = function () {
return this.each(function () {
responsiveSlideshowRefresh($.data(this, 'plugin_' + pluginName));
});
}
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
}
}(jQuery, window));<file_sep>responsive-slideshow
====================
A jQuery plugin for a responsive slideshow that works with touch gestures.
Requires modernizr: http://modernizr.com/
| ba2eb130820319893b7fb037ec17343ed58329b5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Trullus/responsive-slideshow | 3f007f295dfc2a4c7b2bfaaf20ffe2c9d87a3fcd | d6daf31aca4dbc6bafe4ec7bca72d89c95999bf9 |
refs/heads/master | <repo_name>daf/coi-services<file_sep>/ion/services/mi/drivers/sbe37_driver.py
#!/usr/bin/env python
"""
@package ion.services.mi.sbe37_driver
@file ion/services/mi/sbe37_driver.py
@author <NAME>
@brief Driver class for sbe37 CTD instrument.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import logging
import time
import re
import datetime
from ion.services.mi.instrument_driver import InstrumentDriver
from ion.services.mi.instrument_driver import DriverChannel
from ion.services.mi.instrument_driver import DriverCommand
from ion.services.mi.instrument_driver import DriverState
from ion.services.mi.instrument_driver import DriverEvent
from ion.services.mi.instrument_driver import DriverParameter
from ion.services.mi.exceptions import InstrumentProtocolException
from ion.services.mi.exceptions import InstrumentTimeoutException
from ion.services.mi.exceptions import InstrumentStateException
from ion.services.mi.exceptions import InstrumentConnectionException
from ion.services.mi.exceptions import RequiredParameterException
from ion.services.mi.common import InstErrorCode
from ion.services.mi.common import BaseEnum
from ion.services.mi.instrument_protocol import InstrumentProtocol
from ion.services.mi.instrument_protocol import CommandResponseInstrumentProtocol
from ion.services.mi.instrument_fsm_args import InstrumentFSM
#import ion.services.mi.mi_logger
mi_logger = logging.getLogger('mi_logger')
class SBE37State(BaseEnum):
"""
"""
UNCONFIGURED = DriverState.UNCONFIGURED
DISCONNECTED = DriverState.DISCONNECTED
COMMAND = DriverState.COMMAND
AUTOSAMPLE = DriverState.AUTOSAMPLE
class SBE37Event(BaseEnum):
"""
"""
ENTER = DriverEvent.ENTER
EXIT = DriverEvent.EXIT
CONFIGURE = DriverEvent.CONFIGURE
INITIALIZE = DriverEvent.INITIALIZE
CONNECT = DriverEvent.CONNECT
DISCONNECT = DriverEvent.DISCONNECT
DETACH = DriverEvent.DETACH
ACQUIRE_SAMPLE = DriverEvent.ACQUIRE_SAMPLE
START_AUTOSAMPLE = DriverEvent.START_AUTOSAMPLE
STOP_AUTOSAMPLE = DriverEvent.STOP_AUTOSAMPLE
TEST = DriverEvent.TEST
GET = DriverEvent.GET
SET = DriverEvent.SET
UPDATE_PARAMS = DriverEvent.UPDATE_PARAMS
class SBE37Channel(BaseEnum):
"""
"""
CTD = DriverChannel.CTD
ALL = DriverChannel.ALL
class SBE37Command(DriverCommand):
pass
# Device prompts.
class SBE37Prompt(BaseEnum):
"""
SBE37 io prompts.
"""
COMMAND = 'S>'
BAD_COMMAND = '?cmd S>'
AUTOSAMPLE = 'S>\r\n'
SBE37_NEWLINE = '\r\n'
SBE37_SAMPLE = 'SBE37_SAMPLE'
# Device specific parameters.
class SBE37Parameter(DriverParameter):
"""
Add sbe37 specific parameters here.
"""
OUTPUTSAL = 'OUTPUTSAL'
OUTPUTSV = 'OUTPUTSV'
NAVG = 'NAVG'
SAMPLENUM = 'SAMPLENUM'
INTERVAL = 'INTERVAL'
STORETIME = 'STORETIME'
TXREALTIME = 'TXREALTIME'
SYNCMODE = 'SYNCMODE'
SYNCWAIT = 'SYNCWAIT'
TCALDATE = 'TCALDATE'
TA0 = 'TA0'
TA1 = 'TA1'
TA2 = 'TA2'
TA3 = 'TA3'
CCALDATE = 'CCALDATE'
CG = 'CG'
CH = 'CH'
CI = 'CI'
CJ = 'CJ'
WBOTC = 'WBOTC'
CTCOR = 'CTCOR'
CPCOR = 'CPCOR'
PCALDATE = 'PCALDATE'
PA0 = 'PA0'
PA1 = 'PA1'
PA2 = 'PA2'
PTCA0 = 'PTCA0'
PTCA1 = 'PTCA1'
PTCA2 = 'PTCA2'
PTCB0 = 'PTCB0'
PTCB1 = 'PTCB1'
PTCB2 = 'PTCB2'
POFFSET = 'POFFSET'
RCALDATE = 'RCALDATE'
RTCA0 = 'RTCA0'
RTCA1 = 'RTCA1'
RTCA2 = 'RTCA2'
###############################################################################
# Seabird Electronics 37-SMP MicroCAT protocol.
###############################################################################
class SBE37Protocol(CommandResponseInstrumentProtocol):
"""
"""
def __init__(self, prompts, newline, evt_callback):
"""
"""
CommandResponseInstrumentProtocol.__init__(self, evt_callback, prompts, newline)
# Build protocol state machine.
self._fsm = InstrumentFSM(SBE37State, SBE37Event, SBE37Event.ENTER,
SBE37Event.EXIT, InstErrorCode.UNHANDLED_EVENT)
# Add handlers for all events.
self._fsm.add_handler(SBE37State.UNCONFIGURED, SBE37Event.ENTER, self._handler_unconfigured_enter)
self._fsm.add_handler(SBE37State.UNCONFIGURED, SBE37Event.EXIT, self._handler_unconfigured_exit)
self._fsm.add_handler(SBE37State.UNCONFIGURED, SBE37Event.INITIALIZE, self._handler_unconfigured_initialize)
self._fsm.add_handler(SBE37State.UNCONFIGURED, SBE37Event.CONFIGURE, self._handler_unconfigured_configure)
self._fsm.add_handler(SBE37State.DISCONNECTED, SBE37Event.ENTER, self._handler_disconnected_enter)
self._fsm.add_handler(SBE37State.DISCONNECTED, SBE37Event.EXIT, self._handler_disconnected_exit)
self._fsm.add_handler(SBE37State.DISCONNECTED, SBE37Event.INITIALIZE, self._handler_disconnected_initialize)
self._fsm.add_handler(SBE37State.DISCONNECTED, SBE37Event.CONFIGURE, self._handler_disconnected_configure)
self._fsm.add_handler(SBE37State.DISCONNECTED, SBE37Event.CONNECT, self._handler_disconnected_connect)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.ENTER, self._handler_command_enter)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.EXIT, self._handler_command_exit)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.DISCONNECT, self._handler_command_disconnect)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.GET, self._handler_command_autosample_get)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.SET, self._handler_command_set)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.ACQUIRE_SAMPLE, self._handler_command_acquire_sample)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.START_AUTOSAMPLE, self._handler_command_start_autosample)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.TEST, self._handler_command_test)
self._fsm.add_handler(SBE37State.COMMAND, SBE37Event.UPDATE_PARAMS, self._handler_command_update_params)
self._fsm.add_handler(SBE37State.AUTOSAMPLE, SBE37Event.ENTER, self._handler_autosample_enter)
self._fsm.add_handler(SBE37State.AUTOSAMPLE, SBE37Event.EXIT, self._handler_autosample_exit)
self._fsm.add_handler(SBE37State.AUTOSAMPLE, SBE37Event.STOP_AUTOSAMPLE, self._handler_autosample_stop_autosample)
self._fsm.add_handler(SBE37State.AUTOSAMPLE, SBE37Event.GET, self._handler_command_autosample_get)
# Start state machine.
self._fsm.start(SBE37State.UNCONFIGURED)
# Add build command handlers.
self._add_build_handler('ds', self._build_simple_command)
self._add_build_handler('dc', self._build_simple_command)
self._add_build_handler('ts', self._build_simple_command)
self._add_build_handler('startnow', self._build_simple_command)
self._add_build_handler('stop', self._build_simple_command)
self._add_build_handler('set', self._build_set_command)
# Add parse response handlers.
self._add_response_handler('ds', self._parse_dsdc_response)
self._add_response_handler('dc', self._parse_dsdc_response)
self._add_response_handler('ts', self._parse_ts_response)
self._add_response_handler('set', self._parse_set_response)
# Add sample handlers.
self._sample_pattern = r'^#? *(-?\d+\.\d+), *(-?\d+\.\d+), *(-?\d+\.\d+)'
self._sample_pattern += r'(, *(-?\d+\.\d+))?(, *(-?\d+\.\d+))?'
self._sample_pattern += r'(, *(\d+) +([a-zA-Z]+) +(\d+), *(\d+):(\d+):(\d+))?'
self._sample_pattern += r'(, *(\d+)-(\d+)-(\d+), *(\d+):(\d+):(\d+))?'
self._sample_regex = re.compile(self._sample_pattern)
# Add parameter handlers to parameter dict.
self._add_param_dict(SBE37Parameter.OUTPUTSAL,
r'(do not )?output salinity with each sample',
lambda match : False if match.group(1) else True,
self._true_false_to_string)
self._add_param_dict(SBE37Parameter.OUTPUTSV,
r'(do not )?output sound velocity with each sample',
lambda match : False if match.group(1) else True,
self._true_false_to_string)
self._add_param_dict(SBE37Parameter.NAVG,
r'number of samples to average = (\d+)',
lambda match : int(match.group(1)),
self._int_to_string)
self._add_param_dict(SBE37Parameter.SAMPLENUM,
r'samplenumber = (\d+), free = \d+',
lambda match : int(match.group(1)),
self._int_to_string)
self._add_param_dict(SBE37Parameter.INTERVAL,
r'sample interval = (\d+) seconds',
lambda match : int(match.group(1)),
self._int_to_string)
self._add_param_dict(SBE37Parameter.STORETIME,
r'(do not )?store time with each sample',
lambda match : False if match.group(1) else True,
self._true_false_to_string)
self._add_param_dict(SBE37Parameter.TXREALTIME,
r'(do not )?transmit real-time data',
lambda match : False if match.group(1) else True,
self._true_false_to_string)
self._add_param_dict(SBE37Parameter.SYNCMODE,
r'serial sync mode (enabled|disabled)',
lambda match : False if (match.group(1)=='disabled') else True,
self._true_false_to_string)
self._add_param_dict(SBE37Parameter.SYNCWAIT,
r'wait time after serial sync sampling = (\d+) seconds',
lambda match : int(match.group(1)),
self._int_to_string)
self._add_param_dict(SBE37Parameter.TCALDATE,
r'temperature: +((\d+)-([a-zA-Z]+)-(\d+))',
lambda match : self._string_to_date(match.group(1), '%d-%b-%y'),
self._date_to_string)
self._add_param_dict(SBE37Parameter.TA0,
r' +TA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.TA1,
r' +TA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.TA2,
r' +TA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.TA3,
r' +TA3 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.CCALDATE,
r'conductivity: +((\d+)-([a-zA-Z]+)-(\d+))',
lambda match : self._string_to_date(match.group(1), '%d-%b-%y'),
self._date_to_string)
self._add_param_dict(SBE37Parameter.CG,
r' +G = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.CH,
r' +H = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.CI,
r' +I = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.CJ,
r' +J = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.WBOTC,
r' +WBOTC = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.CTCOR,
r' +CTCOR = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.CPCOR,
r' +CPCOR = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PCALDATE,
r'pressure .+ ((\d+)-([a-zA-Z]+)-(\d+))',
lambda match : self._string_to_date(match.group(1), '%d-%b-%y'),
self._date_to_string)
self._add_param_dict(SBE37Parameter.PA0,
r' +PA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PA1,
r' +PA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PA2,
r' +PA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PTCA0,
r' +PTCA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PTCA1,
r' +PTCA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PTCA2,
r' +PTCA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PTCB0,
r' +PTCSB0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PTCB1,
r' +PTCSB1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.PTCB2,
r' +PTCSB2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.POFFSET,
r' +POFFSET = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.RCALDATE,
r'rtc: +((\d+)-([a-zA-Z]+)-(\d+))',
lambda match : self._string_to_date(match.group(1), '%d-%b-%y'),
self._date_to_string)
self._add_param_dict(SBE37Parameter.RTCA0,
r' +RTCA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.RTCA1,
r' +RTCA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
self._add_param_dict(SBE37Parameter.RTCA2,
r' +RTCA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)',
lambda match : float(match.group(1)),
self._float_to_string)
########################################################################
# Protocol connection interface.
########################################################################
def initialize(self, *args, **kwargs):
"""
"""
# Construct state machine params and fire event.
return self._fsm.on_event(SBE37Event.INITIALIZE, *args, **kwargs)
def configure(self, *args, **kwargs):
"""
"""
# Construct state machine params and fire event.
return self._fsm.on_event(SBE37Event.CONFIGURE, *args, **kwargs)
def connect(self, *args, **kwargs):
"""
"""
# Construct state machine params and fire event.
return self._fsm.on_event(SBE37Event.CONNECT, *args, **kwargs)
def disconnect(self, *args, **kwargs):
"""
"""
# Construct state machine params and fire event.
return self._fsm.on_event(SBE37Event.DISCONNECT, *args, **kwargs)
def detach(self, *args, **kwargs):
"""
"""
# Construct state machine params and fire event.
return self._fsm.on_event(SBE37Event.DETACH, *args, **kwargs)
########################################################################
# Protocol command interface.
########################################################################
def get(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.GET, *args, **kwargs)
def set(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.SET, *args, **kwargs)
def execute_direct(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.EXECUTE, *args, **kwargs)
def execute_acquire_sample(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.ACQUIRE_SAMPLE, *args, **kwargs)
def execute_start_autosample(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.START_AUTOSAMPLE, *args, **kwargs)
def execute_stop_autosample(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.STOP_AUTOSAMPLE, *args, **kwargs)
def execute_test(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.TEST, *args, **kwargs)
def update_params(self, *args, **kwargs):
"""
"""
return self._fsm.on_event(SBE37Event.UPDATE_PARAMS, *args, **kwargs)
########################################################################
# Protocol query interface.
########################################################################
def get_resource_commands(self):
"""
"""
return [cmd for cmd in dir(self) if cmd.startswith('execute_')]
def get_resource_params(self):
"""
"""
return self._get_param_dict_names()
def get_current_state(self):
"""
"""
return self._fsm.get_current_state()
########################################################################
# State handlers
########################################################################
########################################################################
# SBE37State.UNCONFIGURED
########################################################################
def _handler_unconfigured_enter(self, *args, **kwargs):
"""
"""
mi_logger.info('channel %s entered state %s', SBE37Channel.CTD,
SBE37State.UNCONFIGURED)
self._publish_state_change(SBE37State.UNCONFIGURED)
# Initialize throws no exceptions.
InstrumentProtocol.initialize(self, *args, **kwargs)
def _handler_unconfigured_exit(self, *args, **kwargs):
"""
"""
pass
def _handler_unconfigured_initialize(self, *args, **kwargs):
"""
"""
next_state = None
result = None
# Reenter initialize.
next_state = SBE37State.UNCONFIGURED
return (next_state, result)
def _handler_unconfigured_configure(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
InstrumentProtocol.configure(self, *args, **kwargs)
except (TypeError, KeyError, InstrumentConnectionException, IndexError):
result = InstErrorCode.INVALID_PARAMETER
next_state = None
# Everything worked, set next state.
else:
next_state = SBE37State.DISCONNECTED
return (next_state, result)
########################################################################
# SBE37State.DISCONNECTED
########################################################################
def _handler_disconnected_enter(self, *args, **kwargs):
"""
"""
mi_logger.info('channel %s entered state %s',SBE37Channel.CTD,
SBE37State.DISCONNECTED)
self._publish_state_change(SBE37State.DISCONNECTED)
def _handler_disconnected_exit(self, *args, **kwargs):
"""
"""
pass
def _handler_disconnected_initialize(self, *args, **kwargs):
"""
"""
next_state = None
result = None
# Switch to unconfigured to initialize comms.
next_state = SBE37State.UNCONFIGURED
return (next_state, result)
def _handler_disconnected_configure(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
InstrumentProtocol.configure(self, *args, **kwargs)
except (TypeError, KeyError, InstrumentConnectionException, IndexError):
result = InstErrorCode.INVALID_PARAMETER
next_state = SBE37State.UNCONFIGURED
return (next_state, result)
def _handler_disconnected_connect(self, *args, **kwargs):
"""
@throw InstrumentTimeoutException on timeout
"""
next_state = None
result = None
try:
InstrumentProtocol.connect(self, *args, **kwargs)
timeout = kwargs.get('timeout', 10)
prompt = self._wakeup(timeout)
if prompt == SBE37Prompt.COMMAND:
next_state = SBE37State.COMMAND
elif prompt == SBE37Prompt.AUTOSAMPLE:
next_state = SBE37State.AUTOSAMPLE
except InstrumentConnectionException:
# Connection failed, fail and stay here.
next_state = None
result = InstErrorCode.DRIVER_CONNECT_FAILED
except InstrumentTimeoutException:
# Timeout connecting or waking device. Stay disconnected.
InstrumentProtocol.disconnect(self, *args, **kwargs)
next_state = None
result = InstErrorCode.DRIVER_CONNECT_FAILED
return (next_state, result)
########################################################################
# SBE37State.COMMAND
########################################################################
def _handler_command_enter(self, *args, **kwargs):
"""
"""
mi_logger.info('channel %s entered state %s',SBE37Channel.CTD,
SBE37State.COMMAND)
self._publish_state_change(SBE37State.COMMAND)
self._update_params(*args, **kwargs)
def _handler_command_exit(self, *args, **kwargs):
"""
"""
pass
def _handler_command_disconnect(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
mi_logger.info('DISCONNECTING')
InstrumentProtocol.disconnect(self, *args, **kwargs)
mi_logger.info('DONE DISCONNECTING')
next_state = SBE37State.DISCONNECTED
except InstrumentConnectionException:
# Disconnect failed. Fail and stay here.
next_state = None
result = InstErrorCode.DISCONNECT_FAILED
else:
next_state = SBE37State.DISCONNECTED
result = InstErrorCode.OK
return (next_state, result)
def _handler_command_set(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
result = self._do_cmd_resp('set', *args, **kwargs)
next_state = None
except InstrumentTimeoutException:
next_state = None
result = InstErrorCode.TIMEOUT
except IndexError:
next_state = None
result = InstErrorCode.REQUIRED_PARAMETER
return (next_state, result)
def _handler_command_acquire_sample(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
result = self._do_cmd_resp('ts', *args, **kwargs)
except InstrumentTimeoutException:
result = InstErrorCode.TIMEOUT
return (next_state, result)
def _handler_command_start_autosample(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
self._do_cmd_no_resp('startnow', *args, **kwargs)
next_state = SBE37State.AUTOSAMPLE
except InstrumentTimeoutException:
result = InstErrorCode.TIMEOUT
return (next_state, result)
def _handler_command_test(self, *args, **kwargs):
"""
"""
next_state = None
result = None
return (next_state, result)
def _handler_command_update_params(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
self._update_params(*args, **kwargs)
except InstrumentTimeoutError:
result = InstErrorCode.TIMEOUT
return (next_state, result)
########################################################################
# SBE37State.AUTOSAMPLE
########################################################################
def _handler_autosample_enter(self, *args, **kwargs):
"""
"""
mi_logger.info('channel %s entered state %s',SBE37Channel.CTD,
SBE37State.AUTOSAMPLE)
self._publish_state_change(SBE37State.AUTOSAMPLE)
def _handler_autosample_exit(self, *args, **kwargs):
"""
"""
pass
def _handler_autosample_stop_autosample(self, *args, **kwargs):
"""
@throw InstrumentProtocolException on invalid command
"""
next_state = None
result = None
try:
prompt = None
timeout = kwargs.get('timeout', 10)
while prompt != SBE37Prompt.AUTOSAMPLE:
prompt = self._wakeup(timeout)
self._do_cmd_resp('stop', *args, **kwargs)
prompt = None
while prompt != SBE37Prompt.COMMAND:
prompt = self._wakeup(timeout)
next_state = SBE37State.COMMAND
except InstrumentTimeoutException:
result = InstErrorCode.TIMEOUT
return (next_state, result)
########################################################################
# SBE37State.COMMAND and SBE37State.AUTOSAMPLE common handlers.
########################################################################
def _handler_command_autosample_get(self, *args, **kwargs):
"""
"""
next_state = None
result = None
try:
parameter = args[0]
except IndexError:
result = InstErrorCode.REQUIRED_PARAMETER
else:
try:
result = self._get_param_dict(parameter)
except KeyError:
result = InstErrorCode.INVALID_PARAMETER
return (next_state, result)
########################################################################
# Private helpers
########################################################################
def _got_data(self, data):
"""
"""
CommandResponseInstrumentProtocol._got_data(self, data)
# Only keep the latest characters in the prompt buffer.
if len(self._promptbuf)>7:
self._promptbuf = self._promptbuf[-7:]
# If we are streaming, process the line buffer for samples.
if self._fsm.get_current_state() == SBE37State.AUTOSAMPLE:
self._process_streaming_data()
def _process_streaming_data(self):
"""
"""
if self.eoln in self._linebuf:
lines = self._linebuf.split(SBE37_NEWLINE)
self._linebuf = lines[-1]
for line in lines:
sample = self._extract_sample(line, True)
def _send_wakeup(self):
"""
"""
self._logger_client.send(SBE37_NEWLINE)
def _update_params(self, *args, **kwargs):
"""
"""
timeout = kwargs.get('timeout', 10)
old_config = self._get_config_param_dict()
self._do_cmd_resp('ds',timeout=timeout)
self._do_cmd_resp('dc',timeout=timeout)
new_config = self._get_config_param_dict()
if new_config != old_config:
if self.send_event:
event = {
'type' : 'config_change',
'value' : new_config
}
self.send_event(event)
def _build_simple_command(self, cmd):
"""
"""
return cmd+SBE37_NEWLINE
def _build_set_command(self, cmd, param, val):
"""
"""
str_val = self._format_param_dict(param, val)
set_cmd = '%s=%s' % (param, str_val)
set_cmd = set_cmd + SBE37_NEWLINE
return set_cmd
def _parse_dsdc_response(self, response, prompt):
"""
"""
for line in response.split(SBE37_NEWLINE):
self._update_param_dict(line)
def _parse_ts_response(self, response, prompt):
"""
"""
sample = None
for line in response.split(SBE37_NEWLINE):
sample = self._extract_sample(line, True)
if sample: break
return sample
def _extract_sample(self, line, publish=True):
"""
"""
sample = None
match = self._sample_regex.match(line)
if match:
sample = {}
sample['t'] = [float(match.group(1))]
sample['c'] = [float(match.group(2))]
sample['p'] = [float(match.group(3))]
# Extract sound velocity and salinity if present.
#if match.group(5) and match.group(7):
# sample['salinity'] = float(match.group(5))
# sample['sound_velocity'] = float(match.group(7))
#elif match.group(5):
# if self._get_param_dict(SBE37Parameter.OUTPUTSAL):
# sample['salinity'] = float(match.group(5))
# elif self._get_param_dict(SBE37Parameter.OUTPUTSV):
# sample['sound_velocity'] = match.group(5)
# Extract date and time if present.
# sample_time = None
#if match.group(8):
# sample_time = time.strptime(match.group(8),', %d %b %Y, %H:%M:%S')
#
#elif match.group(15):
# sample_time = time.strptime(match.group(15),', %m-%d-%Y, %H:%M:%S')
#
#if sample_time:
# sample['time'] = \
# '%4i-%02i-%02iT:%02i:%02i:%02i' % sample_time[:6]
# Add UTC time from driver in iso 8601 format.
#sample['driver_time'] = datetime.datetime.utcnow().isoformat()
# Driver timestamp.
sample['time'] = [time.time()]
if publish and self.send_event:
event = {
'type':'sample',
'name':'ctd_parsed',
'value':sample
}
self.send_event(event)
return sample
def _parse_set_response(self, response, prompt):
"""
"""
if prompt == SBE37Prompt.COMMAND:
return InstErrorCode.OK
else:
return InstErrorCode.BAD_DRIVER_COMMAND
def _publish_state_change(self, state):
"""
"""
if self.send_event:
event = {
'type': 'state_change',
'value': state
}
self.send_event(event)
########################################################################
# Static helpers to format set commands.
########################################################################
@staticmethod
def _true_false_to_string(v):
"""
Write a boolean value to string formatted for sbe37 set operations.
@param v a boolean value.
@retval A yes/no string formatted for sbe37 set operations, or
None if the input is not a valid bool.
"""
if not isinstance(v,bool):
return None
if v:
return 'y'
else:
return 'n'
@staticmethod
def _int_to_string(v):
"""
Write an int value to string formatted for sbe37 set operations.
@param v An int val.
@retval an int string formatted for sbe37 set operations, or None if
the input is not a valid int value.
"""
if not isinstance(v,int):
return None
else:
return '%i' % v
@staticmethod
def _float_to_string(v):
"""
Write a float value to string formatted for sbe37 set operations.
@param v A float val.
@retval a float string formatted for sbe37 set operations, or None if
the input is not a valid float value.
"""
if not isinstance(v,float):
return None
else:
return '%e' % v
@staticmethod
def _date_to_string(v):
"""
Write a date tuple to string formatted for sbe37 set operations.
@param v a date tuple: (day,month,year).
@retval A date string formatted for sbe37 set operations,
or None if the input is not a valid date tuple.
"""
if not isinstance(v,(list,tuple)):
return None
if not len(v)==3:
return None
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep',
'Oct','Nov','Dec']
day = v[0]
month = v[1]
year = v[2]
if len(str(year)) > 2:
year = int(str(year)[-2:])
if not isinstance(day,int) or day < 1 or day > 31:
return None
if not isinstance(month,int) or month < 1 or month > 12:
return None
if not isinstance(year,int) or year < 0 or year > 99:
return None
return '%02i-%s-%02i' % (day,months[month-1],year)
@staticmethod
def _string_to_date(datestr,fmt):
"""
Extract a date tuple from an sbe37 date string.
@param str a string containing date information in sbe37 format.
@retval a date tuple, or None if the input string is not valid.
"""
if not isinstance(datestr,str):
return None
try:
date_time = time.strptime(datestr,fmt)
date = (date_time[2],date_time[1],date_time[0])
except ValueError:
return None
return date
###############################################################################
# Seabird Electronics 37-SMP MicroCAT driver.
###############################################################################
class SBE37Driver(InstrumentDriver):
"""
class docstring
"""
def __init__(self, evt_callback):
"""
method docstring
"""
InstrumentDriver.__init__(self, evt_callback)
# Build the protocol for CTD channel.
protocol = SBE37Protocol(SBE37Prompt, SBE37_NEWLINE, evt_callback)
self._channels = {SBE37Channel.CTD:protocol}
########################################################################
# Channel connection interface.
########################################################################
def initialize(self, channels = [SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[channel].initialize(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
def configure(self, configs, *args, **kwargs):
"""
"""
try:
channels = configs.keys()
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
config = configs[channel]
result[channel] = self._channels[channel].configure(config, *args, **kwargs)
except (RequiredParameterException, TypeError):
result = InstErrorCode.REQUIRED_PARAMETER
return result
def connect(self, channels = [SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[channel].connect(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
def disconnect(self, channels = [SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[channel].disconnect(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
def detach(self, channels=[SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[channel].detach(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
########################################################################
# Channel command interface.
########################################################################
def get(self, params, *args, **kwargs):
"""
"""
try:
(result, params) = self._check_get_args(params)
for (channel, parameter) in params:
success = InstErrorCode.OK
result[(channel, parameter)] = self._channels[channel].get(parameter, *args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
# Return overall success and individual results.
return result
def set(self, params, *args, **kwargs):
"""
"""
try:
(result, params) = self._check_set_args(params)
updated_channels = []
# Process each parameter-value pair.
for (key, val) in params.iteritems():
channel = key[0]
parameter = key[1]
result[key] = self._channels[channel].set(parameter, val, *args, **kwargs)
if channel not in updated_channels:
updated_channels.append(channel)
for channel in updated_channels:
self._channels[channel].update_params(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
# Additional checking can go here.
# Return overall success and individual results.
return result
def execute_direct(self, channels=[SBE37Channel.CTD], *args, **kwargs):
"""
"""
pass
def execute_acquire_sample(self, channels=[SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[SBE37Channel.CTD].\
execute_acquire_sample(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
def start_autosample(self, channels=[SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[SBE37Channel.CTD].\
execute_start_autosample(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
def stop_autosample(self, channels=[SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[SBE37Channel.CTD].\
execute_stop_autosample(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
def execute_test(self, channels=[SBE37Channel.CTD], *args, **kwargs):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[SBE37Channel.CTD].\
execute_test(*args, **kwargs)
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
########################################################################
# TBD.
########################################################################
def get_resource_commands(self):
"""
"""
result = []
cmds = self._channels[SBE37Channel.CTD].get_resource_commands()
if cmds:
result = [(SBE37Channel.CTD, cmd) for cmd in cmds]
return result
def get_resource_params(self):
"""
"""
result = []
params = self._channels[SBE37Channel.CTD].get_resource_params()
if params:
result = [(SBE37Channel.CTD, param) for param in params]
return result
def get_channels(self):
"""
"""
return SBE37Channels.list()
def get_active_channels(self):
"""
"""
state = self.get_current_state()[SBE37Channel.CTD]
if state in [SBE37State.COMMAND, SBE37State.AUTOSAMPLE]:
result = [SBE37Channel.CTD]
else:
result = []
return result
def get_current_state(self, channels=[SBE37Channel.CTD]):
"""
"""
try:
(result, valid_channels) = self._check_channel_args(channels)
for channel in valid_channels:
result[channel] = self._channels[channel].get_current_state()
except RequiredParameterException:
result = InstErrorCode.REQUIRED_PARAMETER
return result
########################################################################
# Private helpers.
########################################################################
@staticmethod
def _check_channel_args(channels):
"""
"""
valid_channels = []
result = {}
if channels == None or not isinstance(channels, (list, tuple)):
raise RequiredParameterException()
elif len(channels) == 0:
raise RequiredParameterException()
else:
clist = SBE37Channel.list()
if SBE37Channel.ALL in clist:
clist.remove(SBE37Channel.ALL)
# Expand "ALL channel keys.
if SBE37Channel.ALL in channels:
channels += clist
channels = [c for c in channels if c != SBE37Channel.ALL]
# Make unique.
channels = list(set(channels))
# Separate valid and invalid channels.
valid_channels = [c for c in channels if c in clist]
invalid_channels = [c for c in channels if c not in clist]
# Build result dict with invalid entries.
for c in invalid_channels:
result[c] = InstErrorCode.INVALID_CHANNEL
return (result, valid_channels)
@staticmethod
def _check_get_args(params):
"""
"""
valid_params = []
result = {}
if params == None or not isinstance(params, (list, tuple)):
raise RequiredParameterException()
elif len(params) == 0:
raise RequiredParameterException()
else:
temp_list = []
plist = SBE37Parameter.list()
if SBE37Parameter.ALL in plist:
plist.remove(SBE37Parameter.ALL)
clist = SBE37Channel.list()
if SBE37Channel.ALL in clist:
clist.remove(SBE37Channel.ALL)
# Expand and remove "ALL" channel specifiers.
params += [(c, parameter) for (channel, parameter) in params
if channel == SBE37Channel.ALL for c in clist]
params = [(c, p) for (c, p) in params if c != SBE37Channel.ALL]
# Expand and remove "ALL" parameter specifiers.
params += [(channel, p) for (channel, parameter) in params
if parameter == SBE37Parameter.ALL for p in plist]
params = [(c, p) for (c, p) in params if p != SBE37Parameter.ALL]
# Make list unique.
params = list(set(params))
# Separate valid and invalid params.
invalid_params = [(c, p) for (c, p) in params if c in clist and p not in plist]
invalid_channels = [(c, p) for (c, p) in params if c not in clist]
valid_params = [(c, p) for (c, p) in params if c in clist and p in plist]
# Build result
for (c, p) in invalid_params:
result[(c, p)] = InstErrorCode.INVALID_PARAMETER
for (c, p) in invalid_channels:
result[(c, p)] = InstErrorCode.INVALID_CHANNEL
return (result, valid_params)
@staticmethod
def _check_set_args(params):
"""
"""
valid_params = {}
result = {}
if params == None or not isinstance(params, dict):
raise RequiredParameterException()
elif len(params) == 0:
raise RequiredParameterException()
else:
plist = SBE37Parameter.list()
if SBE37Parameter.ALL in plist:
plist.remove(SBE37Parameter.ALL)
clist = SBE37Channel.list()
if SBE37Channel.ALL in clist:
clist.remove(SBE37Channel.ALL)
# Expand and remove "ALL" channel specifiers.
for (key, val) in params.iteritems():
if key[0] == SBE37Channel.ALL:
for c in clist: params[(c, key[1])] = val
params.pop(key)
# Remove invalid parameters.
temp_params = params.copy()
for (key, val) in temp_params.iteritems():
if key[0] not in clist:
result[key] = InstErrorCode.INVALID_CHANNEL
params.pop(key)
elif key[1] not in plist:
result[key] = InstErrorCode.INVALID_PARAMETER
params.pop(key)
return (result, params)
########################################################################
# Misc and temp.
########################################################################
def driver_echo(self, msg):
"""
"""
echo = 'driver_echo: %s' % msg
return echo
<file_sep>/ion/core/bootstrap_service.py
#!/usr/bin/env python
"""Process that bootstraps an ION system"""
__author__ = '<NAME>'
from pyon.public import CFG, IonObject, log, get_sys_name, RT, LCS, PRED, iex
from pyon.ion.exchange import ION_ROOT_XS
from interface.services.ibootstrap_service import BaseBootstrapService
class BootstrapService(BaseBootstrapService):
"""
Bootstrap service: This service will initialize the ION system environment.
This service is triggered for each boot level.
"""
def on_init(self):
log.info("Bootstrap service INIT: System init")
def on_start(self):
level = self.CFG.level
log.info("Bootstrap service START: service start, level: %s", level)
self.trigger_level(level, self.CFG)
def trigger_level(self, level, config):
#print "Bootstrap level: %s config: %s" % (str(level),str(config))
if level == "datastore":
self.post_datastore(config)
elif level == "directory":
self.post_directory(config)
elif level == "resource_registry":
self.post_resource_registry(config)
elif level == "identity_management":
self.post_identity_management(config)
elif level == "org_management":
self.post_org_management(config)
elif level == "exchange_management":
self.post_exchange_management(config)
self.post_startup()
# Create ROOT user identity
# Create default roles
# Create default policy
def post_datastore(self, config):
# Make sure to detect that system was already bootstrapped.
# Look in datastore for secret cookie\
cookie_name = get_sys_name() + ".ION_INIT"
try:
res = self.clients.datastore.read_doc(cookie_name)
log.error("System %s already initialized: %s" % (get_sys_name(), res))
return
except iex.NotFound:
pass
# Now set the secret cookie
import time
cookie = dict(container=self.container.id, time=time.time())
cid, _ = self.clients.datastore.create_doc(cookie, cookie_name)
def post_directory(self, config):
# Load service definitions into directory
# Load resource types into directory
# Load object types into directory
pass
def post_resource_registry(self, config):
for res in RT.keys():
rt = IonObject("ResourceType", name=res)
#self.clients.datastore.create(rt)
def post_identity_management(self, config):
# TBD
pass
def post_org_management(self, config):
# Create root Org: ION
root_orgname = CFG.system.root_org
org = IonObject(RT.Org, name=root_orgname, description="Root Org")
self.org_id = self.clients.org_management.create_org(org)
def post_exchange_management(self, config):
# find root org
root_orgname = CFG.system.root_org # @TODO: THIS CAN BE SPECIFIED ON A PER LAUNCH BASIS, HOW TO FIND?
org = self.clients.org_management.find_org(name=root_orgname)
# Create root ExchangeSpace
xs = IonObject(RT.ExchangeSpace, name=ION_ROOT_XS, description="ION service XS")
self.xs_id = self.clients.exchange_management.create_exchange_space(xs, org._id)
#self.clients.resource_registry.find_objects(self.org_id, "HAS-A")
#self.clients.resource_registry.find_subjects(self.xs_id, "HAS-A")
def post_startup(self):
log.info("Cannot sanity check bootstrap yet, need better plan to sync local state (or pull from datastore?)")
# # Do some sanity tests across the board
# org_ids, _ = self.clients.resource_registry.find_resources(RT.Org, None, None, True)
# self.assert_condition(len(org_ids) == 1 and org_ids[0] == self.org_id, "Orgs not properly defined")
#
# xs_ids, _ = self.clients.resource_registry.find_resources(RT.ExchangeSpace, None, None, True)
# self.assert_condition(len(xs_ids) == 1 and xs_ids[0] == self.xs_id, "ExchangeSpace not properly defined")
#
# res_ids, _ = self.clients.resource_registry.find_objects(self.org_id, PRED.hasExchangeSpace, RT.ExchangeSpace, True)
# self.assert_condition(len(res_ids) == 1 and res_ids[0] == self.xs_id, "ExchangeSpace not associated")
#
# res_ids, _ = self.clients.resource_registry.find_subjects(RT.Org, PRED.hasExchangeSpace, self.xs_id, True)
# self.assert_condition(len(res_ids) == 1 and res_ids[0] == self.org_id, "Org not associated")
def on_quit(self):
log.info("Bootstrap service QUIT: System quit")
<file_sep>/ion/services/mi/zmq_driver_process.py
#!/usr/bin/env python
"""
@package ion.services.mi.zmq_driver_process
@file ion/services/mi/zmq_driver_process.py
@author <NAME>
@brief Driver processes using ZMQ messaging.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
"""
To launch this object from class static constructor:
import ion.services.mi.zmq_driver_process as zdp
p = zdp.ZmqDriverProcess.launch_process(5556, 5557, 'ion.services.mi.drivers.sbe37_driver', 'SBE37Driver')
"""
from threading import Thread
from subprocess import Popen
import os
import time
import logging
import sys
import zmq
import ion.services.mi.mi_logger
import ion.services.mi.driver_process as driver_process
mi_logger = logging.getLogger('mi_logger')
class ZmqDriverProcess(driver_process.DriverProcess):
"""
A OS-level driver process that communicates with ZMQ sockets.
Command-REP and event-PUB sockets monitor and react to comms
needs in separate threads, which can be signaled to end
by setting boolean flags stop_cmd_thread and stop_evt_thread.
"""
@classmethod
def launch_process(cls, cmd_port, event_port, driver_module, driver_class):
"""
Class method constructor to launch ZmqDriverProcess as a
separate OS process. Creates command string for this
class and pass to superclass static method. Method has the same
function signature as the class constructor.
@param cmd_port Int IP port of the command REP socket.
@param event_port Int IP port of the event socket.
@param driver_module The python module containing the driver code.
@param driver_class The python driver class.
@retval a Popen object representing the ZMQ driver process.
"""
cmd_str = 'from %s import %s; dp = %s(%i, %i, "%s", "%s");dp.run()' \
% (__name__, cls.__name__, cls.__name__,
cmd_port, event_port, driver_module, driver_class)
return driver_process.DriverProcess.launch_process(cmd_str)
def __init__(self, cmd_port, event_port, driver_module, driver_class):
"""
@param cmd_port Int IP port of the command REP socket.
@param event_port Int IP port of the event socket.
@param driver_module The python module containing the driver code.
@param driver_class The python driver class.
"""
driver_process.DriverProcess.__init__(self, driver_module, driver_class)
self.cmd_port = cmd_port
self.cmd_host_string = 'tcp://*:%i' % self.cmd_port
self.event_port = event_port
self.event_host_string = 'tcp://*:%i' % self.event_port
self.evt_thread = None
self.stop_evt_thread = True
self.cmd_thread = None
self.stop_cmd_thread = True
def start_messaging(self):
"""
Initialize and start messaging resources for the driver, blocking
until messaging terminates. This ZMQ implementation starts and
joins command and event threads, managing nonblocking send/recv calls
on REP and PUB sockets, respectively. Terminate loops and close
sockets when stop flag is set in driver process.
"""
def recv_cmd_msg(zmq_driver_process):
"""
Await commands on a ZMQ REP socket, forwaring them to the
driver for processing and returning the result.
"""
context = zmq.Context()
sock = context.socket(zmq.REP)
sock.bind(zmq_driver_process.cmd_host_string)
mi_logger.info('Driver process cmd socket bound to %s',
zmq_driver_process.cmd_host_string)
zmq_driver_process.stop_cmd_thread = False
while not zmq_driver_process.stop_cmd_thread:
try:
msg = sock.recv_pyobj(flags=zmq.NOBLOCK)
mi_logger.debug('Processing message %s', str(msg))
reply = zmq_driver_process.cmd_driver(msg)
while True:
try:
sock.send_pyobj(reply)
break
except zmq.ZMQError:
time.sleep(.1)
except zmq.ZMQError:
time.sleep(.1)
sock.close()
context.term()
mi_logger.info('Driver process cmd socket closed.')
def send_evt_msg(zmq_driver_process):
"""
Await events on the driver process event queue and publish them
on a ZMQ PUB socket to the driver process client.
"""
context = zmq.Context()
sock = context.socket(zmq.PUB)
sock.bind(zmq_driver_process.event_host_string)
mi_logger.info('Driver process event socket bound to %s',
zmq_driver_process.event_host_string)
zmq_driver_process.stop_evt_thread = False
while not zmq_driver_process.stop_evt_thread:
try:
evt = zmq_driver_process.events.pop(0)
mi_logger.debug('Event thread sending event %s', str(evt))
while evt:
try:
sock.send_pyobj(evt, flags=zmq.NOBLOCK)
evt = None
mi_logger.debug('Event sent!')
except zmq.ZMQError:
time.sleep(.1)
except IndexError:
time.sleep(.1)
sock.close()
context.term()
mi_logger.info('Driver process event socket closed')
self.cmd_thread = Thread(target=recv_cmd_msg, args=(self, ))
self.evt_thread = Thread(target=send_evt_msg, args=(self, ))
self.cmd_thread.start()
self.evt_thread.start()
self.cmd_thread.join()
self.evt_thread.join()
def stop_messaging(self):
"""
Close messaging resource for the driver. Set flags to cause
command and event threads to close sockets and conclude.
"""
self.stop_cmd_thread = True
self.stop_evt_thread = True
def shutdown(self):
"""
Shutdown function prior to process exit.
"""
driver_process.DriverProcess.shutdown(self)
<file_sep>/ion/services/sa/direct_access/ion_telnet_server.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
"""
TELNET server class
"""
from gevent import socket
from pyon.core.exception import ServerError
from pyon.util.log import log
import gevent
class TelnetServer(object):
server_socket = None
port = None
ip_address = None
parent_input_callback = None
username = None
password = None
fileobj = None
parent_requested_close = False
TELNET_PROMPT = 'ION telnet>'
PORT_RANGE_LOWER = 8000
PORT_RANGE_UPPER = 8010
def write(self, text):
self.fileobj.write(text)
self.fileobj.flush()
def writeline(self, text):
"""Send a packet with line ending."""
self.write(text+chr(10))
def authorized(self, username, password):
if username == self.username and password == self.password:
return True
else:
log.debug("un=" + username + " pw=" + password + " sun=" + self.username + " spw=" + self.password)
return False
def close_connection(self):
if not self.parent_requested_close:
self.parent_input_callback(-1)
else:
try:
self.server_socket.shutdown(socket.SHUT_RDWR)
except Exception as ex:
# can happen if telnet client closes session first
log.debug("exception caught for socket shutdown:" + str(ex))
self.server_socket.close()
def exit_handler (self, reason):
self.close_connection()
log.debug("TelnetServer.handler(): stopping, " + reason)
def handler(self, new_socket, address):
"The actual service to which the user has connected."
log.debug("TelnetServer.handler(): starting")
self.fileobj = new_socket.makefile()
username = None
password = None
self.write("Username: ")
try:
username = self.fileobj.readline().rstrip('\n\r')
except EOFError:
self.exit_handler("lost connection")
return
if username == '':
self.exit_handler("lost connection")
return
self.write("Password: ")
try:
password = self.fileobj.readline().rstrip('\n\r')
except EOFError:
self.exit_handler("lost connection")
return
if not self.authorized(username, password):
log.debug("login failed")
self.writeline("login failed")
self.exit_handler("login failed")
return
while True:
self.write(self.TELNET_PROMPT)
try:
input_line = self.fileobj.readline()
except EOFError:
self.exit_handler("lost connection")
break
if input_line == '':
self.exit_handler("lost connection")
break
log.debug("rcvd: " + input_line)
log.debug("len=" + str(len(input_line)))
self.parent_input_callback(input_line.rstrip('\n\r'))
def server_greenlet(self):
log.debug("TelnetServer.server_greenlet(): started")
self.server_socket.listen(1)
new_socket, address = self.server_socket.accept()
self.handler(new_socket, address)
log.debug("TelnetServer.server_greenlet(): stopping")
def __init__(self, input_callback=None):
log.debug("TelnetServer.__init__()")
if not input_callback:
log.warning("TelnetServer.__init__(): callback not specified")
raise ServerError("callback not specified")
self.parent_input_callback = input_callback
# TODO: get username and password dynamically
self.username = 'admin'
self.password = '123'
# TODO: get ip_address & port number dynamically
# TODO: ensure that port is not already in use
self.port = self.PORT_RANGE_LOWER
self.ip_address = 'localhost'
#self.ip_address = '192.168.3.11'
# create telnet server object and start the server process
self.server_socket = socket.socket()
self.server_socket.allow_reuse_address = True
while True:
try:
self.server_socket.bind((self.ip_address, self.port))
break
except:
self.port = self.port + 1
log.debug("trying to bind to port " + str(self.port))
if self.port > self.PORT_RANGE_UPPER:
log.warning("TelnetServer.server_greenlet(): no available ports for server")
self.close_connection()
return
gevent.spawn(self.server_greenlet)
def get_connection_info(self):
return self.ip_address, self.port, self.username, self.password
def stop(self):
log.debug("TelnetServer.stop()")
self.parent_requested_close = True
try:
self.server_socket.shutdown(socket.SHUT_RDWR)
except Exception as ex:
# can happen if telnet client closes session first
log.debug("exception caught for socket shutdown:" + str(ex))
return
gevent.sleep(.1)
self.server_socket.close()
del self.server_socket
def send(self, data):
# send data from parent to telnet server process to forward to client
log.debug("TelnetServer.write(): data = " + str(data))
self.write(data)
<file_sep>/ion/services/dm/presentation/test/user_notification_test.py
'''
@author <NAME>
@file ion/services/dm/presentation/test/user_notification_test.py
@description Unit and Integration test implementations for the user notification service class.
'''
from interface.services.coi.iidentity_management_service import IdentityManagementServiceClient
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from interface.services.dm.iuser_notification_service import UserNotificationServiceClient
from ion.services.dm.presentation.user_notification_service import UserNotificationService
from pyon.util.int_test import IonIntegrationTestCase
from pyon.util.unit_test import PyonTestCase
from pyon.public import IonObject, RT, PRED
from nose.plugins.attrib import attr
import unittest
from pyon.util.log import log
from pyon.event.event import ResourceLifecycleEventPublisher, DataEventPublisher
import gevent
@attr('UNIT',group='dm')
@unittest.skip('not working')
class UserNotificationTest(PyonTestCase):
def setUp(self):
mock_clients = self._create_service_mock('user_notification')
self.user_notification = UserNotificationService()
self.user_notification.clients = mock_clients
self.mock_rr_client = self.user_notification.clients.resource_registry
self.notification_object = IonObject(RT.NotificationRequest, name="notification")
def test_create_one_user_notification(self):
# mocks
self.mock_rr_client.create.return_value = ('notification_id','rev')
self.mock_rr_client.read.return_value = ('user_1_info')
# execution
notification_id = self.user_notification.create_notification(self.notification_object, 'user_1')
# assertions
self.assertEquals(notification_id,'notification_id')
self.assertTrue(self.mock_rr_client.create.called)
def test_update_user_notification(self):
# mocks
# execution
# assertions
pass
def test_delete_user_notification(self):
# mocks
# execution
# assertions
pass
@attr('INT', group='dm')
class UserNotificationIntTest(IonIntegrationTestCase):
def setUp(self):
self._start_container()
self.container.start_rel_from_url('res/deploy/r2dm.yml')
self.unsc = UserNotificationServiceClient(node=self.container.node)
self.rrc = ResourceRegistryServiceClient(node=self.container.node)
self.imc = IdentityManagementServiceClient(node=self.container.node)
def xtest_find_event_types_for_resource(self):
dataset_object = IonObject(RT.DataSet, name="dataset1")
dataset_id, version = self.rrc.create(dataset_object)
events = self.unsc.find_event_types_for_resource(dataset_id)
log.debug("dataset events = " + str(events))
try:
events = self.unsc.find_event_types_for_resource("bogus_id")
self.fail("failed to detect non-existant resource")
except:
pass
def test_create_two_user_notifications(self):
user_identty_object = IonObject(RT.UserIdentity, name="user1")
user_id = self.imc.create_user_identity(user_identty_object)
user_info_object = IonObject(RT.UserInfo, {"name":"user1_info", "contact":{"email":'<EMAIL>'}})
self.imc.create_user_info(user_id, user_info_object)
notification_object = IonObject(RT.NotificationRequest, {"name":"notification1",
"origin_list":['Some_Resource_Agent_ID1'],
"events_list":['resource_lifecycle']})
self.unsc.create_notification(notification_object, user_id)
notification_object = IonObject(RT.NotificationRequest, {"name":"notification2",
"origin_list":['Some_Resource_Agent_ID2'],
"events_list":['data']})
self.unsc.create_notification(notification_object, user_id)
def test_delete_user_notifications(self):
user_identty_object = IonObject(RT.UserIdentity, name="user1")
user_id = self.imc.create_user_identity(user_identty_object)
user_info_object = IonObject(RT.UserInfo, {"name":"user1_info", "contact":{"email":'<EMAIL>'}})
self.imc.create_user_info(user_id, user_info_object)
notification_object1 = IonObject(RT.NotificationRequest, {"name":"notification1",
"origin_list":['Some_Resource_Agent_ID1'],
"events_list":['resource_lifecycle']})
notification1_id = self.unsc.create_notification(notification_object1, user_id)
notification_object2 = IonObject(RT.NotificationRequest, {"name":"notification2",
"origin_list":['Some_Resource_Agent_ID2'],
"events_list":['data']})
notification2_id = self.unsc.create_notification(notification_object2, user_id)
self.unsc.delete_notification(notification1_id)
self.unsc.delete_notification(notification2_id)
def test_find_user_notifications(self):
user_identty_object = IonObject(RT.UserIdentity, name="user1")
user_id = self.imc.create_user_identity(user_identty_object)
user_info_object = IonObject(RT.UserInfo, {"name":"user1_info", "contact":{"email":'<EMAIL>'}})
self.imc.create_user_info(user_id, user_info_object)
notification_object = IonObject(RT.NotificationRequest, {"name":"notification1",
"origin_list":['Some_Resource_Agent_ID1'],
"events_list":['resource_lifecycle']})
self.unsc.create_notification(notification_object, user_id)
notification_object = IonObject(RT.NotificationRequest, {"name":"notification2",
"origin_list":['Some_Resource_Agent_ID2'],
"events_list":['data']})
self.unsc.create_notification(notification_object, user_id)
notifications = self.unsc.find_notifications_by_user(user_id)
for n in notifications:
log.debug("n = " +str(n))
def test_update_user_notification(self):
user_identty_object = IonObject(RT.UserIdentity, name="user1")
user_id = self.imc.create_user_identity(user_identty_object)
user_info_object = IonObject(RT.UserInfo, {"name":"user1_info", "contact":{"email":'<EMAIL>'}})
self.imc.create_user_info(user_id, user_info_object)
notification_object = IonObject(RT.NotificationRequest, {"name":"notification1",
"origin_list":['Some_Resource_Agent_ID1'],
"events_list":['resource_lifecycle']})
notification_id = self.unsc.create_notification(notification_object, user_id)
notification = self.rrc.read(notification_id)
notification.origin_list = ['Some_Resource_Agent_ID5']
self.unsc.update_notification(notification)
def test_send_notification_emails(self):
user_identty_object = IonObject(RT.UserIdentity, name="user1")
user_id = self.imc.create_user_identity(user_identty_object)
user_info_object = IonObject(RT.UserInfo, {"name":"user1_info", "contact":{"email":'<EMAIL>'}})
self.imc.create_user_info(user_id, user_info_object)
notification_object = IonObject(RT.NotificationRequest, {"name":"notification1",
"origin_list":['Some_Resource_Agent_ID1'],
"events_list":['resource_lifecycle']})
self.unsc.create_notification(notification_object, user_id)
notification_object = IonObject(RT.NotificationRequest, {"name":"notification2",
"origin_list":['Some_Resource_Agent_ID2'],
"events_list":['data']})
self.unsc.create_notification(notification_object, user_id)
rle_publisher = ResourceLifecycleEventPublisher()
rle_publisher.create_and_publish_event(origin='Some_Resource_Agent_ID1', description="RLE test event")
de_publisher = DataEventPublisher()
de_publisher.create_and_publish_event(origin='Some_Resource_Agent_ID2', description="DE test event")
gevent.sleep(1)
def test_find_events(self):
rle_publisher = ResourceLifecycleEventPublisher(event_repo=self.container.event_repository)
rle_publisher.create_and_publish_event(origin='Some_Resource_Agent_ID1', description="RLE test event1")
rle_publisher.create_and_publish_event(origin='Some_Resource_Agent_ID1', description="RLE test event2")
de_publisher = DataEventPublisher(event_repo=self.container.event_repository)
de_publisher.create_and_publish_event(origin='Some_Resource_Agent_ID2', description="DE test event1")
de_publisher.create_and_publish_event(origin='Some_Resource_Agent_ID2', description="DE test event2")
events = self.unsc.find_events(origin='Some_Resource_Agent_ID1')
for event in events:
log.debug("event=" + str(event))
events = self.unsc.find_events(type='DataEvent')
for event in events:
log.debug("event=" + str(event))
<file_sep>/ion/services/sa/direct_access/platform_direct_access.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from ion.services.sa.direct_access.direct_access import DirectAccess
class PlatformDirectAccess(DirectAccess):
"""
Class for direct access at the platform level
"""
def request(self, request_params={}):
pass
def stop(self, stop_params={}):
pass
<file_sep>/ion/services/coi/test/test_identity_management_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import unittest
from mock import Mock, patch
from pyon.util.unit_test import PyonTestCase
from pyon.util.int_test import IonIntegrationTestCase
from nose.plugins.attrib import attr
from pyon.core.exception import BadRequest, Conflict, Inconsistent, NotFound
from pyon.public import PRED, RT, IonObject
from ion.services.coi.identity_management_service import IdentityManagementService
from interface.services.icontainer_agent import ContainerAgentClient
from interface.services.coi.iidentity_management_service import IdentityManagementServiceClient, IdentityManagementServiceProcessClient
from pyon.util.context import LocalContextMixin
@attr('UNIT', group='coi')
class TestIdentityManagementService(PyonTestCase):
def setUp(self):
mock_clients = self._create_service_mock('identity_management')
self.identity_management_service = IdentityManagementService()
self.identity_management_service.clients = mock_clients
# Rename to save some typing
self.mock_create = mock_clients.resource_registry.create
self.mock_read = mock_clients.resource_registry.read
self.mock_update = mock_clients.resource_registry.update
self.mock_delete = mock_clients.resource_registry.delete
self.mock_create_association = mock_clients.resource_registry.create_association
self.mock_delete_association = mock_clients.resource_registry.delete_association
self.mock_find_objects = mock_clients.resource_registry.find_objects
self.mock_find_resources = mock_clients.resource_registry.find_resources
self.mock_find_subjects = mock_clients.resource_registry.find_subjects
self.mock_find_associations = mock_clients.resource_registry.find_associations
# UserIdentity
self.user_identity = Mock()
self.user_identity._id = '111'
self.user_identity.name = "Foo"
# UserCredential
self.user_credentials = Mock()
self.user_credentials._id = '222'
self.user_credentials.name = "Bogus subject"
# UserCredential
self.user_credentials2 = Mock()
self.user_credentials2._id = '777'
self.user_credentials2.name = "Bogus subject"
# UserIdentity to UserCredential association
self.user_identity_to_credentials_association = Mock()
self.user_identity_to_credentials_association._id = '333'
self.user_identity_to_credentials_association.s = "111"
self.user_identity_to_credentials_association.st = RT.UserIdentity
self.user_identity_to_credentials_association.p = PRED.hasCredentials
self.user_identity_to_credentials_association.o = "222"
self.user_identity_to_credentials_association.ot = RT.UserCredentials
# UserIdentity to UserCredential association
self.user_identity_to_credentials_association2 = Mock()
self.user_identity_to_credentials_association2._id = '888'
self.user_identity_to_credentials_association2.s = "111"
self.user_identity_to_credentials_association2.st = RT.UserIdentity
self.user_identity_to_credentials_association2.p = PRED.hasCredentials
self.user_identity_to_credentials_association2.o = "222"
self.user_identity_to_credentials_association2.ot = RT.UserCredentials
# UserInfo
self.user_info = Mock()
self.user_info.name = "<NAME>"
self.user_info.email = "<EMAIL>"
self.user_info.phone = "555-555-5555"
self.user_info.variables = [{"name": "subscribeToMailingList", "value": "False"}]
self.user_info2 = Mock()
self.user_info2.name = "<NAME>"
self.user_info2.email = "<EMAIL>"
self.user_info2.phone = "555-555-5556"
self.user_info2.variables = [{"name": "subscribeToMailingList", "value": "True"}]
# UserIdentity to UserInfo association
self.user_identity_to_info_association = Mock()
self.user_identity_to_info_association._id = '555'
self.user_identity_to_info_association.s = "111"
self.user_identity_to_info_association.st = RT.UserIdentity
self.user_identity_to_info_association.p = PRED.hasInfo
self.user_identity_to_info_association.o = "444"
self.user_identity_to_info_association.ot = RT.UserInfo
def test_create_user_identity(self):
self.mock_create.return_value = ['111', 1]
user_id = self.identity_management_service.create_user_identity(self.user_identity)
assert user_id == '111'
self.mock_create.assert_called_once_with(self.user_identity)
def test_read_and_update_user_identity(self):
self.mock_read.return_value = self.user_identity
user_identity = self.identity_management_service.read_user_identity('111')
assert user_identity is self.mock_read.return_value
self.mock_read.assert_called_once_with('111', '')
user_identity.name = 'Bar'
self.mock_update.return_value = ['111', 2]
self.identity_management_service.update_user_identity(user_identity)
self.mock_update.assert_called_once_with(user_identity)
def test_delete_user_identity(self):
self.mock_read.return_value = self.user_identity
self.identity_management_service.delete_user_identity('111')
self.mock_read.assert_called_once_with('111', '')
self.mock_delete.assert_called_once_with('111')
def test_read_user_identity_not_found(self):
self.mock_read.return_value = None
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.identity_management_service.read_user_identity('bad')
ex = cm.exception
self.assertEqual(ex.message, 'UserIdentity bad does not exist')
self.mock_read.assert_called_once_with('bad', '')
def test_delete_user_identity_not_found(self):
self.mock_read.return_value = None
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.identity_management_service.delete_user_identity('bad')
ex = cm.exception
self.assertEqual(ex.message, 'UserIdentity bad does not exist')
self.mock_read.assert_called_once_with('bad', '')
def test_register_user_credentials(self):
self.mock_create.return_value = ['222', 1]
self.mock_create_association.return_value = ['333', 1]
self.identity_management_service.register_user_credentials('111', self.user_credentials)
self.mock_create.assert_called_once_with(self.user_credentials)
self.mock_create_association.assert_called_once_with('111', PRED.hasCredentials, '222', None)
def test_unregister_user_credentials(self):
self.mock_find_resources.return_value = ([self.user_credentials], [self.user_identity_to_credentials_association])
self.mock_find_associations.return_value = [self.user_identity_to_credentials_association]
self.identity_management_service.unregister_user_credentials('111', "<PASSWORD>")
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, self.user_credentials.name, False)
self.mock_find_associations.assert_called_once_with('111', PRED.hasCredentials, '222', False)
self.mock_delete_association.assert_called_once_with('333')
self.mock_delete.assert_called_once_with('222')
def test_unregister_user_credentials_not_found(self):
self.mock_find_resources.return_value = (None, None)
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.identity_management_service.unregister_user_credentials('bad', 'bad')
ex = cm.exception
self.assertEqual(ex.message, 'UserCredentials bad does not exist')
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, 'bad', False)
def test_unregister_user_credentials_association_not_found(self):
self.mock_find_resources.return_value = ([self.user_credentials], [self.user_identity_to_credentials_association])
self.mock_find_associations.return_value = None
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.identity_management_service.unregister_user_credentials('111', "Bogus subject")
ex = cm.exception
self.assertEqual(ex.message, 'UserIdentity to UserCredentials association for user id 111 to credential Bogus subject does not exist')
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, 'Bogus subject', False)
self.mock_find_associations.assert_called_once_with('111', PRED.hasCredentials, '222', False)
def test_create_user_info(self):
self.mock_find_objects.return_value = (None, None)
self.mock_create.return_value = ['444', 1]
self.mock_create_association.return_value = ['555', 1]
result = self.identity_management_service.create_user_info('111', self.user_info)
assert result == '444'
self.mock_create.assert_called_once_with(self.user_info)
self.mock_create_association.assert_called_once_with('111', PRED.hasInfo, '444', None)
def test_create_user_info_fail_already_exists(self):
self.mock_find_objects.return_value = ([self.user_info], [self.user_identity_to_info_association])
# TEST: Execute the service operation call
with self.assertRaises(Conflict) as cm:
self.identity_management_service.create_user_info('111', self.user_info)
ex = cm.exception
self.assertEqual(ex.message, 'UserInfo already exists for user id 111')
self.mock_find_objects.assert_called_once_with('111', PRED.hasInfo, RT.UserInfo, False)
def test_read_and_update_user_info(self):
self.mock_read.return_value = self.user_info
user_info = self.identity_management_service.read_user_info('444')
assert user_info is self.mock_read.return_value
self.mock_read.assert_called_once_with('444', '')
user_info.name = '<NAME>'
self.mock_update.return_value = ['444', 2]
self.identity_management_service.update_user_info(user_info)
self.mock_update.assert_called_once_with(user_info)
def test_delete_user_info(self):
self.mock_read.return_value = self.user_info
self.mock_find_subjects.return_value = ([self.user_identity], [self.user_identity_to_info_association])
self.mock_find_associations.return_value = ([self.user_identity_to_info_association])
self.identity_management_service.delete_user_info('444')
self.mock_find_subjects.assert_called_once_with(RT.UserIdentity, PRED.hasInfo, '444', False)
self.mock_find_associations.assert_called_once_with('111', PRED.hasInfo, '444', False)
self.mock_delete_association.assert_called_once_with('555')
self.mock_delete.assert_called_once_with('444')
def test_read_user_info_not_found(self):
self.mock_read.return_value = None
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.identity_management_service.read_user_info('bad')
ex = cm.exception
self.assertEqual(ex.message, 'UserInfo bad does not exist')
self.mock_read.assert_called_once_with('bad', '')
def test_delete_user_info_not_found(self):
self.mock_read.return_value = None
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.identity_management_service.delete_user_info('bad')
ex = cm.exception
self.assertEqual(ex.message, 'UserInfo bad does not exist')
self.mock_read.assert_called_once_with('bad', '')
def test_delete_user_info_association_not_found(self):
self.mock_read.return_value = self.user_info
self.mock_find_subjects.return_value = (None, None)
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.identity_management_service.delete_user_info('444')
ex = cm.exception
self.assertEqual(ex.message, 'UserIdentity to UserInfo association for user info id 444 does not exist')
self.mock_read.assert_called_once_with('444', '')
self.mock_find_subjects.assert_called_once_with(RT.UserIdentity, PRED.hasInfo, '444', False)
def test_find_user_info_by_id(self):
self.mock_find_objects.return_value = ([self.user_info], [self.user_identity_to_info_association])
result = self.identity_management_service.find_user_info_by_id('111')
assert result == self.user_info
self.mock_find_objects.assert_called_once_with('111', PRED.hasInfo, RT.UserInfo, False)
def test_find_user_info_by_id_association_not_found(self):
self.mock_find_objects.return_value = (None, None)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.find_user_info_by_id('111')
ex = cm.exception
self.assertEqual(ex.message, 'UserInfo for user id 111 does not exist')
self.mock_find_objects.assert_called_once_with('111', PRED.hasInfo, RT.UserInfo, False)
def test_find_user_info_by_name(self):
self.mock_find_resources.return_value = ([self.user_info], [self.user_identity_to_info_association])
result = self.identity_management_service.find_user_info_by_name("<NAME>")
assert result == self.user_info
self.mock_find_resources.assert_called_once_with(RT.UserInfo, None, "<NAME>", False)
def test_find_user_info_by_name_not_found(self):
self.mock_find_resources.return_value = (None, None)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.find_user_info_by_name("<NAME>")
ex = cm.exception
self.assertEqual(ex.message, 'UserInfo with name <NAME> does not exist')
self.mock_find_resources.assert_called_once_with(RT.UserInfo, None, "<NAME>", False)
def test_find_user_info_by_name_multiple_found(self):
self.mock_find_resources.return_value = ([self.user_info, self.user_info2], [self.user_identity_to_info_association])
with self.assertRaises(Inconsistent) as cm:
self.identity_management_service.find_user_info_by_name("<NAME>")
ex = cm.exception
self.assertEqual(ex.message, 'Multiple UserInfos with name <NAME> exist')
self.mock_find_resources.assert_called_once_with(RT.UserInfo, None, "<NAME>", False)
def test_find_user_info_by_subject(self):
self.mock_find_resources.return_value = ([self.user_credentials], [self.user_identity_to_credentials_association])
self.mock_find_subjects.return_value = ([self.user_identity], [self.user_identity_to_credentials_association])
self.mock_find_objects.return_value = ([self.user_info], [self.user_identity_to_info_association])
result = self.identity_management_service.find_user_info_by_subject("Bogus subject")
assert result == self.user_info
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, "Bogus subject", False)
self.mock_find_objects.assert_called_once_with('111', PRED.hasInfo, RT.UserInfo, False)
def test_find_user_info_by_subject_identity_credentials_not_found(self):
self.mock_find_resources.return_value = (None, None)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.find_user_info_by_subject("Bogus subject")
ex = cm.exception
self.assertEqual(ex.message, "UserCredentials with subject Bogus subject does not exist")
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, "Bogus subject", False)
def test_find_user_info_by_subject_identity_multiple_credentials_found(self):
self.mock_find_resources.return_value = ([self.user_credentials, self.user_credentials2], [self.user_identity_to_credentials_association, self.user_identity_to_credentials_association2])
with self.assertRaises(Inconsistent) as cm:
self.identity_management_service.find_user_info_by_subject("Bogus subject")
ex = cm.exception
self.assertEqual(ex.message, "Multiple UserCredentials with subject Bogus subject exist")
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, "Bogus subject", False)
def test_find_user_info_by_subject_identity_association_not_found(self):
self.mock_find_resources.return_value = ([self.user_credentials], None)
self.mock_find_subjects.return_value = (None, None)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.find_user_info_by_subject("Bogus subject")
ex = cm.exception
self.assertEqual(ex.message, "UserIdentity to UserCredentials association for subject Bogus subject does not exist")
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, "Bogus subject", False)
def test_find_user_info_by_subject_identity_multiple_associations_found(self):
self.mock_find_resources.return_value = ([self.user_credentials], [self.user_identity_to_credentials_association, self.user_identity_to_credentials_association2])
self.mock_find_subjects.return_value = ([self.user_info, self.user_info2], [self.user_identity_to_credentials_association, self.user_identity_to_credentials_association2])
with self.assertRaises(Inconsistent) as cm:
self.identity_management_service.find_user_info_by_subject("Bogus subject")
ex = cm.exception
self.assertEqual(ex.message, "Multiple UserIdentity to UserCredentials associations for subject Bogus subject exist")
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, "Bogus subject", False)
def test_find_user_info_by_subject_info_association_not_found(self):
self.mock_find_resources.return_value = ([self.user_credentials], [self.user_identity_to_credentials_association])
self.mock_find_subjects.return_value = ([self.user_identity], [self.user_identity_to_credentials_association])
self.mock_find_objects.return_value = (None, None)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.find_user_info_by_subject("Bogus subject")
ex = cm.exception
self.assertEqual(ex.message, "UserInfo for subject Bogus subject does not exist")
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, "Bogus subject", False)
self.mock_find_objects.assert_called_once_with('111', PRED.hasInfo, RT.UserInfo, False)
def test_find_user_info_by_subject_info_multiple_associations_found(self):
self.mock_find_resources.return_value = ([self.user_credentials], [self.user_identity_to_credentials_association])
self.mock_find_subjects.return_value = ([self.user_info], [self.user_identity_to_credentials_association])
self.mock_find_objects.return_value = ([self.user_info, self.user_info2], [self.user_identity_to_info_association])
with self.assertRaises(Inconsistent) as cm:
self.identity_management_service.find_user_info_by_subject("Bogus subject")
ex = cm.exception
self.assertEqual(ex.message, "Multiple UserInfos for subject Bogus subject exist")
self.mock_find_resources.assert_called_once_with(RT.UserCredentials, None, "Bogus subject", False)
self.mock_find_subjects.assert_called_once_with(RT.UserIdentity, PRED.hasCredentials, '222', False)
# def test_signon_new_user(self):
# user.certificate = """-----BEGIN CERTIFICPREDE-----
#MI<KEY>
#MBUGCgmSJom<KEY>
#-----END CERTIFICPREDE-----"""
#
# def test_signon_known_user(self):
@attr('INT', group='coi')
class TestIdentityManagementServiceInt(IonIntegrationTestCase):
def setUp(self):
self.subject = "/DC=org/DC=cilogon/C=US/O=ProtectNetwork/CN=Roger Unwin A254"
# Start container
self._start_container()
# Establish endpoint with container
container_client = ContainerAgentClient(node=self.container.node, name=self.container.name)
container_client.start_rel_from_url('res/deploy/r2coi.yml')
self.identity_management_service = IdentityManagementServiceClient(node=self.container.node)
def test_user_identity(self):
user_identity_obj = IonObject("UserIdentity", {"name": self.subject})
user_id = self.identity_management_service.create_user_identity(user_identity_obj)
user_identity = self.identity_management_service.read_user_identity(user_id)
user_identity.name = 'Updated subject'
self.identity_management_service.update_user_identity(user_identity)
self.identity_management_service.delete_user_identity(user_id)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.read_user_identity(user_id)
self.assertTrue("does not exist" in cm.exception.message)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.delete_user_identity(user_id)
self.assertTrue("does not exist" in cm.exception.message)
def test_user_credentials(self):
user_identity_obj = IonObject("UserIdentity", {"name": self.subject})
user_id = self.identity_management_service.create_user_identity(user_identity_obj)
user_credentials_obj = IonObject("UserCredentials", {"name": self.subject})
self.identity_management_service.register_user_credentials(user_id, user_credentials_obj)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.unregister_user_credentials("bad", self.subject)
self.assertTrue("does not exist" in cm.exception.message)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.unregister_user_credentials(user_id, "bad")
self.assertTrue("does not exist" in cm.exception.message)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.unregister_user_credentials('bad', 'bad')
self.assertTrue("does not exist" in cm.exception.message)
self.identity_management_service.unregister_user_credentials(user_id, self.subject)
self.identity_management_service.delete_user_identity(user_id)
def test_user_info(self):
user_identity_obj = IonObject("UserIdentity", {"name": self.subject})
user_id = self.identity_management_service.create_user_identity(user_identity_obj)
user_credentials_obj = IonObject("UserCredentials", {"name": self.subject})
self.identity_management_service.register_user_credentials(user_id, user_credentials_obj)
user_info_obj = IonObject("UserInfo", {"name": "Foo"})
user_info = self.identity_management_service.create_user_info(user_id, user_info_obj)
with self.assertRaises(Conflict) as cm:
self.identity_management_service.create_user_info(user_id, user_info_obj)
self.assertTrue("UserInfo already exists for user id" in cm.exception.message)
user_info_obj = self.identity_management_service.find_user_info_by_id(user_id)
user_info_obj = self.identity_management_service.find_user_info_by_name("Foo")
user_info_obj = self.identity_management_service.find_user_info_by_subject(self.subject)
user_info_obj = self.identity_management_service.read_user_info(user_info)
user_info_obj.name = '<NAME>'
self.identity_management_service.update_user_info(user_info_obj)
self.identity_management_service.delete_user_info(user_info)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.read_user_info(user_info)
self.assertTrue('does not exist' in cm.exception.message)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.delete_user_info(user_info)
self.assertTrue('does not exist' in cm.exception.message)
with self.assertRaises(NotFound) as cm:
self.identity_management_service.find_user_info_by_name("<NAME>")
self.assertEqual(cm.exception.message, 'UserInfo with name <NAME> does not exist')
with self.assertRaises(NotFound) as cm:
self.identity_management_service.find_user_info_by_subject("Bogus subject")
self.assertEqual(cm.exception.message, "UserCredentials with subject Bogus subject does not exist")
self.identity_management_service.unregister_user_credentials(user_id, self.subject)
self.identity_management_service.delete_user_identity(user_id)
def test_signon(self):
certificate = """-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----"""
id, valid_until, registered = self.identity_management_service.signon(certificate, True)
self.assertFalse(registered)
id2, valid_until2, registered2 = self.identity_management_service.signon(certificate, True)
self.assertFalse(registered2)
self.assertTrue(id == id2)
self.assertTrue(valid_until == valid_until2)
user_info_obj = IonObject("UserInfo", {"name": "Foo"})
self.identity_management_service.create_user_info(id, user_info_obj)
id3, valid_until3, registered3 = self.identity_management_service.signon(certificate, True)
self.assertTrue(registered3)
self.assertTrue(id == id3)
self.assertTrue(valid_until == valid_until3)
<file_sep>/ion/services/mi/drivers/test/test_sbe37_driver.py
#!/usr/bin/env python
"""
@package ion.services.mi.test.test_sbe37_driver
@file ion/services/mi/test_sbe37_driver.py
@author <NAME>
@brief Test cases for SBE37Driver
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from gevent import monkey; monkey.patch_all()
import time
import unittest
import logging
from subprocess import Popen
import os
import signal
from nose.plugins.attrib import attr
from pyon.util.unit_test import PyonTestCase
from ion.services.mi.zmq_driver_client import ZmqDriverClient
from ion.services.mi.zmq_driver_process import ZmqDriverProcess
from ion.services.mi.drivers.sbe37_driver import SBE37Channel
from ion.services.mi.drivers.sbe37_driver import SBE37Parameter
from ion.services.mi.drivers.sbe37_driver import SBE37Command
from ion.services.mi.drivers.sbe37_driver import SBE37Driver
from ion.services.mi.common import InstErrorCode
import ion.services.mi.mi_logger
mi_logger = logging.getLogger('mi_logger')
#from pyon.public import log
# Make tests verbose and provide stdout
# bin/nosetests -s -v ion/services/mi/drivers/test/test_sbe37_driver.py
# bin/nosetests -s -v ion/services/mi/drivers/test/test_sbe37_driver.py:TestSBE37Driver.test_get_set
# bin/nosetests -s -v ion/services/mi/drivers/test/test_sbe37_driver.py:TestSBE37Driver.test_config
# bin/nosetests -s -v ion/services/mi/drivers/test/test_sbe37_driver.py:TestSBE37Driver.test_connect
# bin/nosetests -s -v ion/services/mi/drivers/test/test_sbe37_driver.py:TestSBE37Driver.test_poll
# bin/nosetests -s -v ion/services/mi/drivers/test/test_sbe37_driver.py:TestSBE37Driver.test_autosample
@unittest.skip('Do not run hardware test.')
@attr('INT', group='mi')
class TestSBE37Driver(PyonTestCase):
"""
Integration tests for the sbe37 driver. This class tests and shows
use patterns for the sbe37 driver as a zmq driver process.
"""
def setUp(self):
"""
Setup test cases.
"""
# Zmq parameters to configure communications with the driver process.
self.server_addr = 'localhost'
self.cmd_port = 5556
self.evt_port = 5557
# Driver module parameters for importing and constructing the driver.
self.dvr_mod = 'ion.services.mi.drivers.sbe37_driver'
self.dvr_cls = 'SBE37Driver'
# Driver comms config. This is passed as a configure message
# argument to transition the driver to disconnected and ready to
# connect.
self.comms_config = {
SBE37Channel.CTD:{
'method':'ethernet',
'device_addr': '192.168.127.12',
'device_port': 4001,
'server_addr': 'localhost',
'server_port': 8888
}
}
# Add cleanup handler functions.
# Add functions to detect and kill processes and remove pidfiles
# as necessary.
#psout = subprocess.check_output(['ps -e | grep python'], shell=True)
#1724 ?? 0:00.01 /Users/edwardhunter/Documents/Dev/virtenvs/coi/bin/python bin/python -c import ion.services.mi.logger_process as lp; l = lp.EthernetD
#1721 ttys000 0:00.24 /Users/edwardhunter/Documents/Dev/virtenvs/coi/bin/python bin/python -c from ion.services.mi.zmq_driver_process import ZmqDriverProce
#
#1742 ?? 0:00.01 /Users/edwardhunter/Documents/Dev/virtenvs/coi/bin/python bin/python -c import ion.services.mi.logger_process as lp; l = lp.EthernetDeviceLogger("192.168.127.12", 4001, 8888, "/", ["<<",">>"]); l.start()
#1739 ttys000 0:02.66 /Users/edwardhunter/Documents/Dev/virtenvs/coi/bin/python bin/python -c from ion.services.mi.zmq_driver_process import ZmqDriverProcess; dp = ZmqDriverProcess(5556, 5557, "ion.services.mi.drivers.sbe37_driver", "SBE37Driver");dp.run()
# self.addCleanup()
self.events = None
def clear_events(self):
"""
Clear the event list.
"""
self.events = []
def evt_recd(self, evt):
"""
Simple callback to catch events from the driver for verification.
"""
self.events.append(evt)
def test_process(self):
"""
Test for correct launch of driver process and communications, including
asynchronous driver events.
"""
# Launch driver process.
driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
self.evt_port, self.dvr_mod, self.dvr_cls)
# Create client and start messaging.
driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
self.evt_port)
self.clear_events()
driver_client.start_messaging(self.evt_recd)
time.sleep(2)
# Add test to verify process exists.
# Send a test message to the process interface, confirm result.
msg = 'I am a ZMQ message going to the process.'
reply = driver_client.cmd_dvr('process_echo', msg)
self.assertEqual(reply,'process_echo: '+msg)
# Send a test message to the driver interface, confirm result.
msg = 'I am a ZMQ message going to the driver.'
reply = driver_client.cmd_dvr('driver_echo', msg)
self.assertEqual(reply, 'driver_echo: '+msg)
# Test the event thread publishes and client side picks up events.
events = [
'I am important event #1!',
'And I am important event #2!'
]
reply = driver_client.cmd_dvr('test_events', events=events)
time.sleep(2)
# Confirm the events received are as expected.
self.assertEqual(self.events, events)
# Terminate driver process and stop client messaging.
driver_client.done()
driver_process.wait()
# Add test to verify process does not exist.
def test_config(self):
"""
Test to configure the driver process for device comms and transition
to disconnected state.
"""
# Launch driver process.
driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
self.evt_port, self.dvr_mod, self.dvr_cls)
# Create client and start messaging.
driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
self.evt_port)
driver_client.start_messaging()
time.sleep(2)
# Configure driver for comms and transition to disconnected.
reply = driver_client.cmd_dvr('configure', self.comms_config)
time.sleep(2)
# Initialize the driver and transition to unconfigured.
reply = driver_client.cmd_dvr('initialize')
time.sleep(2)
# Terminate driver process and stop client messaging.
driver_client.done()
driver_process.wait()
def test_connect(self):
"""
Test to establish device comms and transition to command state.
"""
# Launch driver process.
driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
self.evt_port, self.dvr_mod, self.dvr_cls)
# Create client and start messaging.
driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
self.evt_port)
driver_client.start_messaging()
time.sleep(2)
# Configure driver for comms and transition to disconnected.
reply = driver_client.cmd_dvr('configure', self.comms_config)
time.sleep(2)
# Establish device comms and transition to command.
reply = driver_client.cmd_dvr('connect')
time.sleep(2)
# Disconnect devcie comms and transition to disconnected.
reply = driver_client.cmd_dvr('disconnect')
time.sleep(2)
# Initialize driver and transition to unconfigured.
reply = driver_client.cmd_dvr('initialize')
time.sleep(2)
# Terminate driver process and stop client messaging.
driver_client.done()
driver_process.wait()
def test_get_set(self):
"""
Test driver parameter get/set interface including device persistence.
TA2=-4.858579e-06
PTCA1=-0.6603433
TCALDATE=(8, 11, 2005)
"""
# Launch driver process.
driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
self.evt_port, self.dvr_mod, self.dvr_cls)
# Create client and start messaging.
driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
self.evt_port)
driver_client.start_messaging()
time.sleep(3)
# Configure driver for comms and transition to disconnected.
reply = driver_client.cmd_dvr('configure', self.comms_config)
time.sleep(2)
# Establish devcie comms and transition to command.
reply = driver_client.cmd_dvr('connect')
time.sleep(2)
# Get all parameters.
get_params = [
(SBE37Channel.CTD, SBE37Parameter.ALL)
]
reply = driver_client.cmd_dvr('get', get_params)
time.sleep(2)
# Check overall and individual parameter success. Check parameter types.
self.assertIsInstance(reply, dict)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
(list, tuple))
# Set up a param dict of the original values.
old_ta2 = reply[(SBE37Channel.CTD, SBE37Parameter.TA2)]
old_ptca1 = reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)]
old_tcaldate = reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)]
orig_params = {
(SBE37Channel.CTD, SBE37Parameter.TA2): old_ta2,
(SBE37Channel.CTD, SBE37Parameter.PTCA1): old_ptca1,
(SBE37Channel.CTD, SBE37Parameter.TCALDATE): old_tcaldate
}
# Set up a param dict of new values.
new_ta2 = old_ta2*2
new_ptcal1 = old_ptca1*2
new_tcaldate = list(old_tcaldate)
new_tcaldate[2] = new_tcaldate[2] + 1
new_tcaldate = tuple(new_tcaldate)
new_params = {
(SBE37Channel.CTD, SBE37Parameter.TA2): new_ta2,
(SBE37Channel.CTD, SBE37Parameter.PTCA1): new_ptcal1,
(SBE37Channel.CTD, SBE37Parameter.TCALDATE): new_tcaldate
}
# Set the params to their new values.
reply = driver_client.cmd_dvr('set', new_params)
time.sleep(2)
# Check overall success and success of the individual paramters.
self.assertIsInstance(reply, dict)
mi_logger.debug('set result: %s', str(reply))
# Get the same paramters back from the driver.
get_params = [
(SBE37Channel.CTD, SBE37Parameter.TA2),
(SBE37Channel.CTD, SBE37Parameter.PTCA1),
(SBE37Channel.CTD, SBE37Parameter.TCALDATE)
]
reply = driver_client.cmd_dvr('get', get_params)
time.sleep(2)
# Check success, and check that the parameters were set to the
# new values.
self.assertIsInstance(reply, dict)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
(list, tuple))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
new_ta2, delta=abs(0.01*new_ta2))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
new_ptcal1, delta=abs(0.01*new_ptcal1))
self.assertEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
new_tcaldate)
# Set the paramters back to their original values.
reply = driver_client.cmd_dvr('set', orig_params)
self.assertIsInstance(reply, dict)
mi_logger.debug('set result: %s', str(reply))
# Get the parameters back from the driver.
reply = driver_client.cmd_dvr('get', get_params)
# Check overall and individual sucess, and that paramters were
# returned to their original values.
self.assertIsInstance(reply, dict)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
(list, tuple))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)],
old_ta2, delta=abs(0.01*old_ta2))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)],
old_ptca1, delta=abs(0.01*old_ptca1))
self.assertEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)],
old_tcaldate)
# Disconnect driver from the device and transition to disconnected.
reply = driver_client.cmd_dvr('disconnect', [SBE37Channel.CTD])
time.sleep(2)
# Deconfigure the driver and transition to unconfigured.
reply = driver_client.cmd_dvr('initialize', [SBE37Channel.CTD])
time.sleep(2)
# End driver process and client messaging.
driver_client.done()
driver_process.wait()
def test_poll(self):
"""
Test sample polling commands and events.
"""
# Launch driver process.
driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
self.evt_port, self.dvr_mod, self.dvr_cls)
# Create client and start messaging.
driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
self.evt_port)
self.clear_events()
driver_client.start_messaging(self.evt_recd)
time.sleep(2)
reply = driver_client.cmd_dvr('configure', self.comms_config)
time.sleep(2)
reply = driver_client.cmd_dvr('connect')
time.sleep(2)
reply = driver_client.cmd_dvr('get_active_channels')
time.sleep(2)
reply = driver_client.cmd_dvr('execute_acquire_sample')
time.sleep(2)
reply = driver_client.cmd_dvr('execute_acquire_sample')
time.sleep(2)
reply = driver_client.cmd_dvr('execute_acquire_sample')
time.sleep(2)
print 'EVENTS RECEIVED:'
print str(self.events)
reply = driver_client.cmd_dvr('disconnect')
time.sleep(2)
# Deconfigure the driver.
reply = driver_client.cmd_dvr('initialize')
time.sleep(2)
# Terminate driver process and stop client messaging.
driver_client.done()
driver_process.wait()
def test_autosample(self):
"""
Test autosample command and state, including events.
"""
# Launch driver process.
driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
self.evt_port, self.dvr_mod, self.dvr_cls)
# Create client and start messaging.
driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
self.evt_port)
driver_client.start_messaging()
time.sleep(2)
reply = driver_client.cmd_dvr('configure', self.comms_config)
time.sleep(2)
reply = driver_client.cmd_dvr('connect')
time.sleep(2)
reply = driver_client.cmd_dvr('start_autosample')
time.sleep(30)
while True:
reply = driver_client.cmd_dvr('stop_autosample')
if not reply[SBE37Channel.CTD]:
break
time.sleep(2)
time.sleep(2)
reply = driver_client.cmd_dvr('disconnect')
time.sleep(2)
# Deconfigure the driver.
reply = driver_client.cmd_dvr('initialize')
time.sleep(2)
# Terminate driver process and stop client messaging.
driver_client.done()
driver_process.wait()
<file_sep>/ion/services/mi/drivers/uw_bars/driver0.py
#!/usr/bin/env python
"""
@package ion.services.mi.drivers.uw_bars.driver0
@file ion/services/mi/drivers/uw_bars/driver0.py
@author <NAME>
@brief UW TRHPH BARS driver implementation based on bars_client
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from ion.services.mi.drivers.uw_bars.bars_client import BarsClient
import ion.services.mi.drivers.uw_bars.bars as bars
from ion.services.mi.instrument_driver import InstrumentDriver
from ion.services.mi.instrument_driver import DriverState
from ion.services.mi.exceptions import InstrumentProtocolException
from ion.services.mi.common import InstErrorCode
from ion.services.mi.drivers.uw_bars.common import BarsChannel
from ion.services.mi.drivers.uw_bars.common import BarsParameter
import re
#import ion.services.mi.mi_logger
import logging
log = logging.getLogger('mi_logger')
class BarsInstrumentDriver(InstrumentDriver):
"""
The InstrumentDriver class for the TRHPH BARS sensor.
"""
# TODO actual handling of the "channel" concept in the design.
# TODO NOTE: Assumes all interaction is for the INSTRUMENT special channel
def __init__(self, evt_callback=None):
InstrumentDriver.__init__(self, evt_callback)
self.bars_client = None
self.config = None
self._state = DriverState.UNCONFIGURED
def get_current_state(self):
return self._state
def _assert_state(self, obj):
"""
Asserts that the current state is the same as the one given (if not
a list) or is one of the elements of the given list.
"""
cs = self.get_current_state()
if isinstance(obj, list):
if cs in obj:
return
else:
raise AssertionError("current state=%s, expected one of %s" %
(cs, str(obj)))
state = obj
if cs != state:
raise AssertionError("current state=%s, expected=%s" % (cs, state))
def initialize(self, channels=None, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
self._assert_state([DriverState.UNCONFIGURED,
DriverState.DISCONNECTED])
channels = channels or [BarsChannel.INSTRUMENT]
assert len(channels) == 1
assert channels[0] == BarsChannel.INSTRUMENT
result = None
self._state = DriverState.UNCONFIGURED
return result
def configure(self, configs, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("configs=%s args=%s kwargs=%s" %
(str(configs), str(args), str(kwargs)))
self._assert_state(DriverState.UNCONFIGURED)
assert isinstance(configs, dict)
assert len(configs) == 1
assert BarsChannel.INSTRUMENT in configs
self.config = configs.get(BarsChannel.INSTRUMENT, None)
result = None
self._state = DriverState.DISCONNECTED
return result
def connect(self, channels=None, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
self._assert_state(DriverState.DISCONNECTED)
channels = channels or [BarsChannel.INSTRUMENT]
assert len(channels) == 1
assert channels[0] == BarsChannel.INSTRUMENT
result = None
self._setup_bars_client(self.config)
if self.bars_client.is_collecting_data():
self._state = DriverState.AUTOSAMPLE
else:
#
# TODO proper handling
raise Exception("Not handled yet. BARS not collecting data")
return result
def _setup_bars_client(self, config):
config = self.config
host = config['device_addr']
port = config['device_port']
outfile = file('driver0.txt', 'w')
self.bars_client = BarsClient(host, port, outfile)
self.bars_client.connect()
def disconnect(self, channels=None, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
channels = channels or [BarsChannel.INSTRUMENT]
assert len(channels) == 1
assert channels[0] == BarsChannel.INSTRUMENT
result = None
self.bars_client.end()
self.bars_client = None
self._state = DriverState.DISCONNECTED
return result
def detach(self, channels, *args, **kwargs):
"""
"""
pass
########################################################################
# Channel command interface.
########################################################################
def get(self, params, *args, **kwargs):
# TODO it only handles [(BarsChannel.INSTRUMENT,
# BarsParameter.TIME_BETWEEN_BURSTS)]
if log.isEnabledFor(logging.DEBUG):
log.debug("params=%s args=%s kwargs=%s" %
(str(params), str(args), str(kwargs)))
self._assert_state(DriverState.AUTOSAMPLE)
assert isinstance(params, list)
cp = (BarsChannel.INSTRUMENT, BarsParameter.TIME_BETWEEN_BURSTS)
assert params == [cp]
log.debug("breaking data streaming to enter main menu")
self.bars_client.enter_main_menu()
log.debug("select 2 to get system parameter menu")
self.bars_client.send('2')
self.bars_client.expect_generic_prompt()
buffer = self.bars_client.get_last_buffer()
log.debug("BUFFER='%s'" % repr(buffer))
string = bars.get_cycle_time(buffer)
log.debug("VALUE='%s'" % string)
seconds = bars.get_cycle_time_seconds(string)
if seconds is None:
raise InstrumentProtocolException(
msg="Unexpected: string could not be matched: %s" % string)
log.debug("send 3 to return to main menu")
self.bars_client.send('3')
self.bars_client.expect_generic_prompt()
buffer = self.bars_client.get_last_buffer()
log.debug("BUFFER='%s'" % repr(buffer))
log.debug("resume data streaming")
self.bars_client.send('1')
result = {cp: seconds}
return result
def set(self, params, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("params=%s args=%s kwargs=%s" %
(str(params), str(args), str(kwargs)))
self._assert_state(DriverState.AUTOSAMPLE)
assert isinstance(params, dict)
assert len(params) == 1
cp = (BarsChannel.INSTRUMENT, BarsParameter.TIME_BETWEEN_BURSTS)
assert cp in params
seconds = params.get(cp)
assert isinstance(seconds, int)
assert seconds >= 15
log.debug("break data streaming to enter main menu")
self.bars_client.enter_main_menu()
log.debug("select 2 to get system parameter menu")
self.bars_client.send('2')
self.bars_client.expect_generic_prompt()
buffer = self.bars_client.get_last_buffer()
log.debug("BUFFER='%s'" % repr(buffer))
string = bars.get_cycle_time(buffer)
log.debug("VALUE='%s'" % string)
log.debug("send 1 to change cycle time")
self.bars_client.send('1')
self.bars_client.expect_generic_prompt()
if seconds <= 59:
log.debug("send 0 to change cycle time in seconds")
self.bars_client.send('0')
self.bars_client.expect_generic_prompt()
log.debug("send seconds=%d" % seconds)
self.bars_client.send(str(seconds))
else:
log.debug("send 1 to change cycle time in minutes")
self.bars_client.send('1')
self.bars_client.expect_generic_prompt()
minutes = seconds / 60
log.debug("send minutes=%d" % minutes)
self.bars_client.send(str(minutes))
self.bars_client.expect_generic_prompt()
log.debug("send 3 to return to main menu")
self.bars_client.send('3')
self.bars_client.expect_generic_prompt()
buffer = self.bars_client.get_last_buffer()
log.debug("BUFFER='%s'" % repr(buffer))
log.debug("resume data streaming")
self.bars_client.send('1')
result = {cp: InstErrorCode.OK}
return result
def execute_direct(self, channels, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
pass
def get_channels(self):
"""
"""
return BarsChannel.list()
########################################################################
# TBD.
########################################################################
def get_status(self, params, timeout=10):
"""
@param timeout Number of seconds before this operation times out
"""
# TODO for the moment just returning the current driver state
return self.get_current_state()
def get_capabilities(self, params, timeout=10):
"""
@param timeout Number of seconds before this operation times out
"""
pass
<file_sep>/ion/processes/data/vis_stream_publisher.py
#!/usr/bin/env python
'''
@author <NAME> <<EMAIL>>
@file ion/processes/data/vis_stream_publisher.py
@description A simple example process which publishes prototype ctd data for visualization
To Run:
bin/pycc --rel res/deploy/r2dm.yml
pid = cc.spawn_process(name='ctd_test',module='ion.processes.data.vis_stream_publisher',cls='SimpleCtdPublisher')
'''
from gevent.greenlet import Greenlet
from pyon.datastore.datastore import DataStore
from pyon.ion.endpoint import StreamPublisherRegistrar
from pyon.ion.process import StandaloneProcess
from pyon.public import log
import time
import random
from prototype.sci_data.ctd_stream import ctd_stream_packet, ctd_stream_definition
from ion.processes.data.ctd_stream_publisher import SimpleCtdPublisher
class VisStreamPublisher(SimpleCtdPublisher):
def __init__(self, *args, **kwargs):
super(SimpleCtdPublisher, self).__init__(*args,**kwargs)
#@todo anything you need to do before on start is called...
def on_start(self):
# Do stuff before on start - before the process tries to start publishing...
super(SimpleCtdPublisher, self).on_start()
# Generally can't do stuff here - the process is already trying to publish...
def _trigger_func(self, stream_id):
"""
Implement your own trigger func to load you netcdf data and publish it...
"""
ctd_packet = ctd_stream_packet(stream_id=stream_id,
c=None, t=None, p=None, lat=None, lon=None, time=None)
log.warn('SimpleCtdPublisher sending %d values!' % length)
self.publisher.publish(ctd_packet)
time.sleep(2.0)<file_sep>/ion/services/sa/resource_impl/instrument_device_impl.py
#!/usr/bin/env python
"""
@package ion.services.sa.resource_impl.instrument_device_impl
@author <NAME>
"""
#from pyon.core.exception import BadRequest, NotFound
from pyon.core.bootstrap import IonObject
from pyon.public import PRED, RT
from pyon.util.log import log
######
"""
now TODO
Later TODO
- fix lifecycle states... how?
-
"""
######
from ion.services.sa.resource_impl.resource_impl import ResourceImpl
class InstrumentDeviceImpl(ResourceImpl):
"""
@brief resource management for InstrumentDevice resources
"""
def on_impl_init(self):
#data acquisition management pointer
if hasattr(self.clients, "data_acquisition_management"):
self.DAMS = self.clients.data_acquisition_management
#data product management pointer
if hasattr(self.clients, "data_product_management"):
self.DPMS = self.clients.data_product_management
def _primary_object_name(self):
return RT.InstrumentDevice
def _primary_object_label(self):
return "instrument_device"
### associations
def link_agent_instance(self, instrument_device_id='', instrument_agent_instance_id=''):
return self._link_resources(instrument_device_id, PRED.hasAgentInstance, instrument_agent_instance_id)
def unlink_agent_instance(self, instrument_device_id='', instrument_agent_instance_id=''):
return self._unlink_resources(instrument_device_id, PRED.hasAgentInstance, instrument_agent_instance_id)
def link_assignment(self, instrument_device_id='', logical_instrument_id=''):
return self._link_resources(instrument_device_id, PRED.hasAssignment, logical_instrument_id)
def unlink_assignment(self, instrument_device_id='', logical_instrument_id=''):
return self._unlink_resources(instrument_device_id, PRED.hasAssignment, logical_instrument_id)
def link_data_producer(self, instrument_device_id='', data_producer_id=''):
return self._link_resources(instrument_device_id, PRED.hasDataProducer, data_producer_id)
def unlink_data_producer(self, instrument_device_id='', data_producer_id=''):
return self._unlink_resources(instrument_device_id, PRED.hasDataProducer, data_producer_id)
def link_model(self, instrument_device_id='', instrument_model_id=''):
return self._link_resources(instrument_device_id, PRED.hasModel, instrument_model_id)
def unlink_model(self, instrument_device_id='', instrument_model_id=''):
return self._unlink_resources(instrument_device_id, PRED.hasModel, instrument_model_id)
def link_sensor(self, instrument_device_id='', sensor_device_id=''):
return self._link_resources(instrument_device_id, PRED.hasSensor, sensor_device_id)
def unlink_sensor(self, instrument_device_id='', sensor_device_id=''):
return self._unlink_resources(instrument_device_id, PRED.hasSensor, sensor_device_id)
### finds
def find_having_agent_instance(self, instrument_agent_instance_id):
return self._find_having(PRED.hasAgentInstance, instrument_agent_instance_id)
def find_stemming_agent_instance(self, instrument_device_id):
return self._find_stemming(instrument_device_id, PRED.hasAgentInstance, RT.InstrumentAgentInstance)
def find_having_assignment(self, logical_instrument_id):
return self._find_having(PRED.hasAssignment, logical_instrument_id)
def find_stemming_assignment(self, instrument_device_id):
return self._find_stemming(instrument_device_id, PRED.hasAssignment, RT.LogicalInstrument)
def find_having_data_producer(self, data_producer_id):
return self._find_having(PRED.hasDataProducer, data_producer_id)
def find_stemming_data_producer(self, instrument_device_id):
return self._find_stemming(instrument_device_id, PRED.hasDataProducer, RT.DataProducer)
def find_having_model(self, instrument_model_id):
return self._find_having(PRED.hasModel, instrument_model_id)
def find_stemming_model(self, instrument_device_id):
return self._find_stemming(instrument_device_id, PRED.hasModel, RT.InstrumentModel)
def find_having_sensor(self, sensor_device_id):
return self._find_having(PRED.hasSensor, sensor_device_id)
def find_stemming_sensor(self, instrument_device_id):
return self._find_stemming(instrument_device_id, PRED.hasSensor, RT.SensorDevice)
# LIFECYCLE STATE PRECONDITIONS
# FIXME
<file_sep>/ion/services/sa/test/test_lca_sa.py
#from interface.services.icontainer_agent import ContainerAgentClient
#from pyon.net.endpoint import ProcessRPCClient
from pyon.public import Container, IonObject
#from pyon.util.log import log
from pyon.util.containers import DotDict
from pyon.util.int_test import IonIntegrationTestCase
from interface.services.sa.idata_product_management_service import DataProductManagementServiceClient
from interface.services.sa.idata_acquisition_management_service import DataAcquisitionManagementServiceClient
from interface.services.sa.iinstrument_management_service import InstrumentManagementServiceClient
from interface.services.sa.imarine_facility_management_service import MarineFacilityManagementServiceClient
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.public import RT, LCS # , PRED
from nose.plugins.attrib import attr
import unittest
from ion.services.sa.test.helpers import any_old
# some stuff for logging info to the console
import sys
log = DotDict()
printout = sys.stderr.write
printout = lambda x: None
log.debug = lambda x: printout("DEBUG: %s\n" % x)
log.info = lambda x: printout("INFO: %s\n" % x)
log.warn = lambda x: printout("WARNING: %s\n" % x)
@attr('INT', group='sa')
class TestLCASA(IonIntegrationTestCase):
"""
LCA integration tests at the service level
"""
def setUp(self):
# Start container
self._start_container()
self.container.start_rel_from_url('res/deploy/r2sa.yml')
# Now create client to DataProductManagementService
self.client = DotDict()
self.client.DAMS = DataAcquisitionManagementServiceClient(node=self.container.node)
self.client.DPMS = DataProductManagementServiceClient(node=self.container.node)
self.client.IMS = InstrumentManagementServiceClient(node=self.container.node)
self.client.MFMS = MarineFacilityManagementServiceClient(node=self.container.node)
def test_just_the_setup(self):
return
#@unittest.skip('temporarily')
def test_lca_step_1_to_6(self):
c = self.client
log.info("LCA steps 1.3, 1.4, 1.5, 1.6, 1.7: FCRUF marine facility")
marine_facility_id = self.generic_fcruf_script(RT.MarineFacility,
"marine_facility",
self.client.MFMS,
True)
log.info("LCA steps 3.1, 3.2, 3.3, 3.4: FCRF site")
site_id = self.generic_fcruf_script(RT.Site,
"site",
self.client.MFMS,
True)
log.info("LCA <missing step>: associate site with marine facility")
self.generic_association_script(c.MFMS.assign_site_to_marine_facility,
c.MFMS.find_marine_facility_by_site,
c.MFMS.find_site_by_marine_facility,
marine_facility_id,
site_id)
log.info("LCA step 4.1, 4.2: FCU platform model")
platform_model_id = self.generic_fcruf_script(RT.PlatformModel,
"platform_model",
self.client.IMS,
True)
log.info("LCA step 4.3, 4.4: CF logical platform")
logical_platform_id = self.generic_fcruf_script(RT.LogicalPlatform,
"logical_platform",
self.client.MFMS,
True)
log.info("LCA step 4.5: C platform device")
platform_device_id = self.generic_fcruf_script(RT.PlatformDevice,
"platform_device",
self.client.IMS,
False)
log.info("LCA step 4.6: Assign logical platform to site")
self.generic_association_script(c.MFMS.assign_logical_platform_to_site,
c.MFMS.find_site_by_logical_platform,
c.MFMS.find_logical_platform_by_site,
site_id,
logical_platform_id)
log.info("LCA <missing step>: assign_platform_model_to_platform_device")
self.generic_association_script(c.IMS.assign_platform_model_to_platform_device,
c.IMS.find_platform_device_by_platform_model,
c.IMS.find_platform_model_by_platform_device,
platform_device_id,
platform_model_id)
log.info("LCA <missing step>: assign_logical_platform_to_platform_device")
self.generic_association_script(c.IMS.assign_logical_platform_to_platform_device,
c.IMS.find_platform_device_by_logical_platform,
c.IMS.find_logical_platform_by_platform_device,
platform_device_id,
logical_platform_id)
log.info("LCA step 5.1, 5.2: FCU instrument model")
instrument_model_id = self.generic_fcruf_script(RT.InstrumentModel,
"instrument_model",
self.client.IMS,
True)
log.info("LCA step 5.3: CU logical instrument")
logical_instrument_id = self.generic_fcruf_script(RT.LogicalInstrument,
"logical_instrument",
self.client.MFMS,
True)
log.info("Create a data product for the logical instrument")
#TODO: do this automatically as part of logical instrument association with model?
log_data_product_id = self.generic_fcruf_script(RT.DataProduct,
"data_product",
self.client.DPMS,
False)
#### this is probably not how we'll end up establishing logical instruments
# log.info("add data product to a logical instrument")
# log.info("LCA <possible step>: find data products by logical instrument")
# self.generic_association_script(c.MFMS.assign_data_product_to_logical_instrument,
# c.MFMS.find_logical_instrument_by_data_product,
# c.MFMS.find_data_product_by_logical_instrument,
# logical_instrument_id,
# log_data_product_id)
log.info("Assigning logical instrument to logical platform")
log.info("LCA step 5.4: list logical instrument by platform")
self.generic_association_script(c.MFMS.assign_logical_instrument_to_logical_platform,
c.MFMS.find_logical_platform_by_logical_instrument,
c.MFMS.find_logical_instrument_by_logical_platform,
logical_platform_id,
logical_instrument_id)
#THIS STEP IS IN THE WRONG PLACE...
log.info("LCA step 5.5: list instruments by observatory")
insts = c.MFMS.find_instrument_device_by_marine_facility(marine_facility_id)
self.assertEqual(0, len(insts))
#self.assertIn(instrument_device_id, insts)
log.info("LCA step 5.6, 5.7, 5.9: CRU instrument_device")
instrument_device_id = self.generic_fcruf_script(RT.InstrumentDevice,
"instrument_device",
self.client.IMS,
False)
log.info("LCA <missing step>: assign instrument device to platform device")
self.generic_association_script(c.IMS.assign_instrument_device_to_platform_device,
c.IMS.find_platform_device_by_instrument_device,
c.IMS.find_instrument_device_by_platform_device,
platform_device_id,
instrument_device_id)
#STEP 6.6 should really go here, otherwise there is no way to find instruments
# by a marine facility; only logical platforms are linked to sites
log.info("LCA <6.6>: assign logical instrument to instrument device")
# NOTE TO REVIEWERS
#
# We are not using the low-level association script right now.
#
#self.generic_association_script(c.IMS.assign_logical_instrument_to_instrument_device,
# c.IMS.find_instrument_device_by_logical_instrument,
# c.IMS.find_logical_instrument_by_instrument_device,
# instrument_device_id,
# logical_instrument_id)
#
# Instead, we are using a more complete call that handles the data products
# in addition to the instrument assignment. Deciding what instrument data products
# map to what logical instrument data products is currently a manual step. If
# it ever becomes automatic, the following reassign_... function will become the
# low-level portion of this concept.
#first, we need the data product of the instrument
inst_data_product_id = self.client.IMS.find_data_product_by_instrument_device(instrument_device_id)[0]
#now GO! 2nd and 5th arguments are blank, because there is no prior instrument
c.IMS.reassign_logical_instrument_to_instrument_device(logical_instrument_id,
"",
instrument_device_id,
[log_data_product_id],
[],
[inst_data_product_id])
#THIS IS WHERE STEP 5.5 SHOULD BE
log.info("LCA step 5.5: list instruments by observatory")
insts = c.MFMS.find_instrument_device_by_marine_facility(marine_facility_id)
self.assertIn(instrument_device_id, insts)
log.info("LCA step 5.8: instrument device policy?")
#TODO
#todo: there is no default product created, need to remove asserts or add products based on instrument model first
log.info("LCA step 5.10a: find data products by instrument device")
products = self.client.IMS.find_data_product_by_instrument_device(instrument_device_id)
#self.assertNotEqual(0, len(products))
#data_product_id = products[0]
log.info("LCA step 5.10b: find data products by platform")
products = self.client.IMS.find_data_product_by_platform_device(platform_device_id)
#self.assertIn(data_product_id, products)
log.info("LCA step 5.10c: find data products by logical platform")
products = self.client.MFMS.find_data_product_by_logical_platform(logical_platform_id)
#self.assertIn(data_product_id, products)
log.info("LCA step 5.10d: find data products by site")
products = self.client.MFMS.find_data_product_by_site(site_id)
#self.assertIn(data_product_id, products)
log.info("LCA step 5.10e: find data products by marine facility")
products = self.client.MFMS.find_data_product_by_marine_facility(marine_facility_id)
#self.assertIn(data_product_id, products)
log.info("LCA step 6.1, 6.2: FCU instrument agent")
instrument_agent_id = self.generic_fcruf_script(RT.InstrumentAgent,
"instrument_agent",
self.client.IMS,
True)
log.info("LCA step 6.3: associate instrument model to instrument agent")
log.info("LCA step 6.4: find instrument model by instrument agent")
self.generic_association_script(c.IMS.assign_instrument_model_to_instrument_agent,
c.IMS.find_instrument_agent_by_instrument_model,
c.IMS.find_instrument_model_by_instrument_agent,
instrument_agent_id,
instrument_model_id)
# .-. . . .
# ( )_|_ .'| .'|
# `-. | .-. .,-. | |
# ( ) | (.-' | ) | |
# `-' `-'`--'|`-' '---''---'
# |
# step 11
#first, create an entire new instrument on this platform
instrument_device_id2 = self.generic_fcruf_script(RT.InstrumentDevice,
"instrument_device",
self.client.IMS,
False)
self.generic_association_script(c.IMS.assign_instrument_device_to_platform_device,
c.IMS.find_platform_device_by_instrument_device,
c.IMS.find_instrument_device_by_platform_device,
platform_device_id,
instrument_device_id2)
#get the data product of the new instrument
inst_data_product_id2 = self.client.IMS.find_data_product_by_instrument_device(instrument_device_id2)[0]
#now GO! 2nd and 5th arguments are filled in with the old instrument
c.IMS.reassign_logical_instrument_to_instrument_device(logical_instrument_id,
instrument_device_id,
instrument_device_id2,
[log_data_product_id],
[inst_data_product_id],
[inst_data_product_id2])
def generic_association_script(self,
assign_obj_to_subj_fn,
find_subj_fn,
find_obj_fn,
subj_id,
obj_id):
"""
create an association and test that it went properly
@param assign_obj_to_subj_fn the service method that takes (obj, subj) and associates them
@param find_subj_fn the service method that returns a list of subjects given an object
@param find_obj_fn the service method that returns a list of objects given a subject
@param subj_id the subject id to associate
@param obj_id the object id to associate
"""
initial_subj_count = len(find_subj_fn(obj_id))
initial_obj_count = len(find_obj_fn(subj_id))
log.debug("Creating association")
assign_obj_to_subj_fn(obj_id, subj_id)
log.debug("Verifying find-subj-by-obj")
subjects = find_subj_fn(obj_id)
self.assertEqual(initial_subj_count + 1, len(subjects))
self.assertIn(subj_id, subjects)
log.debug("Verifying find-obj-by-subj")
objects = find_obj_fn(subj_id)
self.assertEqual(initial_obj_count + 1, len(objects))
self.assertIn(obj_id, objects)
def generic_d_script(self, resource_id, resource_label, owner_service):
"""
delete a resource and check that it was properly deleted
@param resource_id id to be deleted
@param resource_label something like platform_model
@param owner_service service client instance
"""
del_op = getattr(owner_service, "delete_%s" % resource_label)
del_op(resource_id)
# try again to make sure that we get NotFound
self.assertRaises(NotFound, del_op, resource_id)
def generic_fcruf_script(self, resource_iontype, resource_label, owner_service, is_simple):
"""
run through find, create, read, update, and find ops on a basic resource
NO DELETE in here.
@param resource_iontype something like RT.BlahBlar
@param resource_label something like platform_model
@param owner_service a service client instance
@param is_simple whether to check for AVAILABLE LCS on create
"""
# this section is just to make the LCA integration script easier to write.
#
# each resource type gets put through (essentially) the same steps.
#
# so, we just set up a generic service-esque object.
# (basically just a nice package of shortcuts):
# create a fake service object and populate it with the methods we need
some_service = DotDict()
def make_plural(noun):
if "y" == noun[-1]:
return noun[:-1] + "ies"
else:
return noun + "s"
def fill(svc, method, plural=False):
"""
make a "shortcut service" for testing crud ops.
@param svc a dotdict
@param method the method name to add
@param plural whether to make the resource label plural
"""
reallabel = resource_label
realmethod = "%s_widget" % method
if plural:
reallabel = make_plural(reallabel)
realmethod = realmethod + "s"
setattr(svc, realmethod,
getattr(owner_service, "%s_%s" % (method, reallabel)))
fill(some_service, "create")
fill(some_service, "read")
fill(some_service, "update")
fill(some_service, "delete")
fill(some_service, "find", True)
#UX team: generic script for LCA resource operations begins here.
# some_service will be replaced with whatever service you're calling
# widget will be replaced with whatever resource you're working with
# resource_label will be data_product or logical_instrument
resource_labels = make_plural(resource_label)
log.info("Finding %s" % resource_labels)
num_objs = len(some_service.find_widgets())
log.info("I found %d %s" % (num_objs, resource_labels))
log.info("Creating a %s" % resource_label)
generic_obj = any_old(resource_iontype)
generic_id = some_service.create_widget(generic_obj)
log.info("Reading %s #%s" % (resource_label, generic_id))
generic_ret = some_service.read_widget(generic_id)
log.info("Verifying equality of stored and retrieved object")
self.assertEqual(generic_obj.name, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
#"simple" resources go available immediately upon creation, so check:
if is_simple:
log.info("Verifying that resource went AVAILABLE on creation")
self.assertEqual(generic_ret.lcstate, LCS.AVAILABLE)
log.info("Updating %s #%s" % (resource_label, generic_id))
generic_newname = "%s updated" % generic_ret.name
generic_ret.name = generic_newname
some_service.update_widget(generic_ret)
log.info("Reading platform model #%s to verify update" % generic_id)
generic_ret = some_service.read_widget(generic_id)
self.assertEqual(generic_newname, generic_ret.name)
self.assertEqual(generic_obj.description, generic_ret.description)
log.info("Finding platform models... checking that there's a new one")
num_objs2 = len(some_service.find_widgets())
self.assertTrue(num_objs2 > num_objs)
return generic_id
<file_sep>/ion/services/mi/instrument_agent.py
#!/usr/bin/env python
"""
@package ion.services.mi.instrument_agent Instrument resource agent
@file ion/services/mi/instrument_agent.py
@author <NAME>
@brief Resource agent derived class providing an instrument agent as a resource.
This resource fronts instruments and instrument drivers one-to-one in ION.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from pyon.core.exception import BadRequest, NotFound
from pyon.public import IonObject, log
from pyon.agent.agent import ResourceAgent
from pyon.core import exception as iex
from pyon.util.containers import get_ion_ts
from pyon.ion.endpoint import StreamPublisherRegistrar
import time
from ion.services.mi.instrument_fsm_args import InstrumentFSM
from ion.services.mi.common import BaseEnum
from ion.services.mi.common import InstErrorCode
from ion.services.mi.zmq_driver_client import ZmqDriverClient
from ion.services.mi.zmq_driver_process import ZmqDriverProcess
class InstrumentAgentState(BaseEnum):
"""
Instrument agent state enum.
"""
POWERED_DOWN = 'INSTRUMENT_AGENT_STATE_POWERED_DOWN'
UNINITIALIZED = 'INSTRUMENT_AGENT_STATE_UNINITIALIZED'
INACTIVE = 'INSTRUMENT_AGENT_STATE_INACTIVE'
IDLE = 'INSTRUMENT_AGENT_STATE_IDLE'
STOPPED = 'INSTRUMENT_AGENT_STATE_STOPPED'
OBSERVATORY = 'INSTRUMENT_AGENT_STATE_OBSERVATORY'
STREAMING = 'INSTRUMENT_AGENT_STATE_STREAMING'
DIRECT_ACCESS = 'INSTRUMENT_AGENT_STATE_DIRECT_ACCESS'
class InstrumentAgentEvent(BaseEnum):
"""
Instrument agent event enum.
"""
ENTER = 'INSTRUMENT_AGENT_EVENT_ENTER'
EXIT = 'INSTRUMENT_AGENT_EVENT_EXIT'
POWER_UP = 'INSTRUMENT_AGENT_EVENT_POWER_UP'
POWER_DOWN = 'INSTRUMENT_AGENT_EVENT_POWER_DOWN'
INITIALIZE = 'INSTRUMENT_AGENT_EVENT_INITIALIZE'
RESET = 'INSTRUMENT_AGENT_EVENT_RESET'
GO_ACTIVE = 'INSTRUMENT_AGENT_EVENT_GO_ACTIVE'
GO_INACTIVE = 'INSTRUMENT_AGENT_EVENT_GO_INACTIVE'
RUN = 'INSTRUMENT_AGENT_EVENT_RUN'
CLEAR = 'INSTRUMENT_AGENT_EVENT_CLEAR'
PAUSE = 'INSTRUMENT_AGENT_EVENT_PAUSE'
RESUME = 'INSTRUMENT_AGENT_EVENT_RESUME'
GO_OBSERVATORY = 'INSTRUMENT_AGENT_EVENT_GO_OBSERVATORY'
GO_DIRECT_ACCESS = 'INSTRUMENT_AGENT_EVENT_GO_DIRECT_ACCESS'
GO_STREAMING = 'INSTRUMENT_AGENT_EVENT_GO_STREAMING'
GET_RESOURCE_PARAMS = 'INSTRUMENT_AGENT_EVENT_GET_RESOURCE_PARAMS'
GET_RESOURCE_COMMANDS = 'INSTRUMENT_AGENT_EVENT_GET_RESOURCE_COMMANDS'
GET_PARAMS = 'INSTRUMENT_AGENT_EVENT_GET_PARAMS'
SET_PARAMS = 'INSTRUMENT_AGENT_EVENT_SET_PARAMS'
EXECUTE_RESOURCE = 'INSTRUMENT_AGENT_EVENT_EXECUTE_RESOURCE'
class InstrumentAgent(ResourceAgent):
"""
ResourceAgent derived class for the instrument agent. This class
logically abstracts instruments as taskable resources in the ION
system. It directly provides common functionality (common state model,
common resource interface, point of publication) and creates
a driver process to specialize for particular hardware.
"""
def __init__(self, initial_state=InstrumentAgentState.UNINITIALIZED):
"""
Initialize instrument agent prior to pyon process initialization.
Define state machine, initialize member variables.
"""
ResourceAgent.__init__(self)
# Instrument agent state machine.
self._fsm = InstrumentFSM(InstrumentAgentState, InstrumentAgentEvent, InstrumentAgentEvent.ENTER,
InstrumentAgentEvent.EXIT, InstErrorCode.UNHANDLED_EVENT)
# Populate state machine for all state-events.
self._fsm.add_handler(InstrumentAgentState.POWERED_DOWN, InstrumentAgentEvent.ENTER, self._handler_powered_down_enter)
self._fsm.add_handler(InstrumentAgentState.POWERED_DOWN, InstrumentAgentEvent.EXIT, self._handler_powered_down_exit)
self._fsm.add_handler(InstrumentAgentState.UNINITIALIZED, InstrumentAgentEvent.ENTER, self._handler_uninitialized_enter)
self._fsm.add_handler(InstrumentAgentState.UNINITIALIZED, InstrumentAgentEvent.EXIT, self._handler_uninitialized_exit)
self._fsm.add_handler(InstrumentAgentState.UNINITIALIZED, InstrumentAgentEvent.POWER_DOWN, self._handler_uninitialized_power_down)
self._fsm.add_handler(InstrumentAgentState.UNINITIALIZED, InstrumentAgentEvent.INITIALIZE, self._handler_uninitialized_initialize)
self._fsm.add_handler(InstrumentAgentState.UNINITIALIZED, InstrumentAgentEvent.RESET, self._handler_uninitialized_reset)
self._fsm.add_handler(InstrumentAgentState.INACTIVE, InstrumentAgentEvent.ENTER, self._handler_inactive_enter)
self._fsm.add_handler(InstrumentAgentState.INACTIVE, InstrumentAgentEvent.EXIT, self._handler_inactive_exit)
self._fsm.add_handler(InstrumentAgentState.INACTIVE, InstrumentAgentEvent.INITIALIZE, self._handler_inactive_initialize)
self._fsm.add_handler(InstrumentAgentState.INACTIVE, InstrumentAgentEvent.RESET, self._handler_inactive_reset)
self._fsm.add_handler(InstrumentAgentState.INACTIVE, InstrumentAgentEvent.GO_ACTIVE, self._handler_inactive_go_active)
self._fsm.add_handler(InstrumentAgentState.INACTIVE, InstrumentAgentEvent.GET_RESOURCE_COMMANDS, self._handler_get_resource_commands)
self._fsm.add_handler(InstrumentAgentState.INACTIVE, InstrumentAgentEvent.GET_RESOURCE_PARAMS, self._handler_get_resource_params)
self._fsm.add_handler(InstrumentAgentState.IDLE, InstrumentAgentEvent.ENTER, self._handler_idle_enter)
self._fsm.add_handler(InstrumentAgentState.IDLE, InstrumentAgentEvent.EXIT, self._handler_idle_exit)
self._fsm.add_handler(InstrumentAgentState.IDLE, InstrumentAgentEvent.GO_INACTIVE, self._handler_idle_go_inactive)
self._fsm.add_handler(InstrumentAgentState.IDLE, InstrumentAgentEvent.RESET, self._handler_idle_reset)
self._fsm.add_handler(InstrumentAgentState.IDLE, InstrumentAgentEvent.RUN, self._handler_idle_run)
self._fsm.add_handler(InstrumentAgentState.IDLE, InstrumentAgentEvent.GET_RESOURCE_COMMANDS, self._handler_get_resource_commands)
self._fsm.add_handler(InstrumentAgentState.IDLE, InstrumentAgentEvent.GET_RESOURCE_PARAMS, self._handler_get_resource_params)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.ENTER, self._handler_stopped_enter)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.EXIT, self._handler_stopped_exit)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.GO_INACTIVE, self._handler_stopped_go_inactive)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.RESET, self._handler_stopped_reset)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.CLEAR, self._handler_stopped_clear)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.RESUME, self._handler_stopped_resume)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.GET_RESOURCE_COMMANDS, self._handler_get_resource_commands)
self._fsm.add_handler(InstrumentAgentState.STOPPED, InstrumentAgentEvent.GET_RESOURCE_PARAMS, self._handler_get_resource_params)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.ENTER, self._handler_observatory_enter)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.EXIT, self._handler_observatory_exit)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.GO_INACTIVE, self._handler_observatory_go_inactive)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.RESET, self._handler_observatory_reset)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.CLEAR, self._handler_observatory_clear)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.PAUSE, self._handler_observatory_pause)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.GO_STREAMING, self._handler_observatory_go_streaming)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.GO_DIRECT_ACCESS, self._handler_observatory_go_direct_access)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.GET_RESOURCE_COMMANDS, self._handler_get_resource_commands)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.GET_RESOURCE_PARAMS, self._handler_get_resource_params)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.GET_PARAMS, self._handler_get_params)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.SET_PARAMS, self._handler_observatory_set_params)
self._fsm.add_handler(InstrumentAgentState.OBSERVATORY, InstrumentAgentEvent.EXECUTE_RESOURCE, self._handler_observatory_execute_resource)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.ENTER, self._handler_streaming_enter)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.EXIT, self._handler_streaming_exit)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.GO_INACTIVE, self._handler_streaming_go_inactive)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.RESET, self._handler_streaming_reset)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.GO_OBSERVATORY, self._handler_streaming_go_observatory)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.GET_RESOURCE_COMMANDS, self._handler_get_resource_commands)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.GET_RESOURCE_PARAMS, self._handler_get_resource_params)
self._fsm.add_handler(InstrumentAgentState.STREAMING, InstrumentAgentEvent.GET_PARAMS, self._handler_get_params)
self._fsm.add_handler(InstrumentAgentState.DIRECT_ACCESS, InstrumentAgentEvent.ENTER, self._handler_direct_access_enter)
self._fsm.add_handler(InstrumentAgentState.DIRECT_ACCESS, InstrumentAgentEvent.EXIT, self._handler_direct_access_exit)
self._fsm.add_handler(InstrumentAgentState.DIRECT_ACCESS, InstrumentAgentEvent.GO_OBSERVATORY, self._handler_direct_access_go_observatory)
self._fsm.add_handler(InstrumentAgentState.DIRECT_ACCESS, InstrumentAgentEvent.GET_RESOURCE_COMMANDS, self._handler_get_resource_commands)
self._fsm.add_handler(InstrumentAgentState.DIRECT_ACCESS, InstrumentAgentEvent.GET_RESOURCE_PARAMS, self._handler_get_resource_params)
###############################################################################
# Instrument agent internal parameters.
###############################################################################
# State machine start state, defaults to unconfigured.
self._initial_state = initial_state
# Driver configuration. Passed as part of the spawn configuration
# or with an initialize command. Sets driver specific
# context.
self._dvr_config = None
# Process ID of the driver process. Useful to identify and signal
# the process if necessary. Set by transition to inactive.
self._dvr_pid = None
# The driver process popen object. To terminate, signal, wait on,
# or otherwise interact with the driver process via subprocess.
# Set by transition to inactive.
self._dvr_proc = None
# The driver client for communicating to the driver process in
# request-response or event publication. Set by transition to
# inactive.
self._dvr_client = None
# UUID of the current transaction.
self.transaction_id = None
# List of pending transactions.
self._pending_transactions = []
# Dictionary of data stream IDs for data publishing. Constructed
# by stream_config agent config member during process on_init.
self._data_streams = {}
# Dictionary of data stream publishers. Constructed by
# stream_config agent config member during process on_init.
self._data_publishers = {}
# Factories for stream packets. Constructed by driver
# configuration information on transition to inactive.
self._packet_factories = {}
# Stream registrar to create publishers. Used to create
# stream publishers, set during process on_init.
self._stream_registrar = None
# Latitude value. Set by subscription to platform. Used to
# append data packets prior to publication.
self._lat = 0
# Longitude value. Set by subscription to platform. Used to
# append data packets prior to publication.
self._lon = 0
###############################################################################
# Instrument agent parameter capabilities.
###############################################################################
self.aparam_ia_param = None
def on_init(self):
"""
Instrument agent pyon process initialization.
Init objects that depend on the container services and start state
machine.
"""
# The registrar to create publishers.
self._stream_registrar = StreamPublisherRegistrar(process=self,
node=self.container.node)
# Set the driver config from the agent config if present.
self._dvr_config = self.CFG.get('driver_config', None)
# Construct stream publishers.
self._construct_data_publishers()
# Start state machine.
self._fsm.start(self._initial_state)
###############################################################################
# Event callback and handling.
###############################################################################
def evt_recv(self, evt):
"""
Callback to receive asynchronous driver events.
@param evt The driver event received.
"""
log.info('Instrument agent %s received driver event %s', self._proc_name,
str(evt))
try:
if evt['type'] == 'sample':
name = evt['name']
value = evt['value']
value['lat'] = [self._lat]
value['lon'] = [self._lon]
value['stream_id'] = self._data_streams[name]
if isinstance(value, dict):
packet = self._packet_factories[name](**value)
self._data_publishers[name].publish(packet)
log.info('Instrument agent %s published data packet.',
self._proc_name)
except (KeyError, TypeError) as e:
pass
except Exception as e:
log.info('Instrument agent %s error %s', self._proc_name, str(e))
###############################################################################
# Instrument agent state transition interface.
# All the following commands are forwarded as a eponymous event to
# the agent state machine and return the state handler result.
###############################################################################
def acmd_power_up(self, *args, **kwargs):
"""
Agent power_up command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.POWER_UP, *args, **kwargs)
def acmd_power_down(self, *args, **kwargs):
"""
Agent power_down command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.POWER_DOWN, *args, **kwargs)
def acmd_initialize(self, *args, **kwargs):
"""
Agent initialize command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.INITIALIZE, *args, **kwargs)
def acmd_reset(self, *args, **kwargs):
"""
Agent reset command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.RESET, *args, **kwargs)
def acmd_go_active(self, *args, **kwargs):
"""
Agent go_active command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.GO_ACTIVE, *args, **kwargs)
def acmd_go_inactive(self, *args, **kwargs):
"""
Agent go_inactive command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.GO_INACTIVE, *args, **kwargs)
def acmd_run(self, *args, **kwargs):
"""
Agent run command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.RUN, *args, **kwargs)
def acmd_clear(self, *args, **kwargs):
"""
Agent clear command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.CLEAR, *args, **kwargs)
def acmd_pause(self, *args, **kwargs):
"""
Agent pause command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.PAUSE, *args, **kwargs)
def acmd_resume(self, *args, **kwargs):
"""
Agent resume command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.RESUME, *args, **kwargs)
def acmd_go_streaming(self, *args, **kwargs):
"""
Agent go_streaming command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.GO_STREAMING, *args, **kwargs)
def acmd_go_direct_access(self, *args, **kwargs):
"""
Agent go_direct_access command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.GO_DIRECT_ACCESS, *args, **kwargs)
def acmd_go_observatory(self, *args, **kwargs):
"""
Agent go_observatory command. Forward with args to state machine.
"""
return self._fsm.on_event(InstrumentAgentEvent.GO_OBSERVATORY, *args, **kwargs)
###############################################################################
# Misc instrument agent command interface.
###############################################################################
def acmd_get_current_state(self, *args, **kwargs):
"""
Query the agent current state.
"""
return self._fsm.get_current_state()
###############################################################################
# Instrument agent capabilities interface. These functions override base
# class helper functinos for specialized instrument agent behavior.
###############################################################################
def _get_resource_commands(self):
"""
Get driver resource commands. Send event to state machine and return
response or empty list if none.
"""
return self._fsm.on_event(InstrumentAgentEvent.GET_RESOURCE_COMMANDS) or []
def _get_resource_params(self):
"""
Get driver resource parameters. Send event to state machine and return
response or empty list if none.
"""
return self._fsm.on_event(InstrumentAgentEvent.GET_RESOURCE_PARAMS) or []
###############################################################################
# Instrument agent resource interface. These functions override ResourceAgent
# base class functions to specialize behavior for instrument driver resources.
###############################################################################
def get_param(self, resource_id="", name=''):
"""
Get driver resource parameters. Send get_params event and args to agent
state machine to handle request.
NOTE: Need to adjust the ResourceAgent class and client for instrument
interface needs.
@param resource_id
@param name A list of (channel, name) tuples of driver parameter
to retrieve
@retval Dict of (channel, name) : value parameter values if handled.
"""
params = name
return self._fsm.on_event(InstrumentAgentEvent.GET_PARAMS, params) or {}
def set_param(self, resource_id="", name='', value=''):
"""
Set driver resource parameters. Send set_params event and args to agent
state machine to handle set driver resource parameters request.
NOTE: Need to adjust the ResourceAgent class and client for instrument
interface needs.
@param resource_id
@param name a Dict of (channel, name) : value for driver parameters
to be set.
@retval Dict of (channel, name) : None or Error if handled.
"""
params = name
return self._fsm.on_event(InstrumentAgentEvent.SET_PARAMS, params) or {}
def execute(self, resource_id="", command=None):
"""
Execute driver resource command. Send execute_resource event and args
to agent state machine to handle resource execute request.
@param resource_id
@param command agent command object containing the driver command
to execute
@retval Resrouce agent command response object if handled.
"""
return self._fsm.on_event(InstrumentAgentEvent.EXECUTE_RESOURCE, command)
###############################################################################
# Instrument agent transaction interface.
###############################################################################
def acmd_start_transaction(self):
"""
"""
pass
def acmd_end_transaction(self):
"""
"""
pass
###############################################################################
# Powered down state handlers.
# TBD. This state requires clarification of use.
###############################################################################
def _handler_powered_down_enter(self, *args, **kwargs):
"""
Handler upon entry to powered_down state.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_powered_down_exit(self, *args, **kwargs):
"""
Handler upon exit from powered_down state.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
###############################################################################
# Uninitialized state handlers.
# Default start state. The driver has not been configured or started.
###############################################################################
def _handler_uninitialized_enter(self, *args, **kwargs):
"""
Handler upon entry to uninitialized state.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_uninitialized_exit(self, *args, **kwargs):
"""
Handler upon exit from uninitialized state.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
def _handler_uninitialized_power_down(self, *args, **kwargs):
"""
Handler for power_down agent command in uninitialized state.
"""
result = InstErrorCode.NOT_IMPLEMENTED
next_state = None
return (next_state, result)
def _handler_uninitialized_initialize(self, dvr_config=None, *args, **kwargs):
"""
Handler for initialize agent command in uninitialized state.
Attempt to start driver process with driver config supplied as
argument or in agent configuration. Switch to inactive state if
successful.
"""
result = None
next_state = None
self._dvr_config = dvr_config or self._dvr_config
result = self._start_driver(self._dvr_config)
if not result:
next_state = InstrumentAgentState.INACTIVE
return (next_state, result)
def _handler_uninitialized_reset(self, *args, **kwargs):
"""
Handler for reset agent command in uninitialized state.
Exit and reenter uninitializeds state.
"""
result = None
next_state = InstrumentAgentState.UNINITIALIZED
return (next_state, result)
###############################################################################
# Inactive state handlers.
# The driver is configured and started, but not connected.
###############################################################################
def _handler_inactive_enter(self, *args, **kwargs):
"""
Handler upon entry to inactive state.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_inactive_exit(self, *args, **kwargs):
"""
Handler upon exit from inactive state.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
def _handler_inactive_initialize(self, dvr_config=None, *args, **kwargs):
"""
Handler for initialize command in inactive state. Stop and restart
driver process using new driver config if supplied.
"""
result = None
next_state = None
result = self._stop_driver()
if result:
return (next_state, result)
self._dvr_config = dvr_config or self._dvr_config
result = self._start_driver(self._dvr_config)
if not result:
next_state = InstrumentAgentState.INACTIVE
return (next_state, result)
def _handler_inactive_reset(self, *args, **kwargs):
"""
Handler for reset agent command in inactive state.
Stop the driver process and switch to unitinitalized state if
successful.
"""
result = None
next_state = None
result = self._stop_driver()
if not result:
next_state = InstrumentAgentState.UNINITIALIZED
return (next_state, result)
def _handler_inactive_go_active(self, dvr_comms=None, *args, **kwargs):
"""
Handler for go_active agent command in inactive state.
Attempt to establsih communications with all device channels.
Switch to active state if any channels activated.
"""
result = None
next_state = None
if not dvr_comms:
dvr_comms = self._dvr_config.get('comms_config', None)
cfg_result = self._dvr_client.cmd_dvr('configure', dvr_comms)
channels = [key for (key, val) in cfg_result.iteritems() if not
InstErrorCode.is_error(val)]
con_result = self._dvr_client.cmd_dvr('connect', channels)
result = cfg_result.copy()
for (key, val) in con_result.iteritems():
result[key] = val
self._active_channels = self._dvr_client.cmd_dvr('get_active_channels')
if len(self._active_channels)>0:
next_state = InstrumentAgentState.IDLE
return (next_state, result)
###############################################################################
# Idle state handlers.
###############################################################################
def _handler_idle_enter(self, *args, **kwargs):
"""
Handler upon entry to idle state.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_idle_exit(self, *args, **kwargs):
"""
Handler upon exit from idle state.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
def _handler_idle_go_inactive(self, *args, **kwargs):
"""
Handler for go_inactive agent command in idle state.
Attempt to disconnect and initialize all active driver channels.
Swtich to inactive state if successful.
"""
result = None
next_state = None
channels = self._dvr_client.cmd_dvr('get_active_channels')
dis_result = self._dvr_client.cmd_dvr('disconnect', channels)
[key for (key, val) in dis_result.iteritems() if not
InstErrorCode.is_error(val)]
init_result = self._dvr_client.cmd_dvr('initialize', channels)
result = dis_result.copy()
for (key, val) in init_result.iteritems():
result[key] = val
self._active_channels = self._dvr_client.cmd_dvr('get_active_channels')
if len(self._active_channels)==0:
next_state = InstrumentAgentState.INACTIVE
return (next_state, result)
def _handler_idle_reset(self, *args, **kwargs):
"""
Handler for reset agent command in idle state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_idle_run(self, *args, **kwargs):
"""
Handler for run agent command in idle state.
Switch to observatory state.
"""
result = None
next_state = InstrumentAgentState.OBSERVATORY
return (next_state, result)
###############################################################################
# Stopped state handlers.
###############################################################################
def _handler_stopped_enter(self, *args, **kwargs):
"""
Handler for entry into stopped state.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_stopped_exit(self, *args, **kwargs):
"""
Handler for exit from stopped state.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
def _handler_stopped_go_inactive(self, *args, **kwargs):
"""
Handler for go_inactive agent command in stopped state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_stopped_reset(self, *args, **kwargs):
"""
Handler for reset agent command in stopped state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_stopped_clear(self, *args, **kwargs):
"""
Handler for clear agent command in stopped state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_stopped_resume(self, *args, **kwargs):
"""
Handler for resume agent command in stopped state.
"""
result = None
next_state = None
return (next_state, result)
###############################################################################
# Observatory state handlers.
###############################################################################
def _handler_observatory_enter(self, *args, **kwargs):
"""
Handler upon entry to observatory state.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_observatory_exit(self, *args, **kwargs):
"""
Handler upon exit from observatory state.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
def _handler_observatory_go_inactive(self, *args, **kwargs):
"""
Handler for go_inactive agent command in observatory state.
Attempt to disconnect and initialize all active driver channels.
Switch to inactive state if successful.
"""
result = None
next_state = None
channels = self._dvr_client.cmd_dvr('get_active_channels')
dis_result = self._dvr_client.cmd_dvr('disconnect', channels)
[key for (key, val) in dis_result.iteritems() if not
InstErrorCode.is_error(val)]
init_result = self._dvr_client.cmd_dvr('initialize', channels)
result = dis_result.copy()
for (key, val) in init_result.iteritems():
result[key] = val
self._active_channels = self._dvr_client.cmd_dvr('get_active_channels')
if len(self._active_channels)==0:
next_state = InstrumentAgentState.INACTIVE
return (next_state, result)
def _handler_observatory_reset(self, *args, **kwargs):
"""
Handler for reset agent command in observatory state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_observatory_clear(self, *args, **kwargs):
"""
Handler for clear agent command in observatory state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_observatory_pause(self, *args, **kwargs):
"""
Handler for pause agent command in observatory state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_observatory_go_streaming(self, *args, **kwargs):
"""
Handler for go_streaming agent command in observatory state.
Send start autosample command to driver and switch to streaming
state if successful.
"""
result = None
next_state = None
result = self._dvr_client.cmd_dvr('start_autosample', *args, **kwargs)
if isinstance(result, dict):
if any([val == None for val in result.values()]):
next_state = InstrumentAgentState.STREAMING
return (next_state, result)
def _handler_observatory_go_direct_access(self, *args, **kwargs):
"""
Handler for go_direct_access agent ommand in observatory state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_get_params(self, params, *args, **kwargs):
"""
Handler for get_params resource command in observatory state.
Send get command to driver and return result.
"""
result = self._dvr_client.cmd_dvr('get', params)
next_state = None
return (next_state, result)
def _handler_observatory_set_params(self, params, *args, **kwargs):
"""
Handler for set_params resource command in observatory state.
Send the set command to the driver and return result.
"""
result = self._dvr_client.cmd_dvr('set', params)
next_state = None
return (next_state, result)
def _handler_observatory_execute_resource(self, command, *args, **kwargs):
"""
Handler for execute_resource command in observatory state.
Issue driver command and return the result.
"""
result = None
next_state = None
if not command:
raise iex.BadRequest("execute argument 'command' not present")
if not command.command:
raise iex.BadRequest("command not set")
cmd_res = IonObject("AgentCommandResult", command_id=command.command_id,
command=command.command)
cmd_res.ts_execute = get_ion_ts()
command.command = 'execute_' + command.command
res = self._dvr_client.cmd_dvr(command.command, *command.args,
**command.kwargs)
cmd_res.status = 0
cmd_res.result = res
result = cmd_res
return (next_state, result)
###############################################################################
# Streaming state handlers.
###############################################################################
def _handler_streaming_enter(self, *args, **kwargs):
"""
Handler for entry to streaming state.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_streaming_exit(self, *args, **kwargs):
"""
Handler upon exit from streaming state.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
def _handler_streaming_go_inactive(self, *args, **kwargs):
"""
Handler for go_inactive agent command within streaming state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_streaming_reset(self, *args, **kwargs):
"""
Handler for reset agent command within streaming state.
"""
result = None
next_state = None
return (next_state, result)
def _handler_streaming_go_observatory(self, *args, **kwargs):
"""
Handler for go_observatory agent command within streaming state. Command
driver to stop autosampling, and switch to observatory mode if
successful.
"""
result = None
next_state = None
result = self._dvr_client.cmd_dvr('stop_autosample', *args, **kwargs)
if isinstance(result, dict):
if all([val == None for val in result.values()]):
next_state = InstrumentAgentState.OBSERVATORY
return (next_state, result)
###############################################################################
# Direct access state handlers.
###############################################################################
def _handler_direct_access_enter(self, *args, **kwargs):
"""
Handler upon direct access entry.
"""
log.info('Instrument agent entered state %s',
self._fsm.get_current_state())
def _handler_direct_access_exit(self, *args, **kwargs):
"""
Handler upon direct access exit.
"""
log.info('Instrument agent left state %s',
self._fsm.get_current_state())
def _handler_direct_access_go_observatory(self, *args, **kwargs):
"""
Handler for go_observatory agent command within direct access state.
"""
result = None
next_state = None
return (next_state, result)
###############################################################################
# Get resource state handlers.
# Available for all states with a valid driver process.
###############################################################################
def _handler_get_resource_params(self, *args, **kwargs):
"""
Handler for get_resource_params resource command. Send
get_resource_params and args to driver and return result.
"""
result = self._dvr_client.cmd_dvr('get_resource_params')
next_state = None
return (next_state, result)
def _handler_get_resource_commands(self, *args, **kwargs):
"""
Handler for get_resource_commands resource command. Send
get_resource_commands and args to driver and return result.
"""
result = self._dvr_client.cmd_dvr('get_resource_commands')
next_state = None
return (next_state, result)
###############################################################################
# Private helpers.
###############################################################################
def _start_driver(self, dvr_config):
"""
Start the driver process and driver client.
@param dvr_config The driver configuration.
@param comms_config The driver communications configuration.
@retval None or error.
"""
try:
cmd_port = dvr_config['cmd_port']
evt_port = dvr_config['evt_port']
dvr_mod = dvr_config['dvr_mod']
dvr_cls = dvr_config['dvr_cls']
svr_addr = dvr_config['svr_addr']
except (TypeError, KeyError):
# Not a dict. or missing required parameter.
log.error('Insturment agent %s missing required parameter in start_driver.',
self._proc_name)
return InstErrorCode.REQUIRED_PARAMETER
# Launch driver process.
self._dvr_proc = ZmqDriverProcess.launch_process(cmd_port, evt_port,
dvr_mod, dvr_cls)
self._dvr_proc.poll()
if self._dvr_proc.returncode:
# Error proc didn't start.
log.error('Insturment agent %s driver process did not launch.',
self._proc_name)
return InstErrorCode.AGENT_INIT_FAILED
log.info('Insturment agent %s launched driver process.', self._proc_name)
# Create client and start messaging.
self._dvr_client = ZmqDriverClient(svr_addr, cmd_port, evt_port)
self._dvr_client.start_messaging(self.evt_recv)
log.info('Insturment agent %s driver process client started.',
self._proc_name)
time.sleep(1)
try:
retval = self._dvr_client.cmd_dvr('process_echo', 'Test.')
log.info('Insturment agent %s driver process echo test: %s.',
self._proc_name, str(retval))
except Exception:
self._dvr_proc.terminate()
self._dvr_proc.wait()
self._dvr_proc = None
self._dvr_client = None
log.error('Insturment agent %s error commanding driver process.',
self._proc_name)
return InstErrorCode.AGENT_INIT_FAILED
else:
log.info('Insturment agent %s started its driver.', self._proc_name)
self._construct_packet_factories()
def _stop_driver(self):
"""
Stop the driver process and driver client.
@retval None.
"""
if self._dvr_client:
self._dvr_client.done()
self._dvr_proc.wait()
self._dvr_proc = None
self._dvr_client = None
self._clear_packet_factories()
log.info('Insturment agent %s stopped its driver.', self._proc_name)
time.sleep(1)
def _construct_data_publishers(self):
"""
Construct the stream publishers from the stream_config agent
config variable.
@retval None
"""
stream_config = self.CFG.stream_config
for (name, stream_id) in stream_config.iteritems():
self._data_streams[name] = stream_id
publisher = self._stream_registrar.create_publisher(stream_id=stream_id)
self._data_publishers[name] = publisher
log.info('Instrumen agent %s created publisher for stream %s',
self._proc_name, name)
def _construct_packet_factories(self):
"""
Construct packet factories from packet_config member of the
driver_config.
@retval None
"""
packet_config = self._dvr_config['packet_config']
for (name, val) in packet_config.iteritems():
if val:
mod = val[0]
cls = val[1]
import_str = 'from %s import %s' % (mod, cls)
ctor_str = 'ctor = %s' % cls
try:
exec import_str
exec ctor_str
except Exception:
log.error('Instrument agent %s had error creating packet factories from %s.%s',
self._proc_name, mod, cls)
else:
self._packet_factories[name] = ctor
log.info('Instrument agent %s created packet factory for stream %s',
self._proc_name, name)
def _clear_packet_factories(self):
"""
Delete packet factories.
@retval None
"""
self._packet_factories.clear()
log.info('Instrument agent %s deleted packet factories.', self._proc_name)
###############################################################################
# Misc and test.
###############################################################################
def test_ia(self):
log.info('Hello from the instrument agent!')
<file_sep>/ion/services/sa/test/test_lca_gw.py
#from interface.services.icontainer_agent import ContainerAgentClient
#from pyon.net.endpoint import ProcessRPCClient
from pyon.public import Container, IonObject
#from pyon.util.log import log
from pyon.util.containers import DotDict
from pyon.util.int_test import IonIntegrationTestCase
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.public import RT, LCS # , PRED
from nose.plugins.attrib import attr
import unittest
from ion.services.sa.test.helpers import any_old
from interface.services.sa.idata_product_management_service import DataProductManagementServiceClient
from interface.services.sa.idata_acquisition_management_service import DataAcquisitionManagementServiceClient
from interface.services.sa.iinstrument_management_service import InstrumentManagementServiceClient
from interface.services.sa.imarine_facility_management_service import MarineFacilityManagementServiceClient
from ion.services.sa.preload.preload_csv import PreloadCSV
# some stuff for logging info to the console
import sys
log = DotDict()
printout = sys.stderr.write
printout = lambda x: None
log.debug = lambda x: printout("DEBUG: %s\n" % x)
log.info = lambda x: printout("INFO: %s\n" % x)
log.warn = lambda x: printout("WARNING: %s\n" % x)
@attr('INT', group='sa')
@unittest.skip('https://github.com/ooici/ion-definitions/pull/94')
class TestLCAServiceGateway(IonIntegrationTestCase):
"""
LCA integration tests at the service gateway level
"""
def setUp(self):
# Start container
self._start_container()
self.container.start_rel_from_url('res/deploy/r2sa.yml')
# Now create client to DataProductManagementService
self.client = DotDict()
self.client.DAMS = DataAcquisitionManagementServiceClient(node=self.container.node)
self.client.DPMS = DataProductManagementServiceClient(node=self.container.node)
self.client.IMS = InstrumentManagementServiceClient(node=self.container.node)
self.client.MFMS = MarineFacilityManagementServiceClient(node=self.container.node)
def test_just_the_setup(self):
return
def test_csv_loader(self):
loader = PreloadCSV("localhost", 5000)
loader.preload(["ion/services/sa/preload/LogicalInstrument.csv",
"ion/services/sa/preload/InstrumentDevice.csv",
"ion/services/sa/preload/associations.csv"])
log_inst_ids = self.client.MFMS.find_logical_instruments()
self.assertEqual(1, len(log_inst_ids))
inst_ids = self.client.IMS.find_instrument_devices()
self.assertEqual(1, len(inst_ids))
associated_ids = self.client.IMS.find_logical_instrument_by_instrument_device(inst_ids[0])
self.assertEqual(1, len(associated_ids))
<file_sep>/ion/services/mi/drivers/uw_bars/test/__init__.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import os
import unittest
@unittest.skipIf(os.getenv('UW_BARS') is None,
'UW_BARS environment variable undefined')
class BarsTestCase(unittest.TestCase):
"""
Base class for test cases dependent on the UW_BARS environment variable
and providing some supporting functionality related with configuration
and launch of simulator.
This base class does not reference any Pyon elements, but can be used as a
mixin, see PyonBarsTestCase.
If the environment variable UW_BARS is not defined, then the test case is
skipped.
Otherwise:
If UW_BARS is the literal value "simulator", then a simulator is
launched as a separate process upon the first call to self.setUp.
Such a process will be terminated at exit of the python instance.
If UW_BARS is the literal value "embsimulator", then a new simulator
is launched in setUp and terminated in tearDown.
Otherwise, UW_BARS is assumed to be in the format address:port and a
connection to such service will be used.
Corresponding self.config object initialized accordingly.
"""
def setUp(self):
"""
Sets up the test case, launching a simulator if so specified and
preparing self.config.
"""
bars = os.getenv('UW_BARS')
if bars is None:
# should not happen, but anyway just skip here:
self.skipTest("Environment variable UW_BARS undefined")
self._sim_launcher = None
if "simulator" == bars or "embsimulator" == bars:
self._sim_launcher = _SimulatorLauncher()
self.device_port = self._sim_launcher.port
self.device_address = 'localhost'
else:
try:
a, p = bars.split(':')
port = int(p)
except:
self.skipTest("Malformed UW_BARS value")
print "==Assuming BARS is listening on %s:%s==" % (a, p)
self.device_address = a
self.device_port = port
self.config = {
'method': 'ethernet',
'device_addr': self.device_address,
'device_port': self.device_port,
'server_addr': 'localhost',
'server_port': 8888
}
if self._sim_launcher is not None:
self._sim_launcher.launch()
def tearDown(self):
"""
Stops simulator if so specified and joins calling thread to that of the
simulator.
"""
if self._sim_launcher is not None:
self._sim_launcher.stop()
class _SimulatorLauncher(object):
"""
Helper for BarsTestCase to run the simulator either in the same python
instance (we call this "embedded simulator") or in a separate OS process.
This is determined by the UW_BARS environment variable:
if UW_BARS=="simulator" then a unique separate process is launched;
otherwise, self.launch() always starts a new simulator (in the running
python instance, not as a separate process)
This helper was mainly created to delat with issues related with gevent
monkey patching that sometimes interferes with some of the tests when
threads are involved. In concrete, the "embedded simulator" style in
combination with pyon initialization makes the test case hang. The
separate process style is more immune to that issue.
In the case of a separate process, such process is launched only once
in the current python execution environment and terminated at exit of the
python instance via atexit.register(cls._os_proc.kill).
"""
_use_separate_process = "simulator" == os.getenv('UW_BARS')
_os_proc = None
_port = None
@classmethod
def _launch_separate_process(cls):
"""
Launches (if not already) the separate process for the simulator.
Returns the TCP port where such simulator has been bound to.
"""
if cls._os_proc is None:
cls._do_launch_separate_process()
return cls._port
@classmethod
def _do_launch_separate_process(cls):
"""
Unconditionally launches a separate process for the simulator.
Sets the _os_proc and _port class variables.
"""
import subprocess
import time
import re
output_name = 'sim_output.txt'
args = ['bin/python',
'ion/services/mi/drivers/uw_bars/test/bars_simulator.py',
'--outfile', output_name
]
print "\n==STARTING SIMULATOR== %s" % str(args)
# bufsize=1: line buffered. The goal is that we be able to scan the
# few first lines of the subprocess output for the port.
cls._os_proc = subprocess.Popen(args, bufsize=1)
print "process launched, pid=%s" % cls._os_proc.pid
time.sleep(0.2)
# now, capture the port used by the simulator:
port = None
fread = file(output_name, 'r')
lineno, max_lines = 0, 10
while port is None and lineno < max_lines:
output = fread.readline()
lineno += 1
mo = re.search(r'bound to port (\d+)', output)
if mo is not None:
port = int(mo.group(1))
fread.close()
if port is None:
print "WARNING: could not scan port number from subprocess output!"
else:
print "simulator subprocess bound to port = %s" % str(port)
cls._port = port
import atexit
atexit.register(cls._os_proc.kill)
def __init__(self):
self._port = None
self._simulator = None
if _SimulatorLauncher._use_separate_process:
self._port = _SimulatorLauncher._launch_separate_process()
else:
import ion.services.mi.drivers.uw_bars.test.bars_simulator as bs
self._simulator = bs.BarsSimulator(accept_timeout=10.0)
self._port = self._simulator.port
def launch(self):
if _SimulatorLauncher._use_separate_process:
pass # already launched in __init__
else:
print "\n==STARTING SIMULATOR=="
self._simulator.start()
@property
def port(self):
return self._port
def stop(self):
if _SimulatorLauncher._use_separate_process:
pass # subprocess will be killed at exit.
else:
print "==STOPPING SIMULATOR=="
self._simulator.stop()
self._simulator.join()
<file_sep>/ion/services/dm/test/test_blog_integration.py
#!/usr/bin/env python
'''
@file ion/services/dm/test/test_blog_integration.py
@author <NAME>
@author <NAME>
@test ion.services.dm.test.test_blog_integration Covers a demonstration of the basic capability to ingest and replay
simple data from a blog consisting of posts and comments.
This test starts the DM services and sets up ingestion for the science_data exachange point. Data is published by a
scapper providing input to the system and then replayed as part of the test. The test also subscribes to the incoming
data and verifies that the initial input matched the replayed data.
'''
import gevent
from interface.services.dm.idataset_management_service import DatasetManagementServiceClient
from pyon.util.int_test import IonIntegrationTestCase
from nose.plugins.attrib import attr
from pyon.public import log, StreamSubscriberRegistrar
from interface.services.dm.iingestion_management_service import IngestionManagementServiceClient
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
from interface.services.dm.itransform_management_service import TransformManagementServiceClient
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from interface.services.dm.idata_retriever_service import DataRetrieverServiceClient
from interface.services.icontainer_agent import ContainerAgentClient
from interface.objects import StreamQuery, ExchangeQuery, CouchStorage
from interface.objects import BlogPost, BlogComment, HdfStorage
import time
class BlogListener(object):
def __init__(self):
#-----------------------------------------------------------------------------------------------------------
# Variables that are used for debugging tests... use find to see how these variables in the course of tests
#-----------------------------------------------------------------------------------------------------------
self.num_of_messages = 0
self.blogs ={}
# Contains the subscriber that calls back on the blog_store method
self.subscriber = None
def blog_store(self, message, headers):
"""
Use a method in BlogListener object to hold state as we receive blog messages
"""
log.debug('blog_store message received' )
# store all posts... since there are very few posts
if isinstance(message, BlogPost):
# make a dictionary to contain the post and comments if it does not already exist
self.blogs[message.post_id] = self.blogs.get(message.post_id, {})
self.blogs[message.post_id]['post'] = message
# store only 3 comments
elif isinstance(message, BlogComment):
# make a dictionary to contain the post and comments if it does not already exist
self.blogs[message.ref_id] = self.blogs.get(message.ref_id, {})
# make a dictionary to contain the comments if it doesn't already exist...
self.blogs[message.ref_id]['comments'] = self.blogs[message.ref_id].get('comments', {})
self.blogs[message.ref_id]['comments'][message.updated] = (message)
@attr('INT', group='dm')
class BlogIntegrationTest(IonIntegrationTestCase):
def setUp(self):
#-------------------------------------------------------------------------------------------------------
# Container
#-------------------------------------------------------------------------------------------------------
self._start_container()
self.container.start_rel_from_url('res/deploy/r2dm.yml')
def test_blog_ingestion_replay(self):
#-----------------------------------------------------------------------------------------------------
# Do this statement just once in your script
#-----------------------------------------------------------------------------------------------------
cc = self.container
#-------------------------------------------------------------------------------------------------------
# Make a registrar object - this is work usually done for you by the container in a transform or data stream process
#-------------------------------------------------------------------------------------------------------
subscriber_registrar = StreamSubscriberRegistrar(process=cc, node=cc.node)
#-----------------------------------------------------------------------------------------------------
# Service clients
#-----------------------------------------------------------------------------------------------------
ingestion_cli = IngestionManagementServiceClient(node=cc.node)
dr_cli = DataRetrieverServiceClient(node=cc.node)
dsm_cli = DatasetManagementServiceClient(node=cc.node)
pubsub_cli = PubsubManagementServiceClient(node=cc.node)
#-------------------------------------------------------------------------------------------------------
# Create and activate ingestion configuration
#-------------------------------------------------------------------------------------------------------
ingestion_configuration_id = ingestion_cli.create_ingestion_configuration(
exchange_point_id='science_data',
couch_storage=CouchStorage(datastore_name='dm_datastore',datastore_profile='EXAMPLES'),
hdf_storage=HdfStorage(),
number_of_workers=6,
)
# activates the transforms... so bindings will be created in this step
ingestion_cli.activate_ingestion_configuration(ingestion_configuration_id)
#------------------------------------------------------------------------------------------------------
# Create subscriber to listen to the messages published to the ingestion
#------------------------------------------------------------------------------------------------------
# Define the query we want
query = ExchangeQuery()
# Create the stateful listener to hold the captured data for comparison with replay
captured_input = BlogListener()
# Make a subscription to the input stream to ingestion
subscription_id = pubsub_cli.create_subscription(query = query, exchange_name='input_capture_queue' ,name = 'input_capture_queue')
# It is not required or even generally a good idea to use the subscription resource name as the queue name, but it makes things simple here
# Normally the container creates and starts subscribers for you when a transform process is spawned
subscriber = subscriber_registrar.create_subscriber(exchange_name='input_capture_queue', callback=captured_input.blog_store)
subscriber.start()
captured_input.subscriber = subscriber
pubsub_cli.activate_subscription(subscription_id)
#-------------------------------------------------------------------------------------------------------
# Launching blog scraper
#-------------------------------------------------------------------------------------------------------
blogs = [
'saintsandspinners',
'strobist',
'voodoofunk'
]
log.debug('before spawning blog scraper')
for blog in blogs:
config = {'process':{'type':'stream_process','blog':blog}}
cc.spawn_process(name=blog,
module='ion.services.dm.ingestion.example.blog_scraper',
cls='FeedStreamer',
config=config)
# wait ten seconds for some data to come in...
log.warn('Sleeping for 10 seconds to wait for some input')
time.sleep(10)
#------------------------------------------------------------------------------------------------------
# For 3 posts captured, make 3 replays and verify we get back what came in
#------------------------------------------------------------------------------------------------------
# Cute list comprehension method does not give enough control
#self.assertTrue(len(captured_input.blogs)>3)
#post_ids = [id for idx, id in enumerate(captured_input.blogs.iterkeys()) if idx < 3]
post_ids = []
for post_id, blog in captured_input.blogs.iteritems(): # Use items not iter items - I copy of fixed length
log.info('Captured Input: %s' % post_id)
if len(blog.get('comments',[])) > 2:
post_ids.append(post_id)
if len(post_ids) >3:
break
###=======================================================
### This section is not scriptable
###=======================================================
if len(post_ids) < 3:
self.fail('Not enough comments returned by the blog scrappers in 30 seconds')
if len(captured_input.blogs) < 1:
self.fail('No data returned in ten seconds by the blog scrappers!')
###=======================================================
### End non-scriptable
###=======================================================
#------------------------------------------------------------------------------------------------------
# Create subscriber to listen to the replays
#------------------------------------------------------------------------------------------------------
captured_replays = {}
for idx, post_id in enumerate(post_ids):
# Create the stateful listener to hold the captured data for comparison with replay
dataset_id = dsm_cli.create_dataset(
stream_id=post_id,
datastore_name='dm_datastore',
view_name='posts/posts_join_comments')
replay_id, stream_id =dr_cli.define_replay(dataset_id)
query = StreamQuery(stream_ids=[stream_id])
captured_replay = BlogListener()
#------------------------------------------------------------------------------------------------------
# Create subscriber to listen to the messages published to the ingestion
#------------------------------------------------------------------------------------------------------
# Make a subscription to the input stream to ingestion
subscription_name = 'replay_capture_queue_%d' % idx
subscription_id = pubsub_cli.create_subscription(query = query, exchange_name=subscription_name ,name = subscription_name)
# It is not required or even generally a good idea to use the subscription resource name as the queue name, but it makes things simple here
# Normally the container creates and starts subscribers for you when a transform process is spawned
subscriber = subscriber_registrar.create_subscriber(exchange_name=subscription_name, callback=captured_replay.blog_store)
subscriber.start()
captured_replay.subscriber = subscriber
pubsub_cli.activate_subscription(subscription_id)
#------------------------------------------------------------------------------------------------------
# Start the replay and listen to the results!
#------------------------------------------------------------------------------------------------------
dr_cli.start_replay(replay_id)
captured_replays[post_id] = captured_replay
###=======================================================
### The rest is not scriptable
###=======================================================
# wait five seconds for some data to come in...
log.warn('Sleeping for 5 seconds to wait for some output')
time.sleep(5)
matched_comments={}
for post_id, captured_replay in captured_replays.iteritems():
# There should be only one blog in here!
self.assertEqual(len(captured_replay.blogs),1)
replayed_blog = captured_replay.blogs[post_id]
input_blog = captured_input.blogs[post_id]
self.assertEqual(replayed_blog['post'].content, input_blog['post'].content)
# can't deterministically assert that the number of comments is the same...
matched_comments[post_id] = 0
for updated, comment in replayed_blog.get('comments',{}).iteritems():
self.assertIn(updated, input_blog['comments'])
matched_comments[post_id] += 1
# Assert that we got some comments back!
self.assertTrue(sum(matched_comments.values()) > 0)
log.info('Matched comments on the following blogs: %s' % matched_comments)
<file_sep>/ion/services/coi/exchange_management_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
from pyon.public import CFG, IonObject, log, RT, PRED
from interface.services.coi.iexchange_management_service import BaseExchangeManagementService
from pyon.core.exception import Conflict, Inconsistent, NotFound
from pyon.util.log import log
class ExchangeManagementService(BaseExchangeManagementService):
"""
The Exchange Management Service is the service that manages the Exchange and its associated resources, such as Exchange Spaces, Names, Points and Brokers.
"""
def create_exchange_space(self, exchange_space=None, org_id=''):
"""Creates an Exchange Space distributed resource from the parameter exchange_space object.
@param exchange_space ExchangeSpace
@param org_id str
@retval exchange_space_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
log.debug("create_exchange_space(%s, org_id=%s)" % (exchange_space, org_id))
self.assert_condition(exchange_space and org_id, "Arguments not set")
#First make sure that Org with the org_id exists, otherwise bail
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
exchange_space_id,rev = self.clients.resource_registry.create(exchange_space)
aid = self.clients.resource_registry.create_association(org_id, PRED.hasExchangeSpace, exchange_space_id)
# Now do the work
if exchange_space.name == "ioncore":
# Bottom turtle initialization
pass
else:
# All other XS initialization
pass
return exchange_space_id
def update_exchange_space(self, exchange_space=None):
"""Updates an existing Exchange Space resource with data passed in as a parameter.
@param exchange_space ExchangeSpace
@throws BadRequest if object does not have _id or _rev attribute
@throws NotFound object with specified id does not exist
@throws Conflict object not based on latest persisted object version
"""
self.clients.resource_registry.update(exchange_space)
def read_exchange_space(self, exchange_space_id=''):
"""Returns an Exchange Space resource for the provided exchange space id.
@param exchange_space_id str
@retval exchange_space ExchangeSpace
@throws NotFound object with specified id does not exist
"""
exchange_space = self.clients.resource_registry.read(exchange_space_id)
if not exchange_space:
raise NotFound("Exchange Space %s does not exist" % exchange_space_id)
return exchange_space
def delete_exchange_space(self, exchange_space_id=''):
"""Deletes an existing exchange space resource for the provided id.
@param exchange_space_id str
@throws NotFound object with specified id does not exist
"""
exchange_space = self.clients.resource_registry.read(exchange_space_id)
if not exchange_space:
raise NotFound("Exchange Space %s does not exist" % exchange_space_id)
self.clients.resource_registry.delete(exchange_space)
def find_exchange_spaces(self, filters=None):
"""Returns a list of Exchange Space resources for the given Resource Filter.
@param filters ResourceFilter
@retval exchange_space_list []
"""
raise NotImplementedError()
def declare_exchange_name(self, exchange_name=None, exchange_space_id=''):
"""Create an Exchange Name resource resource
@param exchange_name ExchangeName
@param exchange_space_id str
@retval canonical_name str
@throws BadRequest if object passed has _id or _rev attribute
"""
exchange_name_id,rev = self.clients.resource_registry.create(exchange_name)
aid = self.clients.resource_registry.create_association(exchange_space, PRED.hasExchangeName, exchange_name_id)
return exchange_name_id #QUestion - is this the correct canonical name?
def undeclare_exchange_name(self, canonical_name='', exchange_space_id=''):
"""Remove an exhange nane resource
@param canonical_name str
@param exchange_space_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
raise NotImplementedError()
def find_exchange_names(self, filters=None):
"""Returns a list of exchange name resources for the given resource filter.
@param filters ResourceFilter
@retval exchange_name_list []
"""
raise NotImplementedError()
def create_exchange_point(self, exchange_point=None, exchange_space_id=''):
"""Create an exchange point resource within the exchange space provided by the id.
@param exchange_point ExchangePoint
@param exchange_space_id str
@retval exchange_point_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
exchange_point_id, _ver = self.clients.resource_registry.create(exchange_point)
#aid = self.clients.resource_registry.create_association(exchange_space_id, PRED.hasExchangePoint, exchange_point_id)
return exchange_point_id
def update_exchange_point(self, exchange_point=None):
"""Update an existing exchange point resource.
@param exchange_point ExchangePoint
@throws BadRequest if object does not have _id or _rev attribute
@throws NotFound object with specified id does not exist
@throws Conflict object not based on latest persisted object version
"""
self.clients.resource_registry.update(exchange_point)
def read_exchange_point(self, exchange_point_id=''):
"""Return an existing exchange point resource.
@param exchange_point_id str
@retval exchange_point ExchangePoint
@throws NotFound object with specified id does not exist
"""
exchange_point = self.clients.resource_registry.read(exchange_point_id)
if not exchange_point:
raise NotFound("Exchange Point %s does not exist" % exchange_point_id)
return exchange_point
def delete_exchange_point(self, exchange_point_id=''):
"""Delete an existing exchange point resource.
@param exchange_point_id str
@throws NotFound object with specified id does not exist
"""
exchange_point = self.clients.resource_registry.read(exchange_point_id)
if not exchange_point:
raise NotFound("Exchange Point %s does not exist" % exchange_point_id)
self.clients.resource_registry.delete(exchange_point)
def find_exchange_points(self, filters=None):
"""Returns a list of exchange point resources for the provided resource filter.
@param filters ResourceFilter
@retval exchange_point_list []
"""
raise NotImplementedError()
def create_exchange_broker(self, exchange_broker=None):
"""Creates an exchange broker resource
@param exchange_broker ExchangeBroker
@retval exchange_broker_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
exchange_point_id, _ver = self.clients.resource_registry.create(exchange_point)
return exchange_point_id
def update_exchange_broker(self, exchange_broker=None):
"""Updates an existing exchange broker resource.
@param exchange_broker ExchangeBroker
@throws BadRequest if object does not have _id or _rev attribute
@throws NotFound object with specified id does not exist
@throws Conflict object not based on latest persisted object version
"""
self.clients.resource_registry.update(exchange_broker)
def read_exchange_broker(self, exchange_broker_id=''):
"""Returns an existing exchange broker resource.
@param exchange_broker_id str
@retval exchange_broker ExchangeBroker
@throws NotFound object with specified id does not exist
"""
exchange_broker = self.clients.resource_registry.read(exchange_broker_id)
if not exchange_broker:
raise NotFound("Exchange Broker %s does not exist" % exchange_broker_id)
return exchange_broker
def delete_exchange_broker(self, exchange_broker_id=''):
"""Deletes an existing exchange broker resource.
@param exchange_broker_id str
@throws NotFound object with specified id does not exist
"""
exchange_broker = self.clients.resource_registry.read(exchange_broker_id)
if not exchange_broker:
raise NotFound("Exchange Broker %s does not exist" % exchange_broker_id)
self.clients.resource_registry.delete(exchange_broker)
def find_exchange_broker(self, filters=None):
"""Returns a list of exchange broker resources for the provided resource filter.
@param filters ResourceFilter
@retval exchange_broker_list []
"""
raise NotImplementedError()
<file_sep>/ion/services/coi/resource_registry_service.py
#!/usr/bin/env python
__author__ = '<NAME>, <NAME>'
__license__ = 'Apache 2.0'
from pyon.core.exception import BadRequest, NotFound, Inconsistent
from pyon.datastore.datastore import DataStore
from pyon.ion.resource import lcs_workflows
from pyon.public import log, LCS
from pyon.util.containers import get_ion_ts
from interface.services.coi.iresource_registry_service import BaseResourceRegistryService
class ResourceRegistryService(BaseResourceRegistryService):
"""
Service that manages resources instances and all cross-cutting concerns of
system resources. Uses a datastore instance for resource object persistence.
"""
def on_init(self):
# Get an instance of datastore configured for resource registry.
# May be persistent or mock, forced clean, with indexes
self.rr_store = self.container.datastore_manager.get_datastore("resources", DataStore.DS_PROFILE.RESOURCES, self.CFG)
# For easier interactive shell debugging
self.dss = self.rr_store.server[self.rr_store.datastore_name] if hasattr(self.rr_store, 'server') else None
self.ds = self.rr_store
def on_quit(self):
BaseResourceRegistryService.on_quit(self)
self.rr_store.close()
def create(self, object={}):
cur_time = get_ion_ts()
object.ts_created = cur_time
object.ts_updated = cur_time
return self.rr_store.create(object)
def read(self, object_id='', rev_id=''):
if not object_id:
raise BadRequest("The object_id parameter is an empty string")
return self.rr_store.read(object_id, rev_id)
def update(self, object={}):
if not hasattr(object, "_id") or not hasattr(object, "_rev"):
raise BadRequest("Object does not have required '_id' or '_rev' attribute")
# Do an check whether LCS has been modified
res_obj = self.read(object._id)
self.assert_condition(res_obj.lcstate == object.lcstate, "Cannot modify life cycle state in update!")
object.ts_updated = get_ion_ts()
return self.rr_store.update(object)
def delete(self, object_id=''):
res_obj = self.read(object_id)
if not res_obj:
raise NotFound("Resource %s does not exist" % object_id)
return self.rr_store.delete(res_obj)
def execute_lifecycle_transition(self, resource_id='', transition_event='', current_lcstate=''):
self.assert_condition(not current_lcstate or current_lcstate in LCS, "Unknown life-cycle state %s" % current_lcstate)
res_obj = self.read(resource_id)
if current_lcstate and res_obj.lcstate != current_lcstate:
raise Inconsistent("Resource id=%s lcstate is %s, expected was %s" % (
resource_id, res_obj.lcstate, current_lcstate))
restype = type(res_obj).__name__
restype_workflow = lcs_workflows.get(restype, None)
if not restype_workflow:
restype_workflow = lcs_workflows['Resource']
new_state = restype_workflow.get_successor(res_obj.lcstate, transition_event)
if not new_state:
raise Inconsistent("Resource id=%s, type=%s, lcstate=%s has no transition for event %s" % (
resource_id, restype, res_obj.lcstate, transition_event))
res_obj.lcstate = new_state
res_obj.ts_updated = get_ion_ts()
updres = self.rr_store.update(res_obj)
return new_state
def create_association(self, subject=None, predicate=None, object=None, assoc_type=None):
return self.rr_store.create_association(subject, predicate, object, assoc_type)
def delete_association(self, association=''):
return self.rr_store.delete_association(association)
def find(self, **kwargs):
raise NotImplementedError("Do not use find. Use a specific find operation instead.")
def find_objects(self, subject="", predicate="", object_type="", id_only=False):
return self.rr_store.find_objects(subject, predicate, object_type, id_only=id_only)
def find_subjects(self, subject_type="", predicate="", object="", id_only=False):
return self.rr_store.find_subjects(subject_type, predicate, object, id_only=id_only)
def find_associations(self, subject="", predicate="", object="", id_only=False):
return self.rr_store.find_associations(subject, predicate, object, id_only=id_only)
def get_association(self, subject="", predicate="", object="", id_only=False):
assoc = self.rr_store.find_associations(subject, predicate, object, id_only=id_only)
if not assoc:
raise NotFound("Association for subject/predicate/object %s/%s/%s not found" % (
str(subject),str(predicate),str(object)))
elif len(assoc) > 1:
raise Inconsistent("Duplicate associations found for subject/predicate/object %s/%s/%s" % (
str(subject),str(predicate),str(object)))
return assoc[0]
def find_resources(self, restype="", lcstate="", name="", id_only=False):
return self.rr_store.find_resources(restype, lcstate, name, id_only=id_only)
<file_sep>/ion/services/mi/drivers/uw_bars/test/test_basic.py
#!/usr/bin/env python
__author__ = "<NAME>"
__license__ = 'Apache 2.0'
"""
Unit tests for the basic bars module.
"""
import ion.services.mi.drivers.uw_bars.bars as bars
from unittest import TestCase
from nose.plugins.attrib import attr
@attr('UNIT', group='mi')
class BasicBarsTest(TestCase):
"""
Unit tests for the basic bars module.
"""
def test_get_cycle_time(self):
val = bars.get_cycle_time(bars.SYSTEM_PARAMETER_MENU)
self.assertEqual(val, '20 Seconds')
def test_get_verbose_vs_data_only(self):
val = bars.get_verbose_vs_data_only(bars.SYSTEM_PARAMETER_MENU)
self.assertEqual(val, 'Data Only')
def test_get_system_date_and_time(self):
res = bars.get_system_date_and_time(bars.ADJUST_SYSTEM_CLOCK_MENU)
self.assertEqual(res, ('02/09/12', '14:21:06'))
def test_get_power_statuses(self):
res = bars.get_power_statuses(bars.SENSOR_POWER_CONTROL_MENU)
self.assertEqual(res, ('On', 'On', 'On', 'On', 'On'))
<file_sep>/ion/services/sa/marine_facility/marine_facility_management_service.py
#!/usr/bin/env python
'''
@package ion.services.sa.marine_facility.marine_facility Implementation of IMarineFacilityManagementService interface
@file ion/services/sa/marine_facility/marine_facility_management_service.py
@author <NAME>
@brief Marine Facility Management service to keep track of Marine Facilities, sites, logical platforms, etc
and the relationships between them
'''
from pyon.core.exception import NotFound
from pyon.public import CFG, IonObject, log, RT, PRED, LCS
from ion.services.sa.resource_impl.logical_instrument_impl import LogicalInstrumentImpl
from ion.services.sa.resource_impl.logical_platform_impl import LogicalPlatformImpl
from ion.services.sa.resource_impl.marine_facility_impl import MarineFacilityImpl
from ion.services.sa.resource_impl.site_impl import SiteImpl
#for logical/physical associations, it makes sense to search from MFMS
from ion.services.sa.resource_impl.instrument_device_impl import InstrumentDeviceImpl
from ion.services.sa.resource_impl.platform_device_impl import PlatformDeviceImpl
from interface.services.sa.imarine_facility_management_service import BaseMarineFacilityManagementService
class MarineFacilityManagementService(BaseMarineFacilityManagementService):
def on_init(self):
IonObject("Resource") # suppress pyflakes error
self.override_clients(self.clients)
def override_clients(self, new_clients):
"""
Replaces the service clients with a new set of them... and makes sure they go to the right places
"""
#shortcut names for the import sub-services
if hasattr(self.clients, "resource_registry"):
self.RR = self.clients.resource_registry
if hasattr(self.clients, "instrument_management"):
self.IMS = self.clients.instrument_management
#farm everything out to the impls
self.logical_instrument = LogicalInstrumentImpl(self.clients)
self.logical_platform = LogicalPlatformImpl(self.clients)
self.marine_facility = MarineFacilityImpl(self.clients)
self.site = SiteImpl(self.clients)
self.instrument_device = InstrumentDeviceImpl(self.clients)
self.platform_device = PlatformDeviceImpl(self.clients)
##########################################################################
#
# MARINE FACILITY
#
##########################################################################
def create_marine_facility(self, marine_facility=None):
"""
create a new instance
@param marine_facility the object to be created as a resource
@retval marine_facility_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.marine_facility.create_one(marine_facility)
def update_marine_facility(self, marine_facility=None):
"""
update an existing instance
@param marine_facility the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.marine_facility.update_one(marine_facility)
def read_marine_facility(self, marine_facility_id=''):
"""
fetch a resource by ID
@param marine_facility_id the id of the object to be fetched
@retval LogicalInstrument resource
"""
return self.marine_facility.read_one(marine_facility_id)
def delete_marine_facility(self, marine_facility_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param marine_facility_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.marine_facility.delete_one(marine_facility_id)
def find_marine_facilities(self, filters=None):
"""
"""
return self.marine_facility.find_some(filters)
##########################################################################
#
# SITE
#
##########################################################################
def create_site(self, site=None):
"""
create a new instance
@param site the object to be created as a resource
@retval site_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.site.create_one(site)
def update_site(self, site=None):
"""
update an existing instance
@param site the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.site.update_one(site)
def read_site(self, site_id=''):
"""
fetch a resource by ID
@param site_id the id of the object to be fetched
@retval LogicalInstrument resource
"""
return self.site.read_one(site_id)
def delete_site(self, site_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param site_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.site.delete_one(site_id)
def find_sites(self, filters=None):
"""
"""
return self.site.find_some(filters)
##########################################################################
#
# LOGICAL INSTRUMENT
#
##########################################################################
def create_logical_instrument(self, logical_instrument=None):
"""
create a new instance
@param logical_instrument the object to be created as a resource
@retval logical_instrument_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.logical_instrument.create_one(logical_instrument)
def update_logical_instrument(self, logical_instrument=None):
"""
update an existing instance
@param logical_instrument the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.logical_instrument.update_one(logical_instrument)
def read_logical_instrument(self, logical_instrument_id=''):
"""
fetch a resource by ID
@param logical_instrument_id the id of the object to be fetched
@retval LogicalInstrument resource
"""
return self.logical_instrument.read_one(logical_instrument_id)
def delete_logical_instrument(self, logical_instrument_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param logical_instrument_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.logical_instrument.delete_one(logical_instrument_id)
def find_logical_instruments(self, filters=None):
"""
"""
return self.logical_instrument.find_some(filters)
##########################################################################
#
# LOGICAL PLATFORM
#
##########################################################################
def create_logical_platform(self, logical_platform=None):
"""
create a new instance
@param logical_platform the object to be created as a resource
@retval logical_platform_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.logical_platform.create_one(logical_platform)
def update_logical_platform(self, logical_platform=None):
"""
update an existing instance
@param logical_platform the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.logical_platform.update_one(logical_platform)
def read_logical_platform(self, logical_platform_id=''):
"""
fetch a resource by ID
@param logical_platform_id the id of the object to be fetched
@retval LogicalPlatform resource
"""
return self.logical_platform.read_one(logical_platform_id)
def delete_logical_platform(self, logical_platform_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param logical_platform_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.logical_platform.delete_one(logical_platform_id)
def find_logical_platforms(self, filters=None):
"""
"""
return self.logical_platform.find_some(filters)
############################
#
# ASSOCIATIONS
#
############################
def assign_platform_to_logical_platform(self, platform_id='', logical_platform_id=''):
self.logical_platform.link_platform(logical_platform_id, platform_id)
def unassign_platform_from_logical_platform(self, platform_id='', logical_platform_id=''):
self.logical_platform.unlink_platform(logical_platform_id, platform_id)
def assign_logical_instrument_to_logical_platform(self, logical_instrument_id='', logical_platform_id=''):
self.logical_platform.link_instrument(logical_platform_id, logical_instrument_id)
def unassign_logical_instrument_from_logical_platform(self, logical_instrument_id='', logical_platform_id=''):
self.logical_platform.unlink_instrument(logical_platform_id, logical_instrument_id)
def assign_site_to_marine_facility(self, site_id='', marine_facility_id=''):
self.marine_facility.link_site(marine_facility_id, site_id)
def unassign_site_from_marine_facility(self, site_id="", marine_facility_id=''):
self.marine_facility.unlink_site(marine_facility_id, site_id)
def assign_site_to_site(self, child_site_id='', parent_site_id=''):
self.site.link_site(parent_site_id, child_site_id)
def unassign_site_from_site(self, child_site_id="", parent_site_id=''):
self.site.unlink_site(parent_site_id, child_site_id)
def assign_logical_platform_to_site(self, logical_platform_id='', site_id=''):
self.site.link_platform(site_id, logical_platform_id)
def unassign_logical_platform_from_site(self, logical_platform_id='', site_id=''):
self.site.unlink_platform(site_id, logical_platform_id)
# def assign_data_product_to_logical_instrument(self, data_product_id='', logical_instrument_id=''):
# self.logical_instrument.link_data_product(logical_instrument_id, data_product_id)
# def unassign_data_product_from_logical_instrument(self, data_product_id='', logical_instrument_id=''):
# self.logical_instrument.unlink_data_product(logical_instrument_id, data_product_id)
def define_observatory_policy(self):
"""method docstring
"""
# Return Value
# ------------
# null
# ...
#
pass
############################
#
# ASSOCIATION FIND METHODS
#
############################
def find_logical_instrument_by_logical_platform(self, logical_platform_id=''):
return self.logical_platform.find_stemming_instrument(logical_platform_id)
def find_logical_platform_by_logical_instrument(self, logical_instrument_id=''):
return self.logical_platform.find_having_instrument(logical_instrument_id)
def find_site_by_child_site(self, child_site_id=''):
return self.site.find_having_site(child_site_id)
def find_site_by_parent_site(self, parent_site_id=''):
return self.site.find_stemming_site(parent_site_id)
def find_logical_platform_by_site(self, site_id=''):
return self.site.find_stemming_platform(site_id)
def find_site_by_logical_platform(self, logical_platform_id=''):
return self.site.find_having_platform(logical_platform_id)
def find_site_by_marine_facility(self, marine_facility_id=''):
return self.marine_facility.find_stemming_site(marine_facility_id)
def find_marine_facility_by_site(self, site_id=''):
return self.marine_facility.find_having_site(site_id)
# def find_data_product_by_logical_instrument(self, logical_instrument_id=''):
# return self.logical_instrument.find_stemming_data_product(logical_instrument_id)
# def find_logical_instrument_by_data_product(self, data_product_id=''):
# return self.logical_instrument.find_having_data_product(data_product_id)
############################
#
# SPECIALIZED FIND METHODS
#
############################
def find_instrument_device_by_logical_platform(self, logical_platform_id=''):
ret = []
for l in self.logical_platform.find_stemming_instrument(logical_platform_id):
for i in self.instrument_device.find_having_assignment(l):
if not i in ret:
ret.append(i)
return ret
def find_instrument_device_by_site(self, site_id=''):
ret = []
for l in self.find_logical_platform_by_site(site_id):
for i in self.find_instrument_device_by_logical_platform(l):
if not i in ret:
ret.append(i)
return ret
def find_instrument_device_by_marine_facility(self, marine_facility_id=''):
ret = []
for s in self.find_site_by_marine_facility(marine_facility_id):
for i in self.find_instrument_device_by_site(s):
if not i in ret:
ret.append(i)
return ret
def find_data_product_by_logical_platform(self, logical_platform_id=''):
ret = []
for i in self.find_instrument_device_by_logical_platform(logical_platform_id):
for dp in self.IMS.find_data_product_by_instrument_device(i):
if not dp in ret:
ret.append(dp)
return ret
def find_data_product_by_site(self, site_id=''):
ret = []
for i in self.find_instrument_device_by_site(site_id):
for dp in self.IMS.find_data_product_by_instrument_device(i):
if not dp in ret:
ret.append(dp)
return ret
def find_data_product_by_marine_facility(self, marine_facility_id=''):
ret = []
for i in self.find_instrument_device_by_marine_facility(marine_facility_id):
for dp in self.IMS.find_data_product_by_instrument_device(i):
if not dp in ret:
ret.append(dp)
return ret
############################
#
# LIFECYCLE TRANSITIONS
#
############################
def set_logical_instrument_lifecycle(self, logical_instrument_id="", lifecycle_state=""):
"""
declare a logical_instrument to be in the given lifecycle state
@param logical_instrument_id the resource id
"""
return self.logical_instrument.advance_lcs(logical_instrument_id, lifecycle_state)
def set_logical_platform_lifecycle(self, logical_platform_id="", lifecycle_state=""):
"""
declare a logical_platform to be in the given lifecycle state
@param logical_platform_id the resource id
"""
return self.logical_platform.advance_lcs(logical_platform_id, lifecycle_state)
def set_marine_facility_lifecycle(self, marine_facility_id="", lifecycle_state=""):
"""
declare a marine_facility to be in the given lifecycle state
@param marine_facility_id the resource id
"""
return self.marine_facility.advance_lcs(marine_facility_id, lifecycle_state)
def set_site_lifecycle(self, site_id="", lifecycle_state=""):
"""
declare a site to be in the given lifecycle state
@param site_id the resource id
"""
return self.site.advance_lcs(site_id, lifecycle_state)
<file_sep>/ion/services/mi/test/test_instrument_agent.py
#!/usr/bin/env python
"""
@package ion.services.mi.test.test_instrument_agent
@file ion/services/mi/test_instrument_agent.py
@author <NAME>
@brief Test cases for R2 instrument agent.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from pyon.public import log
from nose.plugins.attrib import attr
from interface.objects import StreamQuery
from interface.services.dm.itransform_management_service import TransformManagementServiceClient
from interface.services.cei.iprocess_dispatcher_service import ProcessDispatcherServiceClient
from interface.services.icontainer_agent import ContainerAgentClient
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
from pyon.public import StreamSubscriberRegistrar
from prototype.sci_data.ctd_stream import ctd_stream_definition
from pyon.agent.agent import ResourceAgentClient
from interface.objects import AgentCommand
from pyon.util.int_test import IonIntegrationTestCase
from pyon.util.context import LocalContextMixin
from ion.services.mi.drivers.sbe37_driver import SBE37Channel
from ion.services.mi.drivers.sbe37_driver import SBE37Parameter
import time
import unittest
# bin/nosetests -s -v ion/services/mi/test/test_instrument_agent.py:TestInstrumentAgent.test_initialize
# bin/nosetests -s -v ion/services/mi/test/test_instrument_agent.py:TestInstrumentAgent.test_go_active
# bin/nosetests -s -v ion/services/mi/test/test_instrument_agent.py:TestInstrumentAgent.test_get_set
# bin/nosetests -s -v ion/services/mi/test/test_instrument_agent.py:TestInstrumentAgent.test_poll
# bin/nosetests -s -v ion/services/mi/test/test_instrument_agent.py:TestInstrumentAgent.test_autosample
class FakeProcess(LocalContextMixin):
"""
A fake process used because the test case is not an ion process.
"""
name = ''
id=''
process_type = ''
@unittest.skip('Do not run hardware test.')
@attr('INT', group='mi')
class TestInstrumentAgent(IonIntegrationTestCase):
"""
Test cases for instrument agent class. Functions in this class provide
instrument agent integration tests and provide a tutorial on use of
the agent setup and interface.
"""
def setUp(self):
"""
Setup the test environment to exersice use of instrumet agent, including:
* define driver_config parameters.
* create container with required services and container client.
* create publication stream ids for each driver data stream.
* create stream_config parameters.
* create and activate subscriptions for agent data streams.
* spawn instrument agent process and create agent client.
* add cleanup functions to cause subscribers to get stopped.
"""
# Names of agent data streams to be configured.
parsed_stream_name = 'ctd_parsed'
raw_stream_name = 'ctd_raw'
# Driver configuration.
self.driver_config = {
'svr_addr': 'localhost',
'cmd_port': 5556,
'evt_port': 5557,
'dvr_mod': 'ion.services.mi.drivers.sbe37_driver',
'dvr_cls': 'SBE37Driver',
'comms_config': {
SBE37Channel.CTD: {
'method':'ethernet',
'device_addr': '172.16.31.10',
'device_port': 4001,
'server_addr': 'localhost',
'server_port': 8888
}
},
'packet_config' : {
parsed_stream_name : ('prototype.sci_data.ctd_stream',
'ctd_stream_packet'),
raw_stream_name : None
}
}
# Start container.
self._start_container()
# Establish endpoint with container.
self._container_client = ContainerAgentClient(node=self.container.node,
name=self.container.name)
# Bring up services in a deploy file.
self._container_client.start_rel_from_url('res/deploy/r2dm.yml')
# Create a pubsub client to create streams.
self._pubsub_client = PubsubManagementServiceClient(
node=self.container.node)
# Create parsed stream. The stream name must match one
# used by the driver to label packet data.
parsed_stream_def = ctd_stream_definition(stream_id=None)
parsed_stream_def_id = self._pubsub_client.create_stream_definition(
container=parsed_stream_def)
parsed_stream_id = self._pubsub_client.create_stream(
name=parsed_stream_name,
stream_definition_id=parsed_stream_def_id,
original=True,
encoding='ION R2')
# Create raw stream. The stream name must match one used by the
# driver to label packet data. This stream does not yet have a
# packet definition so will not be published.
raw_stream_def = ctd_stream_definition(stream_id=None)
raw_stream_def_id = self._pubsub_client.create_stream_definition(
container=raw_stream_def)
raw_stream_id = self._pubsub_client.create_stream(name=raw_stream_name,
stream_definition_id=raw_stream_def_id,
original=True,
encoding='ION R2')
# Define stream configuration.
self.stream_config = {
parsed_stream_name : parsed_stream_id,
raw_stream_name : raw_stream_id
}
# A callback for processing subscribed-to data.
def consume(message, headers):
log.info('Subscriber received message: %s', str(message))
# Create a stream subscriber registrar to create subscribers.
subscriber_registrar = StreamSubscriberRegistrar(process=self.container,
node=self.container.node)
# Create and activate parsed data subscription.
parsed_sub = subscriber_registrar.create_subscriber(exchange_name=\
'parsed_queue', callback=consume)
parsed_sub.start()
parsed_query = StreamQuery(stream_ids=[parsed_stream_id])
parsed_sub_id = self._pubsub_client.create_subscription(\
query=parsed_query, exchange_name='parsed_queue')
self._pubsub_client.activate_subscription(parsed_sub_id)
# Create and activate raw data subscription.
raw_sub = subscriber_registrar.create_subscriber(exchange_name=\
'raw_queue', callback=consume)
raw_sub.start()
raw_query = StreamQuery(stream_ids=[raw_stream_id])
raw_sub_id = self._pubsub_client.create_subscription(\
query=raw_query, exchange_name='raw_queue')
self._pubsub_client.activate_subscription(raw_sub_id)
# Create agent config.
self.agent_config = {
'driver_config' : self.driver_config,
'stream_config' : self.stream_config
}
# Launch an instrument agent process.
self._ia_name = 'agent007'
self._ia_mod = 'ion.services.mi.instrument_agent'
self._ia_class = 'InstrumentAgent'
self._ia_pid = self._container_client.spawn_process(name=self._ia_name,
module=self._ia_mod, cls=self._ia_class,
config=self.agent_config)
log.info('got pid=%s', str(self._ia_pid))
# Start a resource agent client to talk with the instrument agent.
self._ia_client = ResourceAgentClient('123xyz', name=self._ia_pid,
process=FakeProcess())
log.info('got ia client %s', str(self._ia_client))
# Add cleanup function to stop subscribers.
def stop_subscriber(sub_list):
for sub in sub_list:
sub.stop()
self.addCleanup(stop_subscriber, [parsed_sub, raw_sub])
def test_initialize(self):
"""
Test agent initialize command. This causes creation of
driver process and transition to inactive.
"""
cmd = AgentCommand(command='initialize')
retval = self._ia_client.execute_agent(cmd)
time.sleep(2)
caps = self._ia_client.get_capabilities()
log.info('Capabilities: %s',str(caps))
cmd = AgentCommand(command='reset')
retval = self._ia_client.execute_agent(cmd)
def test_go_active(self):
"""
Test agent go_active command. This causes a driver process to
launch a connection broker, connect to device hardware, determine
entry state of driver and intialize driver parameters.
"""
cmd = AgentCommand(command='initialize')
retval = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='go_active')
retval = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='go_inactive')
retval = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='reset')
retval = self._ia_client.execute_agent(cmd)
time.sleep(2)
def test_get_set(self):
"""
Test instrument driver resource get/set interface. This tests
getting and setting driver reousrce paramters in various syntaxes and
validates results including persistence on device hardware.
"""
cmd = AgentCommand(command='initialize')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='go_active')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='run')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
get_params = [
(SBE37Channel.CTD, SBE37Parameter.ALL)
]
reply = self._ia_client.get_param(get_params)
time.sleep(2)
self.assertIsInstance(reply, dict)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)], float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)], float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)], (tuple, list))
# Set up a param dict of the original values.
old_ta2 = reply[(SBE37Channel.CTD, SBE37Parameter.TA2)]
old_ptca1 = reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)]
old_tcaldate = reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)]
orig_params = {
(SBE37Channel.CTD, SBE37Parameter.TA2): old_ta2,
(SBE37Channel.CTD, SBE37Parameter.PTCA1): old_ptca1,
(SBE37Channel.CTD, SBE37Parameter.TCALDATE): old_tcaldate
}
# Set up a param dict of new values.
new_ta2 = old_ta2*2
new_ptcal1 = old_ptca1*2
new_tcaldate = list(old_tcaldate)
new_tcaldate[2] = new_tcaldate[2] + 1
new_params = {
(SBE37Channel.CTD, SBE37Parameter.TA2): new_ta2,
(SBE37Channel.CTD, SBE37Parameter.PTCA1): new_ptcal1,
(SBE37Channel.CTD, SBE37Parameter.TCALDATE): new_tcaldate
}
# Set the params to their new values.
reply = self._ia_client.set_param(new_params)
time.sleep(2)
# Check overall success and success of the individual paramters.
self.assertIsInstance(reply, dict)
# Get the same paramters back from the driver.
get_params = [
(SBE37Channel.CTD, SBE37Parameter.TA2),
(SBE37Channel.CTD, SBE37Parameter.PTCA1),
(SBE37Channel.CTD, SBE37Parameter.TCALDATE)
]
reply = self._ia_client.get_param(get_params)
time.sleep(2)
# Check success, and check that the parameters were set to the
# new values.
self.assertIsInstance(reply, dict)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)], float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)], float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)], (tuple, list))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)], new_ta2, delta=abs(0.01*new_ta2))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)], new_ptcal1, delta=abs(0.01*new_ptcal1))
self.assertEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)], new_tcaldate)
# Set the paramters back to their original values.
reply = self._ia_client.set_param(orig_params)
self.assertIsInstance(reply, dict)
# Get the parameters back from the driver.
reply = self._ia_client.get_param(get_params)
# Check overall and individual sucess, and that paramters were
# returned to their original values.
self.assertIsInstance(reply, dict)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)], float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)], float)
self.assertIsInstance(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)], (tuple, list))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TA2)], old_ta2, delta=abs(0.01*old_ta2))
self.assertAlmostEqual(reply[(SBE37Channel.CTD, SBE37Parameter.PTCA1)], old_ptca1, delta=abs(0.01*old_ptca1))
self.assertEqual(reply[(SBE37Channel.CTD, SBE37Parameter.TCALDATE)], old_tcaldate)
time.sleep(2)
cmd = AgentCommand(command='go_inactive')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='reset')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
def test_poll(self):
"""
Test instrument driver resource execute interface to do polled
sampling.
"""
cmd = AgentCommand(command='initialize')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='go_active')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='run')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='acquire_sample')
reply = self._ia_client.execute(cmd)
time.sleep(2)
cmd = AgentCommand(command='acquire_sample')
reply = self._ia_client.execute(cmd)
time.sleep(2)
cmd = AgentCommand(command='acquire_sample')
reply = self._ia_client.execute(cmd)
time.sleep(2)
cmd = AgentCommand(command='go_inactive')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='reset')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
def test_autosample(self):
"""
Test instrument driver execute interface to start and stop streaming
mode.
"""
cmd = AgentCommand(command='initialize')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='go_active')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='run')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='go_streaming')
reply = self._ia_client.execute_agent(cmd)
time.sleep(30)
cmd = AgentCommand(command='go_observatory')
while True:
reply = self._ia_client.execute_agent(cmd)
result = reply.result
if isinstance(result, dict):
if all([val == None for val in result.values()]):
break
time.sleep(2)
time.sleep(2)
cmd = AgentCommand(command='go_inactive')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
cmd = AgentCommand(command='reset')
reply = self._ia_client.execute_agent(cmd)
time.sleep(2)
<file_sep>/ion/processes/data/ingestion/ingestion_launcher.py
"""
@author <NAME>
@file ion/processes/data/ingestion/ingestion_launcher.py
@description Ingestion Launcher
"""
from interface.objects import CouchStorage
from interface.services.dm.iingestion_management_service import IngestionManagementServiceClient
from pyon.service.service import BaseService
class IngestionLauncher(BaseService):
def on_start(self):
super(IngestionLauncher,self).on_start()
exchange_point = self.CFG.get('process',{}).get('exchange_point','science_data')
couch_storage = self.CFG.get('process',{}).get('couch_storage',{})
couch_storage = CouchStorage(**couch_storage)
hdf_storage = self.CFG.get('process',{}).get('hdf_storage',{})
number_of_workers = self.CFG.get('process',{}).get('number_of_workers',2)
ingestion_management_service = IngestionManagementServiceClient(node=self.container.node)
ingestion_id = ingestion_management_service.create_ingestion_configuration(
exchange_point_id=exchange_point,
couch_storage=couch_storage,
hdf_storage=hdf_storage,
number_of_workers=number_of_workers,
default_policy={}
)
ingestion_management_service.activate_ingestion_configuration(ingestion_id)
<file_sep>/ion/services/sa/product/data_product_management_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from pyon.util.log import log
from interface.services.sa.idata_product_management_service import BaseDataProductManagementService
from ion.services.sa.resource_impl.data_product_impl import DataProductImpl
from pyon.datastore.datastore import DataStore
from pyon.core.bootstrap import IonObject
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.public import RT, LCS, PRED
class DataProductManagementService(BaseDataProductManagementService):
""" @author <NAME>
@file ion/services/sa/product/data_product_management_service.py
@brief Implementation of the data product management service
"""
def on_init(self):
self.override_clients(self.clients)
def override_clients(self, new_clients):
"""
Replaces the service clients with a new set of them... and makes sure they go to the right places
"""
self.data_product = DataProductImpl(self.clients)
def create_data_product(self, data_product=None, source_resource_id=''):
"""
@param data_product IonObject which defines the general data product resource
@param source_resource_id IonObject id which defines the source for the data
@retval data_product_id
"""
# 1. Verify that a data product with same name does not already exist
# 2. Validate that the data product IonObject does not contain an id_ element
# 3. Create a new data product
# - User must supply the name in the data product
# Create will validate and register a new data product within the system
# Validate - TBD by the work that Karen Stocks is driving with <NAME>
# Register - create and store a new DataProduct resource using provided metadata
log.debug("DataProductManagementService:create_data_product: %s" % str(data_product))
data_product_id = self.data_product.create_one(data_product)
if source_resource_id:
log.debug("DataProductManagementService:create_data_product: source resource id = %s" % source_resource_id)
# TODO: currently create stream for the product is ALWAYS on, this should be surfaced
# Call Data Aquisition Mgmt Svc:assign_data_product to coordinate connection of the data product to data producer and to the source resource
self.clients.data_acquisition_management.assign_data_product(source_resource_id, data_product_id, True) # TODO: what errors can occur here?
# todo: should this method create the hasOutputProduct association?
self.clients.resource_registry.create_association(source_resource_id, PRED.hasOutputProduct, data_product_id)
# Return a resource ref to the new data product
return data_product_id
def read_data_product(self, data_product_id=''):
"""
method docstring
"""
# Retrieve all metadata for a specific data product
# Return data product resource
log.debug("DataProductManagementService:read_data_product: %s" % str(data_product_id))
result = self.data_product.read_one(data_product_id)
return result
def update_data_product(self, data_product=None):
"""
@todo document this interface!!!
@param data_product DataProduct
@throws NotFound object with specified id does not exist
"""
log.debug("DataProductManagementService:update_data_product: %s" % str(data_product))
self.data_product.update_one(data_product)
#TODO: any changes to producer? Call DataAcquisitionMgmtSvc?
return
def delete_data_product(self, data_product_id=''):
#Check if this data product is associated to a producer
producer_ids, _ = self.clients.resource_registry.find_objects(data_product_id, PRED.hasDataProducer, RT.DataProducer, id_only=True)
if producer_ids:
log.debug("DataProductManagementService:delete_data_product: %s" % str(producer_ids))
self.clients.data_acquisition_management.unassign_data_product(data_product_id)
# Delete the data process
self.clients.resource_registry.delete(data_product_id)
return
def find_data_products(self, filters=None):
"""
method docstring
"""
# Validate the input filter and augment context as required
# Define set of resource attributes to filter on, change parameter from "filter" to include attributes and filter values.
# potentially: title, keywords, date_created, creator_name, project, geospatial coords, time range
# Call DM DiscoveryService to query the catalog for matches
# Organize and return the list of matches with summary metadata (title, summary, keywords)
#find the items in the store
if filters is None:
objects, _ = self.clients.resource_registry.find_resources(RT.DataProduct, None, None, False)
else: # TODO: code for all the filter types
objects = []
return objects
def activate_data_product_persistence(self, data_product_id='', persist_data=True, persist_metadata=True):
"""Persist data product data into a data set
@param data_product_id str
@throws NotFound object with specified id does not exist
"""
# retrieve the data_process object
data_product_obj = self.clients.resource_registry.read(data_product_id)
if data_product_obj is None:
raise NotFound("Data Product %s does not exist" % data_product_id)
# get the Stream associated with this data set; if no stream then create one, if multiple streams then Throw
streams, _ = self.clients.resource_registry.find_objects(data_product_id, PRED.hasStream, RT.Stream, True)
if len(streams) > 1 or len(streams) == 0:
raise BadRequest('Data Product must have one stream associated%s' % str(data_product_id))
stream = streams[0]
# Call ingestion management to create a ingestion configuration
# Configure ingestion using eight workers, ingesting to test_dm_integration datastore with the SCIDATA profile
log.debug('activate_data_product_persistence: Calling create_ingestion_configuration')
data_product_obj.ingestion_configuration_id = self.clients.ingestion_management.create_ingestion_configuration(
exchange_point_id='science_data',
couch_storage=CouchStorage(datastore_name=self.datastore_name,datastore_profile='SCIDATA'),
number_of_workers=8
)
#todo: does DPMS need to save the ingest _config_id in the product resource? Can this be found via the stream id?
# activate an ingestion configuration
#todo: Does DPMS call activate?
ret = self.clients.ingestion_management.activate_ingestion_configuration(data_product_obj.ingestion_configuration_id)
# create the dataset for the data
data_product_obj.dataset_id = self.clients.dataset_management.create_dataset(self, stream, data_product_obj.name, data_product_obj.description)
self.clients.resource_registry.update(data_product_obj)
# Call ingestion management to create a dataset configuration
log.debug('activate_data_product_persistence: Calling create_dataset_configuration')
dataset_configuration_id = self.clients.ingestion_management.create_dataset_configuration( dataset_id, persist_data, persist_metadata, ingestion_configuration_id)
#todo: does DPMS need to save the dataset_configuration_id in the product resource? Can this be found via the stream id?
return
def suspend_data_product_persistence(self, data_product_id=''):
"""Suspend data product data persistnce into a data set, multiple options
@param data_product_id str
@param type str
@throws NotFound object with specified id does not exist
"""
# retrieve the data_process object
data_product_obj = self.clients.resource_registry.read(data_product_id)
if data_product_obj is None:
raise NotFound("Data Product %s does not exist" % data_product_id)
if data_product_obj.ingestion_configuration_id is None:
raise NotFound("Data Product %s ingestion configuration does not exist" % data_product_id)
# Change the stream policy to stop ingestion
self.clients.ingestion_management.deactivate_ingestion_configuration(data_product_obj.ingestion_configuration_id)
return
def set_data_product_lifecycle(self, data_product_id="", lifecycle_state=""):
"""
declare a data_product to be in a given state
@param data_product_id the resource id
"""
return self.data_product.advance_lcs(data_product_id, lifecycle_state)
<file_sep>/ion/services/mi/exceptions.py
#!/usr/bin/env python
"""
@package ion.services.mi.exceptions Exception classes for MI work
@file ion/services/mi/exceptions.py
@author <NAME>
@brief Common exceptions used in the MI work. Specific ones can be subclassed
in the driver code
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from ion.services.mi.common import InstErrorCode
class InstrumentException(Exception):
"""Base class for an exception related to physical instruments or their
representation in ION.
"""
def __init__ (self, error_code=None, msg=None):
self.args = (error_code, msg)
self.error_code = error_code
self.msg = msg
class InstrumentConnectionException(InstrumentException):
"""Exception related to connection with a physical instrument"""
class InstrumentProtocolException(InstrumentException):
"""Exception related to an instrument protocol problem
These are generally related to parsing or scripting of what is supposed
to happen when talking at the lowest layer protocol to a device.
@todo Add partial result property?
"""
class InstrumentStateException(InstrumentException):
"""Exception related to an instrument state of any sort"""
class InstrumentTimeoutException(InstrumentException):
"""Exception related to a command, request, or communication timing out"""
def __init__(self, error_code=InstErrorCode.TIMEOUT, msg=None):
InstrumentException.__init__(self, error_code, msg)
class InstrumentDataException(InstrumentException):
"""Exception related to the data returned by an instrument or developed
along the path of handling that data"""
class CommsException(InstrumentException):
"""Exception related to upstream communications trouble"""
class RequiredParameterException(InstrumentException):
"""A required parameter is not supplied"""
<file_sep>/ion/services/sa/direct_access/direct_access.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
class DirectAccess(object):
"""
Interface class for direct access code
"""
def request(self, request_params={}):
pass
def stop(self, stop_params={}):
pass
<file_sep>/ion/services/coi/policy_management_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from interface.services.coi.ipolicy_management_service import BasePolicyManagementService
from pyon.core.exception import NotFound, BadRequest
from pyon.public import PRED, RT
from pyon.util.log import log
MANAGER_ROLE = 'Manager'
MEMBER_ROLE = 'Member'
class PolicyManagementService(BasePolicyManagementService):
"""
Provides the interface to define and manage policy and a repository to store and retrieve policy and templates for
policy definitions, aka attribute authority.
"""
def create_policy(self, policy=None, org_id=''):
"""Persists the provided Policy object for the specified Org id. The id string returned
is the internal id by which Policy will be indentified in the data store.
@param policy Policy
@param org_id str
@retval policy_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
policy_id, version = self.clients.resource_registry.create(policy)
return policy_id
def update_policy(self, policy=None):
"""Updates the provided Policy object. Throws NotFound exception if
an existing version of Policy is not found. Throws Conflict if
the provided Policy object is not based on the latest persisted
version of the object.
@param policy Policy
@throws NotFound object with specified id does not exist
@throws BadRequest if object does not have _id or _rev attribute
@throws Conflict object not based on latest persisted object version
"""
self.clients.resource_registry.update(policy)
def read_policy(self, policy_id=''):
"""Returns the Policy object for the specified policy id.
Throws exception if id does not match any persisted Policy
objects.
@param policy_id str
@retval policy Policy
@throws NotFound object with specified id does not exist
"""
if not policy_id:
raise BadRequest("The policy_id parameter is missing")
policy = self.clients.resource_registry.read(policy_id)
if not policy:
raise NotFound("Policy %s does not exist" % policy_id)
return policy
def delete_policy(self, policy_id=''):
"""For now, permanently deletes Policy object with the specified
id. Throws exception if id does not match any persisted Policy.
@param policy_id str
@throws NotFound object with specified id does not exist
"""
if not policy_id:
raise BadRequest("The policy_id parameter is missing")
policy = self.clients.resource_registry.read(policy_id)
if not policy:
raise NotFound("Policy %s does not exist" % policy_id)
self.clients.resource_registry.delete(policy_id)
def enable_policy(self, policy_id=''):
"""Advances the lifecycle state of the specified Policy object to be enabled. Only
enabled policies should be considered by the policy engine.
@param policy_id str
@throws NotFound object with specified id does not exist
"""
if not policy_id:
raise BadRequest("The policy_id parameter is missing")
raise NotImplementedError()
def disable_policy(self, policy_id=''):
"""Advances the lifecycle state of the specified Policy object to be disabled. Only
enabled policies should be considered by the policy engine.
@param policy_id str
@throws NotFound object with specified id does not exist
"""
if not policy_id:
raise BadRequest("The policy_id parameter is missing")
raise NotImplementedError()
def create_role(self, user_role=None):
"""Persists the provided UserRole object. The id string returned
is the internal id by which a UserRole will be indentified in the data store.
@param user_role UserRole
@retval user_role_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
user_role_id, version = self.clients.resource_registry.create(user_role)
return user_role_id
def update_role(self, user_role=None):
"""Updates the provided UserRole object. Throws NotFound exception if
an existing version of UserRole is not found. Throws Conflict if
the provided UserRole object is not based on the latest persisted
version of the object.
@param user_role UserRole
@retval success bool
@throws NotFound object with specified id does not exist
@throws BadRequest if object does not have _id or _rev attribute
@throws Conflict object not based on latest persisted object version
"""
self.clients.resource_registry.update(user_role)
def read_role(self, user_role_id=''):
"""Returns the UserRole object for the specified role id.
Throws exception if id does not match any persisted UserRole
objects.
@param user_role_id str
@retval user_role UserRole
@throws NotFound object with specified id does not exist
"""
if not user_role_id:
raise BadRequest("The user_role_id parameter is missing")
user_role = self.clients.resource_registry.read(user_role_id)
if not user_role:
raise NotFound("Role %s does not exist" % user_role_id)
return user_role
def delete_role(self, user_role_id=''):
"""For now, permanently deletes UserRole object with the specified
id. Throws exception if id does not match any persisted UserRole.
@param user_role_id str
@throws NotFound object with specified id does not exist
"""
if not user_role_id:
raise BadRequest("The user_role_id parameter is missing")
user_role = self.clients.resource_registry.read(user_role_id)
if not user_role:
raise NotFound("Role %s does not exist" % user_role_id)
self.clients.resource_registry.delete(user_role_id)
def find_roles(self):
"""Returns a list of UserRole objects defined in the resource registry.
@retval user_role_list list
"""
role_list, _ = self.clients.resource_registry.find_resources(RT.UserRole, None, None, False)
return role_list
def find_role(self, name=''):
"""Returns UserRole object that matches the specified name.
@param name str
@retval user_role UserRole
@throws NotFound object with specified id does not exist
"""
role_list, _ = self.clients.resource_registry.find_resources(RT.UserRole, None, name, False)
if not role_list:
raise NotFound('The User Role with name %s does not exist' % name )
return role_list[0]
<file_sep>/ion/processes/data/ctd_stream_publisher.py
#!/usr/bin/env python
'''
@author <NAME> <<EMAIL>>
@file ion/processes/data/ctd_stream_publisher.py
@description A simple example process which publishes prototype ctd data
To Run:
bin/pycc --rel res/deploy/r2dm.yml
pid = cc.spawn_process(name='ctd_test',module='ion.processes.data.ctd_stream_publisher',cls='SimpleCtdPublisher')
'''
from gevent.greenlet import Greenlet
from pyon.datastore.datastore import DataStore
from pyon.ion.endpoint import StreamPublisherRegistrar
from pyon.ion.process import StandaloneProcess
from pyon.public import log
import time
import random
from prototype.sci_data.ctd_stream import ctd_stream_packet, ctd_stream_definition
from prototype.sci_data.constructor_apis import PointSupplementConstructor
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
class SimpleCtdPublisher(StandaloneProcess):
def __init__(self, *args, **kwargs):
super(StandaloneProcess, self).__init__(*args,**kwargs)
#@todo Init stuff
def on_start(self):
'''
Creates a publisher for each stream_id passed in as publish_streams
Creates an attribute with the name matching the stream name which corresponds to the publisher
ex: say we have publish_streams:{'output': my_output_stream_id }
then the instance has an attribute output which corresponds to the publisher for the stream
in my_output_stream_id
'''
# Get the stream(s)
stream_id = self.CFG.get('process',{}).get('stream_id','')
self.greenlet_queue = []
# Stream creation is done in SA, but to make the example go for demonstration create one here if it is not provided...
if not stream_id:
ctd_def = ctd_stream_definition(stream_id=stream_id)
pubsub_cli = PubsubManagementServiceClient(node=self.container.node)
stream_id = pubsub_cli.create_stream(
name='Example CTD Data',
stream_definition=ctd_def,
original=True,
encoding='ION R2')
self.stream_publisher_registrar = StreamPublisherRegistrar(process=self,node=self.container.node)
# Needed to get the originator's stream_id
self.stream_id= stream_id
self.publisher = self.stream_publisher_registrar.create_publisher(stream_id=stream_id)
self.last_time = 0
g = Greenlet(self._trigger_func, stream_id)
log.debug('Starting publisher thread for simple ctd data.')
g.start()
self.greenlet_queue.append(g)
def on_quit(self):
for greenlet in self.greenlet_queue:
greenlet.kill()
super(SimpleCtdPublisher,self).on_quit()
def _trigger_func(self, stream_id):
while True:
length = random.randint(1,20)
c = [random.uniform(0.0,75.0) for i in xrange(length)]
t = [random.uniform(-1.7, 21.0) for i in xrange(length)]
p = [random.lognormvariate(1,2) for i in xrange(length)]
lat = [random.uniform(-90.0, 90.0) for i in xrange(length)]
lon = [random.uniform(0.0, 360.0) for i in xrange(length)]
tvar = [self.last_time + i for i in xrange(1,length+1)]
self.last_time = max(tvar)
ctd_packet = ctd_stream_packet(stream_id=stream_id,
c=c, t=t, p=p, lat=lat, lon=lon, time=tvar)
log.warn('SimpleCtdPublisher sending %d values!' % length)
self.publisher.publish(ctd_packet)
time.sleep(2.0)
class PointCtdPublisher(StandaloneProcess):
#overriding trigger function here to use PointSupplementConstructor
def _trigger_func(self, stream_id):
point_def = ctd_stream_definition(stream_id=stream_id)
point_constructor = PointSupplementConstructor(point_definition=point_def)
while True:
length = 1
c = [random.uniform(0.0,75.0) for i in xrange(length)]
t = [random.uniform(-1.7, 21.0) for i in xrange(length)]
p = [random.lognormvariate(1,2) for i in xrange(length)]
lat = [random.uniform(-90.0, 90.0) for i in xrange(length)]
lon = [random.uniform(0.0, 360.0) for i in xrange(length)]
tvar = [self.last_time + i for i in xrange(1,length+1)]
self.last_time = max(tvar)
point_id = point_constructor.add_point(time=tvar,location=(lon[0],lat[0]))
point_constructor.add_point_coverage(point_id=point_id, coverage_id='temperature', values=t)
point_constructor.add_point_coverage(point_id=point_id, coverage_id='pressure', values=p)
point_constructor.add_point_coverage(point_id=point_id, coverage_id='conductivity', values=c)
ctd_packet = point_constructor.get_stream_granule()
log.warn('SimpleCtdPublisher sending %d values!' % length)
self.publisher.publish(ctd_packet)
time.sleep(2.0)<file_sep>/ion/services/sa/direct_access/telnet_server.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
# The following code is based on telnetsrvlib 1.0.2 from <NAME>
"""TELNET server class
Based on the telnet client in telnetlib.py
Presents a command line interface to the telnet client.
Various settings can affect the operation of the server:
authCallback = Reference to authentication function. If
there is none, no un/pw is requested. Should
terminate the server if authentication fails
Default: None
authNeedUser = Should a username be requested?
Default: False
authNeedPass = Should a password be requested?
Default: False
"""
#from telnetlib import IAC, WILL, WONT, DO, DONT, ECHO, SGA, Telnet
import threading
import SocketServer
import socket
import time
import sys
import traceback
import curses.ascii
import curses.has_key
import curses
import re
#import logging as log
import multiprocessing
import select
from pyon.core.exception import ServerError
from pyon.util.log import log
if not hasattr(socket, 'SHUT_RDWR'):
socket.SHUT_RDWR = 2
__all__ = ["TelnetHandler", "TelnetCLIHandler"]
IAC = chr(255) # "Interpret As Command"
DONT = chr(254)
DO = chr(253)
WONT = chr(252)
WILL = chr(251)
theNULL = chr(0)
SE = chr(240) # Subnegotiation End
NOP = chr(241) # No Operation
DM = chr(242) # Data Mark
BRK = chr(243) # Break
IP = chr(244) # Interrupt process
AO = chr(245) # Abort output
AYT = chr(246) # Are You There
EC = chr(247) # Erase Character
EL = chr(248) # Erase Line
GA = chr(249) # Go Ahead
SB = chr(250) # Subnegotiation Begin
BINARY = chr(0) # 8-bit data path
ECHO = chr(1) # echo
RCP = chr(2) # prepare to reconnect
SGA = chr(3) # suppress go ahead
NAMS = chr(4) # approximate message size
STATUS = chr(5) # give status
TM = chr(6) # timing mark
RCTE = chr(7) # remote controlled transmission and echo
NAOL = chr(8) # negotiate about output line width
NAOP = chr(9) # negotiate about output page size
NAOCRD = chr(10) # negotiate about CR disposition
NAOHTS = chr(11) # negotiate about horizontal tabstops
NAOHTD = chr(12) # negotiate about horizontal tab disposition
NAOFFD = chr(13) # negotiate about formfeed disposition
NAOVTS = chr(14) # negotiate about vertical tab stops
NAOVTD = chr(15) # negotiate about vertical tab disposition
NAOLFD = chr(16) # negotiate about output LF disposition
XASCII = chr(17) # extended ascii character set
LOGOUT = chr(18) # force logout
BM = chr(19) # byte macro
DET = chr(20) # data entry terminal
SUPDUP = chr(21) # supdup protocol
SUPDUPOUTPUT = chr(22) # supdup output
SNDLOC = chr(23) # send location
TTYPE = chr(24) # terminal type
EOR = chr(25) # end or record
TUID = chr(26) # TACACS user identification
OUTMRK = chr(27) # output marking
TTYLOC = chr(28) # terminal location number
VT3270REGIME = chr(29) # 3270 regime
X3PAD = chr(30) # X.3 PAD
NAWS = chr(31) # window size
TSPEED = chr(32) # terminal speed
LFLOW = chr(33) # remote flow control
LINEMODE = chr(34) # Linemode option
XDISPLOC = chr(35) # X Display Location
OLD_ENVIRON = chr(36) # Old - Environment variables
AUTHENTICATION = chr(37) # Authenticate
ENCRYPT = chr(38) # Encryption option
NEW_ENVIRON = chr(39) # New - Environment variables
# the following ones come from
# http://www.iana.org/assignments/telnet-options
# Unfortunately, that document does not assign identifiers
# to all of them, so we are making them up
TN3270E = chr(40) # TN3270E
XAUTH = chr(41) # XAUTH
CHARSET = chr(42) # CHARSET
RSP = chr(43) # Telnet Remote Serial Port
COM_PORT_OPTION = chr(44) # Com Port Control Option
SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
TLS = chr(46) # Telnet Start TLS
KERMIT = chr(47) # KERMIT
SEND_URL = chr(48) # SEND-URL
FORWARD_X = chr(49) # FORWARD_X
PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
EXOPL = chr(255) # Extended-Options-List
NOOPT = chr(0)
#Codes used in SB SE data stream for terminal type negotiation
IS = chr(0)
SEND = chr(1)
CMDS = {
WILL: 'WILL',
WONT: 'WONT',
DO: 'DO',
DONT: 'DONT',
SE: 'Subnegotiation End',
NOP: 'No Operation',
DM: 'Data Mark',
BRK: 'Break',
IP: 'Interrupt process',
AO: 'Abort output',
AYT: 'Are You There',
EC: 'Erase Character',
EL: 'Erase Line',
GA: 'Go Ahead',
SB: 'Subnegotiation Begin',
BINARY: 'Binary',
ECHO: 'Echo',
RCP: 'Prepare to reconnect',
SGA: 'Suppress Go-Ahead',
NAMS: 'Approximate message size',
STATUS: 'Give status',
TM: 'Timing mark',
RCTE: 'Remote controlled transmission and echo',
NAOL: 'Negotiate about output line width',
NAOP: 'Negotiate about output page size',
NAOCRD: 'Negotiate about CR disposition',
NAOHTS: 'Negotiate about horizontal tabstops',
NAOHTD: 'Negotiate about horizontal tab disposition',
NAOFFD: 'Negotiate about formfeed disposition',
NAOVTS: 'Negotiate about vertical tab stops',
NAOVTD: 'Negotiate about vertical tab disposition',
NAOLFD: 'Negotiate about output LF disposition',
XASCII: 'Extended ascii character set',
LOGOUT: 'Force logout',
BM: 'Byte macro',
DET: 'Data entry terminal',
SUPDUP: 'Supdup protocol',
SUPDUPOUTPUT: 'Supdup output',
SNDLOC: 'Send location',
TTYPE: 'Terminal type',
EOR: 'End or record',
TUID: 'TACACS user identification',
OUTMRK: 'Output marking',
TTYLOC: 'Terminal location number',
VT3270REGIME: '3270 regime',
X3PAD: 'X.3 PAD',
NAWS: 'Window size',
TSPEED: 'Terminal speed',
LFLOW: 'Remote flow control',
LINEMODE: 'Linemode option',
XDISPLOC: 'X Display Location',
OLD_ENVIRON: 'Old - Environment variables',
AUTHENTICATION: 'Authenticate',
ENCRYPT: 'Encryption option',
NEW_ENVIRON: 'New - Environment variables',
}
class TelnetHandler(SocketServer.BaseRequestHandler):
"A telnet server based on the client in telnetlib"
# What I am prepared to do?
DOACK = {
ECHO: WILL,
SGA: WILL,
NEW_ENVIRON: WONT,
}
# What do I want the client to do?
WILLACK = {
ECHO: DONT,
SGA: DO,
NAWS: DONT,
TTYPE: DO,
LINEMODE: DONT,
NEW_ENVIRON: DO,
}
# Default terminal type - used if client doesn't tell us its termtype
TERM = "ansi"
# Keycode to name mapping - used to decide which keys to query
KEYS = { # Key escape sequences
curses.KEY_UP: 'Up', # Cursor up
curses.KEY_DOWN: 'Down', # Cursor down
curses.KEY_LEFT: 'Left', # Cursor left
curses.KEY_RIGHT: 'Right', # Cursor right
curses.KEY_DC: 'Delete', # Delete right
curses.KEY_BACKSPACE: 'Backspace', # Delete left
}
# Reverse mapping of KEYS - used for cooking key codes
ESCSEQ = {
}
# Terminal output escape sequences
CODES = {
'DEOL': '', # Delete to end of line
'DEL': '', # Delete and close up
'INS': '', # Insert space
'CSRLEFT': '', # Move cursor left 1 space
'CSRRIGHT': '', # Move cursor right 1 space
}
# What prompt to display
PROMPT = "ION Telnet Server> "
# globals to pass configuration from parent to handler
username = ''
password = ''
child_connection = None
# --------------------------- Environment Setup ----------------------------
def __init__(self, request, client_address, server):
"""Constructor.
When called without arguments, create an unconnected instance.
With a hostname argument, it connects the instance; a port
number is optional.
"""
global username, password, child_connection
log.debug("TelnetHandler.__init__()")
# Am I doing the echoing?
self.DOECHO = True
# What opts have I sent DO/DONT for and what did I send?
self.DOOPTS = {}
# What opts have I sent WILL/WONT for and what did I send?
self.WILLOPTS = {}
# What commands does this CLI support
self.sock = None # TCP socket
self.rawq = '' # Raw input string
self.cookedq = [] # This is the cooked input stream (list of charcodes)
self.sbdataq = '' # Sub-Neg string
self.eof = 0 # Has EOF been reached?
self.quitIC = False
self.iacseq = '' # Buffer for IAC sequence.
self.sb = 0 # Flag for SB and SE sequence.
self.history = [] # Command history
self.IQUEUELOCK = threading.Lock()
self.OQUEUELOCK = threading.Lock()
self.authNeedUser = True
self.authNeedPass = True
self.authCallback = self.authorized
self.username = username
self.password = <PASSWORD>
self.child_connection = child_connection
SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
def setterm(self, term):
"Set the curses structures for this terminal"
log.debug("Setting termtype to %s" % (term, ))
curses.setupterm(term) # This will raise if the termtype is not supported
self.TERM = term
self.ESCSEQ = {}
for k in self.KEYS.keys():
str = curses.tigetstr(curses.has_key._capability_names[k])
if str:
self.ESCSEQ[str] = k
self.CODES['DEOL'] = curses.tigetstr('el')
self.CODES['DEL'] = curses.tigetstr('dch1')
self.CODES['INS'] = curses.tigetstr('ich1')
self.CODES['CSRLEFT'] = curses.tigetstr('cub1')
self.CODES['CSRRIGHT'] = curses.tigetstr('cuf1')
def setup(self):
"Connect incoming connection to a telnet session"
log.debug("TelnetHandler.setup()")
self.setterm(self.TERM)
self.sock = self.request._sock
for k in self.DOACK.keys():
self.sendcommand(self.DOACK[k], k)
for k in self.WILLACK.keys():
self.sendcommand(self.WILLACK[k], k)
self.thread_wr = threading.Thread(target=self.writeReceiver)
self.thread_wr.setDaemon(True)
self.thread_wr.start()
self.thread_ic = threading.Thread(target=self.inputcooker)
self.thread_ic.setDaemon(True)
self.thread_ic.start()
# Sleep for 0.5 second to allow options negotiation
time.sleep(0.5)
def finish(self):
"End this session"
log.debug("TelnetHandler.finish()")
try:
self.sock.shutdown(socket.SHUT_RDWR)
except Exception as ex:
# can happen if telnet client closes session first
log.debug("exception caught for socket shutdown:" + str(ex))
return
# ------------------------- Telnet Options Engine --------------------------
def options_handler(self, sock, cmd, opt):
"Negotiate options"
# if CMDS.has_key(cmd):
# cmdtxt = CMDS[cmd]
# else:
# cmdtxt = "cmd:%d" % ord(cmd)
# if cmd in [WILL, WONT, DO, DONT]:
# if CMDS.has_key(opt):
# opttxt = CMDS[opt]
# else:
# opttxt = "opt:%d" % ord(opt)
# else:
# opttxt = ""
# log.debug("OPTION: %s %s" % (cmdtxt, opttxt, ))
if cmd == NOP:
self.sendcommand(NOP)
elif cmd == WILL or cmd == WONT:
if self.WILLACK.has_key(opt):
self.sendcommand(self.WILLACK[opt], opt)
else:
self.sendcommand(DONT, opt)
if cmd == WILL and opt == TTYPE:
self.writecooked(IAC + SB + TTYPE + SEND + IAC + SE)
elif cmd == DO or cmd == DONT:
if self.DOACK.has_key(opt):
self.sendcommand(self.DOACK[opt], opt)
else:
self.sendcommand(WONT, opt)
if opt == ECHO:
self.DOECHO = (cmd == DO)
elif cmd == SE:
subreq = self.read_sb_data()
if subreq[0] == TTYPE and subreq[1] == IS:
try:
self.setterm(subreq[2:])
except:
log.debug("Terminal type not known")
elif cmd == SB:
pass
else:
log.debug("Unhandled option: %s %s" % (cmdtxt, opttxt, ))
def sendcommand(self, cmd, opt=None):
"Send a telnet command (IAC)"
# if CMDS.has_key(cmd):
# cmdtxt = CMDS[cmd]
# else:
# cmdtxt = "cmd:%d" % ord(cmd)
# if opt == None:
# opttxt = ''
# else:
# if CMDS.has_key(opt):
# opttxt = CMDS[opt]
# else:
# opttxt = "opt:%d" % ord(opt)
if cmd in [DO, DONT]:
if not self.DOOPTS.has_key(opt):
self.DOOPTS[opt] = None
if (((cmd == DO) and (self.DOOPTS[opt] != True))
or ((cmd == DONT) and (self.DOOPTS[opt] != False))):
# log.debug("Sending %s %s" % (cmdtxt, opttxt, ))
self.DOOPTS[opt] = (cmd == DO)
self.writecooked(IAC + cmd + opt)
# else:
# log.debug("Not resending %s %s" % (cmdtxt, opttxt, ))
elif cmd in [WILL, WONT]:
if not self.WILLOPTS.has_key(opt):
self.WILLOPTS[opt] = ''
if (((cmd == WILL) and (self.WILLOPTS[opt] != True))
or ((cmd == WONT) and (self.WILLOPTS[opt] != False))):
# log.debug("Sending %s %s" % (cmdtxt, opttxt, ))
self.WILLOPTS[opt] = (cmd == WILL)
self.writecooked(IAC + cmd + opt)
# else:
# log.debug("Not resending %s %s" % (cmdtxt, opttxt, ))
else:
self.writecooked(IAC + cmd)
def read_sb_data(self):
"""Return any data available in the SB ... SE queue.
Return '' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block.
"""
buf = self.sbdataq
self.sbdataq = ''
return buf
# ---------------------------- Input Functions -----------------------------
def _readline_echo(self, char, echo):
"""Echo a recieved character, move cursor etc..."""
if echo == True or (echo == None and self.DOECHO == True):
self.write(char)
def readline(self, echo=None):
"""Return a line of text, including the terminating LF
If echo is true always echo, if echo is false never echo
If echo is None follow the negotiated setting.
"""
# TODO: fix bug that doesn't display the line correctly when inserting
line = []
insptr = 0
histptr = len(self.history)
while True:
c = self.getc(block=True)
if c == theNULL:
continue
elif c == curses.KEY_LEFT:
if insptr > 0:
insptr = insptr - 1
self._readline_echo(self.CODES['CSRLEFT'], echo)
else:
self._readline_echo(chr(7), echo)
continue
elif c == curses.KEY_RIGHT:
if insptr < len(line):
insptr = insptr + 1
self._readline_echo(self.CODES['CSRRIGHT'], echo)
else:
self._readline_echo(chr(7), echo)
continue
elif c == curses.KEY_UP or c == curses.KEY_DOWN:
if c == curses.KEY_UP:
if histptr > 0:
histptr = histptr - 1
else:
self._readline_echo(chr(7), echo)
continue
elif c == curses.KEY_DOWN:
if histptr < len(self.history):
histptr = histptr + 1
else:
self._readline_echo(chr(7), echo)
continue
line = []
if histptr < len(self.history):
line.extend(self.history[histptr])
for char in range(insptr):
self._readline_echo(self.CODES['CSRLEFT'], echo)
self._readline_echo(self.CODES['DEOL'], echo)
self._readline_echo(''.join(line), echo)
insptr = len(line)
continue
elif c == chr(3):
self._readline_echo('\n' + curses.ascii.unctrl(c) + ' ABORT\n', echo)
return ''
elif c == chr(4):
if len(line) > 0:
self._readline_echo('\n' + curses.ascii.unctrl(c) + ' ABORT (QUIT)\n', echo)
return ''
self._readline_echo('\n' + curses.ascii.unctrl(c) + ' QUIT\n', echo)
return 'QUIT'
elif c == chr(10):
self._readline_echo(c, echo)
if echo == True or (echo == None and self.DOECHO == True):
self.history.append(line)
return ''.join(line)
elif c == curses.KEY_BACKSPACE or c == chr(127) or c == chr(8):
if insptr > 0:
self._readline_echo(self.CODES['CSRLEFT'] + self.CODES['DEL'], echo)
insptr = insptr - 1
del line[insptr]
else:
self._readline_echo(chr(7), echo)
continue
elif c == curses.KEY_DC:
if insptr < len(line):
self._readline_echo(self.CODES['DEL'], echo)
del line[insptr]
else:
self._readline_echo(chr(7), echo)
continue
else:
if ord(c) < 32:
c = curses.ascii.unctrl(c)
self._readline_echo(c, echo)
line[insptr:insptr] = c
insptr = insptr + len(c)
def getc(self, block=True):
"""Return one character from the input queue"""
if not block:
if not len(self.cookedq):
return ''
# loop checking for input or a request to close connection
while not len(self.cookedq):
# check for request to close connection, either from client (eof) or parent (quitIC)
if self.eof or self.quitIC:
# client or parent wants session to close so kill handler and threads
raise EOFError
time.sleep(0.05)
self.IQUEUELOCK.acquire()
ret = self.cookedq[0]
self.cookedq = self.cookedq[1:]
self.IQUEUELOCK.release()
return ret
# --------------------------- Output Functions -----------------------------
def writeline(self, text):
"""Send a packet with line ending."""
self.write(text+chr(10))
def write(self, text):
"""Send a packet to the socket. This function cooks output."""
text = text.replace(IAC, IAC+IAC)
text = text.replace(chr(10), chr(13)+chr(10))
self.writecooked(text)
def writecooked(self, text):
"""Put data directly into the output queue (bypass output cooker)"""
self.OQUEUELOCK.acquire()
self.sock.sendall(text)
self.OQUEUELOCK.release()
def writeReceiver(self):
log.debug("TelnetHandler.writeReceiver(): starting")
# loop checking for input via pipe from parent or EOF from inputcooker
while True:
if self.child_connection.poll():
data = self.child_connection.recv()
if data == -1:
# parent wants server to close
self.quitIC = True
break
self.write(data)
if self.eof:
# inputcooker detected telnet client closed
break
time.sleep(.05)
log.debug("TelnetHandler.writeReceiver(): stopping")
# ------------------------------- Input Cooker -----------------------------
def _inputcooker_getc(self, block=True):
"""Get one character from the raw queue. Optionally blocking.
Raise EOFError on end of stream. SHOULD ONLY BE CALLED FROM THE
INPUT COOKER."""
#log.debug("TelnetHandler._inputcooker_getc()")
if self.rawq:
ret = self.rawq[0]
self.rawq = self.rawq[1:]
return ret
# loop checking for input and quit request via pipe from parent
while True:
if select.select([self.sock.fileno()], [], [], 0) == ([], [], []):
if not block:
return ''
else:
break
if self.quitIC:
# parent wants server to close
raise EOFError
time.sleep(.05)
while True:
try:
ret = self.sock.recv(20)
break
except:
time.sleep(.05)
self.eof = not(ret)
self.rawq = self.rawq + ret
if self.eof:
raise EOFError
return self._inputcooker_getc(block)
def _inputcooker_ungetc(self, char):
"""Put characters back onto the head of the rawq. SHOULD ONLY
BE CALLED FROM THE INPUT COOKER."""
self.rawq = char + self.rawq
def _inputcooker_store(self, char):
"""Put the cooked data in the correct queue (with locking)"""
if self.sb:
self.sbdataq = self.sbdataq + char
else:
self.IQUEUELOCK.acquire()
if type(char) in [type(()), type([]), type("")]:
for v in char:
self.cookedq.append(v)
else:
self.cookedq.append(char)
self.IQUEUELOCK.release()
def inputcooker(self):
"""Input Cooker - Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
log.debug("TelnetHandler.inputcooker(): starting")
try:
while True:
c = self._inputcooker_getc()
if not self.iacseq:
if c == IAC:
self.iacseq += c
continue
elif c == chr(13) and not(self.sb):
c2 = self._inputcooker_getc(block=False)
if c2 == theNULL or c2 == '':
c = chr(10)
elif c2 == chr(10):
c = c2
else:
self._inputcooker_ungetc(c2)
c = chr(10)
elif c in [x[0] for x in self.ESCSEQ.keys()]:
'Looks like the begining of a key sequence'
codes = c
for keyseq in self.ESCSEQ.keys():
if len(keyseq) == 0:
continue
while codes == keyseq[:len(codes)] and len(codes) <= keyseq:
if codes == keyseq:
c = self.ESCSEQ[keyseq]
break
codes = codes + self._inputcooker_getc()
if codes == keyseq:
break
self._inputcooker_ungetc(codes[1:])
codes = codes[0]
self._inputcooker_store(c)
elif len(self.iacseq) == 1:
'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
self.iacseq += c
continue
self.iacseq = ''
if c == IAC:
self._inputcooker_store(c)
else:
if c == SB: # SB ... SE start.
self.sb = 1
self.sbdataq = ''
# continue
elif c == SE: # SB ... SE end.
self.sb = 0
# Callback is supposed to look into
# the sbdataq
self.options_handler(self.sock, c, NOOPT)
elif len(self.iacseq) == 2:
cmd = self.iacseq[1]
self.iacseq = ''
if cmd in (DO, DONT, WILL, WONT):
self.options_handler(self.sock, cmd, c)
except EOFError:
log.debug("TelnetHandler.inputcooker(): stopping")
# ----------------------- Command Line Processor Engine --------------------
def authorized(self, username, password):
if username == self.username and password == self.password:
return True
else:
return False
def handleException(self, exc_type, exc_param, exc_tb):
"Exception handler (False to abort)"
self.writeline(traceback.format_exception_only(exc_type, exc_param)[-1])
return True
def exitHandler (self, reason):
if not self.quitIC:
self.child_connection.send(-1)
time.sleep(.1)
log.debug("Exiting telnet request handler: " + reason)
def handle(self):
"The actual service to which the user has connected."
log.debug("TelnetServer.handle()")
username = None
password = <PASSWORD>
if self.authCallback:
if self.authNeedUser:
if self.DOECHO:
self.write("Username: ")
try:
username = self.readline()
except EOFError:
self.exitHandler("lost connection")
return
if self.authNeedPass:
if self.DOECHO:
self.write("Password: ")
try:
password = self.readline(echo=False)
except EOFError:
self.exitHandler("lost connection")
return
if self.DOECHO:
self.write("\n")
if not self.authCallback(username, password):
log.debug("login failed")
self.writeline("login failed")
self.exitHandler("login failed")
return
while True:
if self.DOECHO:
self.write(self.PROMPT)
try:
inputLine = self.readline()
except EOFError:
self.exitHandler("lost connection")
break
log.debug("rcvd: " + inputLine)
self.child_connection.send(inputLine)
class TcpSocketServer(SocketServer.TCPServer):
# wrapper class to allow setting the allow_reuse_address attribute to True so
# the port can be reused w/o waiting for TIME_WAIT to elapse. This is needed
# to reuse the port before TIME_WAIT has elapsed when the server closes the
# connection (TCP socket needs to wait 2*MSL to assure client got ACK for FIN).
allow_reuse_address = True
class TelnetServer(object):
tns = None
port = None
ip_address = None
serverProcess = None
parent_connection = None
quitProxy = False
callbackProxyThread = None
parentInputCallback = None
def __init__(self, inputCallback=None):
# use globals to pass configuration to telnet handler when it is started by
# TCP socket server
global username, password, child_connection
#log.getLogger('').setLevel(log.DEBUG)
log.debug("TelnetServer.__init__()")
if not inputCallback:
log.warning("TelnetServer.__init__(): callback not specified")
raise ServerError("callback not specified")
self.parentInputCallback = inputCallback
# TODO: get username and password dynamically
username = 'admin'
password = '123'
# TODO: get ip_address & port number dynamically
# TODO: ensure that port is not already in use
self.port = 8000
#self.ip_address = 'localhost'
self.ip_address = '172.16.17.32'
# setup a pipe to allow telnet server process to communicate with callbackProxy
self.parent_connection, child_connection = multiprocessing.Pipe()
# create telnet server object and start the server process
self.tns = TcpSocketServer((self.ip_address, self.port), TelnetHandler)
self.serverProcess = multiprocessing.Process(target=self.runServer)
self.serverProcess.start()
# start the callbackProxy thread to receive client input from telnet server process
self.callbackProxyThread = threading.Thread(target=self.runCallbackProxy)
#log.debug("TelnetHandler.setup(): starting callbackProxy thread")
self.callbackProxyThread.setDaemon(True)
self.callbackProxyThread.start()
def runServer(self):
log.debug("TelnetServer.runServer(): starting")
# accept a single telnet request
self.tns.handle_request()
log.debug("TelnetServer.runServer(): stopping")
def runCallbackProxy(self):
log.debug("TelnetServer.runCallbackProxy(): starting")
# run until quitProxy is True
while not self.quitProxy:
# check for input from telnet server
if self.parent_connection.poll():
# got data, so relay it to parent via callback
data = self.parent_connection.recv()
self.parentInputCallback(data)
# sniff the data to see if 'lost connection' is being sent
# to parent, and if so quit the thread
if data == -1:
break
time.sleep(.05)
log.debug("TelnetServer.runCallbackProxy(): stopping")
def getConnectionInfo(self):
global username, password
return self.ip_address, self.port, username, password
def stop(self):
log.debug("TelnetServer.stop()")
# tell callbackProxyThread to quit
self.quitProxy = True
# wait until it quits
while self.callbackProxyThread.isAlive():
time.sleep(.05)
# send 'close connection' to telnet server process
self.parent_connection.send(-1)
# give telnet server process time to terminate threads
time.sleep(.5)
self.serverProcess.terminate()
del self.serverProcess
del self.tns
def write(self, data):
# send data from parent to telnet server process to forward to client
log.debug("TelnetServer.write(): data = " + str(data))
self.parent_connection.send(data)
if __name__ == '__main__':
"For command line testing - Accept a single connection"
log.info("ION Telnet server starting")
username = "admin"
password = "123"
tns = TcpSocketServer(("localhost", 8000), TelnetHandler)
tns.handle_request()
info("completed request: exiting server")
<file_sep>/ion/services/mi/drivers/uw_bars/common.py
#!/usr/bin/env python
"""
@package ion.services.mi.drivers.uw_bars.common UW TRHPH BARS common module
@file ion/services/mi/drivers/uw_bars/common.py
@author <NAME>
@brief Some common elements.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from ion.services.mi.common import BaseEnum
from ion.services.mi.instrument_driver import DriverChannel
class BarsCommand(BaseEnum):
pass
class BarsChannel(BaseEnum):
RESISTIVITY_5 = "Resistivity/5"
RESISTIVITY_X1 = "Resistivity X1"
RESISTIVITY_X5 = "Resistivity X5"
HYDROGEN_5 = "Hydrogen/5"
HYDROGEN_X1 = "Hydrogen X1"
HYDROGEN_X5 = "Hydrogen X5"
EH_SENSOR = "Eh Sensor"
REFERENCE_TEMP_VOLTS = "Reference Temp Volts"
REFERENCE_TEMP_DEG_C = "Reference Temp Deg C"
RESISTIVITY_TEMP_VOLTS = "Resistivity Temp Volts"
RESISTIVITY_TEMP_DEG_C = "Resistivity Temp Deg C"
BATTERY_VOLTAGE = "Battery Voltage"
ALL = DriverChannel.ALL
INSTRUMENT = DriverChannel.INSTRUMENT
class BarsStatus(BaseEnum):
pass
class BarsMetadataParameter(BaseEnum):
pass
class BarsParameter(BaseEnum):
TIME_BETWEEN_BURSTS = 'TIME_BETWEEN_BURSTS'
pass
class BarsError(BaseEnum):
pass
class BarsCapability(BaseEnum):
pass
<file_sep>/ion/services/coi/test/play/test_service_gateway.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import unittest
import simplejson, urllib
from pyon.util.int_test import IonIntegrationTestCase
from nose.plugins.attrib import attr
from interface.services.icontainer_agent import ContainerAgentClient
from pyon.core.bootstrap import CFG
@attr('SYSTEM', group='coi')
class TestServiceGateway(IonIntegrationTestCase):
def setUp(self):
# Start container
self._start_container()
# Establish endpoint with container
container_client = ContainerAgentClient(node=self.container.node, name=self.container.name)
container_client.start_rel_from_url('res/deploy/r2deploy.yml')
def tearDown(self):
self._stop_container()
def test_list_resource_types(self):
port = 5000
hostname = 'localhost'
if 'web_server' in CFG:
web_server_cfg = CFG['web_server']
if web_server_cfg is not None:
if 'hostname' in web_server_cfg:
hostname = web_server_cfg['hostname']
if 'port' in web_server_cfg:
port = web_server_cfg['port']
SEARCH_BASE = 'http://' + hostname + ':' + str(port) + '/ion-service/list_resource_types'
args = {}
args.update({
#'format': "unix",
#'output': 'json'
})
url = SEARCH_BASE + '?' + urllib.urlencode(args)
result = simplejson.load(urllib.urlopen(url))
self.assertIn('AgentDefinition', result['data'])
self.assertIn('AgentInstance', result['data'])
self.assertIn('Attachment', result['data'])
self.assertIn('BankAccount', result['data'])
self.assertIn('BankCustomer', result['data'])
self.assertIn('Catalog', result['data'])
self.assertIn('Collection', result['data'])
self.assertIn('Conversation', result['data'])
self.assertIn('ConversationRole', result['data'])
self.assertIn('ConversationType', result['data'])
self.assertIn('DataProcess', result['data'])
self.assertIn('DataProcessDefinition', result['data'])
self.assertIn('DataProducer', result['data'])
self.assertIn('DataProduct', result['data'])
self.assertIn('DataSet', result['data'])
self.assertIn('DataSource', result['data'])
self.assertIn('DataStore', result['data'])
self.assertIn('DeployableType', result['data'])
self.assertIn('EPU', result['data'])
self.assertIn('EPUDefinition', result['data'])
self.assertIn('EventType', result['data'])
self.assertIn('ExchangeBroker', result['data'])
self.assertIn('ExchangeName', result['data'])
self.assertIn('ExchangePoint', result['data'])
self.assertIn('ExchangeSpace', result['data'])
self.assertIn('ExecutionEngine', result['data'])
self.assertIn('ExecutionEngineDefinition', result['data'])
self.assertIn('ExternalDataAgent', result['data'])
self.assertIn('ExternalDataAgentInstance', result['data'])
self.assertIn('ExternalDataProvider', result['data'])
self.assertIn('ExternalDataSourceModel', result['data'])
self.assertIn('ExternalDataset', result['data'])
self.assertIn('Index', result['data'])
self.assertIn('InformationResource', result['data'])
self.assertIn('IngestionConfiguration', result['data'])
self.assertIn('InstrumentAgent', result['data'])
self.assertIn('InstrumentAgentInstance', result['data'])
self.assertIn('InstrumentDevice', result['data'])
self.assertIn('InstrumentModel', result['data'])
self.assertIn('LogicalInstrument', result['data'])
self.assertIn('LogicalPlatform', result['data'])
self.assertIn('MarineFacility', result['data'])
self.assertIn('NotificationRequest', result['data'])
self.assertIn('ObjectType', result['data'])
self.assertIn('Org', result['data'])
self.assertIn('PersistentArchive', result['data'])
self.assertIn('PlatformAgent', result['data'])
self.assertIn('PlatformAgentInstance', result['data'])
self.assertIn('PlatformDevice', result['data'])
self.assertIn('PlatformModel', result['data'])
self.assertIn('Policy', result['data'])
self.assertIn('ProcessDefinition', result['data'])
#self.assertIn('ProcessState', result['data'])
self.assertIn('Resource', result['data'])
self.assertIn('ResourceAgentType', result['data'])
self.assertIn('ResourceIdentity', result['data'])
self.assertIn('ResourceLifeCycle', result['data'])
self.assertIn('ResourceType', result['data'])
self.assertIn('SampleResource', result['data'])
self.assertIn('SensorDevice', result['data'])
self.assertIn('SensorModel', result['data'])
self.assertIn('Service', result['data'])
self.assertIn('ServiceDefinition', result['data'])
self.assertIn('Site', result['data'])
self.assertIn('Stream', result['data'])
self.assertIn('StreamIngestionPolicy', result['data'])
self.assertIn('StreamTopology', result['data'])
self.assertIn('Subscription', result['data'])
self.assertIn('TaskableResource', result['data'])
self.assertIn('Transform', result['data'])
self.assertIn('UserCredentials', result['data'])
self.assertIn('UserIdentity', result['data'])
self.assertIn('UserInfo', result['data'])
self.assertIn('UserRole', result['data'])
self.assertIn('View', result['data'])
self.assertIn('VisualizationWorkflow', result['data'])
<file_sep>/ion/services/sa/resource_impl/instrument_model_impl.py
#!/usr/bin/env python
"""
@package ion.services.sa.resource_impl.instrument_model_impl
@author <NAME>
"""
#from pyon.core.exception import BadRequest, NotFound
from pyon.public import RT, LCS
from ion.services.sa.resource_impl.resource_simple_impl import ResourceSimpleImpl
from ion.services.sa.resource_impl.instrument_device_impl import InstrumentDeviceImpl
from ion.services.sa.resource_impl.instrument_agent_impl import InstrumentAgentImpl
class InstrumentModelImpl(ResourceSimpleImpl):
"""
@brief resource management for InstrumentModel resources
"""
def on_simpl_init(self):
self.instrument_agent = InstrumentAgentImpl(self.clients)
self.instrument_device = InstrumentDeviceImpl(self.clients)
self.add_lcs_precondition(LCS.RETIRED, self.lcs_precondition_retired)
def _primary_object_name(self):
return RT.InstrumentModel
def _primary_object_label(self):
return "instrument_model"
def lcs_precondition_retired(self, instrument_model_id):
"""
can't retire if any devices or agents are using this model
"""
found, _ = self.instrument_agent.find_having(instrument_model_id)
if 0 < len(found):
return False
found, _ = self.instrument_device.find_having(instrument_model_id)
if 0 < len(found):
return False
return True
<file_sep>/ion/services/dm/presentation/user_notification_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from pyon.util.log import log
from interface.services.dm.iuser_notification_service import BaseUserNotificationService
from pyon.public import RT, PRED, sys_name, Container, CFG
from pyon.core.exception import BadRequest, NotFound
from pyon.event.event import EventError, EventSubscriber, EventRepository
from pyon.util.async import spawn
from gevent import Greenlet
import string, smtplib, time
from datetime import datetime
from email.mime.text import MIMEText
# the 'from' email address for notification emails
ION_NOTIFICATION_EMAIL_ADDRESS = '<EMAIL>'
# the default smtp server
ION_SMTP_SERVER = 'mail.oceanobservatories.org'
class NotificationEventSubscriber(EventSubscriber):
# encapsulates the event subscriber and the event 'listen loop' greenlet
# implements methods to start/stop the listener
def __init__(self, origin=None, event_name=None, callback=None):
self.listener_greenlet = None
subscriber_event_name = event_name.upper() + "_EVENT"
self.subscriber = EventSubscriber(origin=origin, event_name=subscriber_event_name, callback=callback)
def start_listening(self):
self.listener_greenlet = spawn(self.subscriber.listen)
self.subscriber._ready_event.wait(timeout=5) # not sure this is needed
def stop_listening(self):
if self.listener_greenlet:
self.listener_greenlet.kill(exception=Greenlet.GreenletExit, block=False)
class Notification(object):
# encapsulates a notification's info and it's event subscriber
def __init__(self, notification=None, subscriber_callback=None):
self.notification = notification
# setup subscription using subscription_callback()
# TODO: make this walk the lists and set up a subscriber for every pair of
# origin/event. This will require a list to hold all the subscribers so they can
# be started and killed
self.subscriber = NotificationEventSubscriber(origin=notification.origin_list[0],
event_name=notification.events_list[0],
callback=subscriber_callback)
self.notification_id = None
def set_notification_id(self, id=None):
self.notification_id = id
def start_subscriber(self):
self.subscriber.start_listening()
def kill_subscriber(self):
self.subscriber.stop_listening()
del self.subscriber
class UserEventProcessor(object):
# Encapsulates the user's info and a list of all the notifications they have
# It also contains the callback that is passed to all event subscribers for this user's notifications
# If the callback gets called, then this user had a notification for that event.
def __init__(self, user_id=None, email_addr=None, smtp_server=None):
self.user_id = user_id
self.user_email_addr = email_addr
self.smtp_server = smtp_server
self.notifications = []
log.debug("UserEventProcessor.__init__(): email for user %s set to %s" %(self.user_id, self.user_email_addr))
def subscription_callback(self, *args, **kwargs):
# this callback is given to all the event subscribers that this user wants notifications for
# if this callback gets called the user in this processor should get an email
log.debug("UserEventProcessor.subscription_callback(): args[0]=" + str(args[0]))
log.debug("event type = " + str(args[0]._get_type()))
origin = args[0].origin
event = str(args[0]._get_type())
description = args[0].description
time_stamp = str( datetime.fromtimestamp(time.mktime(time.gmtime(args[0].ts_created))))
# build the email from the event content
BODY = string.join(("Event: %s" % event,
"",
"Originator: %s" % origin,
"",
"Description: %s" % description,
"",
"Time stamp: %s" % time_stamp,
"",
"You received this notification from ION because you asked to be notified about this event from this source. ",
"To modify or remove notifications about this event, please access My Notifications Settings in the ION Web UI.",
"Do not reply to this email. This email address is not monitored and the emails will not be read."),
"\r\n")
SUBJECT = "(SysName: " + sys_name + ") ION event " + event + " from " + origin
FROM = ION_NOTIFICATION_EMAIL_ADDRESS
TO = self.user_email_addr
msg = MIMEText(BODY)
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = TO
log.debug("UserEventProcessor.subscription_callback(): sending email to %s via %s" %(TO, self.smtp_server))
try:
smtp_client = smtplib.SMTP(self.smtp_server)
except Exception as ex:
log.warning("UserEventProcessor.subscription_callback(): failed to connect to SMTP server %s <%s>" %(ION_SMTP_SERVER, ex))
return
try:
smtp_client.sendmail(FROM, TO, msg.as_string())
except Exception as ex:
log.warning("UserEventProcessor.subscription_callback(): failed to send email to %s <%s>" %(TO, ex))
def add_notification(self, notification=None):
for n in self.notifications:
if n.notification == notification:
raise BadRequest("UserEventProcessor.add_notification(): notification " +
str(notification) + " already exists for " + self.user_id)
# create and save notification in notifications list
n = Notification(notification, self.subscription_callback)
self.notifications.append(n)
# start the event subscriber listening
n.start_subscriber()
log.debug("UserEventProcessor.add_notification(): added notification " + str(notification) + " to user " + self.user_id)
return n
def remove_notification(self, notification_id=None):
found_notification = False
for n in self.notifications:
if n.notification_id == notification_id:
self.notifications.remove(n)
found_notification = True
if not found_notification:
raise BadRequest("UserEventProcessor.remove_notification(): notification " +
str(notification_id) + " does not exist for " + self.user_id)
# stop subscription
n.kill_subscriber()
log.debug("UserEventProcessor.remove_notification(): removed notification " + str(n.notification) + " from user " + self.user_id)
# return the number of notifications left for this user
return len(self.notifications)
def __str__(self):
return str(self.__dict__)
class UserNotificationService(BaseUserNotificationService):
user_event_processors = {}
def __init__(self):
# get the event repository from the CC
self.event_repo = Container.instance.event_repository
BaseUserNotificationService.__init__(self)
def on_start(self):
# get the smtp server address if configured
self.smtp_server = self.CFG.get('smtp_server', ION_SMTP_SERVER)
# load event originators, types, and table
self.event_originators = CFG.event.originators
self.event_types = CFG.event.types
self.event_table = {}
for originator in self.event_originators:
try:
self.event_table[originator] = CFG.event[originator]
except:
log.warning("UserNotificationService.on_start(): event originator <%s> not found in configuration" %originator)
log.debug("UserNotificationService.on_start(): event_originators=%s" %str(self.event_originators))
log.debug("UserNotificationService.on_start(): event_types=%s" %str(self.event_types))
log.debug("UserNotificationService.on_start(): event_table=%s" %str(self.event_table))
"""
# code to dump resource types, delete this from file for release
rt = sorted(RT)
for r in rt:
print("RT.%s=%s" %(r, str(RT[r])))
"""
def create_notification(self, notification=None, user_id=''):
"""
Persists the provided NotificationRequest object for the specified Origin id.
Associate the Notification resource with the user_id string.
returned id is the internal id by which NotificationRequest will be identified
in the data store.
@param notification NotificationRequest
@param user_id str
@retval notification_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
# check that user exists
user = self.clients.resource_registry.read(user_id)
if not user:
raise NotFound("UserNotificationService.create_notification(): User %s does not exist" % user_id)
if user_id not in self.user_event_processors:
# user does not have an event processor, so create one
# Retrieve the user's user_info object to get their email address
objects, assocs = self.clients.resource_registry.find_objects(user_id, PRED.hasInfo, RT.UserInfo)
if not objects:
raise NotFound("UserNotificationService.create_notification(): No user_info for user " + user_id)
if len(objects) != 1:
raise BadRequest("UserNotificationService.create_notification(): there should be only ONE user_info for " + user_id)
user_info = objects[0]
if not user_info.contact.email or user_info.contact.email == '':
raise NotFound("UserNotificationService.create_notification(): No email address in user_info for user " + user_id)
# create event processor for user
self.user_event_processors[user_id] = UserEventProcessor(user_id, user_info.contact.email, self.smtp_server)
log.debug("UserNotificationService.create_notification(): added event processor " + str(self.user_event_processors[user_id]))
# add notification to user's event_processor
Notification = self.user_event_processors[user_id].add_notification(notification)
# Persist Notification object
notification_id, version = self.clients.resource_registry.create(notification)
# give the user's user_event_processor the id of the notification
Notification.set_notification_id(notification_id)
# associate the notification to the user
self.clients.resource_registry.create_association(user_id, PRED.hasNotification, notification_id)
return notification_id
def update_notification(self, notification=None):
"""Updates the provided NotificationRequest object. Throws NotFound exception if
an existing version of NotificationRequest is not found. Throws Conflict if
the provided NotificationRequest object is not based on the latest persisted
version of the object.
@param notification NotificationRequest
@throws BadRequest if object does not have _id or _rev attribute
@throws NotFound object with specified id does not exist
@throws Conflict object not based on latest persisted object version
"""
# get the user that this notification is associated with
subjects, assocs = self.clients.resource_registry.find_subjects(RT.UserIdentity, PRED.hasNotification, notification._id)
if not subjects:
raise NotFound("UserNotificationService.delete_notification(): No user for notification " + notification._id)
if len(subjects) != 1:
raise BadRequest("UserNotificationService.delete_notification(): there should be only ONE user for " + notification._id)
user_id = subjects[0]._id
# delete old notification
self.delete_notification(notification._id)
# add new notification after 'deleting' the id and rev
del notification._id
del notification._rev
self.create_notification(notification, user_id)
def read_notification(self, notification_id=''):
"""Returns the NotificationRequest object for the specified notification id.
Throws exception if id does not match any persisted NotificationRequest
objects.
@param notification_id str
@retval notification NotificationRequest
@throws NotFound object with specified id does not exist
"""
# Read UserNotification object with _id matching passed notification_id
notification = self.clients.resource_registry.read(notification_id)
if not notification:
raise NotFound("Notification %s does not exist" % notification_id)
return notification
def delete_notification(self, notification_id=''):
"""For now, permanently deletes NotificationRequest object with the specified
id. Throws exception if id does not match any persisted NotificationRequest.
@param notification_id str
@throws NotFound object with specified id does not exist
"""
# Read specified Notification object and see if it exists
notification = self.clients.resource_registry.read(notification_id)
if not notification:
raise NotFound("UserNotificationService.delete_notification(): Notification %s does not exist" % notification_id)
#now get the user that this notification is associated with
subjects, assocs = self.clients.resource_registry.find_subjects(RT.UserIdentity, PRED.hasNotification, notification_id)
if not subjects:
raise NotFound("UserNotificationService.delete_notification(): No user for notification " + notification_id)
if len(subjects) != 1:
raise BadRequest("UserNotificationService.delete_notification(): there should be only ONE user for " + notification_id)
user_id = subjects[0]._id
#remove the notification from the user's entry in the self.user_event_processors list
#if it's the last notification for the user the delete the user from the self.user_event_processors list
if user_id not in self.user_event_processors:
log.warning("UserNotificationService.delete_notification(): user %s not found in user_event_processors list" % user_id)
user_event_processor = self.user_event_processors[user_id]
if user_event_processor.remove_notification(notification_id) == 0:
del self.user_event_processors[user_id]
log.debug("UserNotificationService.delete_notification(): removed user %s from user_event_processor list" % user_id)
#now find and delete the association
assocs = self.clients.resource_registry.find_associations(user_id, PRED.hasNotification, notification_id)
if not assocs:
raise NotFound("UserNotificationService.delete_notification(): notification association for user %s does not exist" % user_id)
association_id = assocs[0]._id
self.clients.resource_registry.delete_association(association_id)
#finally delete the notification
self.clients.resource_registry.delete(notification_id)
def find_notifications_by_user(self, user_id=''):
"""Returns a list of notifications for a specific user. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param user_id str
@retval notification_list []
@throws NotFound object with specified id does not exist
"""
objects, assocs = self.clients.resource_registry.find_objects(user_id, PRED.hasNotification, RT.NotificationRequest)
# return the list
return objects
def find_events(self, origin='', type='', min_datetime='', max_datetime=''):
"""Returns a list of events that match the specified search criteria. Will throw a not NotFound exception
if no events exist for the given parameters.
@param origin str
@param type str
@param min_datetime str
@param max_datetime str
@retval event_list []
@throws NotFound object with specified paramteres does not exist
"""
return self.event_repo.find_events(event_type=type, origin=origin, start_ts=min_datetime, end_ts=max_datetime)
def find_event_types_for_resource(self, resource_id=''):
resource_object = self.clients.resource_registry.read(resource_id)
if not resource_object:
raise NotFound("UserNotificationService.find_event_types_for_resource(): resource with id %s does not exist" % resource_id)
resource_type = type(resource_object).__name__.lower()
log.debug("UserNotificationService.find_event_types_for_resource(): resource type = " + resource_type)
if resource_type in self.event_table:
return self.event_table[resource_type]
log.debug("UserNotificationService.find_event_types_for_resource(): resource type %s not an event originator" %resource_type)
return []
<file_sep>/ion/services/sa/direct_access/instrument_direct_access.py
#!/usr/bin/env python
__author__ = '<NAME>'
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from ion.services.sa.direct_access.direct_access import DirectAccess
from pyon.core.exception import BadRequest, NotFound
from pyon.util.log import log
class InstrumentDirectAccess(DirectAccess):
"""
Class for direct access at the instrument level
"""
def request(self, request_params={}):
"""
@brief Initiates direct access for the given instrument agent
@param request_params dict
"instrument_agent_id": string ID of the instrument agent
@retval results dict
"success": bool TRUE=success, FALSE=unable to connect
"ip": string IP address of the agent-side server
"port": string IP port of the agent-side server
@throws BadRequest if the instrument_agent_id is missing
"""
log.debug("InstrumentDirectAccess: request()")
log.debug("Requesting Direct Access for " +
str(request_params["instrument_agent_id"]))
# Validate the instrument agent ID
if not request_params["instrument_agent_id"]:
raise BadRequest("no instrument agent ID")
results = {"success": False, "da_ip": "", "da_port": ""}
# TODO: Turn the following description into code
# 2. Request IA transistion to direct access state
# - Call instrument_agent_request_direct_access(DA_type)
# - Expected responses:
# True
# Success. The instrument agent did this:
# - Saved the state and the current parameters of the instrument
# - Launched Direct Access Server with DA type (telnet, SSH, VSP)
# The da_server did this:
# - Launched protocol server(s)
# - Is effectively connected to the IA (via streams?)
# - Changed state to "DIRECT_ACCESS"
# - returns IP Address, Port Number
# False
# Failure. Instrument agent could not complete its tasks
# - State could be anything now
# - return failure to caller
return results
def stop(self, stop_params={}):
log.debug("InstrumentDirectAccess: stop()")
<file_sep>/ion/services/sa/process/test/test_int_data_process_management_service.py
#!/usr/bin/env python
'''
@file ion/services/sa/process/test/test_int_data_process_management_service.py
@author <NAME>
@test ion.services.sa.process.DataProcessManagementService integration test
'''
from nose.plugins.attrib import attr
from interface.services.icontainer_agent import ContainerAgentClient
from interface.services.sa.idata_process_management_service import DataProcessManagementServiceClient
from interface.services.sa.idata_acquisition_management_service import DataAcquisitionManagementServiceClient
from interface.services.sa.idata_product_management_service import DataProductManagementServiceClient
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
from pyon.public import Container, log, IonObject
from pyon.util.containers import DotDict
from pyon.public import CFG, RT, LCS, PRED, StreamPublisher, StreamSubscriber, StreamPublisherRegistrar
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.util.context import LocalContextMixin
from interface.services.icontainer_agent import ContainerAgentClient
import time
from pyon.util.int_test import IonIntegrationTestCase
import unittest
class FakeProcess(LocalContextMixin):
name = ''
@attr('INT', group='sa')
<EMAIL>('need to fix...')
class TestIntDataProcessManagementService(IonIntegrationTestCase):
def setUp(self):
# Start container
self._start_container()
# Establish endpoint with container
container_client = ContainerAgentClient(node=self.container.node, name=self.container.name)
#print 'got CC client'
container_client.start_rel_from_url('res/deploy/r2sa.yml')
# Now create client to DataProcessManagementService
self.Processclient = DataProcessManagementServiceClient(node=self.container.node)
self.RRclient = ResourceRegistryServiceClient(node=self.container.node)
self.DAMSclient = DataAcquisitionManagementServiceClient(node=self.container.node)
self.DPMSclient = DataProductManagementServiceClient(node=self.container.node)
self.PubSubClient = PubsubManagementServiceClient(node=self.container.node)
def test_createDataProcess(self):
#-------------------------------
# Data Process Definition
#-------------------------------
log.debug("TestIntDataProcessManagementService: create data process definition")
dpd_obj = IonObject(RT.DataProcessDefinition,
name='data_process_definition',
description='some new dpd',
module='ion.processes.data.transforms.transform_example',
class_name='TransformExample',
process_source='some_source_reference')
try:
dprocdef_id = self.Processclient.create_data_process_definition(dpd_obj)
except BadRequest as ex:
self.fail("failed to create new data process definition: %s" %ex)
# test Data Process Definition creation in rr
dprocdef_obj = self.Processclient.read_data_process_definition(dprocdef_id)
self.assertEquals(dprocdef_obj.name,'data_process_definition')
# Create an input instrument
instrument_obj = IonObject(RT.InstrumentDevice, name='Inst1',description='an instrument that is creating the data product')
instrument_id, rev = self.RRclient.create(instrument_obj)
# Register the instrument so that the data producer and stream object are created
data_producer_id = self.DAMSclient.register_instrument(instrument_id)
log.debug("TestIntDataProcessManagementService data_producer_id %s" % data_producer_id)
#-------------------------------
# Input Data Product
#-------------------------------
log.debug("TestIntDataProcessManagementService: create input data product")
input_dp_obj = IonObject(RT.DataProduct, name='InputDataProduct', description='some new dp')
try:
input_dp_id = self.DPMSclient.create_data_product(input_dp_obj, instrument_id)
except BadRequest as ex:
self.fail("failed to create new input data product: %s" %ex)
# Retrieve the stream via the DataProduct->Stream associations
stream_ids, _ = self.RRclient.find_objects(input_dp_id, PRED.hasStream, None, True)
log.debug("TestIntDataProcessManagementService: in stream_ids " + str(stream_ids))
self.in_stream_id = stream_ids[0]
log.debug("TestIntDataProcessManagementService: Input Stream: " + str( self.in_stream_id))
#-------------------------------
# Output Data Product
#-------------------------------
log.debug("TestIntDataProcessManagementService: create output data product")
output_dp_obj = IonObject(RT.DataProduct, name='OutDataProduct',description='transform output')
output_dp_id = self.DPMSclient.create_data_product(output_dp_obj)
# this will NOT create a stream for the product becuase the data process (source) resource has not been created yet.
#-------------------------------
# Create the data process
#-------------------------------
log.debug("TestIntDataProcessManagementService: create_data_process start")
try:
dproc_id = self.Processclient.create_data_process(dprocdef_id, input_dp_id, output_dp_id)
except BadRequest as ex:
self.fail("failed to create new data process: %s" %ex)
self.DAMSclient.assign_data_product(dproc_id, output_dp_id, False)
log.debug("TestIntDataProcessManagementService: create_data_process return")
#-------------------------------
# Producer (Sample Input)
#-------------------------------
# Create a producing example process
# cheat to make a publisher object to send messages in the test.
# it is really hokey to pass process=self.cc but it works
#stream_route = self.PubSubClient.register_producer(exchange_name='producer_doesnt_have_a_name1', stream_id=self.in_stream_id)
#self.ctd_stream1_publisher = StreamPublisher(node=self.container.node, name=('science_data',stream_route.routing_key), process=self.container)
pid = self.container.spawn_process(name='dummy_process_for_test',
module='pyon.ion.process',
cls='SimpleProcess',
config={})
dummy_process = self.container.proc_manager.procs[pid]
publisher_registrar = StreamPublisherRegistrar(process=dummy_process, node=self.container.node)
self.ctd_stream1_publisher = publisher_registrar.create_publisher(stream_id=self.in_stream_id)
msg = {'num':'3'}
self.ctd_stream1_publisher.publish(msg)
time.sleep(1)
msg = {'num':'5'}
self.ctd_stream1_publisher.publish(msg)
time.sleep(1)
msg = {'num':'9'}
self.ctd_stream1_publisher.publish(msg)
# See /tmp/transform_output for results.....
# clean up the data process
try:
self.Processclient.delete_data_process(dproc_id)
except BadRequest as ex:
self.fail("failed to create new data process definition: %s" %ex)
with self.assertRaises(NotFound) as e:
self.Processclient.read_data_process(dproc_id)
try:
self.Processclient.delete_data_process_definition(dprocdef_id)
except BadRequest as ex:
self.fail("failed to create new data process definition: %s" %ex)
with self.assertRaises(NotFound) as e:
self.Processclient.read_data_process_definition(dprocdef_id)<file_sep>/ion/services/coi/identity_management_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from pyon.core.exception import Conflict, Inconsistent, NotFound
from pyon.core.security.authentication import Authentication
from pyon.public import PRED, RT, IonObject
from pyon.util.log import log
from interface.services.coi.iidentity_management_service import BaseIdentityManagementService
class IdentityManagementService(BaseIdentityManagementService):
"""
A resource registry that stores identities of users and resources, including bindings of internal identities to external identities. Also stores metadata such as a user profile.a A resource registry that stores identities of users and resources, including bindings of internal identities to external identities. Also stores metadata such as a user profile.a
"""
def on_init(self):
self.authentication = Authentication()
def create_user_identity(self, user_identity=None):
# Persist UserIdentity object and return object _id as OOI id
user_id, version = self.clients.resource_registry.create(user_identity)
return user_id
def update_user_identity(self, user_identity=None):
# Overwrite UserIdentity object
self.clients.resource_registry.update(user_identity)
def read_user_identity(self, user_id=''):
# Read UserIdentity object with _id matching passed user id
user_identity = self.clients.resource_registry.read(user_id)
if not user_identity:
raise NotFound("UserIdentity %s does not exist" % user_id)
return user_identity
def delete_user_identity(self, user_id=''):
# Read and delete specified UserIdentity object
user_identity = self.clients.resource_registry.read(user_id)
if not user_identity:
raise NotFound("UserIdentity %s does not exist" % user_id)
self.clients.resource_registry.delete(user_id)
def register_user_credentials(self, user_id='', credentials=None):
# Create UserCredentials object
credentials_obj_id, version = self.clients.resource_registry.create(credentials)
# Create association with user identity object
res = self.clients.resource_registry.create_association(user_id, PRED.hasCredentials, credentials_obj_id)
def unregister_user_credentials(self, user_id='', credentials_name=''):
# Read UserCredentials
objects, matches = self.clients.resource_registry.find_resources(RT.UserCredentials, None, credentials_name, False)
if not objects or len(objects) == 0:
raise NotFound("UserCredentials %s does not exist" % credentials_name)
if len(objects) > 1:
raise Conflict("Multiple UserCredentials objects found for subject %s" % credentials_name)
user_credentials_id = objects[0]._id
# Find and break association with UserIdentity
assocs = self.clients.resource_registry.find_associations(user_id, PRED.hasCredentials, user_credentials_id)
if not assocs or len(assocs) == 0:
raise NotFound("UserIdentity to UserCredentials association for user id %s to credential %s does not exist" % (user_id,credentials_name))
association_id = assocs[0]._id
self.clients.resource_registry.delete_association(association_id)
# Delete the UserCredentials
self.clients.resource_registry.delete(user_credentials_id)
def create_user_info(self, user_id="", user_info=None):
# Ensure UserInfo association does not already exist
objects, assocs = self.clients.resource_registry.find_objects(user_id, PRED.hasInfo, RT.UserInfo)
if objects:
raise Conflict("UserInfo already exists for user id %s" % (user_id))
# Create UserInfo object
user_info_id, version = self.clients.resource_registry.create(user_info)
# Create association with user identity object
self.clients.resource_registry.create_association(user_id, PRED.hasInfo, user_info_id)
return user_info_id
def update_user_info(self, user_info=None):
# Overwrite UserInfo object
self.clients.resource_registry.update(user_info)
def read_user_info(self, user_info_id=''):
# Read UserInfo object with _id matching passed user id
user_info = self.clients.resource_registry.read(user_info_id)
if not user_info:
raise NotFound("UserInfo %s does not exist" % user_info_id)
return user_info
def delete_user_info(self, user_info_id=''):
# Read UserInfo
user_info = self.clients.resource_registry.read(user_info_id)
if not user_info:
raise NotFound("UserInfo %s does not exist" % user_info_id)
# Find and break association with UserIdentity
subjects, assocs = self.clients.resource_registry.find_subjects(RT.UserIdentity, PRED.hasInfo, user_info_id)
if not assocs:
raise NotFound("UserIdentity to UserInfo association for user info id %s does not exist" % user_info_id)
user_identity_id = subjects[0]._id
assocs = self.clients.resource_registry.find_associations(user_identity_id, PRED.hasInfo, user_info_id)
if not assocs:
raise NotFound("UserIdentity to UserInfo association for user info id %s does not exist" % user_info_id)
association_id = assocs[0]._id
self.clients.resource_registry.delete_association(association_id)
# Delete the UserInfo
self.clients.resource_registry.delete(user_info_id)
def find_user_info_by_id(self, user_id=''):
# Look up UserInfo via association with UserIdentity
objects, assocs = self.clients.resource_registry.find_objects(user_id, PRED.hasInfo, RT.UserInfo)
if not objects:
raise NotFound("UserInfo for user id %s does not exist" % user_id)
user_info = objects[0]
return user_info
def find_user_info_by_name(self, name=''):
objects, matches = self.clients.resource_registry.find_resources(RT.UserInfo, None, name, False)
if not objects:
raise NotFound("UserInfo with name %s does not exist" % name)
if len(objects) > 1:
raise Inconsistent("Multiple UserInfos with name %s exist" % name)
return objects[0]
def find_user_info_by_subject(self, subject=''):
# Find UserCredentials
objects, matches = self.clients.resource_registry.find_resources(RT.UserCredentials, None, subject, False)
if not objects:
raise NotFound("UserCredentials with subject %s does not exist" % subject)
if len(objects) > 1:
raise Inconsistent("Multiple UserCredentials with subject %s exist" % subject)
user_credentials_id = objects[0]._id
subjects, assocs = self.clients.resource_registry.find_subjects(RT.UserIdentity, PRED.hasCredentials, user_credentials_id)
if not subjects or len(subjects) == 0:
raise NotFound("UserIdentity to UserCredentials association for subject %s does not exist" % subject)
if len(subjects) > 1:
raise Inconsistent("Multiple UserIdentity to UserCredentials associations for subject %s exist" % subject)
user_identity_id = subjects[0]._id
# Look up UserInfo via association with UserIdentity
objects, assocs = self.clients.resource_registry.find_objects(user_identity_id, PRED.hasInfo, RT.UserInfo)
if not objects:
raise NotFound("UserInfo for subject %s does not exist" % subject)
if len(objects) > 1:
raise Inconsistent("Multiple UserInfos for subject %s exist" % subject)
user_info = objects[0]
return user_info
def signon(self, certificate='', ignore_date_range=False):
# Check the certificate is currently valid
if not ignore_date_range:
if not self.authentication.is_certificate_within_date_range(certificate):
raise BadRequest("Certificate expired or not yet valid")
# Extract subject line
attributes = self.authentication.decode_certificate(certificate)
subject = attributes["subject"]
valid_until = attributes["not_valid_after"]
# Look for matching UserCredentials object
objects, assocs = self.clients.resource_registry.find_resources(RT.UserCredentials, None, subject, True)
if len(objects) > 1:
raise Conflict("More than one UserCredentials object was found for subject %s" % subject)
if len(assocs) > 1:
raise Conflict("More than one UserIdentity object is associated with subject %s" % subject)
if len(objects) == 1:
# Known user, get UserIdentity object
user_credentials_id = objects[0]
subjects, assocs = self.clients.resource_registry.find_subjects(RT.UserIdentity, PRED.hasCredentials, user_credentials_id)
if len(subjects) == 0:
raise Conflict("UserIdentity object with subject %s was previously created but is not associated with a UserIdentity object" % subject)
user_id = subjects[0]._id
# Find associated UserInfo
registered = True
try:
self.find_user_info_by_id(user_id)
except NotFound:
registered = False
return user_id, valid_until, registered
else:
# New user. Create UserIdentity and UserCredentials
user_identity = IonObject("UserIdentity", {"name": subject})
user_id = self.create_user_identity(user_identity)
user_credentials = IonObject("UserCredentials", {"name": subject})
self.register_user_credentials(user_id, user_credentials)
return user_id, valid_until, False
def create_resource_identity(self, resource_identity=None):
# Persist ResourceIdentity object and return object _id as OOI id
resource_identity_id, version = self.clients.resource_registry.create(resource_identity)
return resource_identity_id
def update_resource_identity(self, resource_identity=None):
# Overwrite ResourceIdentity object
self.clients.resource_registry.update(resource_identity)
def read_resource_identity(self, resource_identity_id=''):
# Read ResourceIdentity object with _id matching passed user id
return self.clients.resource_registry.read(resource_identity_id)
def delete_resource_identity(self, resource_identity_id=''):
# Read and delete specified ResourceIdentity object
resource_identity = self.clients.resource_registry.read(resource_identity_id)
self.clients.resource_registry.delete(resource_identity_id)
<file_sep>/ion/services/sa/acquisition/data_acquisition_management_service.py
#!/usr/bin/env python
'''
@package ion.services.sa.acquisition.data_acquisition_management_service Implementation of IDataAcquisitionManagementService interface
@file ion/services/sa/acquisition/data_acquisition_management_management_service.py
@author <NAME>
@brief Data Acquisition Management service to keep track of Data Producers, Data Sources
and the relationships between them
'''
from interface.services.sa.idata_acquisition_management_service import BaseDataAcquisitionManagementService
from pyon.core.exception import NotFound, BadRequest
from pyon.public import CFG, IonObject, log, RT, LCS, PRED
class DataAcquisitionManagementService(BaseDataAcquisitionManagementService):
# -----------------
# The following operations register different types of data producers
# -----------------
def register_external_data_set(self, external_dataset_id=''):
"""Register an existing external data set as data producer
@param external_dataset_id str
@retval data_producer_id str
"""
# retrieve the data_source object
data_set_obj = self.clients.resource_registry.read(external_dataset_id)
if data_set_obj is None:
raise NotFound("External Data Set %s does not exist" % external_dataset_id)
#create data producer resource and associate to this external_dataset_id
data_producer_obj = IonObject(RT.DataProducer,name=data_set_obj.name, description="primary producer resource for this data set", is_primary=True)
data_producer_id, rev = self.clients.resource_registry.create(data_producer_obj)
# Create association
self.clients.resource_registry.create_association(external_dataset_id, PRED.hasDataProducer, data_producer_id)
return data_producer_id
def unregister_external_data_set(self, external_dataset_id=''):
"""
@param external_dataset_id str
@throws NotFound object with specified id does not exist
"""
"""
Remove the associated DataProducer
"""
# List all resource ids that are objects for this data_source and has the hasDataProducer link
res_ids, _ = self.clients.resource_registry.find_objects(external_dataset_id, PRED.hasDataProducer, None, True)
if res_ids is None:
raise NotFound("Data Producer for External Data Set %d does not exist" % external_dataset_id)
#todo: check that there are not attached data products?
#todo: delete the data producer object and assoc to ext_data_set
return
def register_process(self, data_process_id=''):
"""
Register an existing data process as data producer
"""
# retrieve the data_process object
data_process_obj = self.clients.resource_registry.read(data_process_id)
if data_process_obj is None:
raise NotFound("Data Process %s does not exist" % data_process_id)
#create data producer resource and associate to this data_process_id
data_producer_obj = IonObject(RT.DataProducer,name=data_process_obj.name, description="primary producer resource for this process", is_primary=True)
data_producer_id, rev = self.clients.resource_registry.create(data_producer_obj)
# Create association
self.clients.resource_registry.create_association(data_process_id, PRED.hasDataProducer, data_producer_id)
# TODO: Walk up the assocations to find parent producers:
# proc->subscription->stream->prod
return data_producer_id
def unregister_process(self, data_process_id=''):
"""
Remove the associated DataProcess and disc
"""
# List all resource ids that are objects for this data_source and has the hasDataProducer link
res_ids, _ = self.clients.resource_registry.find_objects(data_process_id, PRED.hasDataProducer, None, True)
if res_ids is None:
raise NotFound("Data Producer for Data Process %d does not exist" % data_process_id)
# TODO: remove associations
#todo: check that there are not attached data products?
#todo: delete the data producer object and assoc to ext_data_set
return
def register_instrument(self, instrument_id=''):
"""
Register an existing instrument as data producer
"""
# retrieve the data_process object
instrument_obj = self.clients.resource_registry.read(instrument_id)
if instrument_obj is None:
raise NotFound("Instrument %s does not exist" % instrument_id)
#create data producer resource and associate to this instrument_id
data_producer_obj = IonObject(RT.DataProducer,name=instrument_obj.name, description="primary producer resource for this instrument", is_primary=True)
data_producer_id, rev = self.clients.resource_registry.create(data_producer_obj)
log.debug("register_instrument data_producer_id %s" % data_producer_id)
# Create association
self.clients.resource_registry.create_association(instrument_id, PRED.hasDataProducer, data_producer_id)
return data_producer_id
def unregister_instrument(self, instrument_id=''):
# Verify that both ids are valid
input_resource_obj = self.clients.resource_registry.read(instrument_id)
if not input_resource_obj:
raise BadRequest("Source resource %s does not exist" % instrument_id)
#find the data producer resource associated with the source resource that is creating the data product
producer_ids, _ = self.clients.resource_registry.find_objects(instrument_id, PRED.hasDataProducer, RT.DataProducer, id_only=True)
if producer_ids is None:
raise NotFound("No Data Producers associated with source resource ID " + str(instrument_id) )
if len(producer_ids) > 1:
raise BadRequest("All child Data Producers associated with instrument must be unassigned before instrument is unregistered " + str(instrument_id))
#find the 'head' producer
self.primary_producer = None
for producer_id in producer_ids:
producer_obj = self.clients.resource_registry.read(producer_id)
if not producer_obj:
raise NotFound("Data Producer %s does not exist" % producer_id)
if producer_obj.is_primary:
self.primary_producer = producer_id
if self.primary_producer is None:
raise NotFound("No primary Data Producer associated with source resource ID " + str(instrument_id))
# TODO: remove associations
#todo: check that there are no attached data products?
#todo: delete the data producer object and assoc to ext_data_set
return
def assign_data_product(self, input_resource_id='', data_product_id='', create_stream=False):
"""Connect the producer for an existing input resource with a data product
@param input_resource_id str
@param data_product_id str
@retval data_producer_id str
"""
# Verify that both ids are valid
input_resource_obj = self.clients.resource_registry.read(input_resource_id)
if not input_resource_obj:
raise BadRequest("Source resource %s does not exist" % input_resource_id)
data_product_obj = self.clients.resource_registry.read(data_product_id)
if not data_product_obj:
raise BadRequest("Data Product resource %s does not exist" % data_product_id)
#find the data producer resource associated with the source resource that is creating the data product
producer_ids, _ = self.clients.resource_registry.find_objects(input_resource_id, PRED.hasDataProducer, RT.DataProducer, id_only=True)
if producer_ids is None:
raise NotFound("No Data Producers associated with source resource ID " + str(input_resource_id))
#find the 'head' producer
self.primary_producer = None
for producer_id in producer_ids:
producer_obj = self.clients.resource_registry.read(producer_id)
if not producer_obj:
raise NotFound("Data Producer %s does not exist" % producer_id)
if producer_obj.is_primary:
self.primary_producer = producer_id
if self.primary_producer is None:
raise NotFound("No primary Data Producer associated with source resource ID " + str(input_resource_id))
#create data producer resource for this data product
data_producer_obj = IonObject(RT.DataProducer,name=data_product_obj.name, description=data_product_obj.description)
data_producer_id, rev = self.clients.resource_registry.create(data_producer_obj)
# Associate the Product with the Producer
self.clients.resource_registry.create_association(data_product_id, PRED.hasDataProducer, data_producer_id)
# Associate the Producer with the main Producer
self.clients.resource_registry.create_association(data_producer_id, PRED.hasParent, self.primary_producer)
# Associate the input resource with the child data Producer
self.clients.resource_registry.create_association(input_resource_id, PRED.hasDataProducer, data_producer_id)
#Create the stream if requested
log.debug("assign_data_product: create_stream %s" % create_stream)
if create_stream:
stream_id = self.clients.pubsub_management.create_stream(name=data_product_obj.name, description=data_product_obj.description)
log.debug("assign_data_product: create stream stream_id %s" % stream_id)
# Associate the Stream with the main Data Product
self.clients.resource_registry.create_association(data_product_id, PRED.hasStream, stream_id)
return
def unassign_data_product(self, input_resource_id='', data_product_id='', delete_stream=False):
"""
Disconnect the Data Product from the Data Producer
@param data_product_id str
@throws NotFound object with specified id does not exist
"""
# Verify that both ids are valid
input_resource_obj = self.clients.resource_registry.read(input_resource_id)
if not input_resource_obj:
raise BadRequest("Source resource %s does not exist" % input_resource_id)
data_product_obj = self.clients.resource_registry.read(data_product_id)
if not data_product_obj:
raise BadRequest("Data Product resource %s does not exist" % data_product_id)
#find the data producer resource associated with the source resource that is creating the data product
producer_ids, _ = self.clients.resource_registry.find_objects(data_product_id, PRED.hasDataProducer, RT.DataProducer, id_only=True)
if producer_ids is None or len(producer_ids) > 1:
raise NotFound("Invalid Data Producers associated with data product ID " + str(data_product_id))
data_producer_obj = self.read_data_producer(producer_ids[0])
if data_producer_obj is None:
raise NotFound("Data producer %d does not exist" % producer_ids[0])
# Remove the link between the child Data Producer resource and the primary Data Producer resource
associations = self.clients.resource_registry.find_associations(producer_ids[0], PRED.hasParent, RT.DataProducer, True)
for association in associations:
log.debug("unassign_data_product: link to primary DataProducer %s" % association)
self.clients.resource_registry.delete_association(association)
# Remove the link between the input resource (instrument/process/ext_data_set) resource and the child Data Producer resource
associations = self.clients.resource_registry.find_associations(input_resource_id, PRED.hasDataProducer, producer_ids[0], True)
for association in associations:
log.debug("unassign_data_product: link from input resource to child DataProducer %s" % association)
self.clients.resource_registry.delete_association(association)
self.clients.resource_registry.delete(producer_ids[0])
return
#Delete the stream if requested
log.debug("assign_data_product: delete_stream %s" % delete_stream)
if delete_stream:
#find the data producer resource associated with the source resource that is creating the data product
stream_ids, _ = self.clients.resource_registry.find_objects(data_product_id, PRED.hasStream, RT.Stream, id_only=True)
if stream_ids is None or len(stream_ids) > 1:
raise NotFound("Invalid Streams associated with data product ID " + str(data_product_id))
# List all association ids with given subject, predicate, object triples
associations = self.clients.resource_registry.find_associations(data_product_id, PRED.hasStream, stream_ids[0], True)
for association in associations:
self.clients.resource_registry.delete_association(association)
self.clients.pubsub_management.delete_stream(stream_ids[0])
return
def create_data_producer(name='', description=''):
"""Create a data producer resource, create a stream reource via DM then associate the two resources. Currently, data producers and streams are one-to-one. If the data producer is a process, connect the data producer to any parent data producers.
@param name str
@param description str
@retval data_producer_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
pass
def update_data_producer(self, data_producer=None):
'''
Update an existing data producer.
@param data_producer The data_producer object with updated properties.
@retval success Boolean to indicate successful update.
@todo Add logic to validate optional attributes. Is this interface correct?
'''
# Return Value
# ------------
# {success: true}
#
log.debug("Updating data_producer object: %s" % data_producer.name)
return self.clients.resource_registry.update(data_producer)
def read_data_producer(self, data_producer_id=''):
'''
Get an existing data_producer object.
@param data_producer The id of the stream.
@retval data_producer The data_producer object.
@throws NotFound when data_producer doesn't exist.
'''
# Return Value
# ------------
# data_producer: {}
#
log.debug("Reading data_producer object id: %s" % data_producer_id)
data_producer_obj = self.clients.resource_registry.read(data_producer_id)
if data_producer_obj is None:
raise NotFound("Data producer %s does not exist" % data_producer_id)
return data_producer_obj
def delete_data_producer(self, data_producer_id=''):
'''
Delete an existing data_producer.
@param data_producer_id The id of the stream.
@retval success Boolean to indicate successful deletion.
@throws NotFound when data_producer doesn't exist.
'''
# Return Value
# ------------
# {success: true}
#
log.debug("Deleting data_producer id: %s" % data_producer_id)
data_producer_obj = self.read_data_producer(data_producer_id)
if data_producer_obj is None:
raise NotFound("Data producer %d does not exist" % data_producer_id)
#Unregister the data producer with PubSub
self.clients.pubsub_management.unregister_producer(data_producer_obj.name, data_producer_obj.stream_id)
#TODO tell PubSub to delete the stream??
return self.clients.resource_registry.delete(data_producer_obj)
# -----------------
# The following operations manage EOI resources
# -----------------
def create_external_data_provider(self, external_data_provider=None):
# Persist ExternalDataProvider object and return object _id as OOI id
external_data_provider_id, version = self.clients.resource_registry.create(external_data_provider)
return external_data_provider_id
def update_external_data_provider(self, external_data_provider=None):
# Overwrite ExternalDataProvider object
self.clients.resource_registry.update(external_data_provider)
def read_external_data_provider(self, external_data_provider_id=''):
# Read ExternalDataProvider object with _id matching passed user id
external_data_provider = self.clients.resource_registry.read(external_data_provider_id)
if not external_data_provider:
raise NotFound("ExternalDataProvider %s does not exist" % external_data_provider_id)
return external_data_provider
def delete_external_data_provider(self, external_data_provider_id=''):
# Read and delete specified ExternalDataProvider object
external_data_provider = self.clients.resource_registry.read(external_data_provider_id)
if not external_data_provider:
raise NotFound("ExternalDataProvider %s does not exist" % external_data_provider_id)
self.clients.resource_registry.delete(external_data_provider_id)
def create_data_source(self, data_source=None):
# Persist DataSource object and return object _id as OOI id
data_source_id, version = self.clients.resource_registry.create(data_source)
return data_source_id
def update_data_source(self, data_source=None):
# Overwrite DataSource object
self.clients.resource_registry.update(data_source)
def read_data_source(self, data_source_id=''):
# Read DataSource object with _id matching passed user id
log.debug("Reading DataSource object id: %s" % data_source_id)
data_source_obj = self.clients.resource_registry.read(data_source_id)
if not data_source_obj:
raise NotFound("DataSource %s does not exist" % data_source_id)
return data_source_obj
def delete_data_source(self, data_source_id=''):
# Read and delete specified DataSource object
log.debug("Deleting DataSource id: %s" % data_source_id)
data_source_obj = self.read_data_source(data_source_id)
if data_source_obj is None:
raise NotFound("DataSource %s does not exist" % data_source_id)
return self.clients.resource_registry.delete(data_source_id)
def create_external_dataset(self, external_dataset=None):
# Persist ExternalDataSet object and return object _id as OOI id
external_dataset_id, version = self.clients.resource_registry.create(external_dataset)
return external_dataset_id
def update_external_dataset(self, external_dataset=None):
# Overwrite ExternalDataSet object
self.clients.resource_registry.update(external_dataset)
def read_external_dataset(self, external_dataset_id=''):
# Read ExternalDataSet object with _id matching passed user id
external_dataset = self.clients.resource_registry.read(external_dataset_id)
if not external_dataset:
raise NotFound("ExternalDataSet %s does not exist" % external_dataset_id)
return external_dataset
def delete_external_dataset(self, external_dataset_id=''):
# Read and delete specified ExternalDataSet object
external_dataset = self.clients.resource_registry.read(external_dataset_id)
if not external_dataset:
raise NotFound("ExternalDataSet %s does not exist" % external_dataset_id)
self.clients.resource_registry.delete(external_dataset_id)
def create_external_data_agent(self, external_data_agent=None):
# Persist ExternalDataAgent object and return object _id as OOI id
external_data_agent_id, version = self.clients.resource_registry.create(external_data_agent)
return external_data_agent_id
def update_external_data_agent(self, external_data_agent=None):
# Overwrite ExternalDataAgent object
self.clients.resource_registry.update(external_data_agent)
def read_external_data_agent(self, external_data_agent_id=''):
# Read ExternalDataAgent object with _id matching passed user id
external_data_agent = self.clients.resource_registry.read(external_data_agent_id)
if not external_data_agent:
raise NotFound("ExternalDataAgent %s does not exist" % external_data_agent_id)
return external_data_agent
def delete_external_data_agent(self, external_data_agent_id=''):
# Read and delete specified ExternalDataAgent object
external_data_agent = self.clients.resource_registry.read(external_data_agent_id)
if not external_data_agent:
raise NotFound("ExternalDataAgent %s does not exist" % external_data_agent_id)
self.clients.resource_registry.delete(external_data_agent_id)
def create_external_data_agent_instance(self, external_data_agent_instance=None):
# Persist ExternalDataAgentInstance object and return object _id as OOI id
external_data_agent_instance_id, version = self.clients.resource_registry.create(external_data_agent_instance)
return external_data_agent_instance_id
def update_external_data_agent_instance(self, external_data_agent_instance=None):
# Overwrite ExternalDataAgentInstance object
self.clients.resource_registry.update(external_data_agent_instance)
def read_external_data_agent_instance(self, external_data_agent_instance_id=''):
# Read ExternalDataAgentInstance object with _id matching passed user id
external_data_agent_instance = self.clients.resource_registry.read(external_data_agent_instance_id)
if not external_data_agent_instance:
raise NotFound("ExternalDataAgentInstance %s does not exist" % external_data_agent_instance_id)
return external_data_agent_instance
def delete_external_data_agent_instance(self, external_data_agent_instance_id=''):
# Read and delete specified ExternalDataAgentInstance object
external_data_agent_instance = self.clients.resource_registry.read(external_data_agent_instance_id)
if not external_data_agent_instance:
raise NotFound("ExternalDataAgentInstance %s does not exist" % external_data_agent_instance_id)
self.clients.resource_registry.delete(external_data_agent_instance_id)
def create_external_data_source_model(self, external_data_source_model=None):
# Persist ExternalDataSourceModel object and return object _id as OOI id
external_data_source_model_id, version = self.clients.resource_registry.create(external_data_source_model)
return external_data_source_model_id
def update_external_data_source_model(self, external_data_source_model=None):
# Overwrite ExternalDataSourceModel object
self.clients.resource_registry.update(external_data_source_model)
def read_external_data_source_model(self, external_data_source_model_id=''):
# Read ExternalDataSourceModel object with _id matching passed user id
external_data_source_model = self.clients.resource_registry.read(external_data_source_model_id)
if not external_data_source_model:
raise NotFound("ExternalDataSourceModel %s does not exist" % external_data_source_model_id)
return external_data_source_model
def delete_external_source_model_instance(self, external_data_source_model_id=''):
# Read and delete specified ExternalDataSourceModel object
external_data_source_model = self.clients.resource_registry.read(external_data_source_model_id)
if not external_data_source_model:
raise NotFound("ExternalDataSourceModel %s does not exist" % external_data_source_model_id)
self.clients.resource_registry.delete(external_data_source_model_id)
def assign_data_source_to_external_data_provider(self, data_source_id='', external_data_provider_id=''):
#Connect the data source with an external data provider
data_source = self.clients.resource_registry.read(data_source_id)
if not data_source:
raise NotFound("ExternalDataSource resource %s does not exist" % data_source_id)
agent_instance = self.clients.resource_registry.read(external_data_provider_id)
if not agent_instance:
raise NotFound("External Data Provider resource %s does not exist" % external_data_provider_id)
self.clients.resource_registry.create_association(data_source_id, PRED.hasProvider, external_data_provider_id)
def unassign_data_source_from_external_data_provider(self, data_source_id='', external_data_provider_id=''):
#Disconnect the data source from the external data provider
data_source = self.clients.resource_registry.read(data_source_id)
if not data_source:
raise NotFound("ExternalDataSource resource %s does not exist" % data_source_id)
agent_instance = self.clients.resource_registry.read(external_data_provider_id)
if not agent_instance:
raise NotFound("External Data Provider resource %s does not exist" % external_data_provider_id)
# delete the associations
# List all association ids with given subject, predicate, object triples
associations = self.clients.resource_registry.find_associations(data_source_id, PRED.hasProvider, external_data_provider_id, True)
for association in associations:
self.clients.resource_registry.delete_association(association)
def assign_data_source_to_data_model(self, data_source_id='', data_source_model_id=''):
#Connect the data source with an external data model
data_source = self.clients.resource_registry.read(data_source_id)
if not data_source:
raise NotFound("ExternalDataSource resource %s does not exist" % data_source_id)
agent_instance = self.clients.resource_registry.read(data_source_model_id)
if not agent_instance:
raise NotFound("External Data Source Model resource %s does not exist" % data_source_model_id)
self.clients.resource_registry.create_association(data_source_id, PRED.hasModel, data_source_model_id)
def unassign_data_source_from_data_model(self, data_source_id='', data_source_model_id=''):
#Disonnect the data source from the external data model
data_source = self.clients.resource_registry.read(data_source_id)
if not data_source:
raise NotFound("ExternalDataSource resource %s does not exist" % data_source_id)
agent_instance = self.clients.resource_registry.read(data_source_model_id)
if not agent_instance:
raise NotFound("External Data Source Model resource %s does not exist" % data_source_model_id)
# delete the associations
# List all association ids with given subject, predicate, object triples
associations = self.clients.resource_registry.find_associations(data_source_id, PRED.hasModel, data_source_model_id, True)
for association in associations:
self.clients.resource_registry.delete_association(association)
def assign_external_dataset_to_agent_instance(self, external_dataset_id='', agent_instance_id=''):
#Connect the agent instance with an external data set
data_source = self.clients.resource_registry.read(external_dataset_id)
if not data_source:
raise NotFound("ExternalDataSet resource %s does not exist" % external_dataset_id)
agent_instance = self.clients.resource_registry.read(agent_instance_id)
if not agent_instance:
raise NotFound("External Data Agent Instance resource %s does not exist" % agent_instance_id)
self.clients.resource_registry.create_association(external_dataset_id, PRED.hasAgentInstance, agent_instance_id)
def unassign_external_dataset_from_agent_instance(self, external_dataset_id='', agent_instance_id=''):
data_source = self.clients.resource_registry.read(external_dataset_id)
if not data_source:
raise NotFound("ExternalDataSet resource %s does not exist" % external_dataset_id)
agent_instance = self.clients.resource_registry.read(agent_instance_id)
if not agent_instance:
raise NotFound("External Data Agent Instance resource %s does not exist" % agent_instance_id)
# delete the associations
# List all association ids with given subject, predicate, object triples
associations = self.clients.resource_registry.find_associations(external_dataset_id, PRED.hasAgentInstance, agent_instance_id, True)
for association in associations:
self.clients.resource_registry.delete_association(association)
def assign_external_data_agent_to_agent_instance(self, external_data_agent_id='', agent_instance_id=''):
#Connect the agent with an agent instance
data_source = self.clients.resource_registry.read(external_data_agent_id)
if not data_source:
raise NotFound("ExternalDataSet resource %s does not exist" % external_data_agent_id)
agent_instance = self.clients.resource_registry.read(agent_instance_id)
if not agent_instance:
raise NotFound("External Data Agent Instance resource %s does not exist" % agent_instance_id)
self.clients.resource_registry.create_association(external_data_agent_id, PRED.hasInstance, agent_instance_id)
def unassign_external_data_agent_from_agent_instance(self, external_data_agent_id='', agent_instance_id=''):
data_source = self.clients.resource_registry.read(external_data_agent_id)
if not data_source:
raise NotFound("ExternalDataSet resource %s does not exist" % external_data_agent_id)
agent_instance = self.clients.resource_registry.read(agent_instance_id)
if not agent_instance:
raise NotFound("External Data Agent Instance resource %s does not exist" % agent_instance_id)
# delete the associations
# List all association ids with given subject, predicate, object triples
associations = self.clients.resource_registry.find_associations(external_data_agent_id, PRED.hasInstance, agent_instance_id, True)
for association in associations:
self.clients.resource_registry.delete_association(association)
def assign_external_data_agent_to_data_model(self, external_data_agent_id='', data_source_model_id=''):
#Connect the external data agent with an external data model
external_data_agent = self.clients.resource_registry.read(external_data_agent_id)
if not external_data_agent:
raise NotFound("ExternalDataAgent resource %s does not exist" % external_data_agent_id)
agent_instance = self.clients.resource_registry.read(data_source_model_id)
if not agent_instance:
raise NotFound("External Data Source Model resource %s does not exist" % data_source_model_id)
self.clients.resource_registry.create_association(external_data_agent_id, PRED.hasModel, data_source_model_id)
def unassign_external_data_agent_from_data_model(self, external_data_agent_id='', data_source_model_id=''):
#Disonnect the external data agent from the external data model
external_data_agent = self.clients.resource_registry.read(external_data_agent_id)
if not external_data_agent:
raise NotFound("ExternalDataAgent resource %s does not exist" % external_data_agent_id)
agent_instance = self.clients.resource_registry.read(data_source_model_id)
if not agent_instance:
raise NotFound("External Data Source Model resource %s does not exist" % data_source_model_id)
# delete the associations
# List all association ids with given subject, predicate, object triples
associations = self.clients.resource_registry.find_associations(external_data_agent_id, PRED.hasModel, data_source_model_id, True)
for association in associations:
self.clients.resource_registry.delete_association(association)
def assign_external_dataset_to_data_source(self, external_dataset_id='', data_source_id=''):
#Connect the external data set to a data source
data_source = self.clients.resource_registry.read(external_dataset_id)
if not data_source:
raise NotFound("ExternalDataSet resource %s does not exist" % external_dataset_id)
agent_instance = self.clients.resource_registry.read(data_source_id)
if not agent_instance:
raise NotFound("External Data Source Instance resource %s does not exist" % data_source_id)
self.clients.resource_registry.create_association(external_dataset_id, PRED.hasSource, data_source_id)
def unassign_external_dataset_from_data_source(self, external_dataset_id='', data_source_id=''):
#Disonnect the external data set from the data source
data_source = self.clients.resource_registry.read(external_dataset_id)
if not data_source:
raise NotFound("ExternalDataSet resource %s does not exist" % external_dataset_id)
agent_instance = self.clients.resource_registry.read(data_source_id)
if not agent_instance:
raise NotFound("External Data Source Instance resource %s does not exist" % data_source_id)
# delete the associations
# List all association ids with given subject, predicate, object triples
associations = self.clients.resource_registry.find_associations(external_dataset_id, PRED.hasSource, data_source_id, True)
for association in associations:
self.clients.resource_registry.delete_association(association)
def assign_eoi_resources(self, external_data_provider_id='', data_source_id='', data_source_model_id='', external_dataset_id='', external_data_agent_id='', agent_instance_id=''):
#Connects multiple eoi resources in batch with assocations
self.assign_data_source_to_external_data_provider(data_source_id, external_data_provider_id )
self.assign_data_source_to_data_model(data_source_id, data_source_model_id)
self.assign_external_dataset_to_data_source(external_dataset_id, data_source_id)
self.assign_external_dataset_to_agent_instance(external_dataset_id, agent_instance_id)
self.assign_external_data_agent_to_data_model(external_data_agent_id, data_source_model_id)
self.assign_external_data_agent_to_agent_instance(external_data_agent_id, agent_instance_id)
<file_sep>/ion/services/coi/test/test_resource_registry_service.py
#!/usr/bin/env python
__author__ = '<NAME>, <NAME>'
from nose.plugins.attrib import attr
from pyon.core.exception import BadRequest, Conflict, NotFound, Inconsistent
from pyon.public import IonObject, PRED, RT, LCS, LCE, iex
from pyon.util.int_test import IonIntegrationTestCase
from interface.services.icontainer_agent import ContainerAgentClient
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient, ResourceRegistryServiceProcessClient
@attr('INT', group='coi')
class TestResourceRegistry(IonIntegrationTestCase):
# service_dependencies = [('resource_registry', {'resource_registry': {'persistent': True, 'force_clean': True}})]
def setUp(self):
# Start container
self._start_container()
# Establish endpoint with container
container_client = ContainerAgentClient(node=self.container.node, name=self.container.name)
container_client.start_rel_from_url('res/deploy/r2coi.yml')
# Now create client to bank service
self.resource_registry_service = ResourceRegistryServiceClient(node=self.container.node)
def test_crud(self):
# Some quick registry tests
# Can't call new with fields that aren't defined in the object's schema
with self.assertRaises(TypeError) as cm:
IonObject("UserInfo", name="name", foo="bar")
self.assertTrue(cm.exception.message == "__init__() got an unexpected keyword argument 'foo'")
# Can't call new with fields that aren't defined in the object's schema
with self.assertRaises(TypeError) as cm:
IonObject("UserInfo", {"name": "name", "foo": "bar"})
self.assertTrue(cm.exception.message == "__init__() got an unexpected keyword argument 'foo'")
# Can't call new with fields that aren't defined in the object's schema
with self.assertRaises(TypeError) as cm:
IonObject("UserInfo", {"name": "name"}, foo="bar")
self.assertTrue(cm.exception.message == "__init__() got an unexpected keyword argument 'foo'")
# Instantiate an object
obj = IonObject("UserInfo", name="name")
# Can set attributes that aren't in the object's schema
with self.assertRaises(AttributeError) as cm:
setattr(obj, "foo", "bar")
self.assertTrue(cm.exception.message == "'UserInfo' object has no attribute 'foo'")
# Cam't call update with object that hasn't been persisted
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.update(obj)
self.assertTrue(cm.exception.message.startswith("Object does not have required '_id' or '_rev' attribute"))
# Persist object and read it back
obj_id, obj_rev = self.resource_registry_service.create(obj)
read_obj = self.resource_registry_service.read(obj_id)
# Cannot create object with _id and _rev fields pre-set
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create(read_obj)
self.assertTrue(cm.exception.message.startswith("Doc must not have '_id'"))
# Update object
read_obj.name = "<NAME>"
self.resource_registry_service.update(read_obj)
# Update should fail with revision mismatch
with self.assertRaises(Conflict) as cm:
self.resource_registry_service.update(read_obj)
self.assertTrue(cm.exception.message.startswith("Object not based on most current version"))
# Re-read and update object
read_obj = self.resource_registry_service.read(obj_id)
self.resource_registry_service.update(read_obj)
# Delete object
self.resource_registry_service.delete(obj_id)
# Make sure read, update and delete report error
with self.assertRaises(NotFound) as cm:
self.resource_registry_service.read(obj_id)
self.assertTrue(cm.exception.message.startswith("Object with id"))
with self.assertRaises(NotFound) as cm:
self.resource_registry_service.update(read_obj)
self.assertTrue(cm.exception.message.startswith("Object with id"))
with self.assertRaises(NotFound) as cm:
self.resource_registry_service.delete(obj_id)
self.assertTrue(cm.exception.message.startswith("Object with id"))
def test_lifecycle(self):
att = IonObject("Attachment", name='mine', description='desc')
rid,rev = self.resource_registry_service.create(att)
att1 = self.resource_registry_service.read(rid)
self.assertEquals(att1.name, att.name)
self.assertEquals(att1.lcstate, LCS.DRAFT)
new_state = self.resource_registry_service.execute_lifecycle_transition(rid, LCE.register)
self.assertEquals(new_state, LCS.PLANNED)
att2 = self.resource_registry_service.read(rid)
self.assertEquals(att2.lcstate, LCS.PLANNED)
with self.assertRaises(Inconsistent) as cm:
self.resource_registry_service.execute_lifecycle_transition(rid, LCE.register)
self.assertTrue("type=Attachment, lcstate=PLANNED has no transition for event register" in cm.exception.message)
new_state = self.resource_registry_service.execute_lifecycle_transition(rid, LCE.develop, LCS.PLANNED)
self.assertEquals(new_state, LCS.DEVELOPED)
self.assertRaises(iex.Inconsistent, self.resource_registry_service.execute_lifecycle_transition,
resource_id=rid, transition_event=LCE.develop, current_lcstate=LCS.PLANNED)
def test_association(self):
# Instantiate UserIdentity object
user_identity_obj = IonObject("UserIdentity", name="name")
user_identity_obj_id, user_identity_obj_rev = self.resource_registry_service.create(user_identity_obj)
read_user_identity_obj = self.resource_registry_service.read(user_identity_obj_id)
# Instantiate UserInfo object
user_info_obj = IonObject("UserInfo", name="name")
user_info_obj_id, user_info_obj_rev = self.resource_registry_service.create(user_info_obj)
read_user_info_obj = self.resource_registry_service.read(user_info_obj_id)
# Test create failures
with self.assertRaises(AttributeError) as cm:
self.resource_registry_service.create_association(user_identity_obj_id, PRED.bogus, user_info_obj_id)
self.assertTrue(cm.exception.message == "bogus")
# Predicate not provided
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(user_identity_obj_id, None, user_info_obj_id)
self.assertTrue(cm.exception.message == "Association must have all elements set")
# Bad association type
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(user_identity_obj_id, PRED.hasInfo, user_info_obj_id, 'bogustype')
self.assertTrue(cm.exception.message == "Unsupported assoc_type: bogustype")
# Subject id or object not provided
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(None, PRED.hasInfo, user_info_obj_id)
self.assertTrue(cm.exception.message == "Association must have all elements set")
# Object id or object not provided
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(user_identity_obj_id, PRED.hasInfo, None)
self.assertTrue(cm.exception.message == "Association must have all elements set")
# Bad subject id
with self.assertRaises(NotFound) as cm:
self.resource_registry_service.create_association("bogus", PRED.hasInfo, user_info_obj_id)
self.assertTrue(cm.exception.message == "Object with id bogus does not exist.")
# Bad object id
with self.assertRaises(NotFound) as cm:
self.resource_registry_service.create_association(user_identity_obj_id, PRED.hasInfo, "bogus")
self.assertTrue(cm.exception.message == "Object with id bogus does not exist.")
# _id missing from subject
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(user_identity_obj, PRED.hasInfo, user_info_obj_id)
self.assertTrue(cm.exception.message == "Subject id or rev not available")
# _id missing from object
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(user_identity_obj_id, PRED.hasInfo, user_info_obj)
self.assertTrue(cm.exception.message == "Object id or rev not available")
# Wrong subject type
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(user_info_obj_id, PRED.hasInfo, user_info_obj_id)
self.assertTrue(cm.exception.message == "Illegal subject type UserInfo for predicate hasInfo")
# Wrong object type
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.create_association(user_identity_obj_id, PRED.hasInfo, user_identity_obj_id)
self.assertTrue(cm.exception.message == "Illegal object type UserIdentity for predicate hasInfo")
# Create duplicate associations
assoc_id1, assoc_rev1 = self.resource_registry_service.create_association(user_identity_obj_id, PRED.hasInfo, user_info_obj_id)
assoc_id2, assoc_rev2 = self.resource_registry_service.create_association(user_identity_obj_id, PRED.hasInfo, user_info_obj_id, "H2R")
# Search for associations (good cases)
ret1 = self.resource_registry_service.find_associations(user_identity_obj_id, PRED.hasInfo, user_info_obj_id)
ret2 = self.resource_registry_service.find_associations(user_identity_obj_id, PRED.hasInfo)
ret3 = self.resource_registry_service.find_associations(None, PRED.hasInfo)
self.assertTrue(len(ret1) == len(ret2) == len(ret3))
self.assertTrue(ret1[0]._id == ret2[0]._id == ret3[0]._id)
ret1 = self.resource_registry_service.find_associations(user_identity_obj_id, PRED.hasInfo, user_info_obj_id, True)
ret2 = self.resource_registry_service.find_associations(user_identity_obj_id, PRED.hasInfo, id_only=True)
ret3 = self.resource_registry_service.find_associations(predicate=PRED.hasInfo, id_only=True)
self.assertTrue(ret1 == ret2 == ret3)
# Search for associations (good cases)
ret1 = self.resource_registry_service.find_associations(read_user_identity_obj, PRED.hasInfo, read_user_info_obj)
ret2 = self.resource_registry_service.find_associations(read_user_identity_obj, PRED.hasInfo)
ret3 = self.resource_registry_service.find_associations(None, PRED.hasInfo)
self.assertTrue(len(ret1) == len(ret2) == len(ret3))
self.assertTrue(ret1[0]._id == ret2[0]._id == ret3[0]._id)
ret1 = self.resource_registry_service.find_associations(user_identity_obj_id, PRED.hasInfo, read_user_info_obj, True)
ret2 = self.resource_registry_service.find_associations(user_identity_obj_id, PRED.hasInfo, id_only=True)
ret3 = self.resource_registry_service.find_associations(predicate=PRED.hasInfo, id_only=True)
self.assertTrue(ret1 == ret2 == ret3)
# Search for associations (bad cases)
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_associations(None, None, None)
self.assertTrue(cm.exception.message == "Illegal parameters")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_associations(user_identity_obj_id, None, None)
self.assertTrue(cm.exception.message == "Illegal parameters")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_associations(None, None, user_info_obj_id)
self.assertTrue(cm.exception.message == "Illegal parameters")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_associations(user_identity_obj, None, user_info_obj_id)
self.assertTrue(cm.exception.message == "Object id not available in subject")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_associations(user_identity_obj_id, None, user_info_obj)
self.assertTrue(cm.exception.message == "Object id not available in object")
# Find subjects (good cases)
subj_ret1 = self.resource_registry_service.find_subjects(RT.UserIdentity, PRED.hasInfo, user_info_obj_id, True)
subj_ret2 = self.resource_registry_service.find_subjects(RT.UserIdentity, PRED.hasInfo, read_user_info_obj, True)
self.assertTrue(len(subj_ret1) == len(subj_ret2))
self.assertTrue(subj_ret1[0] == subj_ret2[0])
self.assertTrue(subj_ret1[1][0]._id == subj_ret2[1][0]._id)
subj_ret3 = self.resource_registry_service.find_subjects(None, PRED.hasInfo, user_info_obj_id, True)
subj_ret4 = self.resource_registry_service.find_subjects(None, None, read_user_info_obj, True)
self.assertTrue(len(subj_ret3) == len(subj_ret4))
self.assertTrue(subj_ret3[0] == subj_ret4[0])
self.assertTrue(subj_ret3[1][0]._id == subj_ret4[1][0]._id)
subj_ret5 = self.resource_registry_service.find_subjects(None, PRED.hasInfo, user_info_obj_id, False)
subj_ret6 = self.resource_registry_service.find_subjects(None, None, read_user_info_obj, False)
self.assertTrue(len(subj_ret5) == len(subj_ret6))
self.assertTrue(subj_ret5[0][0]._id == subj_ret6[0][0]._id)
self.assertTrue(subj_ret5[1][0]._id == subj_ret6[1][0]._id)
# Find subjects (bad cases)
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_subjects(None, None, None)
self.assertTrue(cm.exception.message == "Must provide object")
with self.assertRaises(AttributeError) as cm:
self.resource_registry_service.find_subjects(RT.UserCredentials, PRED.bogus, user_info_obj_id, True)
self.assertTrue(cm.exception.message == "bogus")
ret = self.resource_registry_service.find_subjects(RT.UserInfo, PRED.hasCredentials, user_info_obj_id, True)
self.assertTrue(len(ret[0]) == 0)
ret = self.resource_registry_service.find_subjects(RT.UserCredentials, PRED.hasInfo, user_info_obj_id, True)
self.assertTrue(len(ret[0]) == 0)
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_subjects(RT.UserCredentials, PRED.hasInfo, user_info_obj, True)
self.assertTrue(cm.exception.message == "Object id not available in object")
# Find objects (good cases)
subj_ret1 = self.resource_registry_service.find_objects(user_identity_obj_id, PRED.hasInfo, RT.UserInfo, True)
subj_ret2 = self.resource_registry_service.find_objects(read_user_identity_obj, PRED.hasInfo, RT.UserInfo, True)
self.assertTrue(len(subj_ret1) == len(subj_ret2))
self.assertTrue(subj_ret1[0] == subj_ret2[0])
self.assertTrue(subj_ret1[1][0]._id == subj_ret2[1][0]._id)
subj_ret3 = self.resource_registry_service.find_objects(user_identity_obj_id, PRED.hasInfo, None, True)
subj_ret4 = self.resource_registry_service.find_objects(user_identity_obj_id, None, None, True)
self.assertTrue(len(subj_ret3) == len(subj_ret4))
self.assertTrue(subj_ret3[0] == subj_ret4[0])
self.assertTrue(subj_ret3[1][0]._id == subj_ret4[1][0]._id)
subj_ret5 = self.resource_registry_service.find_objects(user_identity_obj_id, PRED.hasInfo, None, False)
subj_ret6 = self.resource_registry_service.find_objects(read_user_identity_obj, None, None, False)
self.assertTrue(len(subj_ret5) == len(subj_ret6))
self.assertTrue(subj_ret5[0][0]._id == subj_ret6[0][0]._id)
self.assertTrue(subj_ret5[1][0]._id == subj_ret6[1][0]._id)
# Find objects (bad cases)
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_objects(None, None, None)
self.assertTrue(cm.exception.message == "Must provide subject")
with self.assertRaises(AttributeError) as cm:
self.resource_registry_service.find_objects(user_identity_obj_id, PRED.bogus, RT.UserCredentials, True)
self.assertTrue(cm.exception.message == "bogus")
ret = self.resource_registry_service.find_objects(user_identity_obj_id, PRED.hasCredentials, RT.UserIdentity, True)
self.assertTrue(len(ret[0]) == 0)
ret = self.resource_registry_service.find_objects(user_identity_obj_id, PRED.hasInfo, RT.UserCredentials, True)
self.assertTrue(len(ret[0]) == 0)
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_objects(user_identity_obj, PRED.hasInfo, RT.UserInfo, True)
self.assertTrue(cm.exception.message == "Object id not available in subject")
# Get association (bad cases)
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.get_association(None, None, None)
self.assertTrue(cm.exception.message == "Illegal parameters")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.get_association(user_identity_obj_id, None, None)
self.assertTrue(cm.exception.message == "Illegal parameters")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.get_association(None, None, user_info_obj_id)
self.assertTrue(cm.exception.message == "Illegal parameters")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.get_association(user_identity_obj, None, user_info_obj_id)
self.assertTrue(cm.exception.message == "Object id not available in subject")
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.get_association(user_identity_obj_id, None, user_info_obj)
self.assertTrue(cm.exception.message == "Object id not available in object")
with self.assertRaises(Inconsistent) as cm:
self.resource_registry_service.get_association(user_identity_obj_id, PRED.hasInfo, user_info_obj_id)
self.assertTrue(cm.exception.message.startswith("Duplicate associations found for subject/predicate/object"))
# Delete one of the associations
self.resource_registry_service.delete_association(assoc_id1)
assoc = self.resource_registry_service.get_association(user_identity_obj_id, PRED.hasInfo, user_info_obj_id)
self.assertTrue(assoc._id == assoc_id2)
# Delete (bad cases)
with self.assertRaises(NotFound) as cm:
self.resource_registry_service.delete_association("bogus")
self.assertTrue(cm.exception.message == "Object with id bogus does not exist.")
# Delete other association
self.resource_registry_service.delete_association(assoc_id2)
# Delete resources
self.resource_registry_service.delete(user_identity_obj_id)
self.resource_registry_service.delete(user_info_obj_id)
def test_find_resources(self):
with self.assertRaises(BadRequest) as cm:
self.resource_registry_service.find_resources(RT.UserInfo, LCS.DRAFT, "name", False)
self.assertTrue(cm.exception.message == "find by name does not support lcstate")
ret = self.resource_registry_service.find_resources(RT.UserInfo, None, "name", False)
self.assertTrue(len(ret[0]) == 0)
# Instantiate an object
obj = IonObject("UserInfo", name="name")
# Persist object and read it back
obj_id, obj_rev = self.resource_registry_service.create(obj)
read_obj = self.resource_registry_service.read(obj_id)
ret = self.resource_registry_service.find_resources(RT.UserInfo, None, "name", False)
self.assertTrue(len(ret[0]) == 1)
self.assertTrue(ret[0][0]._id == read_obj._id)
ret = self.resource_registry_service.find_resources(RT.UserInfo, LCS.DRAFT, None, False)
self.assertTrue(len(ret[0]) == 1)
self.assertTrue(ret[0][0]._id == read_obj._id)
# def test_service(self):
# res = self.clients.resource_registry.find_resources(RT.Org, None, None, True)
<file_sep>/ion/services/mi/drivers/uw_bars/driver.py
#!/usr/bin/env python
"""
@package ion.services.mi.drivers.uw_bars.driver UW TRHPH BARS driver module
@file ion/services/mi/drivers/uw_bars/driver.py
@author <NAME>
@brief UW TRHPH BARS driver
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from ion.services.mi.drivers.uw_bars.protocol import BarsInstrumentProtocol
from ion.services.mi.instrument_driver import InstrumentDriver
from ion.services.mi.instrument_driver import DriverState
from ion.services.mi.common import InstErrorCode
from ion.services.mi.drivers.uw_bars.common import BarsChannel
from ion.services.mi.drivers.uw_bars.common import BarsParameter
from ion.services.mi.drivers.uw_bars.protocol import BarsProtocolState
#import ion.services.mi.mi_logger
import logging
log = logging.getLogger('mi_logger')
class BarsInstrumentDriver(InstrumentDriver):
"""
The InstrumentDriver class for the TRHPH BARS sensor.
"""
# TODO actual handling of the "channel" concept in the design.
# TODO harmonize with base class.
# TODO NOTE: Assumes all interaction is for the INSTRUMENT special channel
def __init__(self, evt_callback=None):
InstrumentDriver.__init__(self, evt_callback)
self.connection = None
self.protocol = None
self.config = None
self._state = DriverState.UNCONFIGURED
def get_current_state(self):
return self._state
def _assert_state(self, obj):
"""
Asserts that the current state is the same as the one given (if not
a list) or is one of the elements of the given list.
"""
cs = self.get_current_state()
if isinstance(obj, list):
if cs in obj:
return
else:
raise AssertionError("current state=%s, expected one of %s" %
(cs, str(obj)))
state = obj
if cs != state:
raise AssertionError("current state=%s, expected=%s" % (cs, state))
def initialize(self, channels, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
self._assert_state([DriverState.UNCONFIGURED,
DriverState.DISCONNECTED])
assert len(channels) == 1
assert channels[0] == BarsChannel.INSTRUMENT
result = None
self._state = DriverState.UNCONFIGURED
return result
def configure(self, configs, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("configs=%s args=%s kwargs=%s" %
(str(configs), str(args), str(kwargs)))
self._assert_state(DriverState.UNCONFIGURED)
assert isinstance(configs, dict)
assert len(configs) == 1
assert BarsChannel.INSTRUMENT in configs
self.config = configs.get(BarsChannel.INSTRUMENT, None)
result = None
self._state = DriverState.DISCONNECTED
return result
def connect(self, channels, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
self._assert_state(DriverState.DISCONNECTED)
assert len(channels) == 1
assert channels[0] == BarsChannel.INSTRUMENT
result = None
self._setup_protocol(self.config)
prot_state = self.protocol.get_current_state()
if prot_state == BarsProtocolState.COLLECTING_DATA:
self._state = DriverState.AUTOSAMPLE
else:
#
# TODO proper handling
raise Exception("Not handled yet. Expecting protocol to be in %s" %
BarsProtocolState.COLLECTING_DATA)
return result
def _setup_protocol(self, config):
self.protocol = BarsInstrumentProtocol()
self.protocol.configure(self.config)
self.protocol.connect()
def disconnect(self, channels, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
assert len(channels) == 1
assert channels[0] == BarsChannel.INSTRUMENT
result = None
self.protocol.disconnect()
self.protocol = None
self._state = DriverState.DISCONNECTED
return result
def detach(self, channels, *args, **kwargs):
"""
"""
pass
########################################################################
# Channel command interface.
########################################################################
def get(self, params, *args, **kwargs):
if log.isEnabledFor(logging.DEBUG):
log.debug("params=%s args=%s kwargs=%s" %
(str(params), str(args), str(kwargs)))
result = self.protocol.get(params, *args, **kwargs)
return result
def set(self, params, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("params=%s args=%s kwargs=%s" %
(str(params), str(args), str(kwargs)))
pass
def execute(self, channels, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
pass
def execute_direct(self, channels, *args, **kwargs):
"""
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("channels=%s args=%s kwargs=%s" %
(str(channels), str(args), str(kwargs)))
pass
def get_channels(self):
"""
"""
return BarsChannel.list()
########################################################################
# TBD.
########################################################################
def get_status(self, params, timeout=10):
"""
@param timeout Number of seconds before this operation times out
"""
# TODO for the moment just returning the current driver state
return self.get_current_state()
def get_capabilities(self, params, timeout=10):
"""
@param timeout Number of seconds before this operation times out
"""
pass
<file_sep>/ion/services/mi/drivers/uw_bars/test/test_driver_proc.py
#!/usr/bin/env python
"""
@package
@file
@author <NAME>
@brief
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from gevent import monkey
monkey.patch_all()
import time
from ion.services.mi.drivers.uw_bars.test.pyon_test import PyonBarsTestCase
from ion.services.mi.instrument_driver import DriverState
from ion.services.mi.zmq_driver_client import ZmqDriverClient
from ion.services.mi.zmq_driver_process import ZmqDriverProcess
from ion.services.mi.drivers.uw_bars.common import BarsChannel
from ion.services.mi.drivers.uw_bars.common import BarsParameter
import unittest
from nose.plugins.attrib import attr
@attr('UNIT', group='mi')
class BarsDriverTest(PyonBarsTestCase):
"""
Tests involving ZMQ driver process and ZMQ client.
"""
def setUp(self):
super(BarsDriverTest, self).setUp()
# Zmq parameters used by driver process and client.
self.server_addr = 'localhost'
self.cmd_port = 5556
self.evt_port = 5557
# Driver module parameters.
self.dvr_mod = 'ion.services.mi.drivers.uw_bars.driver'
self.dvr_cls = 'BarsInstrumentDriver'
self._driver_process = ZmqDriverProcess.launch_process(self.cmd_port,
self.evt_port, self.dvr_mod, self.dvr_cls)
self._driver_client = ZmqDriverClient(self.server_addr, self.cmd_port,
self.evt_port)
self._driver_client.start_messaging()
time.sleep(1)
self.addCleanup(self._clean_up)
def _clean_up(self):
if self._driver_process:
try:
self._driver_client.done()
self._driver_process.wait()
finally:
self._driver_process = None
def tearDown(self):
super(BarsDriverTest, self).tearDown()
self._clean_up()
def _initialize(self):
driver_client = self._driver_client
reply = driver_client.cmd_dvr('initialize', [BarsChannel.INSTRUMENT])
print("** initialize reply=%s" % str(reply))
reply = driver_client.cmd_dvr('get_current_state')
print("** get_current_state reply=%s" % str(reply))
self.assertEqual(DriverState.UNCONFIGURED, reply)
time.sleep(1)
def _connect(self):
driver_client = self._driver_client
reply = driver_client.cmd_dvr('get_current_state')
print("** get_current_state reply=%s" % str(reply))
self.assertEqual(DriverState.UNCONFIGURED, reply)
self._initialize()
configs = {BarsChannel.INSTRUMENT: self.config}
reply = driver_client.cmd_dvr('configure', configs)
print("** configure reply=%s" % str(reply))
reply = driver_client.cmd_dvr('get_current_state')
print("** get_current_state reply=%s" % str(reply))
reply = driver_client.cmd_dvr('connect', [BarsChannel.INSTRUMENT])
print("** connect reply=%s" % str(reply))
time.sleep(1)
reply = driver_client.cmd_dvr('get_current_state')
print("** get_current_state reply=%s" % str(reply))
self.assertEqual(DriverState.AUTOSAMPLE, reply)
time.sleep(1)
reply = driver_client.cmd_dvr('get_status', [BarsChannel.INSTRUMENT])
print("** get_status reply=%s" % str(reply))
self.assertEqual(DriverState.AUTOSAMPLE, reply)
time.sleep(1)
def _disconnect(self):
driver_client = self._driver_client
reply = driver_client.cmd_dvr('disconnect', [BarsChannel.INSTRUMENT])
print("** disconnect reply=%s" % str(reply))
reply = driver_client.cmd_dvr('get_current_state')
print("** get_current_state reply=%s" % str(reply))
self.assertEqual(DriverState.DISCONNECTED, reply)
time.sleep(1)
self._initialize()
def test_connect_disconnect(self):
"""BARS connect and disconnect"""
self._connect()
self._disconnect()
def test_get(self):
"""BARS get"""
self._connect()
driver_client = self._driver_client
# get a parameter
cp = (BarsChannel.INSTRUMENT, BarsParameter.TIME_BETWEEN_BURSTS)
get_params = [cp]
reply = driver_client.cmd_dvr('get', get_params)
print "get reply = %s" % str(reply)
seconds = reply.get(cp)
assert isinstance(seconds, int)
self._disconnect()
<file_sep>/ion/services/coi/test/test_exchange_management_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import unittest
from mock import Mock, patch
from pyon.util.unit_test import PyonTestCase
from nose.plugins.attrib import attr
from pyon.core.exception import BadRequest, Conflict, Inconsistent, NotFound
from pyon.public import PRED, RT
from ion.services.coi.exchange_management_service import ExchangeManagementService
@attr('UNIT', group='coi')
class TestExchangeManagementService(PyonTestCase):
def setUp(self):
mock_clients = self._create_service_mock('exchange_management')
self.exchange_management_service = ExchangeManagementService()
self.exchange_management_service.clients = mock_clients
# Rename to save some typing
self.mock_create = mock_clients.resource_registry.create
self.mock_read = mock_clients.resource_registry.read
self.mock_update = mock_clients.resource_registry.update
self.mock_delete = mock_clients.resource_registry.delete
self.mock_create_association = mock_clients.resource_registry.create_association
self.mock_delete_association = mock_clients.resource_registry.delete_association
self.mock_find_objects = mock_clients.resource_registry.find_objects
self.mock_find_resources = mock_clients.resource_registry.find_resources
self.mock_find_subjects = mock_clients.resource_registry.find_subjects
# Exchange Space
self.exchange_space = Mock()
self.exchange_space.name = "Foo"
def test_create_exchange_space(self):
self.mock_create.return_value = ['111', 1]
#TODO - Need to mock an org to pass in an valid Org_id
exchange_space_id = self.exchange_management_service.create_exchange_space(self.exchange_space, "1233")
assert exchange_space_id == '111'
self.mock_create.assert_called_once_with(self.exchange_space)
def test_read_and_update_exchange_space(self):
self.mock_read.return_value = self.exchange_space
exchange_space = self.exchange_management_service.read_exchange_space('111')
assert exchange_space is self.mock_read.return_value
self.mock_read.assert_called_once_with('111', '')
exchange_space.name = 'Bar'
self.mock_update.return_value = ['111', 2]
self.exchange_management_service.update_exchange_space(exchange_space)
self.mock_update.assert_called_once_with(exchange_space)
def test_delete_exchange_space(self):
self.mock_read.return_value = self.exchange_space
self.exchange_management_service.delete_exchange_space('111')
self.mock_read.assert_called_once_with('111', '')
self.mock_delete.assert_called_once_with(self.exchange_space)
def test_read_exchange_space_not_found(self):
self.mock_read.return_value = None
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.exchange_management_service.read_exchange_space('bad')
ex = cm.exception
self.assertEqual(ex.message, 'Exchange Space bad does not exist')
self.mock_read.assert_called_once_with('bad', '')
def test_delete_exchange_space_not_found(self):
self.mock_read.return_value = None
# TEST: Execute the service operation call
with self.assertRaises(NotFound) as cm:
self.exchange_management_service.delete_exchange_space('bad')
ex = cm.exception
self.assertEqual(ex.message, 'Exchange Space bad does not exist')
self.mock_read.assert_called_once_with('bad', '')
<file_sep>/ion/services/dm/inventory/test/data_retriever_test.py
'''
@author <NAME> <<EMAIL>>
@file ion/services/dm/inventory/test/data_retriever_test.py
@description Testing Platform for Data Retriver Service
'''
import gevent
from mock import Mock
from interface.objects import Replay, StreamQuery, BlogPost, BlogAuthor, ProcessDefinition
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from interface.services.dm.idata_retriever_service import DataRetrieverServiceClient
from interface.services.dm.idataset_management_service import DatasetManagementServiceClient
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
from ion.services.dm.inventory.data_retriever_service import DataRetrieverService
from prototype.sci_data.ctd_stream import ctd_stream_packet
from pyon.core.exception import NotFound
from pyon.datastore.datastore import DataStore
from pyon.public import StreamSubscriberRegistrar
from pyon.public import PRED
from pyon.util.containers import DotDict
from pyon.util.int_test import IonIntegrationTestCase
from pyon.util.unit_test import PyonTestCase
from nose.plugins.attrib import attr
import unittest, time
from pyon.public import log
import unittest
import os
@attr('UNIT',group='dm')
class DataRetrieverServiceTest(PyonTestCase):
def setUp(self):
mock_clients = self._create_service_mock('data_retriever')
self.data_retriever_service = DataRetrieverService()
self.data_retriever_service.clients = mock_clients
self.mock_rr_create = self.data_retriever_service.clients.resource_registry.create
self.mock_rr_create_assoc = self.data_retriever_service.clients.resource_registry.create_association
self.mock_rr_read = self.data_retriever_service.clients.resource_registry.read
self.mock_rr_update = self.data_retriever_service.clients.resource_registry.update
self.mock_rr_delete = self.data_retriever_service.clients.resource_registry.delete
self.mock_rr_delete_assoc = self.data_retriever_service.clients.resource_registry.delete_association
self.mock_rr_find_assoc = self.data_retriever_service.clients.resource_registry.find_associations
self.mock_ps_create_stream = self.data_retriever_service.clients.pubsub_management.create_stream
self.mock_ps_create_stream_definition = self.data_retriever_service.clients.pubsub_management.create_stream_definition
self.data_retriever_service.container = DotDict({'id':'123','spawn_process':Mock(),'proc_manager':DotDict({'terminate_process':Mock(),'procs':[]})})
self.mock_cc_spawn = self.data_retriever_service.container.spawn_process
self.mock_cc_terminate = self.data_retriever_service.container.proc_manager.terminate_process
self.mock_pd_schedule = self.data_retriever_service.clients.process_dispatcher.schedule_process
self.mock_pd_cancel = self.data_retriever_service.clients.process_dispatcher.cancel_process
self.mock_ds_read = self.data_retriever_service.clients.dataset_management.read_dataset
self.data_retriever_service.process_definition = ProcessDefinition()
self.data_retriever_service.process_definition.executable['module'] = 'ion.processes.data.replay_process'
self.data_retriever_service.process_definition.executable['class'] = 'ReplayProcess'
self.data_retriever_service.process_definition_id = 'mock_procdef_id'
def test_define_replay(self):
#mocks
self.mock_ps_create_stream.return_value = '12345'
self.mock_rr_create.return_value = ('replay_id','garbage')
self.mock_ds_read.return_value = DotDict({
'datastore_name':'unittest',
'view_name':'garbage',
'primary_view_key':'primary key'})
self.mock_pd_schedule.return_value = 'process_id'
config = {'process':{
'query':'myquery',
'datastore_name':'unittest',
'view_name':'garbage',
'key_id':'primary key',
'delivery_format':None,
'publish_streams':{'output':'12345'}
}}
# execution
r,s = self.data_retriever_service.define_replay(dataset_id='dataset_id', query='myquery')
# assertions
self.assertTrue(self.mock_ps_create_stream_definition.called)
self.assertTrue(self.mock_ps_create_stream.called)
self.assertTrue(self.mock_rr_create.called)
self.mock_rr_create_assoc.assert_called_with('replay_id',PRED.hasStream,'12345',None)
self.assertTrue(self.mock_pd_schedule.called)
self.assertTrue(self.mock_rr_update.called)
self.assertEquals(r,'replay_id')
self.assertEquals(s,'12345')
@unittest.skip('Can\'t do unit test here')
def test_start_replay(self):
pass
def test_cancel_replay(self):
#mocks
self.mock_rr_find_assoc.return_value = [1,2,3]
replay = Replay()
replay.process_id = '1'
self.mock_rr_read.return_value = replay
#execution
self.data_retriever_service.cancel_replay('replay_id')
#assertions
self.assertEquals(self.mock_rr_delete_assoc.call_count,3)
self.mock_rr_delete.assert_called_with('replay_id')
self.mock_pd_cancel.assert_called_with('1')
@attr('INT', group='dm')
class DataRetrieverServiceIntTest(IonIntegrationTestCase):
def setUp(self):
super(DataRetrieverServiceIntTest,self).setUp()
self._start_container()
self.container.start_rel_from_url('res/deploy/r2dm.yml')
self.couch = self.container.datastore_manager.get_datastore('test_data_retriever', profile=DataStore.DS_PROFILE.EXAMPLES)
self.datastore_name = 'test_data_retriever'
self.dr_cli = DataRetrieverServiceClient(node=self.container.node)
self.dsm_cli = DatasetManagementServiceClient(node=self.container.node)
self.rr_cli = ResourceRegistryServiceClient(node=self.container.node)
self.ps_cli = PubsubManagementServiceClient(node=self.container.node)
def tearDown(self):
super(DataRetrieverServiceIntTest,self).tearDown()
@unittest.skipIf(os.getenv('CEI_LAUNCH_TEST', False), 'Skip test while in CEI LAUNCH mode')
def test_define_replay(self):
dataset_id = self.dsm_cli.create_dataset(
stream_id='12345',
datastore_name=self.datastore_name,
view_name='posts/posts_join_comments',
name='test define replay'
)
replay_id, stream_id = self.dr_cli.define_replay(dataset_id=dataset_id)
replay = self.rr_cli.read(replay_id)
# Assert that the process was created
self.assertTrue(self.container.proc_manager.procs[replay.process_id])
self.dr_cli.cancel_replay(replay_id)
@unittest.skipIf(os.getenv('CEI_LAUNCH_TEST', False), 'Skip test while in CEI LAUNCH mode')
def test_cancel_replay(self):
dataset_id = self.dsm_cli.create_dataset(
stream_id='12345',
datastore_name=self.datastore_name,
view_name='posts/posts_join_comments',
name='test define replay'
)
replay_id, stream_id = self.dr_cli.define_replay(dataset_id=dataset_id)
replay = self.rr_cli.read(replay_id)
# Assert that the process was created
self.assertTrue(self.container.proc_manager.procs[replay.process_id])
self.dr_cli.cancel_replay(replay_id)
# assert that the process is no more
self.assertFalse(replay.process_id in self.container.proc_manager.procs)
# assert that the resource no longer exists
with self.assertRaises(NotFound):
self.rr_cli.read(replay_id)
@unittest.skipIf(os.getenv('CEI_LAUNCH_TEST', False), 'Skip test while in CEI LAUNCH mode')
def test_start_replay(self):
post = BlogPost(title='test blog post', post_id='12345', author=BlogAuthor(name='<NAME>'), content='this is a blog post',
updated=time.strftime("%Y-%m-%dT%H:%M%S-05"))
dataset_id = self.dsm_cli.create_dataset(
stream_id='12345',
datastore_name=self.datastore_name,
view_name='posts/posts_join_comments',
name='blog posts test'
)
self.couch.create(post)
replay_id, stream_id = self.dr_cli.define_replay(dataset_id)
replay = self.rr_cli.read(replay_id)
# assert that the process was created
self.assertTrue(self.container.proc_manager.procs[replay.process_id])
# pattern from Tim G
ar = gevent.event.AsyncResult()
def consume(message, headers):
ar.set(message)
stream_subscriber = StreamSubscriberRegistrar(process=self.container, node=self.container.node)
subscriber = stream_subscriber.create_subscriber(exchange_name='test_queue', callback=consume)
subscriber.start()
query = StreamQuery(stream_ids=[stream_id])
subscription_id = self.ps_cli.create_subscription(query=query,exchange_name='test_queue')
self.ps_cli.activate_subscription(subscription_id)
self.dr_cli.start_replay(replay_id)
self.assertEqual(ar.get(timeout=10).post_id,post.post_id)
subscriber.stop()
@unittest.skipIf(os.getenv('CEI_LAUNCH_TEST', False), 'Skip test while in CEI LAUNCH mode')
def test_chop_chop(self):
# Override couch
self.couch = self.container.datastore_manager.get_datastore(
ds_name='chopping_block',
profile=DataStore.DS_PROFILE.SCIDATA
)
self.datastore_name = 'chopping_block'
granule = ctd_stream_packet(
stream_id='this_is_only_a_test',
time='12345', #Same combo on my luggage
create_hdf=False
)
self.couch.create(granule)
log.debug("Granule: %s", granule)
dataset_id = self.dsm_cli.create_dataset(
stream_id='this_is_only_a_test',
datastore_name=self.datastore_name,
view_name='datasets/dataset_by_id',
name='sci_data_granule_chop'
)
replay_id, stream_id = self.dr_cli.define_replay(
dataset_id=dataset_id,
delivery_format={'chop':True}
)
replay = self.rr_cli.read(replay_id)
self.assertTrue(self.container.proc_manager.procs[replay.process_id])
async_result = gevent.event.AsyncResult()
def consume(message, headers):
async_result.set(message)
stream_subscriber = StreamSubscriberRegistrar(process=self.container, node=self.container.node)
subscriber = stream_subscriber.create_subscriber(exchange_name = 'chopping_block', callback=consume)
subscriber.start()
query = StreamQuery(stream_ids=[stream_id])
subscription_id = self.ps_cli.create_subscription(query=query, exchange_name='chopping_block')
self.ps_cli.activate_subscription(subscription_id=subscription_id)
self.dr_cli.start_replay(replay_id)
for fields in xrange(4):
self.assertTrue(async_result.get(timeout=10))
subscriber.stop()
self.dr_cli.cancel_replay(replay_id=replay_id)<file_sep>/ion/services/mi/drivers/uw_bars/test/test_bars_client.py
#!/usr/bin/env python
__author__ = "<NAME>"
__license__ = 'Apache 2.0'
from ion.services.mi.drivers.uw_bars.bars_client import BarsClient
import time
from ion.services.mi.drivers.uw_bars.test import BarsTestCase
from nose.plugins.attrib import attr
import unittest
import os
# explicit run_it because of threading + gevent-monkey-patching issues
@unittest.skipIf(os.getenv('run_it') is None, 'define run_it to run this.')
@attr('UNIT', group='mi')
class BarsClientTest(BarsTestCase):
def setUp(self):
super(BarsClientTest, self).setUp()
host = self.device_address
port = self.device_port
outfile = file('test_bars_client.txt', 'w')
self.bars_client = BarsClient(host, port, outfile)
self.bars_client.connect()
def tearDown(self):
super(BarsClientTest, self).tearDown()
self.bars_client.end()
def test_simple(self):
bars_client = self.bars_client
print ":: is instrument collecting data?"
if bars_client.is_collecting_data():
print ":: Instrument is collecting data."
else:
print ":: Instrument in not in collecting data mode."
return
print ":: break data streaming to enter main menu"
bars_client.enter_main_menu()
print ":: select 6 to get system info"
bars_client.send('6')
bars_client.expect_generic_prompt()
print ":: send enter to return to main menu"
bars_client.send_enter()
bars_client.expect_generic_prompt()
print ":: resume data streaming"
bars_client.send('1')
print ":: sleeping for 3 secs to receive some data"
time.sleep(3)
<file_sep>/ion/services/cei/process_dispatcher_service.py
#!/usr/bin/env python
__author__ = '<NAME>, <NAME>'
__license__ = 'Apache 2.0'
import uuid
from pyon.public import log, PRED
from pyon.core.exception import NotFound, BadRequest
from interface.services.cei.iprocess_dispatcher_service import BaseProcessDispatcherService
class ProcessDispatcherService(BaseProcessDispatcherService):
# Implementation notes:
#
# Through Elaboration, the Process Dispatcher and other CEI services
# do not run as pyon services. Instead they run as standalone processes
# and communicate using simple AMQP messaging. However the Process
# Dispatcher needs to be called by the Transform Management Service via
# pyon messaging. To facilitate, this service acts as a bridge to the
# "real" CEI process dispatcher.
#
# Because the real process dispatcher will only be present in a CEI
# launch environment, this bridge service operates in two modes,
# detected based on a config value.
#
# 1. When a "process_dispatcher_bridge" config section is present, this
# service acts as a bridge to the real PD. The real PD must be running
# and some additional dependencies must be available.
#
# 2. Otherwise, processes are started directly in the local container.
# This mode is meant to support the developer and integration use of
# r2deploy.yml and other single-container test deployments.
#
# Note that this is a relatively short-term situation. The PD will soon
# natively run in the container and these tricks will be unnecessary.
def on_init(self):
#am I crazy or does self.CFG.get() not work?
try:
pd_conf = self.CFG.process_dispatcher_bridge
except AttributeError:
pd_conf = None
if pd_conf:
print pd_conf
log.debug("Using Process Dispatcher Bridge backend -- requires running CEI services.")
self.backend = PDBridgeBackend(pd_conf)
else:
log.debug("Using Process Dispatcher Local backend -- spawns processes in local container")
self.backend = PDLocalBackend(self.container)
def on_start(self):
self.backend.initialize()
def create_process_definition(self, process_definition=None):
"""Creates a Process Definition based on given object.
@param process_definition ProcessDefinition
@retval process_definition_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
pd_id, version = self.clients.resource_registry.create(process_definition)
return pd_id
def update_process_definition(self, process_definition=None):
"""Updates a Process Definition based on given object.
@param process_definition ProcessDefinition
@throws BadRequest if object does not have _id or _rev attribute
@throws NotFound object with specified id does not exist
@throws Conflict object not based on latest persisted object version
"""
self.clients.resource_registry.update(process_definition)
def read_process_definition(self, process_definition_id=''):
"""Returns a Process Definition as object.
@param process_definition_id str
@retval process_definition ProcessDefinition
@throws NotFound object with specified id does not exist
"""
pdef = self.clients.resource_registry.read(process_definition_id)
return pdef
def delete_process_definition(self, process_definition_id=''):
"""Deletes/retires a Process Definition.
@param process_definition_id str
@throws NotFound object with specified id does not exist
"""
self.clients.resource_registry.delete(process_definition_id)
def find_process_definitions(self, filters=None):
"""Finds Process Definitions matching filter and returns a list of objects.
@param filters ResourceFilter
@retval process_definition_list []
"""
pass
def associate_execution_engine(self, process_definition_id='', execution_engine_definition_id=''):
"""Declare that the given process definition is compatible with the given execution engine.
@param process_definition_id str
@param execution_engine_definition_id str
@throws NotFound object with specified id does not exist
"""
self.clients.resource_registry.create_association(process_definition_id,
PRED.supportsExecutionEngine,
execution_engine_definition_id)
def dissociate_execution_engine(self, process_definition_id='', execution_engine_definition_id=''):
"""Remove the association of the process definition with an execution engine.
@param process_definition_id str
@param execution_engine_definition_id str
@throws NotFound object with specified id does not exist
"""
assoc = self.clients.resource_registry.get_association(process_definition_id,
PRED.supportsExecutionEngine,
execution_engine_definition_id)
self.clients.resource_registry.delete_association(assoc)
def schedule_process(self, process_definition_id='', schedule=None, configuration={}):
"""Schedule a Process Definition for execution as process on an Execution Engine.
@param process_definition_id str
@param schedule ProcessSchedule
@retval process_id str
@throws BadRequest if object passed has _id or _rev attribute
@throws NotFound object with specified id does not exist
"""
if not process_definition_id:
raise NotFound('No process definition was provided')
process_definition = self.clients.resource_registry.read(process_definition_id)
# early validation before we pass definition through to backend
try:
module = process_definition.executable['module']
cls = process_definition.executable['class']
except KeyError,e:
raise BadRequest("Process definition incomplete. missing: %s", e)
if configuration is None:
configuration = {}
# try to get a unique but still descriptive name
name = str(process_definition.name or "process") + uuid.uuid4().hex
return self.backend.spawn(name, process_definition, schedule, configuration)
def cancel_process(self, process_id=''):
"""Cancels the execution of the given process id.
@param process_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not process_id:
raise NotFound('No process was provided')
return self.backend.cancel(process_id)
class PDLocalBackend(object):
"""Scheduling backend to PD that manages processes in the local container
"""
def __init__(self, container):
self.container = container
def initialize(self):
pass
def spawn(self, name, definition, schedule, configuration):
module = definition.executable['module']
cls = definition.executable['class']
# Spawn the process
pid = self.container.spawn_process(name=name, module=module, cls=cls,
config=configuration)
log.debug('PD: Spawned Process (%s)', pid)
return pid
def cancel(self, process_id):
self.container.proc_manager.terminate_process(process_id)
log.debug('PD: Terminated Process (%s)', process_id)
return True
class PDBridgeBackend(object):
"""Scheduling backend to PD that bridges to external CEI Process Dispatcher
"""
def __init__(self, conf):
self.dashi = None
# grab config parameters used to connect to backend Process Dispatcher
try:
self.uri = conf.uri
self.topic = conf.topic
self.exchange = conf.exchange
except AttributeError,e:
log.warn("Needed Process Dispatcher config not found: %s", e)
raise
def initialize(self):
self.dashi = self._init_dashi()
def _init_dashi(self):
# we are avoiding directly depending on dashi as this bridging approach
# is short term and only used from CEI launches. And we have enough
# deps. Where needed we install dashi specially via a separate
# buildout config.
try:
import dashi
except ImportError:
log.warn("Attempted to use Process Dispatcher bridge mode but the "+
"dashi library dependency is not available.")
raise
return dashi.DashiConnection(self.topic, self.uri, self.exchange)
def spawn(self, name, definition, schedule, configuration):
module = definition.executable['module']
cls = definition.executable['class']
# note: not doing anything with schedule mode yet: the backend PD
# service doesn't fully support it.
constraints = None
if schedule:
if schedule.target and schedule.target.constraints:
constraints = schedule.target.constraints
# form a pyon process spec
# warning: this spec will change in the near future.
config = configuration or {}
app = dict(name=name, version="0,1", processapp=(name, module, cls),
config=config)
rel = dict(type="release", name=name, version="0.1", apps=[app])
spec = dict(run_type="pyon_single", parameters=dict(rel=rel))
proc = self.dashi.call(self.topic, "dispatch_process",
upid=name, spec=spec, subscribers=None, constraints=constraints)
log.debug("Dashi Process Dispatcher returned process: %s", proc)
# name == upid == process_id
return name
def cancel(self, process_id):
if not process_id:
raise ValueError("invalid process id")
proc = self.dashi.call(self.topic, "terminate_process", upid=process_id)
log.debug("Dashi Process Dispatcher terminating process: %s", proc)
return True
<file_sep>/ion/services/mi/instrument_driver.py
#!/usr/bin/env python
"""
@package ion.services.mi.instrument_driver Instrument driver structures
@file ion/services/mi/instrument_driver.py
@author <NAME>
@author <NAME>
@brief Instrument driver classes that provide structure towards interaction
with individual instruments in the system.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from ion.services.mi.common import BaseEnum
from ion.services.mi.exceptions import InstrumentConnectionException
from ion.services.mi.common import DEFAULT_TIMEOUT
class DriverChannel(BaseEnum):
"""Common channels for all sensors. Driver subclasses contain a subset."""
INSTRUMENT = 'CHANNEL_INSTRUMENT'
CTD = 'CHANNEL_CTD'
ALL = 'CHANNEL_ALL'
class DriverCommand(BaseEnum):
"""Common driver commands
Commands and events should have unique strings that either indicate
something or can be used in some other rational fashion."""
ACQUIRE_SAMPLE = 'DRIVER_CMD_ACQUIRE_SAMPLE'
START_AUTO_SAMPLING = 'DRIVER_CMD_START_AUTO_SAMPLING'
STOP_AUTO_SAMPLING = 'DRIVER_CMD_STOP_AUTO_SAMPLING'
TEST = 'DRIVER_CMD_TEST'
CALIBRATE = 'DRIVER_CMD_CALIBRATE'
RESET = 'DRIVER_CMD_RESET'
GET = 'DRIVER_CMD_GET'
SET = 'DRIVER_CMD_SET'
GET_STATUS = 'DRIVER_CMD_GET_STATUS'
GET_METADATA = 'DRIVER_CMD_GET_METADATA'
UPDATE_PARAMS = 'DRIVER_CMD_UPDATE_PARAMS'
TEST_ERRORS = 'DRIVER_CMD_TEST_ERRORS'
class DriverState(BaseEnum):
"""Common driver state enum"""
UNCONFIGURED = 'DRIVER_STATE_UNCONFIGURED'
DISCONNECTED = 'DRIVER_STATE_DISCONNECTED'
CONNECTING = 'DRIVER_STATE_CONNECTING'
DISCONNECTING = 'DRIVER_STATE_DISCONNECTING'
CONNECTED = 'DRIVER_STATE_CONNECTED'
ACQUIRE_SAMPLE = 'DRIVER_STATE_ACQUIRE_SAMPLE'
UPDATE_PARAMS = 'DRIVER_STATE_UPDATE_PARAMS'
SET = 'DRIVER_STATE_SET'
AUTOSAMPLE = 'DRIVER_STATE_AUTOSAMPLE'
TEST = 'DRIVER_STATE_TEST'
CALIBRATE = 'DRIVER_STATE_CALIBRATE'
DETACHED = 'DRIVER_STATE_DETACHED'
COMMAND = 'DRIVER_STATE_COMMAND'
class DriverEvent(BaseEnum):
"""Common driver event enum
Commands and events should have unique strings that either indicate
something or can be used in some other rational fashion."""
CONFIGURE = 'DRIVER_EVENT_CONFIGURE'
INITIALIZE = 'DRIVER_EVENT_INITIALIZE'
CONNECT = 'DRIVER_EVENT_CONNECT'
CONNECTION_COMPLETE = 'DRIVER_EVENT_CONNECTION_COMPLETE'
CONNECTION_FAILED = 'DRIVER_EVENT_CONNECTION_FAILED'
CONNECTION_LOST = 'DRIVER_CONNECTION_LOST'
DISCONNECT = 'DRIVER_EVENT_DISCONNECT'
DISCONNECT_COMPLETE = 'DRIVER_EVENT_DISCONNECT_COMPLETE'
DISCONNECT_FAILED = 'DRIVER_EVENT_DISCONNECT_FAILED'
PROMPTED = 'DRIVER_EVENT_PROMPTED'
DATA_RECEIVED = 'DRIVER_EVENT_DATA_RECEIVED'
COMMAND_RECEIVED = 'DRIVER_EVENT_COMMAND_RECEIVED'
RESPONSE_TIMEOUT = 'DRIVER_EVENT_RESPONSE_TIMEOUT'
SET = 'DRIVER_EVENT_SET'
GET = 'DRIVER_EVENT_GET'
EXECUTE = 'DRIVER_EVENT_EXECUTE'
ACQUIRE_SAMPLE = 'DRIVER_EVENT_ACQUIRE_SAMPLE'
START_AUTOSAMPLE = 'DRIVER_EVENT_START_AUTOSAMPLE'
STOP_AUTOSAMPLE = 'DRIVER_EVENT_STOP_AUTOSAMPLE'
TEST = 'DRIVER_EVENT_TEST'
STOP_TEST = 'DRIVER_EVENT_STOP_TEST'
CALIBRATE = 'DRIVER_EVENT_CALIBRATE'
RESET = 'DRIVER_EVENT_RESET'
ENTER = 'DRIVER_EVENT_ENTER'
EXIT = 'DRIVER_EVENT_EXIT'
ATTACH = 'DRIVER_EVENT_ATTACH'
DETACH = 'DRIVER_EVENT_DETACH'
UPDATE_PARAMS = 'DRIVER_EVENT_UPDATE_PARAMS'
class DriverStatus(BaseEnum):
"""Common driver status enum"""
DRIVER_VERSION = 'DRIVER_STATUS_DRIVER_VERSION'
DRIVER_STATE = 'DRIVER_STATUS_DRIVER_STATE'
OBSERVATORY_STATE = 'DRIVER_STATUS_OBSERVATORY_STATE'
DRIVER_ALARMS = 'DRIVER_STATUS_DRIVER_ALARMS'
ALL = 'DRIVER_STATUS_ALL'
class DriverParameter(BaseEnum):
"""Common driver parameter enum"""
ALL = 'DRIVER_PARAMETER_ALL'
class ObservatoryState(BaseEnum):
"""The status of a device in observatory mode"""
NONE = 'OBSERVATORY_STATUS_NONE'
STANDBY = 'OBSERVATORY_STATUS_STANDBY'
STREAMING = 'OBSERVATORY_STATUS_STREAMING'
TESTING = 'OBSERVATORY_STATUS_TESTING'
CALIBRATING = 'OBSERVATORY_STATUS_CALIBRATING'
UPDATING = 'OBSERVATORY_STATUS_UPDATING'
ACQUIRING = 'OBSERVATORY_STATUS_ACQUIRING'
UNKNOWN = 'OBSERVATORY_STATUS_UNKNOWN'
"""
TODO:
Do we want timeouts in the driver interface. timeout=DEFAULT_TIMEOUT.
How would we provide such behavior?
"""
class InstrumentDriver(object):
"""The base instrument driver class
This is intended to be extended where necessary to provide a coherent
driver for interfacing between the instrument and the instrument agent.
Think of this class as encapsulating the session layer of the instrument
interaction.
@see https://confluence.oceanobservatories.org/display/syseng/CIAD+SA+SV+Instrument+Driver+Interface
"""
def __init__(self, evt_callback):
# Instrument channel dict.
# A dictionary of channel-name keys and channel protocol object values.
# We need to change this to protocol or connection name, rather than channel.
self.channels = {}
self.send_event = evt_callback
# Below are old members with comments from EH.
#
# Protocol will create and own the connection it fronts.
#self.instrument_connection = None
#"""An object for manipulating connect and disconnect to an instrument"""
# This is the self.channels member above. Change name. A dict of protocols.
#self.instrument_protocol = None
#"""The instrument-specific protocol object"""
# This is supplied by the driver process that contains and creates the driver.
#self.instrument_comms_method = None
#"""The communications method formatting object"""
# Probably an enum class with execute commands that are possible.
#self.instrument_commands = None
#"""The instrument-specific command list"""
# Ditch this.
#self.instrument_metadata_parameters = None
#"""The instrument-specific metadata parameter list"""
# To be added. A dictionary or class that knows how to match, parse and format all of its params.
#self.instrument_parameters = None
#"""The instrument-specific parameter list"""
# TBD.
#self.instrument_channels = None
#"""The instrument-specific channel list"""
# Why bother, make errors draw from the common list.
#self.instrument_errors = None
#"""The instrument-specific error list"""
# This should return the instrument commands enum values
#self.instrument_capabilities = None
#"""The instrument-specific capabilities list"""
# TBD.
#self.instrument_status = None
#"""The instrument-specific status list"""
# Do we need this also? Just use simple harmonizing logic
# at driver level if there are multiple connections. If one connection,
# one state machine.
# Setup the state machine
"""
self.driver_fsm = FSM(DriverState.UNCONFIGURED)
self.driver_fsm.add_transition(DriverEvent.CONFIGURE,
DriverState.UNCONFIGURED,
action=self._handle_configure,
next_state=DriverState.DISCONNECTED)
self.driver_fsm.add_transition(DriverEvent.INITIALIZE,
DriverState.DISCONNECTED,
action=self._handle_initialize,
next_state=DriverState.UNCONFIGURED)
self.driver_fsm.add_transition(DriverEvent.DISCONNECT_FAILED,
DriverState.DISCONNECTING,
action=self._handle_disconnect_failure,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.DISCONNECT_COMPLETE,
DriverState.DISCONNECTING,
action=self._handle_disconnect_success,
next_state=DriverState.DISCONNECTED)
self.driver_fsm.add_transition(DriverEvent.DISCONNECT,
DriverState.CONNECTED,
action=self._handle_disconnect,
next_state=DriverState.DISCONNECTING)
self.driver_fsm.add_transition(DriverEvent.CONNECT,
DriverState.DISCONNECTED,
action=self._handle_connect,
next_state=DriverState.CONNECTING)
self.driver_fsm.add_transition(DriverEvent.CONNECTION_COMPLETE,
DriverState.CONNECTING,
action=self._handle_connect_success,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.CONNECTION_FAILED,
DriverState.CONNECTING,
action=self._handle_connect_failed,
next_state=DriverState.DISCONNECTED)
self.driver_fsm.add_transition(DriverEvent.START_AUTOSAMPLE,
DriverState.CONNECTED,
action=self._handle_start_autosample,
next_state=DriverState.AUTOSAMPLE)
self.driver_fsm.add_transition(DriverEvent.STOP_AUTOSAMPLE,
DriverState.AUTOSAMPLE,
action=self._handle_stop_autosample,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.CONNECTION_LOST,
DriverState.AUTOSAMPLE,
action=self._handle_connection_lost,
next_state=DriverState.DISCONNECTED)
self.driver_fsm.add_transition(DriverEvent.CONNECTION_LOST,
DriverState.CONNECTED,
action=self._handle_connection_lost,
next_state=DriverState.DISCONNECTED)
self.driver_fsm.add_transition(DriverEvent.DATA_RECEIVED,
DriverState.CONNECTED,
action=self._handle_data_received,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.DATA_RECEIVED,
DriverState.AUTOSAMPLE,
action=self._handle_data_received,
next_state=DriverState.AUTOSAMPLE)
self.driver_fsm.add_transition(DriverEvent.GET,
DriverState.CONNECTED,
action=self._handle_get,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.SET,
DriverState.CONNECTED,
action=self._handle_set,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.ACQUIRE_SAMPLE,
DriverState.CONNECTED,
action=self._handle_acquire_sample,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.TEST,
DriverState.CONNECTED,
action=self._handle_test,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition(DriverEvent.CALIBRATE,
DriverState.CONNECTED,
action=self._handle_calibrate,
next_state=DriverState.CONNECTED)
self.driver_fsm.add_transition_catch(DriverEvent.RESET,
action=self._handle_reset,
next_state=DriverState.UNCONFIGURED)
"""
########################################################################
# Channel connection interface.
########################################################################
def initialize(self, channels, *args, **kwargs):
"""
Return a device channel to an unconnected, unconfigured state.
@param channels List of channel names to initialize.
@param timeout Number of seconds before this operation times out
"""
pass
def configure(self, configs, *args, **kwargs):
"""
Configure the driver for communications with an instrument channel.
@param config A dict containing channel name keys, with
dict values containing the comms configuration for the named channel.
@param timeout Number of seconds before this operation times out
"""
pass
def connect(self, channels, *args, **kwargs):
"""
Establish communications with a device channel.
@param channels List of channel names to connect.
@param timeout Number of seconds before this operation times out
"""
pass
def disconnect(self, channels, *args, **kwargs):
"""
Disconnect communications with a device channel.
@param channels List of channel names to disconnect.
@param timeout Number of seconds before this operation times out
"""
pass
def detach(self, channels, *args, **kwargs):
"""
Disconnect communications with a device channel.
@param channels List of channel names to disconnect.
@param timeout Number of seconds before this operation times out
"""
pass
########################################################################
# Channel command interface.
########################################################################
def get(self, params, *args, **kwargs):
"""
@param timeout Number of seconds before this operation times out
"""
pass
def set(self, params, *args, **kwargs):
"""
@param timeout Number of seconds before this operation times out
"""
pass
def execute_acquire_sample(self, channels, *args, **kwargs):
"""
"""
pass
def execute_start_autosample(self, channels, *args, **kwargs):
"""
"""
pass
def execute_stop_autosample(self, channels, *args, **kwargs):
"""
"""
pass
def execute_test(self, channels, *args, **kwargs):
"""
"""
pass
def execute_direct(self, channels, *args, **kwargs):
"""
"""
pass
################################
# Announcement callback from protocol
################################
def protocol_callback(self, event):
"""The callback method that the protocol calls when there is some sort
of event worth notifying the driver about.
@param event The event object from the event service
@todo Make event a real event object of some sort instead of the hack
tuple of (DriverAnnouncement enum, any error code, message)
"""
########################################################################
# TBD.
########################################################################
def get_capabilities(self, channels, *args, **kwargs):
"""
@param timeout Number of seconds before this operation times out
"""
pass
def get_channels(self):
"""
"""
pass
def get_active_channels(self):
"""
"""
pass
def get_current_state(self, channels):
"""
"""
pass
#######################
# State change handlers
#######################
#def _handle_configure(self):
# """State change handler"""
#
#def _handle_initialize(self):
# """State change handler"""
#
#def _handle_disconnect_failure(self):
# """State change handler"""
#
#def _handle_disconnect_success(self):
# """State change handler"""
#
#def _handle_disconnect(self):
# """State change handler"""
#
#def _handle_connect(self):
# """State change handler"""
#
#def _handle_connect_success(self):
# """State change handler"""
#
#def _handle_connect_failed(self):
# """State change handler"""
#
#def _handle_start_autosample(self):
# """State change handler"""
#
#def _handle_stop_autosample(self):
# """State change handler"""
#
#def _handle_connection_lost(self):
# """State change handler"""
#
#def _handle_reset(self):
# """State change handler"""
#
#def _handle_handle_data_received(self):
# """State change handler"""
#
#def _handle_handle_get(self):
# """State change handler"""
#
#def _handle_handle_set(self):
# """State change handler"""
#
#def _handle_handle_acquire_sample(self):
# """State change handler"""
#
#def _handle_handle_test(self):
# """State change handler"""
#
#def _handle_handle_calibrate(self):
# """State change handler"""
<file_sep>/ion/services/sa/preload/preload_csv.py
import os
import sys
import csv
from pyon.public import RT, PRED #, LCS
from pyon.core.exception import BadRequest #, NotFound
import requests, json
#from functools import wraps
class PreloadCSV(object):
def __init__(self, hostname, port):
"""
need hostname and port of service gateway
"""
self.host = hostname
self.port = port
#cache 2 dicts
self.lookup_svc = self._get_svc_by_resource()
self.lookup_pyname = self._get_python_by_yaml()
# actual action function to call
def preload(self, csv_files):
associations_file = None
resource_ids = {}
for c in csv_files:
b = os.path.basename(c).split(".")[0]
#sys.stderr.write("%s\n" % b)
with open(c, "rb") as csvfile:
reader = self._get_csv_reader(csvfile)
#determine type of resource
if "associations" == b.lower():
#save for later
associations_file = c
else:
#enter now and save ids
resource_ids[b] = self._preload_resources(b, reader)
#now that all resources are in, do the associations
if associations_file:
with open(associations_file, "rb") as csvfile:
associations_reader = self._get_csv_reader(csvfile)
self._preload_associations(resource_ids, associations_reader)
def _get_csv_reader(self, csvfile):
#determine type of csv
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
return csv.DictReader(csvfile, dialect=dialect)
# get the service responsible for a given resource
def _get_svc_by_resource(self):
return {
RT.InstrumentAgent: "instrument_management",
RT.InstrumentAgentInstance: "instrument_management",
RT.InstrumentModel: "instrument_management",
RT.InstrumentDevice: "instrument_management",
RT.PlatformAgent: "instrument_management",
RT.PlatformAgentInstance: "instrument_management",
RT.PlatformModel: "instrument_management",
RT.PlatformDevice: "instrument_management",
RT.SensorModel: "instrument_management",
RT.SensorDevice: "instrument_management",
RT.MarineFacility: "marine_facility_management",
RT.Site: "marine_facility_management",
RT.LogicalPlatform: "marine_facility_management",
RT.LogicalInstrument: "marine_facility_management",
RT.DataProduct: "data_product_management",
RT.DataProducer: "data_acquisition_management",
}
# get the pythonic (some_widget) name of a yaml (SomeWidget) name
def _get_python_by_yaml(self):
return {
RT.InstrumentAgent: "instrument_agent",
RT.InstrumentAgentInstance: "instrument_agent_instance",
RT.InstrumentModel: "instrument_model",
RT.InstrumentDevice: "instrument_device",
RT.PlatformAgent: "platform_agent",
RT.PlatformAgentInstance: "platform_agent_instance",
RT.PlatformModel: "platform_model",
RT.PlatformDevice: "platform_device",
RT.SensorModel: "sensor_model",
RT.SensorDevice: "sensor_device",
RT.MarineFacility: "marine_facility",
RT.Site: "site",
RT.LogicalPlatform: "logical_platform",
RT.LogicalInstrument: "logical_instrument",
RT.DataProduct: "data_product",
RT.DataProducer: "data_producer",
}
# generate the service call for a given association operaton
# like assign_instrument_model_to_instrument_device
def call_for_association(self, subj_type, pred, obj_type):
#TODO: any nonstandard assignment methods get detected here
#if ("Site", "hasChildSite", "Site") == (subj_type, pred, obj_type):
# return "assign.... etc
return "assign_%s_to_%s" % (self.lookup_pyname[obj_type], self.lookup_pyname[subj_type])
# actually execute a service call with the given params
def _do_service_call(self, service, method, post_data):
url = "http://%s:%s/ion-service/%s/%s" % (self.host, self.port, service, method)
service_gateway_call = requests.post(
url,
data={'payload': json.dumps(post_data)}
)
if service_gateway_call.status_code != 200:
raise BadRequest("The service gateway returned the following error: %d" % service_gateway_call.status_code)
# debug lines
#sys.stderr.write(str(url) + "\n")
#sys.stderr.write(str(post_data['serviceRequest']) + "\n")
resp = json.loads(service_gateway_call.content)
#sys.stderr.write(str(resp) + "\n")
return resp
def _service_request_template(self):
return {
'serviceRequest': {
'serviceName': '',
'serviceOp': '',
'params': {
#'object': [] # Ex. [BankObject, {'name': '...'}]
}
}
}
# process a csv full of associations. # TODO: NOT TESTED YET
def _preload_associations(self, resource_ids, associations_reader):
for row in associations_reader:
valuesonly = []
for f in associations_reader.fieldnames:
valuesonly.append(row[f])
row = valuesonly
if not 5 <= len(row) < 7:
#5 fields are necessary, if there are 6 we'll ignore it. 7 we assume error
raise BadRequest("Wrong number of fields in associations CSV!")
# 5 fields expected: InstrumentDevice,#1,hasModel,InstrumentModel,#32
#sys.stderr.write("\n\n%s\n\n" % str(row))
subj_type = row[0]
subj_id = row[1]
pred = row[2]
obj_type = row[3]
obj_id = row[4]
#make sure types exist
if not subj_type in resource_ids:
raise BadRequest("Can't associate a '%s' because none were loaded" % subj_type)
if not subj_id in resource_ids[subj_type]:
raise BadRequest("Can't associate a '%s' with ID '%s' because it was never defined" % (subj_type, subj_id))
if not obj_type in resource_ids:
raise BadRequest("Can't associate a '%s' because none were loaded" % obj_type)
if not obj_id in resource_ids[obj_type]:
raise BadRequest("Can't associate a '%s' with ID '%s' because it was never defined" % (obj_type, obj_id))
if not pred in PRED:
raise BadRequest("Unknown association type '%s'" % pred)
# generate the service method that we need
associate_op = self.call_for_association(subj_type, pred, obj_type)
py = self.lookup_pyname
#build payload
post_data = self._service_request_template()
post_data['serviceRequest']['serviceName'] = self.lookup_svc[subj_type]
post_data['serviceRequest']['serviceOp'] = associate_op
post_data['serviceRequest']['params']["%s_id" % py[subj_type]] = resource_ids[subj_type][subj_id]
post_data['serviceRequest']['params']["%s_id" % py[obj_type]] = resource_ids[obj_type][obj_id]
response = self._do_service_call(self.lookup_svc[subj_type],
associate_op,
post_data)
response
def _preload_resources(self, resource_type, reader):
if not resource_type in self.lookup_svc:
raise NotImplementedError("'%s' is not a recognized resource type" % resource_type)
ids = {}
for row in reader:
if not "ID" in row:
raise BadRequest("ID field missing from first column of %s.csv" % resource_type)
#store ID and delete it
friendly_id = row["ID"]
del row["ID"]
#load the rest of the params into a dict
resource_type_params = {}
for key, value in row.iteritems():
resource_type_params[key] = value
# generate the service method we need
resource_py = self.lookup_pyname[resource_type]
create_op = "create_%s" % resource_py
#special syntax for ionobjects: [resource_type, dict]
post_data = self._service_request_template()
post_data['serviceRequest']['serviceName'] = self.lookup_svc[resource_type]
post_data['serviceRequest']['serviceOp'] = create_op
post_data['serviceRequest']['params'][resource_py] = [resource_type, resource_type_params]
# make the call
response = self._do_service_call(self.lookup_svc[resource_type],
create_op,
post_data)
ids[friendly_id] = response['data']['GatewayResponse']
return ids
<file_sep>/ion/services/mi/drivers/uw_bars/test/test_driver.py
#!/usr/bin/env python
__author__ = "<NAME>"
__license__ = 'Apache 2.0'
from ion.services.mi.drivers.uw_bars.test.pyon_test import PyonBarsTestCase
from ion.services.mi.drivers.uw_bars.driver import BarsInstrumentDriver
from ion.services.mi.drivers.uw_bars.common import BarsChannel
from ion.services.mi.drivers.uw_bars.common import BarsParameter
from ion.services.mi.instrument_driver import DriverState
from ion.services.mi.common import InstErrorCode
import time
from nose.plugins.attrib import attr
from unittest import skip
@skip('not yet easy to test driver in isolation')
@attr('UNIT', group='mi')
class DriverTest(PyonBarsTestCase):
def test(self):
"""
BARS driver tests
"""
driver = BarsInstrumentDriver()
self.assertEqual(DriverState.UNCONFIGURED, driver.get_current_state())
# initialize
result = driver.initialize([BarsChannel.INSTRUMENT])
self.assertEqual(DriverState.UNCONFIGURED, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
# configure
configs = {BarsChannel.INSTRUMENT: self.config}
result = driver.configure(configs)
self.assertEqual(DriverState.DISCONNECTED, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
# connect
result = driver.connect([BarsChannel.INSTRUMENT])
print "connect result = %s" % str(result)
self.assertEqual(DriverState.AUTOSAMPLE, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
print "sleeping for a bit to see data streaming"
time.sleep(4)
# get a parameter
cp = (BarsChannel.INSTRUMENT, BarsParameter.TIME_BETWEEN_BURSTS)
result = driver.get([cp])
print "get result = %s" % str(result)
# should be back in AUTOSAMPLE state:
self.assertEqual(DriverState.AUTOSAMPLE, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
print "sleeping a bit more"
time.sleep(4)
# disconnect
print "disconnecting"
result = driver.disconnect([BarsChannel.INSTRUMENT])
self.assertEqual(DriverState.DISCONNECTED, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
<file_sep>/ion/services/sa/process/data_process_management_service.py
#!/usr/bin/env python
"""
@package ion.services.sa.process.test.test_int_data_process_management_service
@author <NAME>
"""
from pyon.util.log import log
import time
from interface.services.sa.idata_process_management_service import BaseDataProcessManagementService
from pyon.public import log, RT, PRED
from pyon.core.bootstrap import IonObject
from pyon.core.exception import BadRequest, NotFound
from interface.objects import ProcessDefinition, StreamQuery
from ion.services.sa.resource_impl.data_process_impl import DataProcessImpl
class DataProcessManagementService(BaseDataProcessManagementService):
def on_init(self):
IonObject("Resource") # suppress pyflakes error
self.override_clients(self.clients)
def override_clients(self, new_clients):
"""
Replaces the service clients with a new set of them... and makes sure they go to the right places
"""
#shortcut names for the import sub-services
if hasattr(self.clients, "resource_registry"):
self.RR = self.clients.resource_registry
if hasattr(self.clients, "transform_management_service"):
self.TMS = self.clients.transform_management_service
#farm everything out to the impls
self.data_process = DataProcessImpl(self.clients)
def create_data_process_definition(self, data_process_definition=None):
result, _ = self.clients.resource_registry.find_resources(RT.DataProcessDefinition, None, data_process_definition.name, True)
if result:
raise BadRequest("A data process definition named '%s' already exists" % data_process_definition.name)
if not data_process_definition.process_source:
raise BadRequest("Data process definition has invalid process source.")
data_process_definition_id, version = self.clients.resource_registry.create(data_process_definition)
return data_process_definition_id
def update_data_process_definition(self, data_process_definition=None):
# Overwrite DataProcessDefinition object
self.clients.resource_registry.update(data_process_definition)
def read_data_process_definition(self, data_process_definition_id=''):
# Read DataProcessDefinition object with _id matching id
log.debug("Reading DataProcessDefinition object id: %s" % data_process_definition_id)
data_proc_def_obj = self.clients.resource_registry.read(data_process_definition_id)
if not data_proc_def_obj:
raise NotFound("DataProcessDefinition %s does not exist" % data_process_definition_id)
return data_proc_def_obj
def delete_data_process_definition(self, data_process_definition_id=''):
data_proc_def_obj = self.clients.resource_registry.read(data_process_definition_id)
if data_proc_def_obj is None:
raise NotFound("DataProcessDefinition %s does not exist" % data_process_definition_id)
# Delete the data process
self.clients.resource_registry.delete(data_process_definition_id)
return
def find_data_process_definitions(self, filters=None):
"""
@param filters: dict of parameters to filter down
the list of possible data proc.
@retval
"""
#todo: add filtering
data_process_def_list , _ = self.clients.resource_registry.find_resources(RT.DataProcessDefinition, None, None, True)
return data_process_def_list
def create_data_process(self,
data_process_definition_id='',
in_data_product_id='',
out_data_product_id=''):
"""
@param data_process_definition_id: Object with definition of the
transform to apply to the input data product
@param in_data_product_id: ID of the input data product
@param out_data_product_id: ID of the output data product
@retval data_process_id: ID of the newly created data process object
"""
#
#
#
#todo: break this method up into: 1. create data process, 2. assign in/out products, 3. activate data proces
#
#
#
inform = "Input Data Product: "+str(in_data_product_id)+\
"Transformed by: "+str(data_process_definition_id)+\
"To create output Product: "+str(out_data_product_id)
log.debug("DataProcessManagementService:create_data_process()\n" +
inform)
# Create and store a new DataProcess with the resource registry
log.debug("DataProcessManagementService:create_data_process - Create and store a new DataProcess with the resource registry")
data_process_def_obj = self.read_data_process_definition(data_process_definition_id)
data_process_name = "process_" + data_process_def_obj.name \
+ " - calculates " + \
str(out_data_product_id) + time.ctime()
self.data_process = IonObject(RT.DataProcess, name=data_process_name)
data_process_id, version = self.clients.resource_registry.create(self.data_process)
log.debug("DataProcessManagementService:create_data_process - Create and store a new DataProcess with the resource registry data_process_id: " + str(data_process_id))
# Register the data process instance as a data producer with DataAcquisitionMgmtSvc
log.debug("DataProcessManagementService:create_data_process - Register the data process instance as a data producer with DataAcquisitionMgmtSvc, then retrieve the id of the OUTPUT stream")
#TODO: should this be outside this method? Called by orchastration?
data_producer_id = self.clients.data_acquisition_management.register_process(data_process_id)
#Assign the output Data Product to this producer resource
#todo: check that the product is not already associated with a producer
#TODO: should this be outside this method? Called by orchastration?
self.clients.data_acquisition_management.assign_data_product(data_process_id, out_data_product_id, True)
# Associate with dataProcess
self.clients.resource_registry.create_association(data_process_definition_id, PRED.hasInstance, data_process_id)
self.clients.resource_registry.create_association(data_process_id, PRED.hasInputProduct, in_data_product_id)
self.clients.resource_registry.create_association(data_process_id, PRED.hasOutputProduct, out_data_product_id)
# Retrieve the id of the OUTPUT stream from the out Data Product
stream_ids, _ = self.clients.resource_registry.find_objects(out_data_product_id, PRED.hasStream, None, True)
if not stream_ids:
raise NotFound("No Stream created for output Data Product " + str(out_data_product_id))
if len(stream_ids) != 1:
raise BadRequest("Data Product should only have ONE stream at this time" + str(out_data_product_id))
out_stream_id = stream_ids[0]
log.debug("DataProcessManagementService:create_data_process -Register the data process instance as a data producer with DataAcquisitionMgmtSvc, then retrieve the id of the OUTPUT stream out_stream_id: " + str(out_stream_id))
#-------------------------------
# Create subscription from in_data_product, which should already be associated with a stream via the Data Producer
#-------------------------------
# # first - get the data producer associated with this IN data product
# log.debug("DataProcessManagementService:create_data_process - get the data producer associated with this IN data product")
# producer_ids, _ = self.clients.resource_registry.find_objects(in_data_product_id, PRED.hasDataProducer, RT.DataProducer, True)
# if not producer_ids:
# raise NotFound("No Data Producer created for this Data Product " + str(in_data_product_id))
# if len(producer_ids) != 1:
# raise BadRequest("Data Product should only have ONE Data Producers at this time" + str(in_data_product_id))
# in_product_producer = producer_ids[0]
# log.debug("DataProcessManagementService:create_data_process - get the data producer associated with this IN data product in_product_producer: " + str(in_product_producer))
# second - get the stream associated with this IN data product
log.debug("DataProcessManagementService:create_data_process - get the stream associated with this IN data product")
stream_ids, _ = self.clients.resource_registry.find_objects(in_data_product_id, PRED.hasStream, RT.Stream, True)
if not stream_ids:
raise NotFound("No Stream created for this IN Data Product " + str(in_data_product_id))
if len(stream_ids) != 1:
raise BadRequest("IN Data Product should only have ONE stream at this time" + str(in_data_product_id))
in_stream_id = stream_ids[0]
log.debug("DataProcessManagementService:create_data_process - get the stream associated with this IN data product in_stream_id" + str(in_stream_id))
# Finally - create a subscription to the input stream
log.debug("DataProcessManagementService:create_data_process - Finally - create a subscription to the input stream")
in_data_product_obj = self.clients.data_product_management.read_data_product(in_data_product_id)
query = StreamQuery(stream_ids=[in_stream_id])
self.input_subscription_id = self.clients.pubsub_management.create_subscription(query=query, exchange_name=in_data_product_obj.name)
log.debug("DataProcessManagementService:create_data_process - Finally - create a subscription to the input stream input_subscription_id" + str(self.input_subscription_id))
# add the subscription id to the resource for clean up later
data_process_obj = self.clients.resource_registry.read(data_process_id)
data_process_obj.input_subscription_id = self.input_subscription_id;
self.clients.resource_registry.update(data_process_obj)
#-------------------------------
# Process Definition
#-------------------------------
# Create the process definition for the basic transform
transform_definition = ProcessDefinition()
transform_definition.executable = { 'module':data_process_def_obj.module, 'class':data_process_def_obj.class_name }
transform_definition_id = self.clients.process_dispatcher.create_process_definition(process_definition=transform_definition)
# Launch the first transform process
log.debug("DataProcessManagementService:create_data_process - Launch the first transform process: ")
log.debug("DataProcessManagementService:create_data_process - input_subscription_id: " + str(self.input_subscription_id) )
log.debug("DataProcessManagementService:create_data_process - out_stream_id: " + str(out_stream_id) )
log.debug("DataProcessManagementService:create_data_process - transform_definition_id: " + str(transform_definition_id) )
log.debug("DataProcessManagementService:create_data_process - data_process_id: " + str(data_process_id) )
transform_id = self.clients.transform_management.create_transform( name='data_process_id', description='data_process_id',
in_subscription_id=self.input_subscription_id,
out_streams={'output':out_stream_id},
process_definition_id=transform_definition_id,
configuration={})
log.debug("DataProcessManagementService:create_data_process - transform_id: " + str(transform_id) )
self.clients.resource_registry.create_association(data_process_id, PRED.hasTransform, transform_id)
log.debug("DataProcessManagementService:create_data_process - Launch the first transform process transform_id" + str(transform_id))
# TODO: Flesh details of transform mgmt svc schedule and bind methods
# self.clients.transform_management_service.schedule_transform(transform_id)
# self.clients.transform_management_service.bind_transform(transform_id)
# TODO: Where should activate take place?
log.debug("DataProcessManagementService:create_data_process - transform_management.activate_transform")
self.clients.transform_management.activate_transform(transform_id)
return data_process_id
def update_data_process(self,):
#todo: What are valid ways to update a data process?.
return
def read_data_process(self, data_process_id=""):
# Read DataProcess object with _id matching id
log.debug("Reading DataProcess object id: %s" % data_process_id)
data_proc_obj = self.clients.resource_registry.read(data_process_id)
if not data_proc_obj:
raise NotFound("DataProcess %s does not exist" % data_process_id)
return data_proc_obj
def delete_data_process(self, data_process_id=""):
# Delete the specified DataProcessDefinition object
data_process_obj = self.clients.resource_registry.read(data_process_id)
if data_process_obj is None:
raise NotFound("Data Process %s does not exist" % data_process_id)
# Deactivates and deletes the input subscription
# todo: create did not activate the subscription, should Transform deactivate?
self.clients.pubsub_management.deactivate_subscription(data_process_obj.input_subscription_id)
self.clients.pubsub_management.delete_subscription(data_process_obj.input_subscription_id)
# Delete the output stream, but not the output product
out_products, _ = self.clients.resource_registry.find_objects(data_process_id, PRED.hasOutputProduct, RT.DataProduct, True)
if len(out_products) < 1:
raise NotFound('The the Data Process %s output product cannot be located.' % str(data_process_id))
for out_product in out_products:
out_streams, _ = self.clients.resource_registry.find_objects(out_product, PRED.hasStream, RT.Stream, True)
for out_stream in out_streams:
self.clients.pubsub_management.delete_stream(out_stream)
# delete the connector as well
associations = self.clients.resource_registry.find_associations(out_product, PRED.hasStream)
for association in associations:
self.clients.resource_registry.delete_association(association)
# Delete the transform
transforms, _ = self.clients.resource_registry.find_objects(data_process_id, PRED.hasTransform, RT.Transform, True)
if len(transforms) < 1:
raise NotFound('There is no Transform linked to this Data Process %s' % str(data_process_id))
for transform in transforms:
self.clients.transform_management.delete_transform(transform)
# delete the transform associations link as well
transforms = self.clients.resource_registry.find_associations(data_process_id, PRED.hasTransform)
for transform in transforms:
self.clients.resource_registry.delete_association(transform)
# Delete the assoc with Data Process Definition
data_process_defs = self.clients.resource_registry.find_associations(None, PRED.hasInstance, data_process_id)
if len(data_process_defs) < 1:
raise NotFound('The the Data Process %s is not linked to a Data Process Definition.' % str(data_process_id))
for data_process_def in data_process_defs:
self.clients.resource_registry.delete_association(data_process_def)
# Delete the data process
self.clients.resource_registry.delete(data_process_id)
return
def find_data_process(self, filters=None):
"""
@param filters: dict of parameters to filter down
the list of possible data proc.
@retval
"""
#todo: add filter processing
data_process_list , _ = self.clients.resource_registry.find_resources(RT.DataProcess, None, None, True)
return data_process_list
def attach_process(self, process=''):
"""
@param process: Should this be the data_process_id?
@retval
"""
# TODO: Determine the proper input param
pass
<file_sep>/ion/services/coi/org_management_service.py
#!/usr/bin/env python
__author__ = '<NAME>, <NAME>'
import datetime
from pyon.public import CFG, IonObject, log, RT, PRED
from interface.services.coi.iorg_management_service import BaseOrgManagementService
from ion.services.coi.policy_management_service import MEMBER_ROLE, MANAGER_ROLE
from pyon.core.exception import Inconsistent, NotFound, BadRequest
from pyon.ion.directory import Directory
from pyon.util.log import log
ROOT_ION_ORG_NAME = 'ION'
now = datetime.datetime.now()
class OrgManagementService(BaseOrgManagementService):
"""
Services to define and administer a facility (synonymous Org, community), to enroll/remove members and to provide
access to the resources of an Org to enrolled or affiliated entities (identities). Contains contract
and commitment repository
"""
def create_org(self, org=None):
"""Persists the provided Org object. The id string returned
is the internal id by which Org will be identified in the data store.
@param org Org
@retval org_id str
@throws BadRequest if object passed has _id or _rev attribute
"""
#Only allow one root ION Org in the system
if org.name == ROOT_ION_ORG_NAME:
res_list,_ = self.clients.resource_registry.find_resources(restype=RT.Org, name=ROOT_ION_ORG_NAME)
if len(res_list) > 0:
raise BadRequest('There can only be one Org named %s' % ROOT_ION_ORG_NAME)
org_id, version = self.clients.resource_registry.create(org)
#Instantiate a Directory for this Org
directory = Directory(orgname=org.name)
#Instantiate initial set of User Roles for this Org
role_obj = IonObject(RT.UserRole, name=MANAGER_ROLE, description='Users assigned to this role are Managers of the Org')
role_id = self.clients.policy_management.create_role(role_obj)
self.add_user_role(org_id, role_id)
role_obj = IonObject(RT.UserRole, name=MEMBER_ROLE, description='Users assigned to this role are members of the Org')
role_id = self.clients.policy_management.create_role(role_obj)
self.add_user_role(org_id, role_id)
return org_id
def update_org(self, org=None):
"""Updates the provided Org object. Throws NotFound exception if
an existing version of Org is not found. Throws Conflict if
the provided Policy object is not based on the latest persisted
version of the object.
@param org Org
@throws BadRequest if object does not have _id or _rev attribute
@throws NotFound object with specified id does not exist
@throws Conflict object not based on latest persisted object version
"""
self.clients.resource_registry.update(org)
def read_org(self, org_id=''):
"""Returns the Org object for the specified policy id.
Throws exception if id does not match any persisted Policy
objects.
@param org_id str
@retval org Org
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
return org
def delete_org(self, org_id=''):
"""Permanently deletes Org object with the specified
id. Throws exception if id does not match any persisted Policy.
@param org_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
self.clients.resource_registry.delete(org_id)
def find_org(self, name=ROOT_ION_ORG_NAME):
"""Finds an Org object with the specified name. Defaults to the
root ION object. Throws a NotFound exception if the object
does not exist.
@param name str
@retval org Org
@throws NotFound Org with name does not exist
"""
res_list,_ = self.clients.resource_registry.find_resources(restype=RT.Org, name=name)
if not res_list:
raise NotFound('The Org with name %s does not exist' % name )
return res_list[0]
def add_user_role(self, org_id='', user_role_id=''):
"""Adds a UserRole to an Org.
Throws exception if either id does not exist.
@param org_id str
@param user_role_id str
@retval success bool
@throws NotFound object with specified name does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
user_role = self.clients.policy_management.read_role(user_role_id)
if not user_role:
raise NotFound("User Role %s does not exist" % user_role_id)
role_list = self.find_org_roles(org_id)
for role in role_list:
if role.name == user_role.name:
raise BadRequest("The User Role '%s' is already associated with this Org" % user_role.name )
aid = self.clients.resource_registry.create_association(org, PRED.hasRole, user_role)
if not aid:
return False
return True
def remove_user_role(self, org_id='', user_role_id='', force_removal=False):
"""Removes a UserRole from an Org. The UserRole will not be removed if there are
users associated with the UserRole unless the force_removal paramater is set to True
Throws exception if either id does not exist.
@param org_id str
@param user_role_id str
@param force_removal bool
@retval success bool
@throws NotFound object with specified name does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not user_role_id:
raise BadRequest("The user_role_id parameter is missing")
user_role = self.clients.policy_management.read_role(user_role_id)
if not user_role:
raise NotFound("User Role %s does not exist" % user_role_id)
try:
aid = self.clients.resource_registry.get_association(org, PRED.hasRole, user_role)
except NotFound, e:
raise NotFound("The association between the specified User Role and Org was not found")
if not force_removal:
alist,_ = self.clients.resource_registry.find_subjects(RT.UserIdentity, PRED.hasRole, user_role)
if len(alist) > 0:
raise BadRequest('This User Role cannot be removed as there are %d users associated to it' % len(alist))
self.clients.resource_registry.delete_association(aid)
return True
def find_org_role_by_name(self, org_id='', name=''):
"""Returns the User Role object for the specified name in the Org.
Throws exception if name does not match any persisted User Role or the Org does not exist.
objects.
@param org_id str
@param name str
@retval user_role UserRole
@throws NotFound object with specified name or if does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not name:
raise BadRequest("The name parameter is missing")
role = self._find_role(org_id, name)
if role is None:
raise NotFound('The %s User Role is not found.' % name)
return role
def _find_role(self, org_id='', name=MEMBER_ROLE):
if not org_id:
raise BadRequest("The org_id parameter is missing")
org_roles = self.find_org_roles(org_id)
for role in org_roles:
if role.name == name:
return role
return None
def find_org_roles(self, org_id=''):
"""Returns a list of roles available in an Org. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param org_id str
@retval user_role_list list
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
role_list,_ = self.clients.resource_registry.find_objects(org, PRED.hasRole, RT.UserRole)
return role_list
def request_enroll(self, org_id='', user_id=''):
"""Requests for an enrollment with an Org which must be accepted or denied as a separate process.
Membership in the ION Org is implied by registration with the system, so a membership
association to the ION Org is not maintained. Throws a NotFound exception if neither id is found.
@param org_id str
@param user_id str
@retval request_id str
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if org.name == ROOT_ION_ORG_NAME:
raise BadRequest("A request to enroll in the root ION Org is not allowed")
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.resource_registry.read(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
req_obj = IonObject(RT.UserRequest,name='Enroll Request',type="Enroll", org_id=org_id,
user_id=user_id, status="Open", description='%s Org Enroll Request at %s' % (user_id, str(now)))
req_id, _ = self.clients.resource_registry.create(req_obj)
req_obj = self.clients.resource_registry.read(req_id)
self.clients.resource_registry.create_association(org, PRED.hasRequest, req_obj)
self.clients.resource_registry.create_association(user, PRED.hasRequest, req_obj)
return req_id
def request_role(self, org_id='', user_id='', user_role_id=''):
"""Requests for an role within an Org which must be accepted or denied as a separate process.
A role of Member is automatically implied with successfull enrollment. Throws a
NotFound exception if neither id is found.
@param org_id str
@param user_id str
@param user_role_id str
@retval request_id str
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not user_role_id:
raise BadRequest("The user_role_id parameter is missing")
user_role = self.clients.policy_management.read_role(user_role_id)
if not user_role:
raise NotFound("User Role %s does not exist" % user_role_id)
if user_role.name == MEMBER_ROLE:
raise BadRequest("The Member User Role is already assigned with an enrollment to an Org")
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.resource_registry.read(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
req_obj = IonObject(RT.UserRequest,name='User Role Request',type="User Role", org_id=org_id,
user_id=user_id, status="Open", description='%s User Role Request at %s' % (user_id, str(now)))
req_id, _ = self.clients.resource_registry.create(req_obj)
req_obj = self.clients.resource_registry.read(req_id)
self.clients.resource_registry.create_association(org, PRED.hasRequest, req_obj)
self.clients.resource_registry.create_association(user, PRED.hasRequest, req_obj)
#If the user is not enrolled with the Org then immediately deny the request
if not self.is_enrolled(org_id, user_id):
self.deny_request(org_id, req_id, "The user id %s is not enrolled in the specified Org %s" % (user_id, org_id))
return req_id
def find_requests(self, org_id=''):
"""Returns a list of open requests for an Org. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param org_id str
@retval requests list
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
request_list,_ = self.clients.resource_registry.find_objects(org, PRED.hasRequest, RT.UserRequest)
return request_list
def approve_request(self, org_id='', request_id=''):
"""Approves a request made to an Org. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param org_id str
@param request_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not request_id:
raise BadRequest("The request_id parameter is missing")
request = self.clients.resource_registry.read(object_id=request_id)
if not request:
raise NotFound("User Request %s does not exist" % request_id)
request.status = "Approved"
self.clients.resource_registry.update(request)
def deny_request(self, org_id='', request_id='', reason=''):
"""Denys a request made to an Org. An optional reason can be recorded with the denial.
Will throw a not NotFound exception if none of the specified ids do not exist.
@param org_id str
@param request_id str
@param reason str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not request_id:
raise BadRequest("The request_id parameter is missing")
request = self.clients.resource_registry.read(object_id=request_id)
if not request:
raise NotFound("User Request %s does not exist" % request_id)
request.status = "Denied"
request.status_description = reason
self.clients.resource_registry.update(request)
def find_user_requests(self, user_id='', org_id=''):
"""Returns a list of requests for a specified User. All requests for all Orgs will be returned
unless an org_id is specified. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param user_id str
@param org_id str
@retval requests list
@throws NotFound object with specified id does not exist
"""
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.policy_management.read_role(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
ret_list = []
if org_id:
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
request_list,_ = self.clients.resource_registry.find_objects(org, PRED.hasRequest, RT.UserRequest)
for req in request_list:
if req.user_id == user_id:
ret_list.append(req)
return ret_list
request_list,_ = self.clients.resource_registry.find_objects(user, PRED.hasRequest, RT.UserRequest)
return request_list
def grant_role(self, org_id='', user_id='', user_role_id='', scope=None):
"""Grants a defined role within an organization to a specific user. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param org_id str
@param user_id str
@param user_role_id str
@param scope RoleScope
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.policy_management.read_role(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
if not user_role_id:
raise BadRequest("The user_role_id parameter is missing")
user_role = self.clients.policy_management.read_role(user_role_id)
if not user_role:
raise NotFound("User Role %s does not exist" % user_role_id)
#First make sure the user is enrolled with the Org
if not self.is_enrolled(org_id, user_id):
raise BadRequest("The user id %s is not enrolled in the specified Org %s" % (user_id, org_id))
return self._add_role_association(user, user_role)
def _add_role_association(self, user, user_role):
aid = self.clients.resource_registry.create_association(user, PRED.hasRole, user_role)
if not aid:
return False
return True
def _delete_role_association(self, user, user_role):
aid = self.clients.resource_registry.get_association(user, PRED.hasRole, user_role)
if not aid:
raise NotFound("The association between the specified User Role and User was not found")
self.clients.resource_registry.delete_association(aid)
return True
def revoke_role(self, org_id='', user_id='', user_role_id=''):
"""Revokes a defined role within an organization to a specific user. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param org_id str
@param user_id str
@param user_role_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.policy_management.read_role(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
if not user_role_id:
raise BadRequest("The user_role_id parameter is missing")
user_role = self.clients.policy_management.read_role(user_role_id)
if not user_role:
raise NotFound("User Role %s does not exist" % user_role_id)
return _delete_role_association(user, user_role)
def find_roles_by_user(self, org_id='', user_id=''):
"""Returns a list of organization roles for a specific user. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param org_id str
@param user_id str
@retval user_role_list []
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.policy_management.read_role(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
#First make sure the user is enrolled with the Org
if not self.is_enrolled(org_id, user_id):
raise BadRequest("The user id %s is not enrolled in the specified Org %s" % (user_id, org_id))
role_list,_ = self.clients.resource_registry.find_objects(user_id, PRED.hasRole, RT.UserRole)
#Because a user is enrolled with an Org then the membership role is implied - so add it to the list
member_role = self._find_role(org_id, MEMBER_ROLE)
if member_role is None:
raise Inconsistent('The %s User Role is not found.' % MEMBER_ROLE)
role_list.append(member_role)
return role_list
def enroll_member(self, org_id='', user_id=''):
"""Enrolls a specified user into the specified Org so that they may find and negotiate to use resources
of the Org. Membership in the ION Org is implied by registration with the system, so a membership
association to the ION Org is not maintained. Throws a NotFound exception if neither id is found.
@param org_id str
@param user_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if org.name == ROOT_ION_ORG_NAME:
raise BadRequest("A request to enroll in the root ION Org is not allowed")
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.resource_registry.read(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
aid = self.clients.resource_registry.create_association(org, PRED.hasMembership, user)
if not aid:
return False
return True
def cancel_member_enrollment(self, org_id='', user_id=''):
"""Cancels the membership of a specified user within the specified Org. Once canceled, the user will no longer
have access to the resource of that Org. Throws a NotFound exception if neither id is found.
@param org_id str
@param user_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if org.name == ROOT_ION_ORG_NAME:
raise BadRequest("A request to cancel enrollment in the root ION Org is not allowed")
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.resource_registry.read(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
#First remove all associations to any roles
role_list = self.find_roles_by_user(org_id, user_id)
for user_role in role_list:
self._delete_role_association(user, user_role)
#Finally remove the association to the Org
aid = self.clients.resource_registry.get_association(org, PRED.hasMembership, user)
if not aid:
raise NotFound("The membership association between the specified user and Org is not found")
self.clients.resource_registry.delete_association(aid)
return True
def is_enrolled(self, org_id='', user_id=''):
"""Returns True if the specified user_id is enrolled in the Org and False if not.
Throws a NotFound exception if neither id is found.
@param org_id str
@param user_id str
@retval is_enrolled bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
#Membership into the Root ION Org is implied as part of registration
if org.name == ROOT_ION_ORG_NAME:
return True
if not user_id:
raise BadRequest("The user_id parameter is missing")
user = self.clients.resource_registry.read(user_id)
if not user:
raise NotFound("User %s does not exist" % user_id)
try:
aid = self.clients.resource_registry.get_association(org, PRED.hasMembership, user)
except NotFound, e:
return False
return True
def find_enrolled_users(self, org_id=''):
"""Returns a list of users enrolled in an Org. Will throw a not NotFound exception
if none of the specified ids do not exist.
@param org_id str
@retval user_list list
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
#Membership into the Root ION Org is implied as part of registration
if org.name == ROOT_ION_ORG_NAME:
user_list,_ = self.clients.resource_registry.find_resources(RT.UserIdentity)
else:
user_list,_ = self.clients.resource_registry.find_objects(org, PRED.hasMembership, RT.UserIdentity)
return user_list
def has_permission(self, org_id='', user_id='', action_id='', resource_id=''):
"""Returns a boolean of the specified user has permission for the specified action on a specified resource. Will
throw a NotFound exception if none of the specified ids do not exist.
@param org_id str
@param user_id str
@param action_id str
@param resource_id str
@retval has_permission bool
@throws NotFound object with specified id does not exist
"""
raise NotImplementedError()
def share_resource(self, org_id='', resource_id=''):
"""Share a specified resource with the specified Org. Once shared, the resource will be added to a directory
of available resources within the Org. Throws a NotFound exception if neither id is found.
@param org_id str
@param resource_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not resource_id:
raise BadRequest("The resource_id parameter is missing")
resource = self.clients.resource_registry.read(resource_id)
if not resource:
raise NotFound("Resource %s does not exist" % resource_id)
aid = self.clients.resource_registry.create_association(org, PRED.hasResource, resource)
if not aid:
return False
return True
def unshare_resource(self, org_id='', resource_id=''):
"""Unshare a specified resource with the specified Org. Once unshared, the resource will be removed from a directory
of available resources within the Org. Throws a NotFound exception if neither id is found.
@param org_id str
@param resource_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org = self.clients.resource_registry.read(org_id)
if not org:
raise NotFound("Org %s does not exist" % org_id)
if not resource_id:
raise BadRequest("The resource_id parameter is missing")
resource = self.clients.resource_registry.read(resource_id)
if not resource:
raise NotFound("Resource %s does not exist" % resource_id)
aid = self.clients.resource_registry.get_association(org, PRED.hasMembership, resource)
if not aid:
raise NotFound("The shared association between the specified resource and Org is not found")
self.clients.resource_registry.delete_association(aid)
return True
def affiliate_org(self, org_id='', affiliate_org_id=''):
"""Creates an association between multiple Orgs as an affiliation
so that they may coordinate activities between them.
Throws a NotFound exception if neither id is found.
@param org_id str
@param affiliate_org_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org1 = self.clients.resource_registry.read(org_id)
if not org1:
raise NotFound("Org %s does not exist" % org_id)
if not affiliate_org_id:
raise BadRequest("The affiliate_org_id parameter is missing")
org2 = self.clients.resource_registry.read(affiliate_org_id)
if not org2:
raise NotFound("Org %s does not exist" % affiliate_org_id)
aid = self.clients.resource_registry.create_association(org1, PRED.affiliatedWith, org2)
if not aid:
return False
return True
def unaffiliate_org(self, org_id='', affiliate_org_id=''):
"""Removes an association between multiple Orgs as an affiliation.
Throws a NotFound exception if neither id is found.
@param org_id str
@param affiliate_org_id str
@retval success bool
@throws NotFound object with specified id does not exist
"""
if not org_id:
raise BadRequest("The org_id parameter is missing")
org1 = self.clients.resource_registry.read(org_id)
if not org1:
raise NotFound("Org %s does not exist" % org_id)
if not affiliate_org_id:
raise BadRequest("The affiliate_org_id parameter is missing")
org2 = self.clients.resource_registry.read(affiliate_org_id)
if not org2:
raise NotFound("Org %s does not exist" % affiliate_org_id)
aid = self.clients.resource_registry.get_association(org1, PRED.affiliatedWith, org2)
if not aid:
raise NotFound("The affiliation association between the specified Orgs is not found")
self.clients.resource_registry.delete_association(aid)
return True
<file_sep>/ion/services/sa/marine_facility/test/test_marine_facility_management_service_meta.py
#from interface.services.icontainer_agent import ContainerAgentClient
#from pyon.net.endpoint import ProcessRPCClient
#from pyon.public import Container, log, IonObject
from pyon.util.int_test import IonIntegrationTestCase
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from ion.services.sa.marine_facility.marine_facility_management_service import MarineFacilityManagementService
#from interface.services.sa.imarine_facility_management_service import IMarineFacilityManagementService, MarineFacilityManagementServiceClient
from pyon.util.context import LocalContextMixin
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.public import RT, PRED, LCS
#from mock import Mock, patch
from pyon.util.unit_test import PyonTestCase
from nose.plugins.attrib import attr
import unittest
from pyon.util.log import log
from ion.services.sa.resource_impl.resource_impl_metatest_integration import ResourceImplMetatestIntegration
from ion.services.sa.resource_impl.logical_instrument_impl import LogicalInstrumentImpl
from ion.services.sa.resource_impl.logical_platform_impl import LogicalPlatformImpl
from ion.services.sa.resource_impl.marine_facility_impl import MarineFacilityImpl
from ion.services.sa.resource_impl.site_impl import SiteImpl
class FakeProcess(LocalContextMixin):
name = ''
@attr('META', group='sa')
class TestMarineFacilityManagementServiceMeta(IonIntegrationTestCase):
def setUp(self):
# Start container
#print 'instantiating container'
self._start_container()
#container = Container()
#print 'starting container'
#container.start()
#print 'started container'
self.container.start_rel_from_url('res/deploy/r2sa.yml')
self.RR = ResourceRegistryServiceClient(node=self.container.node)
print 'started services'
def test_just_the_setup(self):
return
rimi = ResourceImplMetatestIntegration(TestMarineFacilityManagementServiceMeta, MarineFacilityManagementService, log)
rimi.add_resource_impl_inttests(LogicalInstrumentImpl, {})
rimi.add_resource_impl_inttests(LogicalPlatformImpl, {})
rimi.add_resource_impl_inttests(MarineFacilityImpl, {})
rimi.add_resource_impl_inttests(SiteImpl, {})
<file_sep>/ion/services/mi/drivers/uw_bars/test/pyon_test.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from pyon.util.unit_test import PyonTestCase
from ion.services.mi.drivers.uw_bars.test import BarsTestCase
class PyonBarsTestCase(PyonTestCase, BarsTestCase):
"""
PyonTestCase base class for BARS test cases.
"""
<file_sep>/ion/services/mi/instrument_fsm_old.py
#!/usr/bin/env python
"""
@package ion.services.mi.instrument_fsm
@file ion/services/mi/instrument_fsm.py
@author <NAME>
@brief Simple state mahcine for driver and agent classes.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import logging
mi_logger = logging.getLogger('mi_logger')
class InstrumentFSM():
"""
Simple state mahcine for driver and agent classes.
"""
def __init__(self, states, events, state_handlers,enter_event,exit_event):
"""
Initialize states, events, handlers.
"""
self.states = states
self.events = events
self.state_handlers = state_handlers
self.current_state = None
self.previous_state = None
self.enter_event = enter_event
self.exit_event = exit_event
def get_current_state(self):
"""
Return current state.
"""
return self.current_state
def start(self,state,params=None):
"""
Start the state machine. Initializes current state and fires the
EVENT_ENTER event.
"""
#if state not in self.states:
# return False
if not self.states.has(state):
return False
self.current_state = state
self.state_handlers[self.current_state](self.enter_event,params)
return True
def on_event(self,event,params=None):
"""
Handle an event. Call the current state handler passing the event
and paramters.
@param event A string indicating the event that has occurred.
@param params Optional parameters to be sent with the event to the
handler.
@retval Success/fail if the event was handled by the current state.
"""
(success,next_state,result) = self.state_handlers[self.current_state](event,params)
#if next_state in self.states:
if self.states.has(next_state):
self._on_transition(next_state,params)
return (success,result)
def _on_transition(self,next_state,params):
"""
Call the sequence of events to cause a state transition. Called from
on_event if the handler causes a transition.
@param next_state The state to transition to.
@param params Opional parameters passed from on_event
"""
self.state_handlers[self.current_state](self.exit_event,params)
self.previous_state = self.current_state
self.current_state = next_state
self.state_handlers[self.current_state](self.enter_event,params)
<file_sep>/ion/services/sa/resource_impl/platform_device_impl.py
#!/usr/bin/env python
"""
@package ion.services.sa.resource_impl.platform_device_impl
@author <NAME>
"""
#from pyon.core.exception import BadRequest, NotFound
from pyon.public import PRED, RT
from ion.services.sa.resource_impl.resource_impl import ResourceImpl
class PlatformDeviceImpl(ResourceImpl):
"""
@brief resource management for PlatformDevice resources
"""
def _primary_object_name(self):
return RT.PlatformDevice
def _primary_object_label(self):
return "platform_device"
def link_agent_instance(self, platform_device_id='', platform_agent_instance_id=''):
return self._link_resources(platform_device_id, PRED.hasAgentInstance, platform_agent_instance_id)
def unlink_agent_instance(self, platform_device_id='', platform_agent_instance_id=''):
return self._unlink_resources(platform_device_id, PRED.hasAgentInstance, platform_agent_instance_id)
def link_assignment(self, platform_device_id='', logical_platform_id=''):
return self._link_resources(platform_device_id, PRED.hasAssignment, logical_platform_id)
def unlink_assignment(self, platform_device_id='', logical_platform_id=''):
return self._unlink_resources(platform_device_id, PRED.hasAssignment, logical_platform_id)
def link_model(self, platform_device_id='', platform_model_id=''):
return self._link_resources(platform_device_id, PRED.hasModel, platform_model_id)
def unlink_model(self, platform_device_id='', platform_model_id=''):
return self._unlink_resources(platform_device_id, PRED.hasModel, platform_model_id)
def link_instrument(self, platform_device_id='', instrument_device_id=''):
return self._link_resources(platform_device_id, PRED.hasInstrument, instrument_device_id)
def unlink_instrument(self, platform_device_id='', instrument_device_id=''):
return self._unlink_resources(platform_device_id, PRED.hasInstrument, instrument_device_id)
### finds
def find_having_agent_instance(self, platform_agent_instance_id):
return self._find_having(PRED.hasAgentInstance, platform_agent_instance_id)
def find_stemming_agent_instance(self, platform_device_id):
return self._find_stemming(platform_device_id, PRED.hasAgentInstance, RT.PlatformAgentInstance)
def find_having_assignment(self, logical_platform_id):
return self._find_having(PRED.hasAssignment, logical_platform_id)
def find_stemming_assignment(self, platform_device_id):
return self._find_stemming(platform_device_id, PRED.hasAssignment, RT.LogicalPlatform)
def find_having_model(self, platform_model_id):
return self._find_having(PRED.hasModel, platform_model_id)
def find_stemming_model(self, platform_device_id):
return self._find_stemming(platform_device_id, PRED.hasModel, RT.PlatformModel)
def find_having_instrument(self, instrument_device_id):
return self._find_having(PRED.hasInstrument, instrument_device_id)
def find_stemming_instrument(self, platform_device_id):
return self._find_stemming(platform_device_id, PRED.hasInstrument, RT.InstrumentDevice)
<file_sep>/ion/services/sa/marine_facility/test/test_marine_facility_management_service.py
#!/usr/bin/env python
'''
@file ion/services/sa/marine_facility/test/test_marine_facility_management_service.py
@author <NAME>
@author <NAME>
@test ion.services.sa.marine_facility.marine_facility Unit test suite to cover all service code
'''
#from mock import Mock , sentinel, patch
from ion.services.sa.marine_facility.marine_facility_management_service import MarineFacilityManagementService
from nose.plugins.attrib import attr
from pyon.public import PRED #, RT
from pyon.util.log import log
from ion.services.sa.resource_impl.resource_impl_metatest import ResourceImplMetatest
from ion.services.sa.resource_impl.logical_instrument_impl import LogicalInstrumentImpl
from ion.services.sa.resource_impl.logical_platform_impl import LogicalPlatformImpl
from ion.services.sa.resource_impl.marine_facility_impl import MarineFacilityImpl
from ion.services.sa.resource_impl.site_impl import SiteImpl
#from pyon.core.exception import BadRequest, Conflict, Inconsistent, NotFound
#import unittest
from pyon.util.unit_test import PyonTestCase
@attr('UNIT', group='sa')
class TestMarineFacilityManagement(PyonTestCase):
def setUp(self):
self.mock_ionobj = self._create_IonObject_mock('ion.services.sa.marine_facility.marine_facility_management_service.IonObject')
#self.mock_ionobj = IonObject
mock_clients = self._create_service_mock('marine_facility_management')
self.marine_facility_mgmt_service = MarineFacilityManagementService()
self.marine_facility_mgmt_service.clients = mock_clients
# must call this manually
self.marine_facility_mgmt_service.on_init()
rim = ResourceImplMetatest(TestMarineFacilityManagement, MarineFacilityManagementService, log)
rim.add_resource_impl_unittests(LogicalInstrumentImpl, {})
rim.add_resource_impl_unittests(LogicalPlatformImpl, {})
rim.add_resource_impl_unittests(MarineFacilityImpl, {})
rim.add_resource_impl_unittests(SiteImpl, {})
<file_sep>/ion/services/mi/drivers/uw_bars/test/test_driver0.py
#!/usr/bin/env python
__author__ = "<NAME>"
__license__ = 'Apache 2.0'
from ion.services.mi.drivers.uw_bars.driver0 import BarsInstrumentDriver
from ion.services.mi.drivers.uw_bars.common import BarsChannel
from ion.services.mi.drivers.uw_bars.common import BarsParameter
from ion.services.mi.instrument_driver import DriverState
from ion.services.mi.common import InstErrorCode
import time
from ion.services.mi.drivers.uw_bars.test import BarsTestCase
from nose.plugins.attrib import attr
import unittest
import os
# explicit run_it because of threading + gevent-monkey-patching issues
@unittest.skipIf(os.getenv('run_it') is None, 'define run_it to run this.')
@attr('UNIT', group='mi')
class DriverTest(BarsTestCase):
def _connect(self):
self.driver = BarsInstrumentDriver()
driver = self.driver
self.assertEqual(DriverState.UNCONFIGURED, driver.get_current_state())
# initialize
result = driver.initialize([BarsChannel.INSTRUMENT])
self.assertEqual(DriverState.UNCONFIGURED, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
# configure
configs = {BarsChannel.INSTRUMENT: self.config}
result = driver.configure(configs)
self.assertEqual(DriverState.DISCONNECTED, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
# connect
result = driver.connect([BarsChannel.INSTRUMENT])
print "connect result = %s" % str(result)
self._assert_auto_sample()
print "sleeping for a bit to see data streaming"
time.sleep(4)
def _disconnect(self):
print "disconnecting"
driver = self.driver
result = driver.disconnect([BarsChannel.INSTRUMENT])
self.assertEqual(DriverState.DISCONNECTED, driver.get_current_state())
print "driver state = %s" % str(driver.get_current_state())
def test_connect_disconnect(self):
self._connect()
self._disconnect()
def _get(self, params):
driver = self.driver
result = driver.get(params)
print "get result = %s" % str(result)
assert isinstance(result, dict)
self._assert_auto_sample()
return result
def test_get(self):
self._connect()
cp = (BarsChannel.INSTRUMENT, BarsParameter.TIME_BETWEEN_BURSTS)
params = [cp]
result = self._get(params)
seconds = result.get(cp)
assert isinstance(seconds, int)
time.sleep(1)
self._disconnect()
def test_get_set(self):
self._connect()
cp = (BarsChannel.INSTRUMENT, BarsParameter.TIME_BETWEEN_BURSTS)
params = [cp]
result = self._get(params)
seconds = result.get(cp)
assert isinstance(seconds, int)
driver = self.driver
new_seconds = seconds + 5
if new_seconds > 30 or new_seconds < 15:
new_seconds = 15
# get a parameter
result = driver.set({cp: new_seconds})
print "set result = %s" % str(result)
code = result.get(cp)
InstErrorCode.is_ok(code)
self._assert_auto_sample()
result = self._get(params)
seconds = result.get(cp)
self.assertEqual(new_seconds, seconds)
time.sleep(1)
self._disconnect()
def _assert_auto_sample(self):
"""asserts AUTOSAMPLE state"""
curr_state = self.driver.get_current_state()
self.assertEqual(DriverState.AUTOSAMPLE, curr_state)
print "driver state = %s" % str(curr_state)
<file_sep>/ion/services/sa/resource_impl/site_impl.py
#!/usr/bin/env python
"""
@package ion.services.sa.resource_impl.management.site_impl
@author <NAME>
"""
#from pyon.core.exception import BadRequest, NotFound
from pyon.public import PRED, RT
from ion.services.sa.resource_impl.resource_simple_impl import ResourceSimpleImpl
class SiteImpl(ResourceSimpleImpl):
"""
@brief resource management for Site resources
"""
def _primary_object_name(self):
return RT.Site
def _primary_object_label(self):
return "site"
def link_platform(self, site_id='', logical_platform_id=''):
return self._link_resources(site_id, PRED.hasPlatform, logical_platform_id)
def unlink_platform(self, site_id='', logical_platform_id=''):
return self._unlink_resources(site_id, PRED.hasPlatform, logical_platform_id)
def link_site(self, site_id='', site_child_id=''):
return self._link_resources(site_id, PRED.hasSite, site_child_id)
def unlink_site(self, site_id='', site_child_id=''):
return self._unlink_resources(site_id, PRED.hasSite, site_child_id)
def find_having_platform(self, logical_platform_id):
return self._find_having(PRED.hasPlatform, logical_platform_id)
def find_stemming_platform(self, logical_platform_id):
return self._find_stemming(logical_platform_id, PRED.hasPlatform, RT.LogicalPlatform)
def find_having_site(self, site_child_id):
return self._find_having(PRED.hasSite, site_child_id)
def find_stemming_site(self, site_id):
return self._find_stemming(site_id, PRED.hasSite, RT.Site)
<file_sep>/ion/services/mi/drivers/uw_bars/bars.py
#!/usr/bin/env python
"""
@package ion.services.mi.drivers.uw_bars.bars
@file ion/services/mi/drivers/uw_bars/bars.py
@author <NAME>
@brief UW TRHPH BARS definitions and misc utilities
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import re
###########################################################################
#
# Menus, typical responses, and associated regexs and utilities.
#
# Leading blank lines in the actual responses are ignored in these strings.
# The lines here are '\n'-terminated while the instrument actually uses '\r\n.'
#
MAIN_MENU = """
***************************************************************
* *
* Welcome to the BARS Program Main Menu *
* (Benthic And Resistivity Sensors) *
* (Serial Number 002) *
* *
***************************************************************
Version 1.7 - Last Revision: July 11, 2011
Written by:
<NAME>
Engineering Services
School of Oceanography
University of Washington
Seattle, WA 98195
The System Clock has not been set.
Use option 4 to Set the Clock.
Select one of the following functions:
0). Reprint Time & this Menu.
1). Restart Data Collection.
2). Change Data Collection Parameters.
3). System Diagnostics.
4). Set the System Clock.
5). Control Power to Sensors.
6). Provide Information on this System.
7). Exit this Program.
Enter 0, 1, 2, 3, 4, 5, 6 or 7 here --> """
#----------------------------------------------
# 0). Reprint Time & this Menu.
# Also \r can be entered here to re-generate the main menu.
#----------------------------------------------
# 1). Restart Data Collection.
# A typical line when data streaming is resumed:
# 0.000 0.000 0.000 4.095 4.095 4.095 2.007 1.165 20.98 0.008 22.9 9.2
#----------------------------------------------
# 2). Change Data Collection Parameters.
SYSTEM_PARAMETER_MENU_FORMAT = """
System Parameter Menu
*****************************************************************************
The present value for the Cycle Time is
%s %s.
The present setting for Verbose versus Data only is
%s.
*****************************************************************************
Select one of the following functions:
0). Reprint this Menu.
1). Change the Cycle Time.
2). Change the Verbose Setting.
3). Return to the Main Menu.
Enter 0, 1, 2, or 3 here --> """
SYSTEM_PARAMETER_MENU = SYSTEM_PARAMETER_MENU_FORMAT % (
"20", "Seconds", "Data Only")
# to extract cycle time from system parameter menu:
CYCLE_TIME_PATTERN = re.compile(
r'present value for the Cycle Time is\s+([^.]*)\.')
# to extract "Verbose versus Data only" from system parameter menu:
VERBOSE_VS_DATA_ONLY_PATTERN = re.compile(
r'present setting for Verbose versus Data only is\s+([^.]*)\.')
def _search_in_pattern(string, pattern, *groups):
"""
Extracts the groups corresponding to the given pattern in the string.
Return None if pattern not found.
"""
mo = re.search(pattern, string)
return None if mo is None else mo.group(*groups)
def get_cycle_time(string):
"""
Extract the cycle time text from the given string. None if not found.
"""
return _search_in_pattern(string, CYCLE_TIME_PATTERN, 1)
def get_cycle_time_seconds(string):
"""
Parses the string to get the corresponding number of seconds, for example,
if string="20 Seconds" then returns 20,
if string="2 Minutes" then returns 120.
@param string the text presumably obtained by get_cycle_time.
@return the number of seconds. None if the string cannot be parsed.
"""
mo = re.match(r"(\d+)\s+(Seconds|Minutes)", string)
if mo is not None:
value = int(mo.group(1))
units = mo.group(2)
if units == "Seconds":
seconds = value
else:
seconds = 60 * value
return seconds
else:
return None
def get_verbose_vs_data_only(string):
"""
Extract the verbose vs. data only mode text from the given string. None
if not found.
"""
return _search_in_pattern(string, VERBOSE_VS_DATA_ONLY_PATTERN, 1)
CHANGE_CYCLE_TIME = """
Do you want to specify a Cycle Time in
in Seconds or Minutes?
Enter 0 for Seconds, 1 for Minutes --> """
# if 0 is entered:
CHANGE_CYCLE_TIME_IN_SECONDS = "Enter a new value between 15 and 59 here --> "
# TODO determine prompt when 1 is entered
CHANGE_CYCLE_TIME_IN_MINUTES = "Enter a new value between _ and _ here --> "
#----------------------------------------------
# 3). System Diagnostics.
HOW_MANY_SCANS_FOR_SYSTEM_DIAGNOSTICS = """
This Test Routine Prints out the actual Analog Voltages
from all the Analog Inputs.
This should be helpful for system testing.
How Many Scans do you want? --> """
# sample of response:
SYSTEM_DIAGNOSTICS_RESPONSE = """
-Res/5- -ResX1- -ResX5- -*H2/5- -*H2X1- -*H2X5- -*Eh**- RefTemp ResTemp -VBatt-
0.000 0.000 0.000 4.096 4.096 4.096 2.007 1.151 0.011 9.292
0.000 0.000 0.000 4.096 4.096 4.096 2.007 1.154 0.010 9.242
0.000 0.000 0.000 4.096 4.096 4.096 2.008 1.152 0.006 9.242
0.000 0.000 0.000 4.096 4.096 4.096 2.010 1.157 0.010 9.252
Press Enter to return to Main Menu."""
#----------------------------------------------
# 4). Set the System Clock.
ADJUST_SYSTEM_CLOCK_MENU = """
This routine is to set or adjust the System Clock.
The Current System Date = 02/09/12
The Current System Time = 14:21:06
Do you want to Change the Current Time? (0 = No, 1 = Yes) --> """
# also \r can be entered to return to main menu.
# To extract date and time from adjust system clock menu:
CURRENT_SYSTEM_DATE_AND_TIME_PATTERN = re.compile(
r'The Current System Date =\s*([^\s]*)\s+' +
'The Current System Time =\s*([^\s]*)')
def get_system_date_and_time(string):
"""
Returns (date,time), the system date and time from the given string.
None if not found.
"""
return _search_in_pattern(string, CURRENT_SYSTEM_DATE_AND_TIME_PATTERN,
1, 2)
# prompts to set system clock:
ENTER_MONTH = """Enter the Month (1-12) : """
ENTER_DAY = """Enter the Day (1-31) : """
ENTER_YEAR = """Enter the Year (Two Digits): """
ENTER_HOUR = """Enter the Hour (0-23) : """
ENTER_MINUTE = """Enter the Minute (0-59) : """
ENTER_SECOND = """Enter the Second (0-59) : """
#----------------------------------------------
# 5). Control Power to Sensors.
SENSOR_POWER_CONTROL_MENU = """
Sensor Power Control Menu
*****************************************************************************
Here is the current status of power to each sensor
Res Sensor Power is ............. On
Instrumentation Amp Power is .... On
eH Isolation Amp Power is ....... On
Hydrogen Power .................. On
Reference Temperature Power ..... On
*****************************************************************************
Select one of the following functions:
0). Reprint this Menu.
1). Toggle Power to Res Sensor.
2). Toggle Power to the Instrumentation Amp.
3). Toggle Power to the eH Isolation Amp.
4). Toggle Power to the Hydrogen Sensor.
5). Toggle Power to the Reference Temperature Sensor.
6). Return to the Main Menu.
Enter 0, 1, 2, 3, 4, 5, or 6 here --> """
# To extract power statuses from sensor power control menu
CURRENT_POWER_STATUS_PATTERN = re.compile(
r'Res Sensor Power is\s*\.*\s*([^\s]*)\s+' +
r'Instrumentation Amp Power is\s*\.*\s*([^\s]*)\s+' +
r'eH Isolation Amp Power is\s*\.*\s*([^\s]*)\s+' +
r'Hydrogen Power\s*\.*\s*([^\s]*)\s+' +
r'Reference Temperature Power\s*\.*\s*([^\s]*)\s+')
def get_power_statuses(string):
"""
Returns (rs, ia, eh, hy, rt), the current power status of:
- Res Sensor Power
- Instrumentation Amp Power
- eH Isolation Amp Power
- Hydrogen Power
- Reference Temperature Power.
None if not found.
"""
return _search_in_pattern(string, CURRENT_POWER_STATUS_PATTERN,
1, 2, 3, 4, 5)
#----------------------------------------------
# 6). Provide Information on this System.
SYSTEM_INFO = """
System Name: BARS (Benthic And Resistivity Sensors)
System Owner: <NAME>, University of Washington
Owner Contact Phone #: 206-543-0859
System Serial #: 002
Press Enter to return to the Main Menu. --> """
<file_sep>/ion/processes/data/replay_process.py
#!/usr/bin/env python
'''
@author <NAME> <<EMAIL>>
@file ion/processes/data/replay_process.py
@description Implementation for the Replay Agent
'''
from gevent.greenlet import Greenlet
from gevent.coros import RLock
from interface.objects import BlogBase, StreamGranuleContainer, DataStream, Encoding, StreamDefinitionContainer
from pyon.datastore.datastore import DataStore
from pyon.ion.endpoint import StreamPublisherRegistrar
from pyon.public import log
from interface.services.dm.ireplay_process import BaseReplayProcess
from pyon.util.containers import DotDict
from pyon.core.exception import IonException
from pyon.util.file_sys import FS, FileSystem
import hashlib
class ReplayProcessException(IonException):
"""
Exception class for IngestionManagementService exceptions. This class inherits from IonException
and implements the __str__() method.
"""
def __str__(self):
return str(self.get_status_code()) + str(self.get_error_message())
class ReplayProcess(BaseReplayProcess):
process_type="standalone"
def __init__(self, *args, **kwargs):
super(ReplayProcess, self).__init__(*args,**kwargs)
#@todo Init stuff
# mutex for shared resources between threads
self.lock = RLock()
def on_start(self):
'''
Creates a publisher for each stream_id passed in as publish_streams
Creates an attribute with the name matching the stream name which corresponds to the publisher
ex: say we have publish_streams:{'output': my_output_stream_id }
then the instance has an attribute output which corresponds to the publisher for the stream
in my_output_stream_id
'''
self.stream_publisher_registrar = StreamPublisherRegistrar(process=self,node=self.container.node)
# Get the query
self.query = self.CFG.get_safe('process.query',{})
# Get the delivery_format
self.delivery_format = self.CFG.get_safe('process.delivery_format',{})
self.datastore_name = self.CFG.get_safe('process.datastore_name','dm_datastore')
self.view_name = self.CFG.get_safe('process.view_name','datasets/dataset_by_id')
self.key_id = self.CFG.get_safe('process.key_id')
# Get a stream_id for this process
self.stream_id = self.CFG.get_safe('process.publish_streams.output',{})
if not (self.stream_id and hasattr(self,'output')):
raise RuntimeError('The replay agent requires an output stream publisher named output. Invalid configuration!')
def _records(self, records, n):
"""
Given a list of records, yield at most n at a time
"""
while True:
yval = []
try:
for i in xrange(n):
yval = yval + [records.pop(0)]
yield yval
except IndexError:
if yval:
yield yval
break
def _publish_query(self, results):
'''
Callback to publish the specified results
'''
#-----------------------
# Iteration
#-----------------------
# - Go through the results, if the user had include_docs=True in the options field
# then the full document is in result.doc; however if the query did not include_docs,
# then only the doc_id is provided in the result.value.
#
# - What this allows us to do is limit the amount of traffic in information for large queries.
# If we only are making a query in a sequence of queries (such as map and reduce) then we don't
# care about the full document, yet, we only care about the doc id and will retrieve the document later.
# - Example:
# Imagine the blogging example, we want the latest blog by author George and all the comments for that blog
# The series of queries would go, post_by_updated -> posts_by_author -> posts_join_comments and then
# in the last query we'll set include_docs to true and parse the docs.
#-----------------------
log.warn('results: %s', results)
for result in results:
log.warn('REPLAY Result: %s' % result)
assert('doc' in result)
replay_obj_msg = result['doc']
if isinstance(replay_obj_msg, BlogBase):
replay_obj_msg.is_replay = True
self.lock.acquire()
self.output.publish(replay_obj_msg)
self.lock.release()
elif isinstance(replay_obj_msg, StreamDefinitionContainer):
replay_obj_msg.stream_resource_id = self.stream_id
elif isinstance(replay_obj_msg, StreamGranuleContainer):
# Override the resource_stream_id so ingestion doesn't reingest, also this is a NEW stream (replay)
replay_obj_msg.stream_resource_id = self.stream_id
datastream = None
sha1 = None
for key, identifiable in replay_obj_msg.identifiables.iteritems():
if isinstance(identifiable, DataStream):
datastream = identifiable
elif isinstance(identifiable, Encoding):
sha1 = identifiable.sha1
if sha1: # if there is an encoding
# Get the file from disk
filename = FileSystem.get_url(FS.CACHE, sha1, ".hdf5")
log.warn('Replay reading from filename: %s' % filename)
hdf_string = ''
try:
with open(filename, mode='rb') as f:
hdf_string = f.read()
f.close()
# Check the Sha1
retreived_hdfstring_sha1 = hashlib.sha1(hdf_string).hexdigest().upper()
if sha1 != retreived_hdfstring_sha1:
raise ReplayProcessException('The sha1 mismatch between the sha1 in datastream and the sha1 of hdf_string in the saved file in hdf storage')
except IOError:
log.warn('No HDF file found!')
#@todo deal with this situation? How?
hdf_string = 'HDF File %s not found!' % filename
# set the datastream.value field!
datastream.values = hdf_string
else:
log.warn('No encoding in the StreamGranuleContainer!')
self.lock.acquire()
self.output.publish(replay_obj_msg)
self.lock.release()
else:
log.warn('Unknown type retrieved in DOC!')
#@todo: log when there are not results
if results is None:
log.warn('No results found in replay query!')
else:
log.debug('Published replay!')
def execute_replay(self):
log.debug('(Replay Agent %s)', self.name)
# Handle the query
datastore_name = self.datastore_name
key_id = self.key_id
# Got the post ID, pull the post and the comments
view_name = self.view_name
opts = {
'start_key':[key_id, 0],
'end_key':[key_id,2],
'include_docs': True
}
g = Greenlet(self._query,datastore_name=datastore_name, view_name=view_name, opts=opts,
callback=lambda results: self._publish_query(results))
g.start()
def _query(self,datastore_name='dm_datastore', view_name='posts/posts_by_id', opts={}, callback=None):
'''
Performs the query action
'''
log.debug('Couch Query:\n\t%s\n\t%s\n\t%s', datastore_name, view_name, opts)
#@todo: Fix this datastore management profile with correct data profile in near future
db = self.container.datastore_manager.get_datastore(datastore_name, DataStore.DS_PROFILE.EXAMPLES, self.CFG)
ret = db.query_view(view_name=view_name,opts=opts)
callback(ret)
<file_sep>/ion/services/sa/marine_facility/test/test_marine_facility_management_service_integration.py
#from interface.services.icontainer_agent import ContainerAgentClient
#from pyon.net.endpoint import ProcessRPCClient
#from pyon.public import Container, log, IonObject
from pyon.util.int_test import IonIntegrationTestCase
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from ion.services.sa.marine_facility.marine_facility_management_service import MarineFacilityManagementService
#from interface.services.sa.imarine_facility_management_service import IMarineFacilityManagementService, MarineFacilityManagementServiceClient
from pyon.util.context import LocalContextMixin
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.public import RT, PRED, LCS
#from mock import Mock, patch
from pyon.util.unit_test import PyonTestCase
from nose.plugins.attrib import attr
import unittest
from pyon.util.log import log
from ion.services.sa.test.helpers import any_old
class FakeProcess(LocalContextMixin):
name = ''
@attr('INT', group='sa')
class TestMarineFacilityManagementServiceIntegration(IonIntegrationTestCase):
def setUp(self):
# Start container
#print 'instantiating container'
self._start_container()
#container = Container()
#print 'starting container'
#container.start()
#print 'started container'
self.container.start_rel_from_url('res/deploy/r2sa.yml')
self.RR = ResourceRegistryServiceClient(node=self.container.node)
print 'started services'
def test_just_the_setup(self):
return
def test_resources_associations(self):
"""
create one of each resource and association used by MFMS
to guard against problems in ion-definitions
"""
#raise unittest.SkipTest("https://jira.oceanobservatories.org/tasks/browse/CISWCORE-41")
#stuff we control
logical_instrument_id, _ = self.RR.create(any_old(RT.LogicalInstrument))
logical_platform_id, _ = self.RR.create(any_old(RT.LogicalPlatform))
logical_platform2_id, _ = self.RR.create(any_old(RT.LogicalPlatform))
marine_facility_id, _ = self.RR.create(any_old(RT.MarineFacility))
site_id, _ = self.RR.create(any_old(RT.Site))
site2_id, _ = self.RR.create(any_old(RT.Site))
#stuff we associate to
instrument_agent_id, _ = self.RR.create(any_old(RT.InstrumentAgent))
platform_agent_id, _ = self.RR.create(any_old(RT.PlatformAgent))
#logical_instrument
self.RR.create_association(logical_instrument_id, PRED.hasAgent, instrument_agent_id)
#logical_platform
self.RR.create_association(logical_platform_id, PRED.hasPlatform, logical_platform2_id)
self.RR.create_association(logical_platform_id, PRED.hasInstrument, logical_instrument_id)
self.RR.create_association(logical_platform_id, PRED.hasAgent, platform_agent_id)
#marine_facility
self.RR.create_association(marine_facility_id, PRED.hasSite, site_id)
self.RR.create_association(marine_facility_id, PRED.hasPlatform, logical_platform_id)
#site
self.RR.create_association(site_id, PRED.hasSite, site2_id)
<file_sep>/ion/services/cei/test/test_process_dispatcher.py
import gevent
from mock import Mock
from unittest import SkipTest
from nose.plugins.attrib import attr
from pyon.util.containers import DotDict
from pyon.util.unit_test import PyonTestCase
from pyon.util.int_test import IonIntegrationTestCase
from pyon.core.exception import NotFound
from pyon.public import CFG
from interface.services.cei.iprocess_dispatcher_service import ProcessDispatcherServiceClient
from interface.objects import ProcessDefinition, ProcessSchedule, ProcessTarget
from interface.services.icontainer_agent import ContainerAgentClient
from ion.processes.data.transforms.transform_example import TransformExample
from ion.services.cei.process_dispatcher_service import ProcessDispatcherService,\
PDLocalBackend, PDBridgeBackend
@attr('UNIT',group='cei')
class ProcessDispatcherServiceTest(PyonTestCase):
def setUp(self):
mock_clients = self._create_service_mock('process_dispatcher')
self.pd_service = ProcessDispatcherService()
self.pd_service.clients = mock_clients
self.pd_service.container = DotDict()
self.pd_service.container['spawn_process'] = Mock()
self.pd_service.container['id'] = 'mock_container_id'
self.pd_service.container['proc_manager'] = DotDict()
self.pd_service.container.proc_manager['terminate_process'] = Mock()
self.pd_service.container.proc_manager['procs'] = {}
# CRUD Shortcuts
self.mock_rr_create = self.pd_service.clients.resource_registry.create
self.mock_rr_read = self.pd_service.clients.resource_registry.read
self.mock_rr_update = self.pd_service.clients.resource_registry.update
self.mock_rr_delete = self.pd_service.clients.resource_registry.delete
self.mock_rr_find = self.pd_service.clients.resource_registry.find_objects
self.mock_rr_find_res = self.pd_service.clients.resource_registry.find_resources
self.mock_rr_assoc = self.pd_service.clients.resource_registry.find_associations
self.mock_rr_create_assoc = self.pd_service.clients.resource_registry.create_association
self.mock_rr_del_assoc = self.pd_service.clients.resource_registry.delete_association
self.mock_cc_spawn = self.pd_service.container.spawn_process
self.mock_cc_terminate = self.pd_service.container.proc_manager.terminate_process
self.mock_cc_procs = self.pd_service.container.proc_manager.procs
def test_local_schedule(self):
self.pd_service.init()
self.assertIsInstance(self.pd_service.backend, PDLocalBackend)
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module':'my_module', 'class':'class'}
self.mock_rr_read.return_value = proc_def
self.mock_cc_spawn.return_value = '123'
# not used for anything in local mode
proc_schedule = DotDict()
configuration = {"some": "value"}
pid = self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration)
self.mock_rr_read.assert_called_once_with("fake-process-def-id", "")
self.assertEqual(pid, '123')
self.assertEqual(self.mock_cc_spawn.call_count, 1)
call_args, call_kwargs = self.mock_cc_spawn.call_args
self.assertFalse(call_args)
# name should be def name followed by a uuid
name = call_kwargs['name']
self.assertTrue(name.startswith(proc_def.name) and name != proc_def.name)
self.assertEqual(len(call_kwargs), 4)
self.assertEqual(call_kwargs['module'], 'my_module')
self.assertEqual(call_kwargs['cls'], 'class')
called_config = call_kwargs['config']
self.assertEqual(called_config, configuration)
def test_schedule_process_notfound(self):
proc_schedule = DotDict()
configuration = {}
self.mock_rr_read.side_effect = NotFound()
with self.assertRaises(NotFound):
self.pd_service.schedule_process("not-a-real-process-id",
proc_schedule, configuration)
self.mock_rr_read.assert_called_once_with("not-a-real-process-id", "")
def test_local_cancel(self):
self.pd_service.init()
self.assertIsInstance(self.pd_service.backend, PDLocalBackend)
ok = self.pd_service.cancel_process("process-id")
self.assertTrue(ok)
self.mock_cc_terminate.assert_called_once_with("process-id")
def test_bridge_schedule(self):
pdcfg = dict(uri="amqp://hello", topic="pd", exchange="123")
self.pd_service.CFG = DotDict()
self.pd_service.CFG['process_dispatcher_bridge'] = pdcfg
self.pd_service.init()
self.assertIsInstance(self.pd_service.backend, PDBridgeBackend)
# sneak in and replace dashi connection method
mock_dashi = Mock()
self.pd_service.backend._init_dashi = lambda : mock_dashi
self.pd_service.start()
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module':'my_module', 'class':'class'}
self.mock_rr_read.return_value = proc_def
proc_schedule = DotDict()
proc_schedule['target'] = DotDict()
proc_schedule.target['constraints'] = {"hats" : 4}
configuration = {"some": "value"}
pid = self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration)
self.mock_rr_read.assert_called_once_with("fake-process-def-id", "")
self.assertTrue(pid.startswith(proc_def.name) and pid != proc_def.name)
self.assertEqual(mock_dashi.call.call_count, 1)
call_args, call_kwargs = mock_dashi.call.call_args
self.assertEqual(set(call_kwargs),
set(['upid', 'spec', 'subscribers', 'constraints']))
self.assertEqual(call_kwargs['constraints'],
proc_schedule.target['constraints'])
self.assertEqual(call_args, ("pd", "dispatch_process"))
def test_bridge_cancel(self):
pdcfg = dict(uri="amqp://hello", topic="pd", exchange="123")
self.pd_service.CFG = DotDict()
self.pd_service.CFG['process_dispatcher_bridge'] = pdcfg
self.pd_service.init()
self.assertIsInstance(self.pd_service.backend, PDBridgeBackend)
# sneak in and replace dashi connection method
mock_dashi = Mock()
self.pd_service.backend._init_dashi = lambda : mock_dashi
self.pd_service.start()
ok = self.pd_service.cancel_process("process-id")
self.assertTrue(ok)
mock_dashi.call.assert_called_once_with("pd", "terminate_process",
upid="process-id")
@attr('INT', group='cei')
class ProcessDispatcherServiceLocalIntTest(IonIntegrationTestCase):
"""Integration tests for the "local" mode of the PD
In local mode processes are directly started on the local container. This
is provided to allow use of PD functionality when launching via a single
rel file instead of via a "real" CEI launch.
"""
def setUp(self):
# ensure bridge mode is disabled
if 'process_dispatcher_bridge' in CFG:
del CFG['process_dispatcher_bridge']
# set up the container
self._start_container()
self.cc = ContainerAgentClient(node=self.container.node, name=self.container.name)
self.cc.start_rel_from_url('res/deploy/r2cei.yml')
self.pd_cli = ProcessDispatcherServiceClient(node=self.cc.node)
self.process_definition = ProcessDefinition(name='basic_transform_definition')
self.process_definition.executable = {'module': 'ion.processes.data.transforms.transform_example',
'class':'TransformExample'}
self.process_definition_id = self.pd_cli.create_process_definition(self.process_definition)
def test_schedule_cancel(self):
process_schedule = ProcessSchedule()
pid = self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration={})
proc = self.container.proc_manager.procs.get(pid)
self.assertIsInstance(proc, TransformExample)
# failures could theoretically leak processes but I don't think that
# matters since everything gets torn down between tests
self.pd_cli.cancel_process(pid)
self.assertNotIn(pid, self.container.proc_manager.procs)
@attr('INT', group='cei')
class ProcessDispatcherServiceBridgeIntTest(IonIntegrationTestCase):
"""Integration tests for the "bridge" mode of the PD
In bridge mode requests are bridged to a backend Process Dispatcher
service running outside of the container and launched out of band.
"""
dashi_uri = "memory://local"
dashi_exchange = "test_pd_bridge_exchange"
dashi_pd_topic = "processdispatcher"
def setUp(self):
# set up a fake dashi consumer to act as the PD
try:
import dashi
except ImportError:
raise SkipTest("Process Dispatcher Bridge integration test "+
"requires the dashi library. Skipping.")
self.fake_pd = FakePD(dashi.DashiConnection(self.dashi_pd_topic,
self.dashi_uri, self.dashi_exchange))
self.fake_pd.consume_in_thread()
# set up the container
self._start_container()
self.cc = ContainerAgentClient(node=self.container.node, name=self.container.name)
CFG['process_dispatcher_bridge'] = dict(uri="memory://local",
exchange="test_pd_bridge_exchange", topic="processdispatcher")
self.cc.start_rel_from_url('res/deploy/r2cei.yml')
self.pd_cli = ProcessDispatcherServiceClient(node=self.cc.node)
self.process_definition = ProcessDefinition(name='basic_transform_definition')
self.process_definition.executable = {'module': 'ion.processes.data.transforms.transform_example',
'class':'TransformExample'}
self.process_definition_id = self.pd_cli.create_process_definition(self.process_definition)
def tearDown(self):
if hasattr(self, "fake_pd") and self.fake_pd:
self.fake_pd.shutdown()
def test_schedule_cancel(self):
process_schedule = ProcessSchedule()
process_schedule.target = ProcessTarget()
process_schedule.target.constraints = {'site' : 'chicago'}
config = {'some': "value"}
pid = self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration=config)
self.assertEqual(self.fake_pd.dispatch_process.call_count, 1)
args, kwargs = self.fake_pd.dispatch_process.call_args
self.assertFalse(args)
self.assertEqual(set(kwargs),
set(['upid', 'spec', 'subscribers', 'constraints']))
spec = kwargs['spec']
self.assertEqual(spec['run_type'], 'pyon_single')
self.assertEqual(spec['parameters']['rel']['apps'][0]['config'],
config)
self.pd_cli.cancel_process(pid)
self.fake_pd.terminate_process.assert_called_once_with(upid=pid)
class FakePD(object):
"""object which uses CEI messaging to simulate the backend PD service
We cannot stand up the real service for true integration testing but
this at least verifies that the messaging works.
"""
consume_timeout = 5
def __init__(self, dashi):
self.dashi = dashi
# return values do not match service responses yet
self.dispatch_process = Mock()
self.dispatch_process.return_value = {}
self.dashi.handle(self.dispatch_process, 'dispatch_process')
self.terminate_process = Mock()
self.terminate_process.return_value = {}
self.dashi.handle(self.terminate_process, 'terminate_process')
def consume_in_thread(self):
self.consumer_thread = gevent.spawn(self.dashi.consume)
def shutdown(self):
if self.consumer_thread:
self.dashi.cancel(block=False)
self.consumer_thread.kill()
self.consumer_thread = None
<file_sep>/ion/services/mi/instrument_protocol.py
#!/usr/bin/env python
"""
@package ion.services.mi.instrument_protocol Base instrument protocol structure
@file ion/services/mi/instrument_protocol.py
@author <NAME>
@brief Instrument protocol classes that provide structure towards the
nitty-gritty interaction with individual instruments in the system.
@todo Figure out what gets thrown on errors
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
from zope.interface import Interface, implements
import logging
import time
import os
import signal
import re
from ion.services.mi.exceptions import InstrumentProtocolException
from ion.services.mi.exceptions import InstrumentTimeoutException
from ion.services.mi.exceptions import InstrumentStateException
from ion.services.mi.exceptions import InstrumentConnectionException
from ion.services.mi.instrument_connection import IInstrumentConnection
from ion.services.mi.common import InstErrorCode, EventKey
from ion.services.mi.logger_process import EthernetDeviceLogger, LoggerClient
mi_logger = logging.getLogger('mi_logger')
class ParameterDictVal(object):
"""
"""
def __init__(self, name, pattern, f_getval, f_format, value=None):
"""
"""
self.name = name
self.pattern = pattern
self.regex = re.compile(pattern)
self.f_getval = f_getval
self.f_format = f_format
self.value = value
def update(self, input):
"""
"""
match = self.regex.match(input)
if match:
self.value = self.f_getval(match)
mi_logger.debug('Updated parameter %s=%s', self.name, str(self.value))
return True
else: return False
class InstrumentProtocol(object):
"""The base class for an instrument protocol
The classes derived from this class will carry out the specific
interactions between a specific device and the instrument driver. At this
layer of interaction, there are no conflicts or transactions as that is
handled at the layer above this. Think of this as encapsulating the
transport layer of the communications.
"""
implements(IInstrumentConnection)
def __init__(self, evt_callback=None):
"""Set instrument connect at creation
@param connection An InstrumetnConnection object
"""
self._logger = None
self._logger_client = None
self._logger_popen = None
self._fsm = None
self.send_event = evt_callback
"""The driver callback where we an publish events. Should be a link
to a function. Currently a dict with keys in EventKey enum."""
########################################################################
# Protocol connection interface.
########################################################################
"""
@todo Move this into the driver state machine?
"""
def initialize(self, *args, **kwargs):
"""
"""
mi_logger.info('Initializing device comms.')
self._logger = None
self._logger_client = None
def configure(self, config, *args, **kwargs):
"""
"""
mi_logger.info('Configuring for device comms.')
method = config['method']
if method == 'ethernet':
device_addr = config['device_addr']
device_port = config['device_port']
server_addr = config['server_addr']
server_port = config['server_port']
self._logger = EthernetDeviceLogger(device_addr, device_port,
server_port)
self._logger_client = LoggerClient(server_addr, server_port)
elif method == 'serial':
# The config dict does not have a valid connection method.
raise InstrumentConnectionException()
else:
# The config dict does not have a valid connection method.
raise InstrumentConnectionException()
def connect(self, *args, **kwargs):
"""Connect via the instrument connection object
@param args connection arguments
@throws InstrumentConnectionException
"""
mi_logger.info('Connecting to device.')
logger_pid = self._logger.get_pid()
mi_logger.info('Found logger pid: %s.', str(logger_pid))
if not logger_pid:
self._logger_popen = self._logger.launch_process()
time.sleep(0.2)
try:
retval = os.wait()
mi_logger.debug('os.wait returned %s' % str(retval))
except Exception as e:
mi_logger.debug('os.wait() threw %s: %s' %
(e.__class__.__name__, str(e)))
mi_logger.debug('popen wait returned %s', str(self._logger_popen.wait()))
time.sleep(1)
self.attach()
else:
# There was a pidfile for the device.
raise InstrumentConnectionException()
return logger_pid
def disconnect(self, *args, **kwargs):
"""Disconnect via the instrument connection object
@throws InstrumentConnectionException
"""
mi_logger.info('Disconnecting from device.')
self.detach()
self._logger.stop()
def attach(self, *args, **kwargs):
"""
"""
mi_logger.info('Attaching to device.')
self._logger_client.init_comms(self._got_data)
def detach(self, *args, **kwargs):
"""
"""
mi_logger.info('Detaching from device.')
self._logger_client.stop_comms()
def reset(self, *args, **kwargs):
"""Reset via the instrument connection object"""
# Call logger reset here.
pass
########################################################################
# Protocol command interface.
########################################################################
def get(self, *args, **kwargs):
"""Get some parameters
@param params A list of parameters to fetch. These must be in the
fetchable parameter list
@retval results A dict of the parameters that were queried
@throws InstrumentProtocolException Confusion dealing with the
physical device
@throws InstrumentStateException Unable to handle current or future
state properly
@throws InstrumentTimeoutException Timeout
"""
pass
def set(self, *args, **kwargs):
"""Get some parameters
@throws InstrumentProtocolException Confusion dealing with the
physical device
@throws InstrumentStateException Unable to handle current or future
state properly
@throws InstrumentTimeoutException Timeout
"""
pass
def execute(self, *args, **kwargs):
"""Execute a command
@param command A single command as a list with the command ID followed
by the parameters for that command
@throws InstrumentProtocolException Confusion dealing with the
physical device
@throws InstrumentStateException Unable to handle current or future
state properly
@throws InstrumentTimeoutException Timeout
"""
pass
def execute_direct(self, *args, **kwargs):
"""
"""
pass
########################################################################
# TBD.
########################################################################
def get_capabilities(self):
"""
"""
pass
########################################################################
# Helper methods
########################################################################
def _got_data(self, data):
"""
Called by the logger whenever there is data available
"""
pass
def announce_to_driver(self, type, error_code=None, msg=None):
"""
Announce an event to the driver via the callback
@param type The DriverAnnouncement enum type of the event
@param args Any arguments involved
@param msg A message to be included
@todo Clean this up, promote to InstrumentProtocol?
"""
assert type != None
event = {EventKey:type}
if error_code:
event.update({EventKey.ERROR_CODE:error_code})
if msg:
event.update({EventKey.MESSAGE:msg})
self.send_event(event)
class BinaryInstrumentProtocol(InstrumentProtocol):
"""Instrument protocol description for a binary-based instrument
This class wraps standard protocol operations with methods to pack
commands into the binary structures that they need to be in for the
instrument to operate on them.
@todo Consider removing this class if insufficient parameterization of
message packing is done
"""
def _pack_msg(self, msg=None):
"""Pack the message according to the field before sending it to the
instrument.
This may involve special packing per parameter, possibly checksumming
across the whole message, too.
@param msg The message to pack for the instrument. May need to be
inspected to determine the proper packing structure
@retval packed_msg The packed message
"""
# Default implementation
return msg.checksum
def _unpack_response(self, type=None, packed_msg=None):
"""Unpack a message from an instrument
When a binary instrument responsed with a packed binary, this routine
unbundles the response into something usable. Checksums may be added
@param type The type of message to be unpacked. Will like be a key to
an unpacking description string.
@param packed_msg The packed message needing to be unpacked
@retval msg The unpacked message
"""
# Default implementation
return packed_msg
class ScriptInstrumentProtocol(InstrumentProtocol):
"""A class to handle a simple scripted interaction with an instrument
For instruments with a predictable interface (such as a menu or well
known paths through options), this class can be setup to follow a simple
script of interactions to manipulate the instrument. The script language
is currently as follows:
* Commands are in name value pairs separated by an =, no whitespace
around the equals
* Commands are separated from each other by \n.
* Control keys are the letter preceeded by a ^ symbol.
* Use \ to protect a ^ or \n and include it in the string being sent.
* A final \n is optional.
* Commands will be executed in order
* The send command name is "S"
* The delay command is "D", delay measured in seconds, but is a
python formatted floating point value
For example, the following script issues a Control-C, "3", "1", "val1\n", then a "0"
with a 1.5 second delay between to do something like walk through a menu,
select a parameter, name its value, then return to the previous menu:
"S=^C\nD=1.5\nS=3\nD=1.5\nS=1\nD=1.5\nS=val1\\nD=1.5\nS=0"
@todo Add a wait-for command?
"""
def run_script(self, script):
"""Interpret the supplied script and apply it to the instrument
@param script The script to execute in string form
@throws InstrumentProtocolException Confusion dealing with the
physical device, possibly due to interrupted communications
@throws InstrumentStateException Unable to handle current or future
state properly
@throws InstrumentTimeoutException Timeout
"""
class CommandResponseInstrumentProtocol(InstrumentProtocol):
"""A base class for text-based command/response instruments
For instruments that have simple command and response interations, this
class provides some structure for manipulating data to and from the
instrument.
"""
def __init__(self, callback, prompts, newline):
InstrumentProtocol.__init__(self, callback)
self.eoln = newline
"""The end-of-line delimiter to use"""
self.prompts = prompts
self._linebuf = ''
self._promptbuf = ''
self._datalines = []
self._build_handlers = {}
self._response_handlers = {}
self._parameters = {}
########################################################################
# Incomming data callback.
########################################################################
def _add_build_handler(self, cmd, func):
"""
Insert a handler class responsible for building a command to send to
the instrument.
@param cmd The high level key of the command to build for.
"""
self._build_handlers[cmd] = func
def _add_response_handler(self, cmd, func):
"""
Insert a handler class responsible for handling the response to a
command sent to the instrument.
@param cmd The high level key of the command to responsd to.
"""
self._response_handlers[cmd] = func
def _got_data(self, data):
"""
"""
# Update the line and prompt buffers.
self._linebuf += data
self._promptbuf += data
########################################################################
# Wakeup helpers.
########################################################################
def _send_wakeup(self):
"""
Use the logger to send what needs to be sent to wake up the device.
This is intended to be overridden if there is any wake up needed.
"""
pass
def _wakeup(self, timeout=10):
"""
Clear buffers and send a wakeup command to the instrument
@todo Consider the case where there is no prompt returned when the
instrument is awake.
@param timeout The timeout in seconds
@throw InstrumentProtocolExecption on timeout
"""
# Clear the prompt buffer.
self._promptbuf = ''
# Grab time for timeout.
starttime = time.time()
while True:
# Send a line return and wait a sec.
mi_logger.debug('Sending wakeup.')
self._send_wakeup()
time.sleep(1)
for item in self.prompts.list():
if self._promptbuf.endswith(item):
mi_logger.debug('Got prompt: %s', repr(item))
return item
if time.time() > starttime + timeout:
raise InstrumentTimeoutException()
########################################################################
# Command-response helpers.
########################################################################
def _add_build_handler(self, cmd, func):
"""
"""
self._build_handlers[cmd] = func
def _add_response_handler(self, cmd, func):
"""
"""
self._response_handlers[cmd] = func
def _get_response(self, timeout=10):
"""
Get a response from the instrument
@todo Consider cases with no prompt
@param timeout The timeout in seconds
@throw InstrumentProtocolExecption on timeout
"""
# Grab time for timeout and wait for prompt.
starttime = time.time()
while True:
for item in self.prompts.list():
if self._promptbuf.endswith(item):
mi_logger.debug('Got prompt: %s', repr(item))
return (item, self._linebuf)
else:
time.sleep(.1)
if time.time() > starttime + timeout:
raise InstrumentTimeoutException()
def _do_cmd_resp(self, cmd, *args, **kwargs):
"""
Issue a command to the instrument after a wake up and clearing of
buffers. Find the response handler, handle the response, and return it.
@param cmd The high level command to issue
@param args Arguments for the command
@param kwargs timeout if one exists, defaults to 10
@retval resp_result The response handler's return value
@throw InstrumentProtocolException Bad command
@throw InstrumentTimeoutException Timeout
"""
timeout = kwargs.get('timeout', 10)
retval = None
build_handler = self._build_handlers.get(cmd, None)
if not build_handler:
raise InstrumentProtocolException(InstErrorCode.BAD_DRIVER_COMMAND)
cmd_line = build_handler(cmd, *args)
# Wakeup the device, pass up exeception if timeout
prompt = self._wakeup(timeout)
# Clear line and prompt buffers for result.
self._linebuf = ''
self._promptbuf = ''
# Send command.
mi_logger.debug('_do_cmd_resp: %s', repr(cmd_line))
self._logger_client.send(cmd_line)
# Wait for the prompt, prepare result and return, timeout exception
(prompt, result) = self._get_response(timeout)
resp_handler = self._response_handlers.get(cmd, None)
resp_result = None
if resp_handler:
resp_result = resp_handler(result, prompt)
return resp_result
def _do_cmd_no_resp(self, cmd, *args, **kwargs):
"""
Issue a command to the instrument after a wake up and clearing of
buffers. No response is handled as a result of the command.
@param cmd The high level command to issue
@param args Arguments for the command
@param kwargs timeout if one exists, defaults to 10
@throw InstrumentProtocolException Bad command
@throw InstrumentTimeoutException Timeout
"""
timeout = kwargs.get('timeout', 10)
build_handler = self._build_handlers.get(cmd, None)
if not build_handler:
raise InstrumentProtocolException(InstErrorCode.BAD_DRIVER_COMMAND)
cmd_line = build_handler(cmd, *args)
# Wakeup the device, timeout exception as needed
prompt = self._wakeup(timeout)
# Clear line and prompt buffers for result.
self._linebuf = ''
# Send command.
mi_logger.debug('_do_cmd_no_resp: %s', repr(cmd_line))
self._logger_client.send(cmd_line)
return InstErrorCode.OK
########################################################################
# Parameter dict helpers.
########################################################################
def _add_param_dict(self, name, pattern, f_getval, f_format, value=None):
"""
"""
self._parameters[name] = ParameterDictVal(name, pattern, f_getval,
f_format, value)
def _get_param_dict(self, name):
"""
"""
return self._parameters[name].value
def _get_param_dict_names(self):
"""
"""
return self._parameters.keys()
def _get_config_param_dict(self):
"""
"""
config = {}
for (key, val) in self._parameters.iteritems():
config[key] = val.value
return config
def _set_param_dict(self, name, value):
"""
"""
self._parameters[name] = value
def _update_param_dict(self, input):
"""
"""
for (name, val) in self._parameters.iteritems():
if val.update(input):
break
def _format_param_dict(self, name, val):
"""
"""
return self._parameters[name].f_format(val)
def _build_simple_command(self, command):
"""
Build a very simple command string consisting of the command and the
newline associated with this class. This is intended to be extended as
needed by subclasses.
@param command The command string to send.
@retval The complete command, ready to send to the device.
"""
return command+self.eoln
@staticmethod
def _int_to_string(v):
"""
Write an int value to string formatted for sbe37 set operations.
@param v An int val.
@retval an int string formatted for sbe37 set operations, or None if
the input is not a valid int value.
"""
if not isinstance(v,int):
return None
else:
return '%i' % v
@staticmethod
def _float_to_string(v):
"""
Write a float value to string formatted for sbe37 set operations.
@param v A float val.
@retval a float string formatted for sbe37 set operations, or None if
the input is not a valid float value.
"""
if not isinstance(v,float):
return None
else:
return '%e' % v
<file_sep>/ion/services/mi/common.py
#!/usr/bin/env python
"""
@package ion.services.mi.common Common classes for MI work
@file ion/services/mi/common.py
@author <NAME>
@brief Common enumerations, constants, utilities used in the MI work
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
# imports could go here
"""Default timeout value in seconds"""
DEFAULT_TIMEOUT = 30
class BaseEnum(object):
"""Base class for enums.
Used to code agent and instrument states, events, commands and errors.
To use, derive a class from this subclass and set values equal to it
such as:
@code
class FooEnum(BaseEnum):
VALUE1 = "Value 1"
VALUE2 = "Value 2"
@endcode
and address the values as FooEnum.VALUE1 after you import the
class/package.
Enumerations are part of the code in the MI modules since they are tightly
coupled with what the drivers can do. By putting the values here, they
are quicker to execute and more compartmentalized so that code can be
re-used more easily outside of a capability container as needed.
"""
@classmethod
def list(cls):
"""List the values of this enum."""
return [getattr(cls,attr) for attr in dir(cls) if \
not callable(getattr(cls,attr)) and not attr.startswith('__')]
@classmethod
def has(cls, item):
"""Is the object defined in the class?
Use this function to test
a variable for enum membership. For example,
@code
if not FooEnum.has(possible_value)
@endcode
@param item The attribute value to test for.
@retval True if one of the class attributes has value item, false
otherwise.
"""
return item in cls.list()
###############################################################################
# Common driver elements. Below are the constants intended for all instrument
# specific driver implementations, and part of the driver implementation
# framework.
##############################################################################
###############################################################################
# Instrument agent constants.
##############################################################################
class AgentState(BaseEnum):
"""Common agent state enum.
Includes aggregate states of the agent state machine.
"""
UNKNOWN = 'AGENT_STATE_UNKNOWN'
POWERED_DOWN = 'AGENT_STATE_POWERED_DOWN'
POWERED_UP = 'AGENT_STATE_POWERED_UP'
UNINITIALIZED = 'AGENT_STATE_UNINITIALIZED'
ACTIVE = 'AGENT_STATE_ACTIVE'
INACTIVE = 'AGENT_STATE_INACTIVE'
STOPPED = 'AGENT_STATE_STOPPED'
IDLE = 'AGENT_STATE_IDLE'
RUNNING = 'AGENT_STATE_RUNNING'
OBSERVATORY_MODE = 'AGENT_STATE_OBSERVATORY_MODE'
DIRECT_ACCESS_MODE = 'AGENT_STATE_DIRECT_ACCESS_MODE'
class AgentEvent(BaseEnum):
"""Common agent event enum"""
GO_POWER_UP = 'AGENT_EVENT_GO_POWER_DOWN'
GO_POWER_DOWN = 'AGENT_EVENT_GO_POWER_UP'
INITIALIZE = 'AGENT_EVENT_INITIALIZE'
RESET = 'AGENT_EVENT_RESET'
GO_ACTIVE = 'AGENT_EVENT_GO_ACTIVE'
GO_INACTIVE = 'AGENT_EVENT_GO_INACTIVE'
CLEAR = 'AGENT_EVENT_CLEAR'
RESUME = 'AGENT_EVENT_RESUME'
RUN = 'AGENT_EVENT_RUN'
PAUSE = 'AGENT_EVENT_PAUSE'
GO_OBSERVATORY_MODE = 'AGENT_EVENT_GO_OBSERVATORY_MODE'
GO_DIRECT_ACCESS_MODE = 'AGENT_EVENT_GO_DIRECT_ACCESS_MODE'
ENTER = 'AGENT_EVENT_ENTER'
EXIT = 'AGENT_EVENT_EXIT'
class AgentCommand(BaseEnum):
""" Common agent commands enum"""
TRANSITION = 'AGENT_CMD_TRANSITION'
TRANSMIT_DATA = 'AGENT_CMD_TRANSMIT_DATA'
SLEEP = 'AGENT_CMD_SLEEP'
class AgentParameter(BaseEnum):
"""Common agent parameters"""
EVENT_PUBLISHER_ORIGIN = 'AGENT_PARAM_EVENT_PUBLISHER_ORIGIN'
TIME_SOURCE = 'AGENT_PARAM_TIME_SOURCE'
CONNECTION_METHOD = 'AGENT_PARAM_CONNECTION_METHOD'
MAX_ACQ_TIMEOUT = 'AGENT_PARAM_MAX_ACQ_TIMEOUT'
DEFAULT_EXP_TIMEOUT = 'AGENT_PARAM_DEFAULT_EXP_TIMEOUT'
MAX_EXP_TIMEOUT = 'AGENT_PARAM_MAX_EXP_TIMEOUT'
DRIVER_DESC = 'AGENT_PARAM_DRIVER_DESC'
DRIVER_CLIENT_DESC = 'AGENT_PARAM_DRIVER_CLIENT_DESC'
DRIVER_CONFIG = 'AGENT_PARAM_DRIVER_CONFIG'
BUFFER_SIZE = 'AGENT_PARAM_BUFFER_SIZE'
ALL = 'AGENT_PARAM_ALL'
class AgentStatus(BaseEnum):
"""Common agent status enum"""
AGENT_STATE = 'AGENT_STATUS_AGENT_STATE'
CONNECTION_STATE = 'AGENT_STATUS_CONNECTION_STATE'
ALARMS = 'AGENT_STATUS_ALARMS'
TIME_STATUS = 'AGENT_STATUS_TIME_STATUS'
BUFFER_SIZE = 'AGENT_STATUS_BUFFER_SIZE'
AGENT_VERSION = 'AGENT_STATUS_AGENT_VERSION'
PENDING_TRANSACTIONS = 'AGENT_STATUS_PENDING_TRANSACTIONS'
ALL = 'AGENT_STATUS_ALL'
class AgentConnectionState(BaseEnum):
"""Common agent connection state enum.
Possible states of connection/disconnection an agent may be in, among the
shore and wet side agent, the driver and the hardware iteself.
"""
REMOTE_DISCONNECTED = 'AGENT_CONNECTION_STATE_REMOTE_DISCONNECTED'
POWERED_DOWN = 'AGENT_CONNECTION_STATE_POWERED_DOWN'
NO_DRIVER = 'AGENT_CONNECTION_STATE_NO_DRIVER'
DISCONNECTED = 'AGENT_CONNECTION_STATE_DISCONNECTED'
CONNECTED = 'AGENT_CONNECTION_STATE_CONNECTED'
UNKOWN = 'AGENT_CONNECTION_STATE_UNKNOWN'
class Datatype(BaseEnum):
"""Common agent parameter and metadata types"""
DATATYPE = 'TYPE_DATATYPE' # This type.
INT = 'TYPE_INT' # int.
FLOAT = 'TYPE_FLOAT' # float.
BOOL = 'TYPE_BOOL' # bool.
STRING = 'TYPE_STRING' # str.
INT_RANGE = 'TYPE_INT_RANGE' # (int,int).
FLOAT_RANGE = 'TYPE_FLOAT_RANGE' # (float,float).
TIMESTAMP = 'TYPE_TIMESTAMP' # (int seconds,int nanoseconds).
TIME_DURATION = 'TYPE_TIME_DURATION' # TBD.
PUBSUB_TOPIC_DICT = 'TYPE_PUBSUB_TOPIC_DICT' # dict of topic strings.
RESOURCE_ID = 'TYPE_RESOURCE_ID' # str (possible validation).
ADDRESS = 'TYPE_ADDRESS' # str (possible validation).
ENUM = 'TYPE_ENUM' # str with valid values.
PUBSUB_ORIGIN = 'TYPE_PUBSUB_ORIGIN'
"""
@todo Used by the existing drivers...need to fix.
"""
publish_msg_type = {
'Error':'Error',
'StateChange':'StateChange',
'ConfigChange':'ConfigChange',
'Data':'Data',
'Event':'Event'
}
driver_client = "PLACEHOLDER"
class DriverAnnouncement(BaseEnum):
"""Common publish message type enum"""
ERROR = 'DRIVER_ANNOUNCEMENT_ERROR'
STATE_CHANGE = 'DRIVER_ANNOUNCEMENT_STATE_CHANGE'
CONFIG_CHANGE = 'DRIVER_ANNOUNCEMENT_CONIFG_CHANGE'
DATA_RECEIVED = 'DRIVER_ANNOUNCEMENT_DATA_RECEIVED'
EVENT_OCCURRED = 'DRIVER_ANNOUNCEMENT_EVENT_OCCURRED'
class TimeSource(BaseEnum):
"""Common time source enum for the device fronted by the agent"""
NOT_SPECIFIED = 'TIME_SOURCE_NOT_SPECIFIED'
PTP_DIRECT = 'TIME_SOURCE_PTP_DIRECT' # IEEE 1588 PTP connection directly supported.
NTP_UNICAST = 'TIME_SOURCE_NTP_UNICAST' # NTP unicast to the instrument.
NTP_BROADCAST = 'TIME_SOURCE_NTP_BROADCAST' # NTP broadcast to the instrument.
LOCAL_OSCILLATOR = 'TIME_SOURCE_LOCAL_OSCILLATOR' # Device has own clock.
DRIVER_SET_INTERVAL = 'TIME_SOURCE_DRIVER_SET_INTERVAL' # Driver sets clock at interval.
class ConnectionMethod(BaseEnum):
"""Common connection method to agent and device enum"""
NOT_SPECIFIED = 'CONNECTION_METHOD_NOT_SPECIFIED'
OFFLINE = 'CONNECTION_METHOD_OFFLINE'
CABLED_OBSERVATORY = 'CONNECTION_METHOD_CABLED_OBSERVATORY'
SHORE_NETWORK = 'CONNECTION_METHOD_SHORE_NETWORK'
PART_TIME_SCHEDULED = 'CONNECTION_METHOD_PART_TIME_SCHEDULED'
PART_TIME_RANDOM = 'CONNECTION_METHOD_PART_TIME_RANDOM'
class AlarmType(BaseEnum):
"""Common agent observatory alarm enum"""
CANNOT_PUBLISH = ('ALARM_CANNOT_PUBLISH','Attempted to publish but cannot.')
INSTRUMENT_UNREACHABLE = ('ALARM_INSTRUMENT_UNREACHABLE',
'Instrument cannot be contacted when it should be.')
MESSAGING_ERROR = ('ALARM_MESSAGING_ERROR','Error when sending messages.')
HARDWARE_ERROR = ('ALARM_HARDWARE_ERROR','Hardware problem detected.')
UNKNOWN_ERROR = ('ALARM_UNKNOWN_ERROR','An unknown error has occurred.')
class ObservatoryCapability(BaseEnum):
"""Common agent observatory capabilies enum"""
OBSERVATORY_COMMANDS = 'CAP_OBSERVATORY_COMMANDS'
OBSERVATORY_PARAMS = 'CAP_OBSERVATORY_PARAMS'
OBSERVATORY_STATUSES = 'CAP_OBSERVATORY_STATUSES'
OBSERVATORY_METADATA = 'CAP_OBSERVATORY_METADATA'
OBSERVATORY_ALL = 'CAP_OBSERVATORY_ALL'
class DriverCapability(BaseEnum):
"""Common device capabilities enum"""
DEVICE_METADATA = 'CAP_DEVICE_METADATA'
DEVICE_COMMANDS = 'CAP_DEVICE_COMMANDS'
DEVICE_PARAMS = 'CAP_DEVICE_PARAMS'
DEVICE_STATUSES = 'CAP_DEVICE_STATUSES'
DEVICE_CHANNELS = 'CAP_DEVICE_CHANNELS'
DEVICE_ALL = 'CAP_DEVICE_ALL'
class InstrumentCapability(ObservatoryCapability,DriverCapability):
"""Comination of agent and device capabilities enum"""
ALL = 'CAP_ALL'
class MetadataParameter(BaseEnum):
"""Common metadata parameter names enum"""
DATATYPE = 'META_DATATYPE'
PHYSICAL_PARAMETER_TYPE = 'META_PHYSICAL_PARAMETER_TYPE'
MINIMUM_VALUE = 'META_MINIMUM_VALUE'
MAXIMUM_VALUE = 'META_MAXIMUM_VALUE'
UNITS = 'META_UNITS'
UNCERTAINTY = 'META_UNCERTAINTY'
LAST_CHANGE_TIMESTAMP = 'META_LAST_CHANGE_TIMESTAMP'
WRITABLE = 'META_WRITABLE'
VALID_VALUES = 'META_VALID_VALUES'
FRIENDLY_NAME = 'META_FRIENDLY_NAME'
DESCRIPTION = 'META_DESCRIPTION'
ALL = 'META_ALL'
class EventKey(BaseEnum):
"""Keys to the event dictionary fields as used by the InstrumentProtocol
and InstrumentDriver classes.
"""
TYPE = 'type'
ERROR_CODE = 'error_code'
MESSAGE = 'message'
###############################################################################
# Error constants.
##############################################################################
class InstErrorCode(BaseEnum):
"""Error codes generated by instrument drivers and agents"""
OK = ['OK']
INVALID_DESTINATION = ['ERROR_INVALID_DESTINATION','Intended destination for a message or operation is not valid.']
TIMEOUT = ['ERROR_TIMEOUT','The message or operation timed out.']
NETWORK_FAILURE = ['ERROR_NETWORK_FAILURE','A network failure has been detected.']
NETWORK_CORRUPTION = ['ERROR_NETWORK_CORRUPTION','A message passing through the network has been determined to be corrupt.']
OUT_OF_MEMORY = ['ERROR_OUT_OF_MEMORY','There is no more free memory to complete the operation.']
LOCKED_RESOURCE = ['ERROR_LOCKED_RESOURCE','The resource being accessed is in use by another exclusive operation.']
RESOURCE_NOT_LOCKED = ['ERROR_RESOURCE_NOT_LOCKED','Attempted to unlock a free resource.']
RESOURCE_UNAVAILABLE = ['ERROR_RESOURCE_UNAVAILABLE','The resource being accessed is unavailable.']
TRANSACTION_REQUIRED = ['ERROR_TRANSACTION_REQUIRED','The operation requires a transaction with the agent.']
UNKNOWN_ERROR = ['ERROR_UNKNOWN_ERROR','An unknown error has been encountered.']
PERMISSION_ERROR = ['ERROR_PERMISSION_ERROR','The user does not have the correct permission to access the resource in the desired way.']
INVALID_TRANSITION = ['ERROR_INVALID_TRANSITION','The transition being requested does not apply for the current state.']
INCORRECT_STATE = ['ERROR_INCORRECT_STATE','The operation being requested does not apply to the current state.']
UNKNOWN_EVENT = ['ERROR_UNKNOWN_EVENT','The event is not defined for this driver.']
UNHANDLED_EVENT = ['ERROR_UNHANDLED_EVENT','The event was not handled by the state.']
UNKNOWN_TRANSITION = ['ERROR_UNKNOWN_TRANSITION','The specified state transition does not exist.']
CANNOT_PUBLISH = ['ERROR_CANNOT_PUBLISH','An attempt to publish has failed.']
INSTRUMENT_UNREACHABLE = ['ERROR_INSTRUMENT_UNREACHABLE','The agent cannot communicate with the device.']
MESSAGING_ERROR = ['ERROR_MESSAGING_ERROR','An error has been encountered during a messaging operation.']
HARDWARE_ERROR = ['ERROR_HARDWARE_ERROR','An error has been encountered with a hardware element.']
WRONG_TYPE = ['ERROR_WRONG_TYPE','The type of operation is not valid in the current state.']
INVALID_COMMAND = ['ERROR_INVALID_COMMAND','The command is not valid in the given context.']
UNKNOWN_COMMAND = ['ERROR_UNKNOWN_COMMAND','The command is not recognized.']
UNKNOWN_CHANNEL = ['ERROR_UNKNOWN_CHANNEL','The channel is not recognized.']
INVALID_CHANNEL = ['ERROR_INVALID_CHANNEL','The channel is not valid for the requested command.']
NOT_IMPLEMENTED = ['ERROR_NOT_IMPLEMENTED','The command is not implemented.']
INVALID_TRANSACTION_ID = ['ERROR_INVALID_TRANSACTION_ID','The transaction ID is not a valid value.']
INVALID_DRIVER = ['ERROR_INVALID_DRIVER','Driver or driver client invalid.']
GET_OBSERVATORY_ERR = ['ERROR_GET_OBSERVATORY','Could not retrieve all parameters.']
EXE_OBSERVATORY_ERR = ['ERROR_EXE_OBSERVATORY','Could not execute observatory command.']
SET_OBSERVATORY_ERR = ['ERROR_SET_OBSERVATORY','Could not set all parameters.']
PARAMETER_READ_ONLY = ['ERROR_PARAMETER_READ_ONLY','Parameter is read only.']
INVALID_PARAMETER = ['ERROR_INVALID_PARAMETER','The parameter is not available.']
REQUIRED_PARAMETER = ['ERROR_REQUIRED_PARAMETER','A required parameter was not specified.']
INVALID_PARAM_VALUE = ['ERROR_INVALID_PARAM_VALUE','The parameter value is out of range.']
INVALID_METADATA = ['ERROR_INVALID_METADATA','The metadata parameter is not available.']
NO_PARAM_METADATA = ['ERROR_NO_PARAM_METADATA','The parameter has no associated metadata.']
INVALID_STATUS = ['ERROR_INVALID_STATUS','The status parameter is not available.']
INVALID_CAPABILITY = ['ERROR_INVALID_CAPABILITY','The capability parameter is not available.']
BAD_DRIVER_COMMAND = ['ERROR_BAD_DRIVER_COMMAND','The driver did not recognize the command.']
EVENT_NOT_HANDLED = ['ERROR_EVENT_NOT_HANDLED','The current state did not handle a received event.']
GET_DEVICE_ERR = ['ERROR_GET_DEVICE','Could not retrieve all parameters from the device.']
EXE_DEVICE_ERR = ['ERROR_EXE_DEVICE','Could not execute device command.']
SET_DEVICE_ERR = ['ERROR_SET_DEVICE','Could not set all device parameters.']
ACQUIRE_SAMPLE_ERR = ['ERROR_ACQUIRE_SAMPLE','Could not acquire a data sample.']
DRIVER_NOT_CONFIGURED = ['ERROR_DRIVER_NOT_CONFIGURED','The driver could not be configured.']
DISCONNECT_FAILED = ['ERROR_DISCONNECT_FAILED','The driver could not be properly disconnected.']
AGENT_INIT_FAILED = ['ERROR_AGENT_INIT_FAILED','The agent could not be initialized.']
AGENT_DEINIT_FAILED = ['ERROR_AGENT_DEINIT_FAILED','The agent could not be deinitialized.']
DRIVER_CONNECT_FAILED = ['ERROR_DRIVER_CONNECT_FAILED','The agent could not connect to the driver.']
DRIVER_DISCONNECT_FAILED = ['ERROR_DRIVER_DISCONNECT_FAILED_FAILED','The agent could not disconnect to the driver.']
INVALID_STATUS = ['ERROR_INVALID_STATUS','The given argument is not a valid status key.']
@classmethod
def is_ok(cls,x):
"""Success test functional synonym. Will need iterable type checking
if success codes get additional info in the future.
@param x a str, tuple or list to match to an error code success value.
@retval True if x is a success value, False otherwise.
"""
try:
x = cls.get_list_val(x)
except AssertionError:
return False
return x == cls.OK
@classmethod
def is_error(cls,x):
"""Generic error test.
@param x a str, tuple or list to match to an error code error value.
@retval True if x is an error value, False otherwise.
"""
try:
x = cls.get_list_val(x)
except AssertionError:
return False
return (cls.has(x) and x != cls.OK)
@classmethod
def is_equal(cls,val1,val2):
"""Compare error codes.
Used so we are insulated against the framework
converting error codes to tuples or other iterables.
@param val1 str, tuple or list matching an error code value.
@param val2 str, tuple or list matching an error code value.
@retval True if val1 and val2 are equal and defined, False otherwise.
"""
val1 = cls.get_list_val(val1)
val2 = cls.get_list_val(val2)
return cls.has(val1) and cls.has(val2) and (val1 == val2)
@classmethod
def get_list_val(cls,x):
"""Convert error code values to lists.
The messaging framework can convert lists to tuples. Allow for simple
strings to be compared also.
"""
assert(isinstance(x,(str,tuple,list))), 'Expected a str, tuple or list \
error code value.'
# Object is a list, return unmodified.
if isinstance(x,list):
return x
# Object is a string, return length 1 list with string as the value.
elif isinstance(x,str):
return list((x,))
# Object is a tuple, return a tuple with same elements.
else:
return list(x)
@classmethod
def get_string(cls,x):
"""Convert an error code to a printable string"""
x = cls.get_list_val(x)
if cls.has(x):
strval = ''
for item in x:
strval += str(item) + ', '
strval = strval[:-2]
return strval
else:
return None<file_sep>/ion/services/mi/drivers/uw_bars/README.txt
Driver code for the UW TRHPH BARS instrument
============================================
The real instrument was made accessible on 10.180.80.172 port 2001.
Our code assumes the BARS Program Version 1.7 - Last Revision: July 11, 2011
(or one with similar interaction characteristics) is running on the other side
of the communication. The real_bars_interaction.txt file captures a typical
interaction (via telnet).
Some preliminary programs
-------------------------
The following programs do a direct TCP connection with the instrument and were
mainly intended to examine actual interactions and eventually serve as a basis
for the actual implementation
* test/direct.py
Simple program for direct user iteraction with the instrument:
$ bin/python ion/services/mi/drivers/uw_bars/test/direct.py 10.180.80.172 2001
See source code for details.
* bars_client.py
Class BarsClient does a direct communication with the instrument while
allowing some high-level operations (eg., is_collecting_data, enter_main_menu,
expect_generic_prompt).
The demo program is a complete script (no user interaction needed) involving:
check for data collection, break to main menu, see system info, and resume
data collection:
$ bin/python ion/services/mi/drivers/uw_bars/bars_client.py \
--host 10.180.80.172 --port 2001 --outfile output.txt --loglevel debug
DEBUG bars_client 5988 MainThread - ### connecting to 10.180.80.172:2001
DEBUG bars_client 5988 _Recv - ### _Recv running.
:: is instrument collecting data?
DEBUG bars_client 5988 MainThread - ### is_collecting_data? ...
:: Instrument is collecting data.
:: break data streaming to enter main menu
DEBUG bars_client 5988 MainThread - ### automatic ^S
DEBUG bars_client 5988 MainThread - ### sending ^S
DEBUG bars_client 5988 MainThread - ### sending ^S
DEBUG bars_client 5988 MainThread - ### sending ^S
DEBUG bars_client 5988 MainThread - ### sending ^S
DEBUG bars_client 5988 MainThread - ### sending ^S
DEBUG bars_client 5988 MainThread - ### sending ^S
DEBUG bars_client 5988 MainThread - ### sending ^S
DEBUG bars_client 5988 MainThread - ### got prompt. Sending one ^m to clean up any ^S leftover
:: select 6 to get system info
DEBUG bars_client 5988 MainThread - ### send: '6'
DEBUG bars_client 5988 MainThread - ### expecting '.*--> '
:: send enter to return to main menu
DEBUG bars_client 5988 MainThread - ### send_enter
DEBUG bars_client 5988 MainThread - ### expecting '.*--> '
:: resume data streaming
DEBUG bars_client 5988 MainThread - ### send: '1'
:: sleeping for 10 secs to receive some data
:: bye
* test/expect.py
A simple program exercising the pexpect library to communicate with the BARS
instrument. It works fine with an immediate pexpect.spawn.interact call
(basically emulating a telnet session) but further investigation would be
needed for programmatic interaction in case we wanted a pexpect-based
implementation for the driver.
* test/bars_simulator.py
A partial simulator for the BARS instrument intended to facilitate testing.
It accepts a TCP connection on a port and starts by sending out bursts of
random data every few seconds. By default it binds the service to an
automatically assigned port.
It accepts multiple clients but in sequential order.
$ bin/python ion/services/mi/drivers/uw_bars/test/bars_simulator.py
|* [1]BarsSimulator: bound to port 53922
|* [1]BarsSimulator: ---waiting for connection---
Using MI core classes
---------------------
<file_sep>/ion/services/mi/drivers/uw_bars/test/test_protocol.py
#!/usr/bin/env python
__author__ = "<NAME>"
__license__ = 'Apache 2.0'
from ion.services.mi.drivers.uw_bars.test.pyon_test import PyonBarsTestCase
from ion.services.mi.drivers.uw_bars.protocol import BarsInstrumentProtocol
from ion.services.mi.drivers.uw_bars.protocol import BarsProtocolState
import time
from nose.plugins.attrib import attr
from unittest import skip
@skip('not yet easy to test protocol in isolation')
@attr('UNIT', group='mi')
class ProtocolTest(PyonBarsTestCase):
def test(self):
"""
BARS protocol tests
"""
protocol = BarsInstrumentProtocol()
self.assertEqual(BarsProtocolState.PRE_INIT,
protocol.get_current_state())
protocol.initialize()
protocol.configure(self.config)
protocol.connect()
self.assertEqual(BarsProtocolState.COLLECTING_DATA,
protocol.get_current_state())
print "sleeping for a bit"
time.sleep(5)
print "disconnecting"
protocol.disconnect()
<file_sep>/ion/services/mi/drivers/uw_bars/test/bars_simulator.py
#!/usr/bin/env python
"""
@package ion.services.mi.drivers.test.bars_simulator
@file ion/services/mi/drivers/test/bars_simulator.py
@author <NAME>
@brief A partial simulator for the BARS instrument intended to facilitate
testing.
It accepts a TCP connection on a port and starts by sending out bursts of
random data every few seconds. By default it binds the service to an
automatically assigned port.
It accepts multiple clients but in sequential order.
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import ion.services.mi.drivers.uw_bars.bars as bars
import socket
import random
import time
import sys
from threading import Thread
NEWLINE = '\r\n'
EOF = '\x04'
CONTROL_S = '\x13'
time_between_bursts = 2
def _escape(str):
str = str.replace('\r', '\\r')
str = str.replace('\n', '\\n')
str = str.replace(EOF, '^D')
s = ''
for c in str:
o = ord(c)
if o < 32 or (127 <= o < 160):
s += '\\%02d' % o
else:
s += c
str = s
return str
class _BurstThread(Thread):
"""Thread to generate data bursts"""
def __init__(self, conn, log_prefix, outfile=sys.stdout):
Thread.__init__(self, name="_BurstThread")
self._outfile = outfile
self._conn = conn
self._running = True
self._enabled = True
self._log_prefix = log_prefix
def _log(self, m):
self._outfile.write("%s_BurstThread: %s\n" % (self._log_prefix, m))
self._outfile.flush()
def run(self):
self._log("burst thread running")
time_next_burst = time.time() # just now
while self._running:
if self._enabled:
if time.time() >= time_next_burst:
values = self._generate_burst()
reply = "%s%s" % (" ".join(values), NEWLINE)
self._conn.sendall(reply)
time_next_burst = time.time() + time_between_bursts
time.sleep(0.2)
self._log("burst thread exiting")
def set_enabled(self, enabled):
self._log("set_enabled: %s" % str(enabled))
self._enabled = enabled
def end(self):
self._log("end")
self._enabled = False
self._running = False
def _generate_burst(self):
values = []
for i in range(12):
r = random.random()
values.append("%.3f" % r)
return values
class BarsSimulator(Thread):
"""
Dispatches multiple clients but sequentially. The special command
'q' can be requested by a client to make the whole simulator terminate.
"""
_next_simulator_no = 0
def __init__(self, host='', port=0, accept_timeout=None,
outfile=sys.stdout,
log_prefix='\t\t\t\t|* '):
"""
@param host Socket is bound to given (host,port)
@param port Socket is bound to given (host,port)
@param accept_timeout Timeout for accepting a connection
@param log_prefix a prefix for every log message
"""
Thread.__init__(self, name="BarsSimulator")
self._outfile = outfile
BarsSimulator._next_simulator_no += 1
self._simulator_no = BarsSimulator._next_simulator_no
self._client_no = 0
self._log_prefix = log_prefix
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.bind((host, port))
self._sock.listen(1)
self._accept_timeout = accept_timeout
self._port = self._sock.getsockname()[1]
self._log("bound to port %s" % self._port)
self._bt = None
self._cycle_time = "20"
self._cycle_time_units = "Seconds"
self._verbose_vs_data_only = "Data Only"
def _log_client(self, m):
self._outfile.write("%s[%d.%d] BarsSimulator: %s\n" %
(self._log_prefix,
self._simulator_no,
self._client_no,
m))
self._outfile.flush()
def _log(self, m):
self._outfile.write("%s[%d]BarsSimulator: %s\n" %
(self._log_prefix,
self._simulator_no,
m))
self._outfile.flush()
@property
def port(self):
return self._port
def run(self):
try:
self._run()
finally:
self._end_burst_thread()
def _run(self):
#
# internal timeout for the accept. It allows to check regularly if
# the simulator has been requested to terminate.
#
self._sock.settimeout(0.2)
self._enabled = True
explicit_quit = False
while self._enabled and not explicit_quit:
if self._accept_timeout is not None:
accept_time_limit = time.time() + self._accept_timeout
self._log('---waiting for connection---')
while self._enabled:
try:
self._conn, addr = self._sock.accept()
break # connected
except socket.timeout:
if self._accept_timeout is not None and \
time.time() > accept_time_limit:
# real timeout
self._log("accept timeout. Simulator stopping")
return
if not self._enabled:
break
self._client_no += 1
self._log_client('Connected by %s' % str(addr))
self._bt = _BurstThread(self._conn, self._log_prefix,
outfile=self._outfile)
self._bt.start()
explicit_quit = self._connected()
self._end_burst_thread()
self._conn.close()
self._log("bye.")
time.sleep(1)
self._sock.close()
def _end_burst_thread(self):
self._log_client('end burst thread %s' % str(self._bt))
self._bt, bt = None, self._bt
if bt is not None:
bt.end()
bt.join()
def stop(self):
"""Requests that the simulator terminate"""
self._enabled = False
self._log("simulator requested to stop.")
def _clear_screen(self, info):
clear_screen = NEWLINE * 20
info = info.replace('\n', NEWLINE)
self._conn.sendall(clear_screen + info)
def _recv(self):
"""
does the recv call with handling of timeout
"""
while self._enabled:
try:
input = None
recv = self._conn.recv(4096)
if recv is not None:
self._log_client("RECV: '%s'" % _escape(recv))
if EOF == recv:
self._enabled = False
break
if '\r' == recv:
input = recv
elif len(recv.strip()) > 0:
input = recv.strip()
else:
input = recv
else:
self._log_client("RECV: None")
if input is not None:
self._log_client("input: '%s'" % _escape(input))
return input
except socket.timeout:
# ok, retry receiving
continue
except Exception as e:
self._log_client("!!!!! %s " % str(e))
break
return None
def _connected(self):
"""
Dispatches the main initial state which is streaming data.
@relval True if an explicit quit command ('q') was received;
False otherwise.
"""
# set an ad hoc timeout to regularly check whether termination has been
# requested
self._conn.settimeout(1.0)
while self._enabled:
input = self._recv()
if not self._enabled:
break
if not input:
break
if input == "q":
self._log_client("exiting connected, explicit quit request")
return True # explicit quit
if input == CONTROL_S:
self._bt.set_enabled(False)
self._main_menu()
else:
response = "invalid input: '%s'" % _escape(input)
self._log_client(response)
self._log_client("exiting connected")
return False
def _main_menu(self):
menu = bars.MAIN_MENU
while self._enabled:
self._clear_screen(menu)
input = self._recv()
if not self._enabled:
break
if not input:
break
if input == "0":
self._print_date_time()
elif input == "1":
self._restart_data_collection()
break
elif input == "2":
self._change_params_menu()
elif input == "3":
self._diagnostics()
elif input == "4":
self._reset_clock()
elif input == "5":
self._sensor_power_menu()
elif input == "6":
self._system_info()
elif input == "7":
self._log_client("exit program -- IGNORED")
pass
else:
# just continue
continue
self._log_client("exiting _main_menu so resuming data collection")
def _print_date_time(self):
# TODO print date time
self._conn.sendall("TODO date time" + NEWLINE)
def _restart_data_collection(self):
"""restarts data collection"""
self._bt.set_enabled(True)
def _change_params_menu(self):
while self._enabled:
menu = bars.SYSTEM_PARAMETER_MENU_FORMAT % (
self._cycle_time, self._cycle_time_units,
self._verbose_vs_data_only
)
self._clear_screen(menu)
input = self._recv()
if not self._enabled:
break
if not input:
break
if input == "0":
pass
elif input == "1":
self._change_cycle_time()
continue
elif input == "2":
# TODO change verbose setting
break
elif input == "3":
break
else:
# just continue
continue
self._log_client("exiting _change_params_menu")
def _change_cycle_time(self):
menu = bars.CHANGE_CYCLE_TIME
while self._enabled:
self._clear_screen(menu)
input = self._recv()
if not self._enabled:
break
if not input:
break
if input in ["0", "1"]:
if input == "0": # enter seconds
self._conn.sendall(bars.CHANGE_CYCLE_TIME_IN_SECONDS)
units = "Seconds"
else: # enter minutes
self._conn.sendall(bars.CHANGE_CYCLE_TIME_IN_MINUTES)
units = "Minutes"
input = self._recv()
value = int(input)
self._cycle_time = value
self._cycle_time_units = units
break
else:
# just continue
continue
self._log_client("exiting _change_cycle_time")
def _diagnostics(self):
# TODO diagnostics
self._conn.sendall("TODO diagnostics" + NEWLINE)
def _reset_clock(self):
# TODO reset clock
self._conn.sendall("TODO reset clock" + NEWLINE)
def _system_info(self):
info = bars.SYSTEM_INFO
while self._enabled:
self._clear_screen(info)
input = self._recv()
if not self._enabled:
break
if not input:
break
if input == "\r":
break
else:
# just continue
continue
self._log_client("exiting _system_info")
def _sensor_power_menu(self):
menu = bars.SENSOR_POWER_CONTROL_MENU
while self._enabled:
self._clear_screen(menu)
input = self._recv()
if not self._enabled:
break
if not input:
break
if input == "0":
pass
elif input == "1":
# TODO Toggle Power to Res Sensor.
break
elif input == "2":
# TODO Toggle Power to the Instrumentation Amp.
break
elif input == "3":
# TODO Toggle Power to the eH Isolation Amp.
break
elif input == "4":
# TODO Toggle Power to the Hydrogen Sensor.
break
elif input == "5":
# TODO Toggle Power to the Reference Temperature Sensor.
break
elif input == "6":
break
else:
# just continue
continue
self._log_client("exiting _sensor_power_menu")
if __name__ == '__main__':
usage = """USAGE: bars_simulator.py [options]
--port port # port to bind to (0 by default)
--accept_timeout time # accept timeout (no timeout by default)
--outfile filename # file to write messages to (stdout by default)
--loglevel level # used to eval mi_logger.setLevel(logging.%s)
Output will show actual port used.
"""
accept_timeout = None
port = 0
outfile = sys.stdout
show_usage = False
arg = 1
while arg < len(sys.argv):
if sys.argv[arg] == "--accept_timeout":
arg += 1
accept_timeout = int(sys.argv[arg])
elif sys.argv[arg] == "--port":
arg += 1
port = int(sys.argv[arg])
elif sys.argv[arg] == "--outfile":
arg += 1
outfile = file(sys.argv[arg], 'w')
elif sys.argv[arg] == "--loglevel":
arg += 1
loglevel = sys.argv[arg].upper()
import logging
mi_logger = logging.getLogger('mi_logger')
eval("mi_logger.setLevel(logging.%s)" % loglevel)
elif sys.argv[arg] == "--help":
show_usage = True
break
else:
sys.stderr.write("error: unrecognized option %s\n" % sys.argv[arg])
sys.stderr.flush()
show_usage = True
break
arg += 1
if show_usage:
print usage
else:
simulator = BarsSimulator(port=port,
accept_timeout=accept_timeout,
outfile=outfile)
simulator.run()
<file_sep>/ion/services/sa/instrument/instrument_management_service.py
#!/usr/bin/env python
"""
@package ion.services.sa.instrument.instrument_management_service
@author <NAME>
@author <NAME>
"""
#from pyon.public import Container
from pyon.public import LCS #, LCE
from pyon.public import RT, PRED
from pyon.core.bootstrap import IonObject
from pyon.core.exception import Inconsistent,BadRequest #, NotFound
#from pyon.datastore.datastore import DataStore
#from pyon.net.endpoint import RPCClient
from pyon.util.log import log
from ion.services.sa.resource_impl.instrument_agent_impl import InstrumentAgentImpl
from ion.services.sa.resource_impl.instrument_agent_instance_impl import InstrumentAgentInstanceImpl
from ion.services.sa.resource_impl.instrument_model_impl import InstrumentModelImpl
from ion.services.sa.resource_impl.instrument_device_impl import InstrumentDeviceImpl
from ion.services.sa.resource_impl.platform_agent_impl import PlatformAgentImpl
from ion.services.sa.resource_impl.platform_agent_instance_impl import PlatformAgentInstanceImpl
from ion.services.sa.resource_impl.platform_model_impl import PlatformModelImpl
from ion.services.sa.resource_impl.platform_device_impl import PlatformDeviceImpl
from ion.services.sa.resource_impl.sensor_model_impl import SensorModelImpl
from ion.services.sa.resource_impl.sensor_device_impl import SensorDeviceImpl
# TODO: these are for methods which may belong in DAMS/DPMS/MFMS
from ion.services.sa.resource_impl.data_product_impl import DataProductImpl
from ion.services.sa.resource_impl.data_producer_impl import DataProducerImpl
from ion.services.sa.resource_impl.logical_instrument_impl import LogicalInstrumentImpl
from interface.services.sa.iinstrument_management_service import BaseInstrumentManagementService
class InstrumentManagementService(BaseInstrumentManagementService):
"""
@brief Service to manage instrument, platform, and sensor resources, their relationships, and direct access
"""
def on_init(self):
#suppress a few "variable declared but not used" annoying pyflakes errors
IonObject("Resource")
log
self.override_clients(self.clients)
def override_clients(self, new_clients):
"""
Replaces the service clients with a new set of them... and makes sure they go to the right places
"""
#shortcut names for the import sub-services
# we hide these behind checks even though we expect them so that
# the resource_impl_metatests will work
if hasattr(self.clients, "resource_registry"):
self.RR = self.clients.resource_registry
if hasattr(self.clients, "data_acquisition_management"):
self.DAMS = self.clients.data_acquisition_management
if hasattr(self.clients, "data_product_management"):
self.DPMS = self.clients.data_product_management
#farm everything out to the impls
self.instrument_agent = InstrumentAgentImpl(self.clients)
self.instrument_agent_instance = InstrumentAgentInstanceImpl(self.clients)
self.instrument_model = InstrumentModelImpl(self.clients)
self.instrument_device = InstrumentDeviceImpl(self.clients)
self.platform_agent = PlatformAgentImpl(self.clients)
self.platform_agent_instance = PlatformAgentInstanceImpl(self.clients)
self.platform_model = PlatformModelImpl(self.clients)
self.platform_device = PlatformDeviceImpl(self.clients)
self.sensor_model = SensorModelImpl(self.clients)
self.sensor_device = SensorDeviceImpl(self.clients)
#TODO: may not belong in this service
self.data_product = DataProductImpl(self.clients)
self.data_producer = DataProducerImpl(self.clients)
self.logical_instrument = LogicalInstrumentImpl(self.clients)
##########################################################################
#
# INSTRUMENT AGENT INSTANCE
#
##########################################################################
def create_instrument_agent_instance(self, instrument_agent_instance=None):
"""
create a new instance
@param instrument_agent_instance the object to be created as a resource
@retval instrument_agent_instance_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.instrument_agent_instance.create_one(instrument_agent_instance)
def update_instrument_agent_instance(self, instrument_agent_instance=None):
"""
update an existing instance
@param instrument_agent_instance the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.instrument_agent_instance.update_one(instrument_agent_instance)
def read_instrument_agent_instance(self, instrument_agent_instance_id=''):
"""
fetch a resource by ID
@param instrument_agent_instance_id the id of the object to be fetched
@retval InstrumentAgentInstance resource
"""
return self.instrument_agent_instance.read_one(instrument_agent_instance_id)
def delete_instrument_agent_instance(self, instrument_agent_instance_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param instrument_agent_instance_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.instrument_agent_instance.delete_one(instrument_agent_instance_id)
def find_instrument_agent_instances(self, filters=None):
"""
"""
return self.instrument_agent_instance.find_some(filters)
##########################################################################
#
# INSTRUMENT AGENT
#
##########################################################################
def create_instrument_agent(self, instrument_agent=None):
"""
create a new instance
@param instrument_agent the object to be created as a resource
@retval instrument_agent_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.instrument_agent.create_one(instrument_agent)
def update_instrument_agent(self, instrument_agent=None):
"""
update an existing instance
@param instrument_agent the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.instrument_agent.update_one(instrument_agent)
def read_instrument_agent(self, instrument_agent_id=''):
"""
fetch a resource by ID
@param instrument_agent_id the id of the object to be fetched
@retval InstrumentAgent resource
"""
return self.instrument_agent.read_one(instrument_agent_id)
def delete_instrument_agent(self, instrument_agent_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param instrument_agent_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.instrument_agent.delete_one(instrument_agent_id)
def find_instrument_agents(self, filters=None):
"""
"""
return self.instrument_agent.find_some(filters)
##########################################################################
#
# INSTRUMENT MODEL
#
##########################################################################
def create_instrument_model(self, instrument_model=None):
"""
create a new instance
@param instrument_model the object to be created as a resource
@retval instrument_model_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.instrument_model.create_one(instrument_model)
def update_instrument_model(self, instrument_model=None):
"""
update an existing instance
@param instrument_model the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.instrument_model.update_one(instrument_model)
def read_instrument_model(self, instrument_model_id=''):
"""
fetch a resource by ID
@param instrument_model_id the id of the object to be fetched
@retval InstrumentModel resource
"""
return self.instrument_model.read_one(instrument_model_id)
def delete_instrument_model(self, instrument_model_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param instrument_model_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.instrument_model.delete_one(instrument_model_id)
def find_instrument_models(self, filters=None):
"""
"""
return self.instrument_model.find_some(filters)
##########################################################################
#
# PHYSICAL INSTRUMENT
#
##########################################################################
def setup_data_production_chain(self, instrument_device_id=''):
"""
create a data product (L0) for the instrument, and establish provenance
between the corresponding data producers
"""
#get instrument object and instrument's data producer
inst_obj = self.instrument_device.read_one(instrument_device_id)
inst_pducers = self.instrument_device.find_stemming_data_producer(instrument_device_id)
inst_pducer_id = inst_pducers[0]
log.debug("instrument data producer id='%s'" % inst_pducer_id)
#create a new data product
dpms_pduct_obj = IonObject(RT.DataProduct,
name=str(inst_obj.name + " L0 Product"),
description=str("L0 DataProduct for " + inst_obj.name))
pduct_id = self.DPMS.create_data_product(dpms_pduct_obj)
#TODO: DPMS isn't creating a data producer for new data products. not sure why.
#
prod_pducer_id = self.data_producer.create_one(IonObject(RT.DataProducer,
name=str(inst_obj.name + " L0 Producer"),
description=str("L0 DataProducer for " + inst_obj.name)))
self.data_product.link_data_producer(pduct_id, prod_pducer_id)
# get data product's data producer (via association)
#TODO: this belongs in DPMS
prod_pducers = self.data_product.find_stemming_data_producer(pduct_id)
# (TODO: there should only be one assoc_id. what error to raise?)
# TODO: what error to raise if there are no assoc ids?
prod_pducer_id = prod_pducers[0]
# instrument data producer is the parent of the data product producer
#TODO: this belongs in DAMS
self.data_producer.link_input_data_producer(prod_pducer_id, inst_pducer_id)
#TODO: error checking
def create_instrument_device(self, instrument_device=None):
"""
create a new instance
@param instrument_device the object to be created as a resource
@retval instrument_device_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
instrument_device_id = self.instrument_device.create_one(instrument_device)
self.DAMS.register_instrument(instrument_device_id)
#TODO: create data producer and product
self.setup_data_production_chain(instrument_device_id)
return instrument_device_id
def update_instrument_device(self, instrument_device=None):
"""
update an existing instance
@param instrument_device the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.instrument_device.update_one(instrument_device)
def read_instrument_device(self, instrument_device_id=''):
"""
fetch a resource by ID
@param instrument_device_id the id of the object to be fetched
@retval InstrumentDevice resource
"""
return self.instrument_device.read_one(instrument_device_id)
def delete_instrument_device(self, instrument_device_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param instrument_device_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.instrument_device.delete_one(instrument_device_id)
def find_instrument_devices(self, filters=None):
"""
"""
return self.instrument_device.find_some(filters)
##
##
## DIRECT ACCESS
##
##
def request_direct_access(self, instrument_device_id=''):
"""
"""
# determine whether id is for physical or logical instrument
# look up instrument if not
# Validate request; current instrument state, policy, and other
# Retrieve and save current instrument settings
# Request DA channel, save reference
# Return direct access channel
raise NotImplementedError()
pass
def stop_direct_access(self, instrument_device_id=''):
"""
"""
# Return Value
# ------------
# {success: true}
#
raise NotImplementedError()
pass
##########################################################################
#
# PLATFORM AGENT INSTANCE
#
##########################################################################
def create_platform_agent_instance(self, platform_agent_instance=None):
"""
create a new instance
@param platform_agent_instance the object to be created as a resource
@retval platform_agent_instance_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_agent_instance.create_one(platform_agent_instance)
def update_platform_agent_instance(self, platform_agent_instance=None):
"""
update an existing instance
@param platform_agent_instance the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_agent_instance.update_one(platform_agent_instance)
def read_platform_agent_instance(self, platform_agent_instance_id=''):
"""
fetch a resource by ID
@param platform_agent_instance_id the id of the object to be fetched
@retval PlatformAgentInstance resource
"""
return self.platform_agent_instance.read_one(platform_agent_instance_id)
def delete_platform_agent_instance(self, platform_agent_instance_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param platform_agent_instance_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.platform_agent_instance.delete_one(platform_agent_instance_id)
def find_platform_agent_instances(self, filters=None):
"""
"""
return self.platform_agent_instance.find_some(filters)
##########################################################################
#
# PLATFORM AGENT
#
##########################################################################
def create_platform_agent(self, platform_agent=None):
"""
create a new instance
@param platform_agent the object to be created as a resource
@retval platform_agent_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_agent.create_one(platform_agent)
def update_platform_agent(self, platform_agent=None):
"""
update an existing instance
@param platform_agent the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_agent.update_one(platform_agent)
def read_platform_agent(self, platform_agent_id=''):
"""
fetch a resource by ID
@param platform_agent_id the id of the object to be fetched
@retval PlatformAgent resource
"""
return self.platform_agent.read_one(platform_agent_id)
def delete_platform_agent(self, platform_agent_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param platform_agent_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.platform_agent.delete_one(platform_agent_id)
def find_platform_agents(self, filters=None):
"""
"""
return self.platform_agent.find_some(filters)
##########################################################################
#
# PLATFORM MODEL
#
##########################################################################
def create_platform_model(self, platform_model=None):
"""
create a new instance
@param platform_model the object to be created as a resource
@retval platform_model_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_model.create_one(platform_model)
def update_platform_model(self, platform_model=None):
"""
update an existing instance
@param platform_model the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_model.update_one(platform_model)
def read_platform_model(self, platform_model_id=''):
"""
fetch a resource by ID
@param platform_model_id the id of the object to be fetched
@retval PlatformModel resource
"""
return self.platform_model.read_one(platform_model_id)
def delete_platform_model(self, platform_model_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param platform_model_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.platform_model.delete_one(platform_model_id)
def find_platform_models(self, filters=None):
"""
"""
return self.platform_model.find_some(filters)
##########################################################################
#
# PHYSICAL PLATFORM
#
##########################################################################
def create_platform_device(self, platform_device=None):
"""
create a new instance
@param platform_device the object to be created as a resource
@retval platform_device_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_device.create_one(platform_device)
def update_platform_device(self, platform_device=None):
"""
update an existing instance
@param platform_device the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.platform_device.update_one(platform_device)
def read_platform_device(self, platform_device_id=''):
"""
fetch a resource by ID
@param platform_device_id the id of the object to be fetched
@retval PlatformDevice resource
"""
return self.platform_device.read_one(platform_device_id)
def delete_platform_device(self, platform_device_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param platform_device_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.platform_device.delete_one(platform_device_id)
def find_platform_devices(self, filters=None):
"""
"""
return self.platform_device.find_some(filters)
##########################################################################
#
# SENSOR MODEL
#
##########################################################################
def create_sensor_model(self, sensor_model=None):
"""
create a new instance
@param sensor_model the object to be created as a resource
@retval sensor_model_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.sensor_model.create_one(sensor_model)
def update_sensor_model(self, sensor_model=None):
"""
update an existing instance
@param sensor_model the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.sensor_model.update_one(sensor_model)
def read_sensor_model(self, sensor_model_id=''):
"""
fetch a resource by ID
@param sensor_model_id the id of the object to be fetched
@retval SensorModel resource
"""
return self.sensor_model.read_one(sensor_model_id)
def delete_sensor_model(self, sensor_model_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param sensor_model_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.sensor_model.delete_one(sensor_model_id)
def find_sensor_models(self, filters=None):
"""
"""
return self.sensor_model.find_some(filters)
##########################################################################
#
# PHYSICAL SENSOR
#
##########################################################################
def create_sensor_device(self, sensor_device=None):
"""
create a new instance
@param sensor_device the object to be created as a resource
@retval sensor_device_id the id of the new object
@throws BadRequest if the incoming _id field is set
@throws BadReqeust if the incoming name already exists
"""
return self.sensor_device.create_one(sensor_device)
def update_sensor_device(self, sensor_device=None):
"""
update an existing instance
@param sensor_device the object to be created as a resource
@retval success whether we succeeded
@throws BadRequest if the incoming _id field is not set
@throws BadReqeust if the incoming name already exists
"""
return self.sensor_device.update_one(sensor_device)
def read_sensor_device(self, sensor_device_id=''):
"""
fetch a resource by ID
@param sensor_device_id the id of the object to be fetched
@retval SensorDevice resource
"""
return self.sensor_device.read_one(sensor_device_id)
def delete_sensor_device(self, sensor_device_id=''):
"""
delete a resource, including its history (for less ominous deletion, use retire)
@param sensor_device_id the id of the object to be deleted
@retval success whether it succeeded
"""
return self.sensor_device.delete_one(sensor_device_id)
def find_sensor_devices(self, filters=None):
"""
"""
return self.sensor_device.find_some(filters)
##########################################################################
#
# ASSOCIATIONS
#
##########################################################################
def assign_instrument_model_to_instrument_device(self, instrument_model_id='', instrument_device_id=''):
self.instrument_device.link_model(instrument_device_id, instrument_model_id)
def unassign_instrument_model_from_instrument_device(self, instrument_model_id='', instrument_device_id=''):
self.instrument_device.unlink_model(instrument_device_id, instrument_model_id)
def assign_instrument_model_to_instrument_agent(self, instrument_model_id='', instrument_agent_id=''):
self.instrument_agent.link_model(instrument_agent_id, instrument_model_id)
def unassign_instrument_model_from_instrument_agent(self, instrument_model_id='', instrument_agent_id=''):
self.instrument_agent.unlink_model(instrument_agent_id, instrument_model_id)
def assign_sensor_model_to_sensor_device(self, sensor_model_id='', sensor_device_id=''):
self.sensor_device.link_model(sensor_device_id, sensor_model_id)
def unassign_sensor_model_from_sensor_device(self, sensor_model_id='', sensor_device_id=''):
self.sensor_device.unlink_model(sensor_device_id, sensor_model_id)
def assign_platform_model_to_platform_device(self, platform_model_id='', platform_device_id=''):
self.platform_device.link_model(platform_device_id, platform_model_id)
def unassign_platform_model_from_platform_device(self, platform_model_id='', platform_device_id=''):
self.platform_device.unlink_model(platform_device_id, platform_model_id)
def assign_instrument_device_to_platform_device(self, instrument_device_id='', platform_device_id=''):
self.platform_device.link_instrument(platform_device_id, instrument_device_id)
def unassign_instrument_device_from_platform_device(self, instrument_device_id='', platform_device_id=''):
self.platform_device.unlink_instrument(platform_device_id, instrument_device_id)
def assign_logical_instrument_to_instrument_device(self, logical_instrument_id='', instrument_device_id=''):
self.instrument_device.link_assignment(instrument_device_id, logical_instrument_id)
def unassign_logical_instrument_from_instrument_device(self, logical_instrument_id='', instrument_device_id=''):
self.instrument_device.unlink_assignment(instrument_device_id, logical_instrument_id)
def assign_logical_platform_to_platform_device(self, logical_platform_id='', platform_device_id=''):
self.platform_device.link_assignment(platform_device_id, logical_platform_id)
def unassign_logical_platform_from_platform_device(self, logical_platform_id='', platform_device_id=''):
self.platform_device.unlink_assignment(platform_device_id, logical_platform_id)
def assign_platform_agent_instance_to_platform_agent(self, platform_agent_instance_id='', platform_agent_id=''):
self.platform_agent.link_instance(platform_agent_id, platform_agent_instance_id)
def unassign_platform_agent_instance_from_platform_agent(self, platform_agent_instance_id='', platform_agent_id=''):
self.platform_agent.unlink_instance(platform_agent_id, platform_agent_instance_id)
def assign_instrument_agent_instance_to_instrument_agent(self, instrument_agent_instance_id='', instrument_agent_id=''):
self.instrument_agent.link_instance(instrument_agent_id, instrument_agent_instance_id)
def unassign_instrument_agent_instance_from_instrument_agent(self, instrument_agent_instance_id='', instrument_agent_id=''):
self.instrument_agent.unlink_instance(instrument_agent_id, instrument_agent_instance_id)
# reassigning a logical instrument to an instrument device is a little bit special
# TODO: someday we may be able to dig up the correct data products automatically,
# but once we have them this is the function that does all the work.
def reassign_logical_instrument_to_instrument_device(self, logical_instrument_id='',
old_instrument_device_id='',
new_instrument_device_id='',
logical_data_product_ids=[],
old_instrument_data_product_ids=[],
new_instrument_data_product_ids=[]):
"""
associate a logical instrument with a physical one. this involves linking the
physical instrument's data product(s) to the logical one(s).
the 2 lists of data products must be of equal length, and will map 1-1
@param logical_instrument_id
@param instrument_device_id
@param logical_data_product_ids a list of data products associated to a logical instrument
@param instrument_data_product_ids a list of data products coming from an instrument device
"""
def verify_dp_origin(supplied_dps, assigned_dps, instrument_id, instrument_label):
"""
check that the supplied dps (data products) are in the set of what's actually assigned
@param supplied_dps list of data product ids
@param assigned_dps list of data product ids
@param instrument_id a logical or instrument device id
"""
badones = []
for p in supplied_dps:
if not p in assigned_dps:
badones.append(p)
if 0 < len(badones):
raise BadRequest("want to assign %s's data products, but the following were supplied " +
"that don't seem to come from %s '%s': [%s]" %
(instrument_label, instrument_label, instrument_id, ", ".join(badones)))
log.info("Checking consistency of existing logical/instrument assignments")
existing_assignments = self.instrument_device.find_having_assignment(logical_instrument_id)
if 1 < len(existing_assignments):
raise Inconsistent("There is more than 1 instrument device associated with logical instrument '%s'" %
logical_instrument_id)
log.info("Checking whether supplied logical/instrument arguments are proper")
if 0 < len(existing_assignments):
if not old_instrument_device_id:
raise BadRequest(("Tried to assign logical instrument '%s' for the first time, but it is already " +
"assigned to instrument device '%s'") % (logical_instrument_id, existing_assignments[0]))
elif old_instrument_device_id != existing_assignments[0]:
raise BadRequest(("Tried to reassign logical instrument '%s' from instrument device '%s' but it is " +
"actually associated to instrument device '%s'") %
(logical_instrument_id, old_instrument_device_id, existing_assignments[0]))
# log.info("Checking whether supplied data products are proper")
# existing_logical_data_products = self.logical_instrument.find_stemming_data_product(logical_instrument_id)
#
#TODO: need a check that all the logical data products are being provided for
#
# log.info("Checking whether all logical data products are provided")
# if len(logical_data_product_ids) != len(existing_logical_data_products):
# raise BadRequest("tried to assign logical instrument but only provided %d of %d " +
# "data products" % (len(logical_data_product_ids), len(existing_logical_data_products)))
#
# log.info("Checking that supplied logical data products are properly rooted")
# verify_dp_origin(logical_data_product_ids,
# existing_logical_data_products,
# logical_instrument_id,
# "logical_instrument")
if old_instrument_device_id:
log.info("Checking that the data product to be dissociated are properly rooted")
verify_dp_origin(old_instrument_data_product_ids,
self.find_data_product_by_instrument_device(old_instrument_device_id),
old_instrument_device_id,
"instrument_device")
log.info("Checking that all data products to be dissociated have been supplied")
if len(logical_data_product_ids) != len(old_instrument_data_product_ids):
raise BadRequest("Can't unmap %d instrument data products from %d logical products" %
(len(old_instrument_data_product_ids), len(logical_data_product_ids)))
log.info("Checking that supplied instrument data products are properly rooted")
verify_dp_origin(new_instrument_data_product_ids,
self.find_data_product_by_instrument_device(new_instrument_device_id),
new_instrument_device_id,
"instrument_device")
log.info("Checking that all data products to be associated have been supplied")
if len(logical_data_product_ids) != len(new_instrument_data_product_ids):
raise BadRequest("Can't map %d instrument data products to %d logical products" %
(len(new_instrument_data_product_ids), len(logical_data_product_ids)))
log.info("Assigning the instruments themselves")
if "" != old_instrument_device_id:
self.instrument_device.unlink_assignment(old_instrument_device_id, logical_instrument_id)
self.instrument_device.link_assignment(new_instrument_device_id, logical_instrument_id)
# functions to link and unlink data products as appropriate
def link_logical_dp_to_instrument_dp(logical_dp_id, inst_dp_id):
# TODO: this should be a function call, probably to DPMS,
# which sets up inst_dp to copy its data stream
# directly into the logical_dp
pass
def unlink_logical_dp_from_instrument_dp(logical_dp_id, inst_dp_id):
#TODO: undo the above
pass
if old_instrument_device_id:
log.info("Unlinking existing instrument data product(s) from logical instrument's product(s)")
map(unlink_logical_dp_from_instrument_dp, logical_data_product_ids, old_instrument_data_product_ids)
log.info("Linking new instrument data products with logical instrument's product(s)")
map(link_logical_dp_to_instrument_dp, logical_data_product_ids, new_instrument_data_product_ids)
############################
#
# ASSOCIATION FIND METHODS
#
############################
def find_instrument_model_by_instrument_device(self, instrument_device_id=''):
return self.instrument_device.find_stemming_model(instrument_device_id)
def find_instrument_device_by_instrument_model(self, instrument_model_id=''):
return self.instrument_device.find_having_model(instrument_model_id)
def find_platform_model_by_platform_device(self, platform_device_id=''):
return self.platform_device.find_stemming_model(platform_device_id)
def find_platform_device_by_platform_model(self, platform_model_id=''):
return self.platform_device.find_having_model(platform_model_id)
def find_instrument_model_by_instrument_agent(self, instrument_agent_id=''):
return self.instrument_agent.find_stemming_model(instrument_agent_id)
def find_instrument_agent_by_instrument_model(self, instrument_model_id=''):
return self.instrument_agent.find_having_model(instrument_model_id)
def find_instrument_device_by_platform_device(self, platform_device_id=''):
return self.platform_device.find_stemming_instrument(platform_device_id)
def find_platform_device_by_instrument_device(self, instrument_device_id=''):
return self.platform_device.find_having_instrument(instrument_device_id)
def find_instrument_device_by_logical_instrument(self, logical_instrument_id=''):
return self.instrument_device.find_having_assignment(logical_instrument_id)
def find_logical_instrument_by_instrument_device(self, instrument_device_id=''):
return self.instrument_device.find_stemming_assignment(instrument_device_id)
def find_platform_device_by_logical_platform(self, logical_platform_id=''):
return self.platform_device.find_having_assignment(logical_platform_id)
def find_logical_platform_by_platform_device(self, platform_device_id=''):
return self.platform_device.find_stemming_assignment(platform_device_id)
############################
#
# SPECIALIZED FIND METHODS
#
############################
def find_data_product_by_instrument_device(self, instrument_device_id=''):
log.debug("FIND DATA PRODUCT BY INSTRUMENT DEVICE")
#init return value, a list of data products
data_products = []
seen_data_producers = []
#init working set of data producers to walk
data_producers = []
pducers = self.instrument_device.find_stemming_data_producer(instrument_device_id)
data_producers += pducers
#iterate through all un-processed data producers (could also do recursively)
while 0 < len(data_producers):
producer_id = data_producers.pop()
if producer_id in seen_data_producers:
raise Inconsistent("There is a cycle in data producers that includes '%s'" % producer_id)
seen_data_producers.append(producer_id)
log.debug("Analyzing data producer '%s'" % producer_id)
#get any products that are associated with this data producer and return them
#TODO: this belongs in DPMS
new_data_products = self.data_product.find_having_data_producer(producer_id)
#get any producers that receive input from this data producer
#TODO: this belongs in DAMS
new_data_producers = self.data_producer.find_having_input_data_producer(producer_id)
log.debug("Got %d new products, %d new producers" % (len(new_data_products),
len(new_data_producers)))
data_products += new_data_products
data_producers += new_data_producers
return data_products
def find_instrument_device_by_data_product(self, data_product_id=''):
log.debug("FIND INSTRUMENT DEVICE BY DATA PRODUCT")
#init return value, a list of instrument devices
instrument_devices = []
seen_data_producers = []
#init working set of data producers to walk
data_producers = []
#TODO: this belongs in DPMS
pducers = self.data_product.find_stemming_data_producer(data_product_id)
data_producers += pducers
#iterate through all un-processed data producers (could also do recursively)
while 0 < len(data_producers):
producer_id = data_producers.pop()
if producer_id in seen_data_producers:
raise Inconsistent("There is a cycle in data producers that includes '%s'" % producer_id)
seen_data_producers.append(producer_id)
log.debug("Analyzing data producer '%s'" % producer_id)
#get any devices that are associated with this data producer and return them
new_instrument_devices = self.instrument_device.find_having_data_producer(producer_id)
#get any producers that give input to this data producer
#TODO: this belongs in DPMS
new_data_producers = self.data_producer.find_stemming_input_data_producer(producer_id)
log.debug("Got %d new devices, %d new producers" % (len(new_instrument_devices),
len(new_data_producers)))
instrument_devices += new_instrument_devices
data_producers += new_data_producers
return instrument_devices
def find_data_product_by_platform_device(self, platform_device_id=''):
ret = []
for i in self.find_instrument_device_by_platform_device(platform_device_id):
data_products = self.find_data_product_by_instrument_device(i)
for d in data_products:
if not d in ret:
ret.append(d)
return ret
############################
#
# LIFECYCLE TRANSITIONS
#
############################
def set_instrument_agent_lifecycle(self, instrument_agent_id="", lifecycle_state=""):
"""
declare a instrument_agent to be in a given state
@param instrument_agent_id the resource id
"""
return self.instrument_agent.advance_lcs(instrument_agent_id, lifecycle_state)
def set_instrument_agent_instance_lifecycle(self, instrument_agent_instance_id="", lifecycle_state=""):
"""
declare a instrument_agent_instance to be in a given state
@param instrument_agent_instance_id the resource id
"""
return self.instrument_agent_instance.advance_lcs(instrument_agent_instance_id, lifecycle_state)
def set_instrument_model_lifecycle(self, instrument_model_id="", lifecycle_state=""):
"""
declare a instrument_model to be in a given state
@param instrument_model_id the resource id
"""
return self.instrument_model.advance_lcs(instrument_model_id, lifecycle_state)
def set_instrument_device_lifecycle(self, instrument_device_id="", lifecycle_state=""):
"""
declare an instrument_device to be in a given state
@param instrument_device_id the resource id
"""
return self.instrument_device.advance_lcs(instrument_device_id, lifecycle_state)
def set_platform_agent_lifecycle(self, platform_agent_id="", lifecycle_state=""):
"""
declare a platform_agent to be in a given state
@param platform_agent_id the resource id
"""
return self.platform_agent.advance_lcs(platform_agent_id, lifecycle_state)
def set_platform_agent_instance_lifecycle(self, platform_agent_instance_id="", lifecycle_state=""):
"""
declare a platform_agent_instance to be in a given state
@param platform_agent_instance_id the resource id
"""
return self.platform_agent_instance.advance_lcs(platform_agent_instance_id, lifecycle_state)
def set_platform_model_lifecycle(self, platform_model_id="", lifecycle_state=""):
"""
declare a platform_model to be in a given state
@param platform_model_id the resource id
"""
return self.platform_model.advance_lcs(platform_model_id, lifecycle_state)
def set_platform_device_lifecycle(self, platform_device_id="", lifecycle_state=""):
"""
declare a platform_device to be in a given state
@param platform_device_id the resource id
"""
return self.platform_device.advance_lcs(platform_device_id, lifecycle_state)
def set_sensor_model_lifecycle(self, sensor_model_id="", lifecycle_state=""):
"""
declare a sensor_model to be in a given state
@param sensor_model_id the resource id
"""
return self.sensor_model.advance_lcs(sensor_model_id, lifecycle_state)
def set_sensor_device_lifecycle(self, sensor_device_id="", lifecycle_state=""):
"""
declare a sensor_device to be in a given state
@param sensor_device_id the resource id
"""
return self.sensor_device.advance_lcs(sensor_device_id, lifecycle_state)
<file_sep>/ion/services/coi/service_gateway_service.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import inspect, collections, ast, simplejson, json, sys
from flask import Flask, request
from gevent.wsgi import WSGIServer
from pyon.public import IonObject, Container, ProcessRPCClient
from pyon.core.exception import NotFound, Inconsistent, BadRequest
from pyon.core.registry import get_message_class_in_parm_type, getextends
from interface.services.coi.iservice_gateway_service import BaseServiceGatewayService
from interface.services.coi.iresource_registry_service import IResourceRegistryService, ResourceRegistryServiceProcessClient
#Initialize the flask app
app = Flask(__name__)
#Retain a module level reference to the service class for use with Process RPC calls below
service_gateway_instance = None
DEFAULT_WEB_SERVER_HOSTNAME = ""
DEFAULT_WEB_SERVER_PORT = 5000
GATEWAY_RESPONSE = 'GatewayResponse'
GATEWAY_ERROR = 'GatewayError'
GATEWAY_ERROR_EXCEPTION = 'Exception'
GATEWAY_ERROR_MESSAGE = 'Message'
#This class is used to manage the WSGI/Flask server as an ION process - and as a process endpoint for ION RPC calls
class ServiceGatewayService(BaseServiceGatewayService):
"""
The Service Gateway Service is the service that uses a gevent web server and Flask to bridge HTTP requests to AMQP RPC ION process service calls.
"""
def on_init(self):
#defaults
self.http_server = None
self.server_hostname = DEFAULT_WEB_SERVER_HOSTNAME
self.server_port = DEFAULT_WEB_SERVER_PORT
self.web_server_enabled = True
self.logging = None
#retain a pointer to this object for use in ProcessRPC calls
global service_gateway_instance
service_gateway_instance = self
#get configuration settings if specified
if 'web_server' in self.CFG:
web_server_cfg = self.CFG['web_server']
if web_server_cfg is not None:
if 'hostname' in web_server_cfg:
self.server_hostname = web_server_cfg['hostname']
if 'port' in web_server_cfg:
self.server_port = web_server_cfg['port']
if 'enabled' in web_server_cfg:
self.web_server_enabled = web_server_cfg['enabled']
if 'log' in web_server_cfg:
self.logging = web_server_cfg['log']
#need to figure out how to redirect HTTP logging to a file
if self.web_server_enabled:
self.start_service(self.server_hostname,self.server_port)
def on_quit(self):
self.stop_service()
def start_service(self, hostname=DEFAULT_WEB_SERVER_HOSTNAME, port=DEFAULT_WEB_SERVER_PORT):
"""Responsible for starting the gevent based web server."""
if self.http_server is not None:
self.stop_service()
self.http_server = WSGIServer((hostname, port), app, log=self.logging)
self.http_server.start()
return True
def stop_service(self):
"""Responsible for stopping the gevent based web server."""
if self.http_server is not None:
self.http_server.stop()
return True
# This is a service operation for handling generic service operation calls with arguments passed as query string parameters; like this:
# http://hostname:port/ion-service/resource_registry/find_resources?restype=BankAccount&id_only=False
# Shows how to handle POST requests with the parameters passed in posted JSON object, though has both since it is easier to use a browser URL GET than a POST by hand.
# An example post of json data using wget
# wget -o out.txt --post-data 'payload={"serviceRequest": { "serviceName": "resource_registry", "serviceOp": "find_resources",
# "params": { "restype": "BankAccount", "lcstate": "", "name": "", "id_only": true } } }' http://localhost:5000/ion-service/resource_registry/find_resources
#
# Probably should make this service smarter to respond to the mime type in the request data ( ie. json vs text )
#
@app.route('/ion-service/<service_name>/<operation>', methods=['GET','POST'])
def process_gateway_request(service_name, operation):
try:
if not service_name:
raise BadRequest("Target service name not found in the URL")
#Retrieve service definition
from pyon.core.bootstrap import service_registry
# MM: Note: service_registry can do more now
target_service = service_registry.get_service_by_name(service_name)
if not target_service:
raise BadRequest("The requested service (%s) is not available" % service_name)
if operation == '':
raise BadRequest("Service operation not specified in the URL")
#Find the concrete client class for making the RPC calls.
if not target_service.client:
raise BadRequest("Cannot find a client class for the specified service: %s" % service_name )
target_client = target_service.client
#Retrieve json data from HTTP Post payload
json_params = None
if request.method == "POST":
payload = request.form['payload']
#debug only
#payload = '{"serviceRequest": { "serviceName": "resource_registry", "serviceOp": "find_resources", "params": { "restype": "BankAccount", "lcstate": "", "name": "", "id_only": false } } }'
json_params = json.loads(payload)
if not json_params.has_key('serviceRequest'):
raise Inconsistent("The JSON request is missing the 'serviceRequest' key in the request")
if not json_params['serviceRequest'].has_key('serviceName'):
raise Inconsistent("The JSON request is missing the 'serviceName' key in the request")
if not json_params['serviceRequest'].has_key('serviceOp'):
raise Inconsistent("The JSON request is missing the 'serviceOp' key in the request")
if json_params['serviceRequest']['serviceName'] != target_service.name:
raise Inconsistent("Target service name in the JSON request (%s) does not match service name in URL (%s)" % (str(json_params['serviceRequest']['serviceName']), target_service.name ) )
if json_params['serviceRequest']['serviceOp'] != operation:
raise Inconsistent("Target service operation in the JSON request (%s) does not match service name in URL (%s)" % ( str(json_params['serviceRequest']['serviceOp']), operation ) )
param_list = create_parameter_list(service_name, target_client,operation, json_params)
#Add governance headers - these are the default values.
ion_actor_id = 'anonymous'
expiry = '0'
param_list['headers'] = {'ion-actor-id': ion_actor_id, 'expiry': expiry}
client = target_client(node=Container.instance.node, process=service_gateway_instance)
methodToCall = getattr(client, operation)
result = methodToCall(**param_list)
return json_response({GATEWAY_RESPONSE: result})
except Exception, e:
return build_error_response(e)
#Private implementation of standard flask jsonify to specify the use of an encoder to walk ION objects
def json_response(response_data):
return app.response_class(simplejson.dumps({'data': response_data}, default=ion_object_encoder,
indent=None if request.is_xhr else 2), mimetype='application/json')
def build_error_response(e):
exc_type, exc_obj, exc_tb = sys.exc_info()
result = {
GATEWAY_ERROR_EXCEPTION : exc_type.__name__,
GATEWAY_ERROR_MESSAGE : str(e.message)
}
return json_response({ GATEWAY_ERROR :result } )
#Build parameter list dynamically from
def create_parameter_list(service_name, target_client,operation, json_params):
param_list = {}
method_args = inspect.getargspec(getattr(target_client,operation))
for arg in method_args[0]:
if arg == 'self' or arg == 'headers': continue # skip self and headers from being set
if not json_params:
if request.args.has_key(arg):
param_type = get_message_class_in_parm_type(service_name, operation, arg)
if param_type == 'str':
param_list[arg] = convert_unicode(request.args[arg])
else:
param_list[arg] = ast.literal_eval(convert_unicode(request.args[arg]))
else:
if json_params['serviceRequest']['params'].has_key(arg):
#This if handles ION objects as a 2 element list: [Object Type, { field1: val1, ...}]
if isinstance(json_params['serviceRequest']['params'][arg], list):
#TODO - Potentially remove these conversions whenever ION objects support unicode
# UNICODE strings are not supported with ION objects
ion_object_name = convert_unicode(json_params['serviceRequest']['params'][arg][0])
object_params = convert_unicode(json_params['serviceRequest']['params'][arg][1])
param_list[arg] = create_ion_object(ion_object_name, object_params)
else: # The else branch is for simple types ( non-ION objects )
param_list[arg] = convert_unicode(json_params['serviceRequest']['params'][arg])
return param_list
#Helper function for creating and initializing an ION object from a dictionary of parameters.
def create_ion_object(ion_object_name, object_params):
new_obj = IonObject(ion_object_name)
#Iterate over the parameters to add to object; have to do this instead
#of passing a dict to get around restrictions in object creation on setting _id, _rev params
for param in object_params:
set_object_field(new_obj, param, object_params.get(param))
new_obj._validate() # verify that all of the object fields were set with proper types
return new_obj
#Use this function internally to recursively set sub object field values
def set_object_field(obj, field, field_val):
if isinstance(field_val,dict):
sub_obj = getattr(obj,field)
for sub_field in field_val:
set_object_field(sub_obj, sub_field, field_val.get(sub_field))
else:
setattr(obj, field, field_val)
#Used by json encoder
def ion_object_encoder(obj):
return obj.__dict__
#Used to recursively convert unicode in JSON structures into proper data structures
def convert_unicode(data):
if isinstance(data, unicode):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(convert_unicode, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convert_unicode, data))
else:
return data
# This service method returns the list of registered resource objects sorted alphabetically. Optional query
# string parameter will filter by extended type i.e. type=InformationResource. All registered objects
# will be returned if not filtered
#
# Examples:
# http://hostname:port/ion-service/list_resource_types
# http://hostname:port/ion-service/list_resource_types?type=InformationResource
# http://hostname:port/ion-service/list_resource_types?type=TaskableResource
#
@app.route('/ion-service/list_resource_types', methods=['GET','POST'])
def list_resource_types():
try:
#Look to see if a specific resource type has been specified - if not default to all
if request.args.has_key('type'):
resultSet = set(getextends(request.args['type'])) if getextends(request.args['type']) is not None else set()
else:
type_list = getextends('Resource')
resultSet = set(type_list)
ret_list = []
for res in sorted(resultSet):
ret_list.append(res)
return json_response({ GATEWAY_RESPONSE :ret_list } )
except Exception, e:
return build_error_response(e)
#Returns a json object for a specified resource type with all default values.
@app.route('/ion-service/resource_type_schema/<resource_type>')
def get_resource_schema(resource_type):
try:
#ION Objects are not registered as UNICODE names
ion_object_name = convert_unicode(resource_type)
ret_obj = IonObject(ion_object_name, {})
# If it's an op input param or response message object.
# Walk param list instantiating any params that were marked None as default.
if hasattr(ret_obj, "_svc_name"):
schema = ret_obj._schema
for field in ret_obj._schema:
if schema[field]["default"] is None:
try:
value = IonObject(schema[field]["type"], {})
except NotFound:
# TODO
# Some other non-IonObject type. Just use None as default for now.
value = None
setattr(ret_obj, field, value)
return json_response({ GATEWAY_RESPONSE :ret_obj } )
except Exception, e:
return build_error_response(e)
#More RESTfull examples...should probably not use but here for example reference
#This example calls the resource registry with an id passed in as part of the URL
#http://hostname:port/ion-service/resource/c1b6fa6aadbd4eb696a9407a39adbdc8
@app.route('/ion-service/rest/resource/<resource_id>')
def get_resource(resource_id):
result = None
client = ResourceRegistryServiceProcessClient(node=Container.instance.node, process=service_gateway_instance)
if resource_id != '':
try:
#Database object IDs are not unicode
result = client.read(convert_unicode(resource_id))
if not result:
raise NotFound("No resource found for id: %s " % resource_id)
return json_response({ GATEWAY_RESPONSE :result } )
except Exception, e:
return build_error_response(e)
#Example operation to return a list of resources of a specific type like
#http://hostname:port/ion-service/find_resources/BankAccount
@app.route('/ion-service/rest/find_resources/<resource_type>')
def list_resources_by_type(resource_type):
result = None
client = ResourceRegistryServiceProcessClient(node=Container.instance.node, process=service_gateway_instance)
try:
#Resource Types are not in unicode
res_list,_ = client.find_resources(restype=convert_unicode(resource_type) )
return json_response({ GATEWAY_RESPONSE :res_list } )
except Exception, e:
return build_error_response(e)
#Example restful call to a client function for another service like
#http://hostname:port/ion-service/run_bank_client
@app.route('/ion-service/run_bank_client')
def create_accounts():
from examples.bank.bank_client import run_client
run_client(Container.instance, process=service_gateway_instance)
return json_response("")
@app.route('/ion-service/seed_gov')
def seed_gov():
from examples.gov_client import seed_gov
seed_gov(Container.instance)
return json_response("")
<file_sep>/ion/services/dm/test/test_replay_integration.py
"""
@author <NAME>
@file ion/services/dm/test/test_replay_integration.py
@description Provides a full fledged integration from ingestion to replay using scidata
"""
from interface.objects import CouchStorage, StreamQuery, HdfStorage
from interface.services.cei.iprocess_dispatcher_service import ProcessDispatcherServiceClient
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from interface.services.dm.idata_retriever_service import DataRetrieverServiceClient
from interface.services.dm.idataset_management_service import DatasetManagementServiceClient
from interface.services.dm.iingestion_management_service import IngestionManagementServiceClient
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
from interface.services.dm.itransform_management_service import TransformManagementServiceClient
from pyon.util.int_test import IonIntegrationTestCase
from pyon.public import StreamPublisherRegistrar, StreamSubscriberRegistrar
from nose.plugins.attrib import attr
from prototype.sci_data.ctd_stream import ctd_stream_packet, ctd_stream_definition
from pyon.public import RT, PRED, log, IonObject
import unittest
import os
import random
import gevent
#------------------------------------------------------------------------------------------------------
# Create an async result
#------------------------------------------------------------------------------------------------------
ar = gevent.event.AsyncResult()
ar2 = gevent.event.AsyncResult()
def _create_packet( stream_id):
"""
Create a ctd_packet for scientific data
"""
length = random.randint(1,20)
c = [random.uniform(0.0,75.0) for i in xrange(length)]
t = [random.uniform(-1.7, 21.0) for i in xrange(length)]
p = [random.lognormvariate(1,2) for i in xrange(length)]
lat = [random.uniform(-90.0, 90.0) for i in xrange(length)]
lon = [random.uniform(0.0, 360.0) for i in xrange(length)]
tvar = [ i for i in xrange(1,length+1)]
ctd_packet = ctd_stream_packet(stream_id=stream_id,
c=c, t=t, p=p, lat=lat, lon=lon, time=tvar, create_hdf=True)
return ctd_packet
def _subscriber_call_back(message, headers):
"""
Checks that what replay was sending out was of correct format
"""
retrieved_hdf_string = message.identifiables['ctd_data'].values
ar2.set(retrieved_hdf_string)
@attr('INT',group='dm')
class ReplayIntegrationTest(IonIntegrationTestCase):
def setUp(self):
self._start_container()
self.container.start_rel_from_url('res/deploy/r2dm.yml')
@unittest.skipIf(os.getenv('CEI_LAUNCH_TEST', False), 'Skip test while in CEI LAUNCH mode')
def test_replay_integration(self):
'''
Test full DM Services Integration
'''
cc = self.container
### Every thing below here can be run as a script:
pubsub_management_service = PubsubManagementServiceClient(node=cc.node)
ingestion_management_service = IngestionManagementServiceClient(node=cc.node)
dataset_management_service = DatasetManagementServiceClient(node=cc.node)
data_retriever_service = DataRetrieverServiceClient(node=cc.node)
resource_registry_service = ResourceRegistryServiceClient(node=cc.node)
#------------------------------------------------------------------------------------------------------
# Datastore name
#------------------------------------------------------------------------------------------------------
datastore_name = 'test_replay_integration'
#------------------------------------------------------------------------------------------------------
# Spawn process
#------------------------------------------------------------------------------------------------------
pid = cc.spawn_process(name='dummy_process_for_test',
module='pyon.ion.process',
cls='SimpleProcess',
config={})
dummy_process = cc.proc_manager.procs[pid]
#------------------------------------------------------------------------------------------------------
# Set up subscriber
#------------------------------------------------------------------------------------------------------
# Normally the user does not see or create the publisher, this is part of the containers business.
# For the test we need to set it up explicitly
publisher_registrar = StreamPublisherRegistrar(process=dummy_process, node=cc.node)
subscriber_registrar = StreamSubscriberRegistrar(process=cc, node=cc.node)
#------------------------------------------------------------------------------------------------------
# Set up ingestion
#------------------------------------------------------------------------------------------------------
# Configure ingestion using eight workers, ingesting to test_dm_integration datastore with the SCIDATA profile
ingestion_configuration_id = ingestion_management_service.create_ingestion_configuration(
exchange_point_id='science_data',
couch_storage=CouchStorage(datastore_name=datastore_name, datastore_profile='SCIDATA'),
hdf_storage=HdfStorage(),
number_of_workers=1,
)
ingestion_management_service.activate_ingestion_configuration(
ingestion_configuration_id=ingestion_configuration_id)
#------------------------------------------------------------------------------------------------------
# Grab the transforms acting as ingestion workers
#------------------------------------------------------------------------------------------------------
transforms = [resource_registry_service.read(assoc.o)
for assoc in resource_registry_service.find_associations(ingestion_configuration_id, PRED.hasTransform)]
proc_1 = cc.proc_manager.procs[transforms[0].process_id]
log.info("PROCESS 1: %s" % str(proc_1))
#------------------------------------------------------------------------------------------------------
# Set up the test hooks for the gevent event AsyncResult object
#------------------------------------------------------------------------------------------------------
def ingestion_worker_received(message, headers):
ar.set(message)
proc_1.ingest_process_test_hook = ingestion_worker_received
#------------------------------------------------------------------------------------------------------
# Set up the producers (CTD Simulators)
#------------------------------------------------------------------------------------------------------
ctd_stream_def = ctd_stream_definition()
stream_def_id = pubsub_management_service.create_stream_definition(container=ctd_stream_def, name='Junk definition')
stream_id = pubsub_management_service.create_stream(stream_definition_id=stream_def_id)
#------------------------------------------------------------------------------------------------------
# Set up the dataset config
#------------------------------------------------------------------------------------------------------
dataset_id = dataset_management_service.create_dataset(
stream_id=stream_id,
datastore_name=datastore_name,
view_name='datasets/stream_join_granule'
)
dataset_config_id = ingestion_management_service.create_dataset_configuration(
dataset_id = dataset_id,
archive_data = True,
archive_metadata = True,
ingestion_configuration_id = ingestion_configuration_id
)
#------------------------------------------------------------------------------------------------------
# Launch a ctd_publisher
#------------------------------------------------------------------------------------------------------
publisher = publisher_registrar.create_publisher(stream_id=stream_id)
#------------------------------------------------------------------------
# Create a packet and publish it
#------------------------------------------------------------------------
ctd_packet = _create_packet(stream_id)
published_hdfstring = ctd_packet.identifiables['ctd_data'].values
publisher.publish(ctd_packet)
#------------------------------------------------------------------------------------------------------
# Catch what the ingestion worker gets! Assert it is the same packet that was published!
#------------------------------------------------------------------------------------------------------
packet = ar.get(timeout=2)
#------------------------------------------------------------------------------------------------------
# Create subscriber to listen to the replays
#------------------------------------------------------------------------------------------------------
replay_id, replay_stream_id = data_retriever_service.define_replay(dataset_id)
query = StreamQuery(stream_ids=[replay_stream_id])
subscription_id = pubsub_management_service.create_subscription(query = query, exchange_name='replay_capture_point' ,name = 'replay_capture_point')
# It is not required or even generally a good idea to use the subscription resource name as the queue name, but it makes things simple here
# Normally the container creates and starts subscribers for you when a transform process is spawned
subscriber = subscriber_registrar.create_subscriber(exchange_name='replay_capture_point', callback=_subscriber_call_back)
subscriber.start()
pubsub_management_service.activate_subscription(subscription_id)
#------------------------------------------------------------------------------------------------------
# Start the replay
#------------------------------------------------------------------------------------------------------
data_retriever_service.start_replay(replay_id)
#------------------------------------------------------------------------------------------------------
# Get the hdf string from the captured stream in the replay
#------------------------------------------------------------------------------------------------------
retrieved_hdf_string = ar2.get(timeout=2)
### Non scriptable portion of the test
#------------------------------------------------------------------------------------------------------
# Assert that it matches the message we sent
#------------------------------------------------------------------------------------------------------
self.assertEquals(packet.identifiables['stream_encoding'].sha1, ctd_packet.identifiables['stream_encoding'].sha1)
self.assertEquals(retrieved_hdf_string, published_hdfstring)
<file_sep>/ion/services/mi/drivers/uw_bars/bars_client.py
#!/usr/bin/env python
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
"""
BarsClient allows direct iteraction with the instrument via a socket.
A demo program can be run as follows:
$ bin/python ion/services/mi/drivers/uw_bars/bars_client.py \
--host 10.180.80.172 --port 2001 --outfile output.txt
"""
import sys
import socket
import os
import re
import time
from threading import Thread
import ion.services.mi.mi_logger
import logging
log = logging.getLogger('mi_logger')
EOF = '\x04'
CONTROL_S = '\x13'
DATA_LINE_PATTERN = re.compile(r'.*(\d+\.\d*\s*){12}.*')
GENERIC_PROMPT_PATTERN = re.compile(r'.*--> ')
MAX_NUM_LINES = 100
class _Recv(Thread):
"""
Thread to receive and optionaly write the received data to a given file.
It keeps internal buffers to support the check for expected contents.
"""
def __init__(self, conn, outfile=None):
Thread.__init__(self, name="_Recv")
self._conn = conn
self._last_line = ''
self._new_line = ''
self._lines = []
self._active = True
self._outfile = outfile
self.setDaemon(True)
log.debug("### _Recv created.")
def _update_lines(self, recv):
if recv == '\n':
self._last_line = self._new_line
self._new_line = ''
self._lines.append(self._last_line)
if len(self._lines) > MAX_NUM_LINES:
self._lines = self._lines[MAX_NUM_LINES - 1:]
return True
else:
self._new_line += recv
return False
def end(self):
self._active = False
def run(self):
log.debug("### _Recv running.")
while self._active:
recv = self._conn.recv(1)
self._update_lines(recv)
if self._outfile:
os.write(self._outfile.fileno(), recv)
self._outfile.flush()
log.debug("### _Recv.run done.")
class BarsClient(object):
"""
TCP based client for communication with the BARS instrument.
"""
def __init__(self, host, port, outfile=None):
"""
Establishes the connection and starts the receiving thread.
"""
self._host = host
self._port = port
self._sock = None
self._outfile = outfile
self._bt = None
"""sleep time used just before sending data"""
self.delay_before_send = 0.2
"""sleep time used just before a expect operation"""
self.delay_before_expect = 2
def connect(self):
host, port = self._host, self._port
log.debug("### connecting to %s:%s" % (host, port))
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((host, port))
log.debug("### connected to %s:%s" % (host, port))
self._bt = _Recv(self._sock, self._outfile)
self._bt.start()
log.debug("### _Recv started.")
def is_collecting_data(self, timeout=30):
"""
Determines whether the instrument is currently collecting data.
@param timeout Timeout for the check.
"""
log.debug("### is_collecting_data? ...")
time_limit = time.time() + timeout
got_data = False
while not got_data and time.time() <= time_limit:
time.sleep(1)
string = self._bt._last_line
got_data = DATA_LINE_PATTERN.match(string) is not None
return got_data
def enter_main_menu(self):
"""
Sends ^S repeatily until getting a prompt.
It does the check every 2 seconds.
"""
log.debug("### automatic ^S")
got_prompt = False
while not got_prompt:
log.debug("### sending ^S")
self._send_control('s')
time.sleep(2)
string = self._bt._new_line
got_prompt = GENERIC_PROMPT_PATTERN.match(string) is not None
log.debug("### got prompt. Sending one ^m to clean up any ^S leftover")
self._send_control('m')
def get_last_buffer(self):
return '\n'.join(self._bt._lines)
def send_enter(self):
"""
Sleeps for self.delay_before_send and calls self._send_control('m').
"""
time.sleep(self.delay_before_send)
log.debug("### send_enter")
self._send_control('m')
def send(self, string):
"""
Sleeps for self.delay_before_send and then sends string + '\r'
"""
time.sleep(self.delay_before_send)
s = string + '\r'
log.debug("### send: '%s'" % repr(s))
self._send(s)
def expect_line(self, pattern, pre_delay=None, timeout=30):
"""
Sleeps for the given pre_delay seconds (self.delay_before_expect by
default).
Then waits until the given pattern matches the current contents of the
last received line. It does the check every second.
@pattern The pattern (a string or the result of a re.compile)
@param pre_delay For the initial sleep (self.delay_before_expect by
default).
@param timeout Timeout for the wait.
"""
pre_delay = pre_delay if pre_delay else self.delay_before_expect
time.sleep(pre_delay)
patt_str = pattern if isinstance(pattern, str) else pattern.pattern
log.debug("### expecting '%s'" % patt_str)
time_limit = time.time() + timeout
got_it = False
while not got_it and time.time() <= time_limit:
time.sleep(1)
string = self._bt._new_line
got_it = re.match(pattern, string) is not None
return got_it
def expect_generic_prompt(self, pre_delay=None, timeout=30):
"""
returns self.expect_line(GENERIC_PROMPT_PATTERN, pre_delay, timeout)
where pre_delay is self.delay_before_expect by default.
Note that the pre_delay is intended to allow the instrument to send new
info after a preceeding requested option so as to avoid a false
positive prompt verification.
@param pre_delay For the initial sleep (self.delay_before_expect by
default).
@param timeout Timeout for the wait.
"""
pre_delay = pre_delay if pre_delay else self.delay_before_expect
return self.expect_line(GENERIC_PROMPT_PATTERN, pre_delay, timeout)
def end(self):
"""
Ends the client.
"""
log.debug("### ending")
self._bt.end()
self._sock.close()
def _send(self, s):
"""
Sends a string. Returns the number of bytes written.
"""
c = os.write(self._sock.fileno(), s)
return c
def _send_control(self, char):
"""
Sends a control character.
@param char must satisfy 'a' <= char.lower() <= 'z'
"""
char = char.lower()
assert 'a' <= char <= 'z'
a = ord(char)
a = a - ord('a') + 1
return self._send(chr(a))
def main(host, port, outfile=sys.stdout):
"""
Demo program:
- checks if the instrument is collecting data
- if not, this function returns False
- breaks data streaming to enter main menu
- selects 6 to get system info
- sends enter to return to main menu
- resumes data streaming
- sleeps a few seconds to let some data to come in
- returns True
@param host Host of the instrument
@param port Port of the instrument
@param outfile File object used to echo all received data from the socket
(by default, sys.stdout).
"""
bars_client = BarsClient(host, port, outfile)
bars_client.connect()
print ":: is instrument collecting data?"
if bars_client.is_collecting_data():
print ":: Instrument is collecting data."
else:
print ":: Instrument in not in collecting data mode. Exiting."
return False
print ":: break data streaming to enter main menu"
bars_client.enter_main_menu()
print ":: select 6 to get system info"
bars_client.send('6')
bars_client.expect_generic_prompt()
print ":: send enter to return to main menu"
bars_client.send_enter()
bars_client.expect_generic_prompt()
print ":: resume data streaming"
bars_client.send('1')
print ":: sleeping for 10 secs to receive some data"
time.sleep(10)
print ":: bye"
bars_client.end()
return True
if __name__ == '__main__':
usage = """USAGE: bars_client.py [options]
--host address # instrument address (localhost by default)
--port port # instrument port (required)
--outfile filename # file to save all received data (stdout by default)
--loglevel level # used to eval mi_logger.setLevel(logging.%s)
"""
usage += """\nExample: bars_client.py --host 10.180.80.172 --port 2001"""
host = 'localhost'
port = None
outfile = sys.stdout
arg = 1
while arg < len(sys.argv):
if sys.argv[arg] == "--host":
arg += 1
host = sys.argv[arg]
elif sys.argv[arg] == "--port":
arg += 1
port = int(sys.argv[arg])
elif sys.argv[arg] == "--outfile":
arg += 1
outfile = file(sys.argv[arg], 'w')
elif sys.argv[arg] == "--loglevel":
arg += 1
loglevel = sys.argv[arg].upper()
mi_logger = logging.getLogger('mi_logger')
eval("mi_logger.setLevel(logging.%s)" % loglevel)
else:
print "error: unrecognized option %s" % sys.argv[arg]
port = None
break
arg += 1
if port is None:
print usage
else:
main(host, port, outfile)
<file_sep>/ion/services/sa/product/test/test_data_product_management_service.py
from interface.services.icontainer_agent import ContainerAgentClient
#from pyon.net.endpoint import ProcessRPCClient
from pyon.public import Container, log, IonObject
from pyon.util.int_test import IonIntegrationTestCase
from ion.services.sa.product.data_product_management_service import DataProductManagementService
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from interface.services.sa.idata_product_management_service import IDataProductManagementService, DataProductManagementServiceClient
from interface.services.sa.idata_acquisition_management_service import DataAcquisitionManagementServiceClient
from pyon.util.context import LocalContextMixin
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.public import RT, LCS, PRED
from mock import Mock, patch
from pyon.util.unit_test import PyonTestCase
from nose.plugins.attrib import attr
import unittest
from ion.services.sa.resource_impl.data_product_impl import DataProductImpl
from ion.services.sa.resource_impl.resource_impl_metatest import ResourceImplMetatest
class FakeProcess(LocalContextMixin):
name = ''
@attr('UNIT', group='sa')
<EMAIL>('not working')
class TestDataProductManagementServiceUnit(PyonTestCase):
def setUp(self):
self.clients = self._create_service_mock('data_product_management')
self.data_product_management_service = DataProductManagementService()
self.data_product_management_service.clients = self.clients
# must call this manually
self.data_product_management_service.on_init()
self.data_source = Mock()
self.data_source.name = 'data_source_name'
self.data_source.description = 'data source desc'
def test_createDataProduct_and_DataProducer_success(self):
# setup
self.resource_registry.find_resources.return_value = ([], 'do not care')
self.resource_registry.create.return_value = ('SOME_RR_ID1', 'Version_1')
self.data_acquisition_management.assign_data_product.return_value = None
# Data Product
dpt_obj = IonObject(RT.DataProduct,
name='DPT_Y',
description='some new data product')
# test call
dp_id = self.data_product_management_service.create_data_product(dpt_obj, 'source_resource_id')
# check results
self.assertEqual(dp_id, 'SOME_RR_ID1')
self.resource_registry.find_resources.assert_called_once_with(RT.DataProduct, None, dpt_obj.name, True)
self.resource_registry.create.assert_called_once_with(dpt_obj)
#self.data_acquisition_management.assign_data_product.assert_called_once_with('source_resource_id', 'SOME_RR_ID1', True)
def test_createDataProduct_and_DataProducer_with_id_NotFound(self):
# setup
self.resource_registry.find_resources.return_value = ([], 'do not care')
self.resource_registry.create.return_value = ('SOME_RR_ID1', 'Version_1')
self.data_acquisition_management.assign_data_product.return_value = None
self.data_acquisition_management.assign_data_product.side_effect = NotFound("Object with id SOME_RR_ID1 does not exist.")
# Data Product
dpt_obj = IonObject(RT.DataProduct, name='DPT_X', description='some new data product')
# test call
with self.assertRaises(NotFound) as cm:
dp_id = self.data_product_management_service.create_data_product(dpt_obj, 'source_resource_id')
# check results
self.resource_registry.find_resources.assert_called_once_with(RT.DataProduct, None, dpt_obj.name, True)
self.resource_registry.create.assert_called_once_with(dpt_obj)
#self.data_acquisition_management.assign_data_product.assert_called_once_with('source_resource_id', 'SOME_RR_ID1', True)
ex = cm.exception
self.assertEqual(ex.message, "Object with id SOME_RR_ID1 does not exist.")
def test_findDataProduct_success(self):
# setup
# Data Product
dp_obj = IonObject(RT.DataProduct,
name='DP_X',
description='some existing dp')
self.resource_registry.find_resources.return_value = ([dp_obj], [])
# test call
result = self.data_product_management_service.find_data_products()
# check results
self.assertEqual(result, [dp_obj])
self.resource_registry.find_resources.assert_called_once_with(RT.DataProduct, None, None, False)
@attr('INT', group='sa')
<EMAIL>('not working')
class TestDataProductManagementServiceIntegration(IonIntegrationTestCase):
def setUp(self):
# Start container
#print 'instantiating container'
self._start_container()
#container = Container()
#print 'starting container'
#container.start()
#print 'started container'
self.container.start_rel_from_url('res/deploy/r2sa.yml')
print 'started services'
# Now create client to DataProductManagementService
self.client = DataProductManagementServiceClient(node=self.container.node)
self.rrclient = ResourceRegistryServiceClient(node=self.container.node)
self.damsclient = DataAcquisitionManagementServiceClient(node=self.container.node)
def test_createDataProduct(self):
client = self.client
rrclient = self.rrclient
#Not sure we want to mix in DAMS tests here
# set up initial data source and its associated data producer
#instrument_obj = IonObject(RT.InstrumentDevice, name='Inst1',description='an instrument that is creating the data product')
#instrument_id, rev = rrclient.create(instrument_obj)
#self.damsclient.register_instrument(instrument_id)
# test creating a new data product w/o a data producer
print 'Creating new data product w/o a data producer'
dp_obj = IonObject(RT.DataProduct,
name='DP1',
description='some new dp')
try:
dp_id = client.create_data_product(dp_obj, '')
except BadRequest as ex:
self.fail("failed to create new data product: %s" %ex)
print 'new dp_id = ', dp_id
# test creating a duplicate data product
print 'Creating the same data product a second time (duplicate)'
dp_obj.description = 'the first dp'
try:
dp_id = client.create_data_product(dp_obj, 'source_resource_id')
except BadRequest as ex:
print ex
else:
self.fail("duplicate data product was created with the same name")
"""
# This is broken until the interceptor handles lists properly (w/o converting them to constants)
# and DAMS works with pubsub_management.register_producer() correctly
# test creating a new data product with a data producer
print 'Creating new data product with a data producer'
dp_obj = IonObject(RT.DataProduct,
name='DP2',
description='another new dp')
data_producer_obj = IonObject(RT.DataProducer,
name='DataProducer1',
description='a new data producer')
try:
dp_id = client.create_data_product(dp_obj, data_producer_obj)
except BadRequest as ex:
self.fail("failed to create new data product")
print 'new dp_id = ', dp_id
"""
# test reading a non-existent data product
print 'reading non-existent data product'
try:
dp_obj = client.read_data_product('some_fake_id')
except NotFound as ex:
pass
else:
self.fail("non-existing data product was found during read: %s" %dp_obj)
# update a data product (tests read also)
print 'Updating data product'
# first get the existing dp object
try:
dp_obj = client.read_data_product(dp_id)
except NotFound as ex:
self.fail("existing data product was not found during read")
else:
pass
#print 'dp_obj = ', dp_obj
# now tweak the object
dp_obj.description = 'the very first dp'
# now write the dp back to the registry
try:
update_result = client.update_data_product(dp_obj)
except NotFound as ex:
self.fail("existing data product was not found during update")
except Conflict as ex:
self.fail("revision conflict exception during data product update")
# now get the dp back to see if it was updated
try:
dp_obj = client.read_data_product(dp_id)
except NotFound as ex:
self.fail("existing data product was not found during read")
else:
pass
#print 'dp_obj = ', dp_obj
self.assertTrue(dp_obj.description == 'the very first dp')
# now 'delete' the data product
print "deleting data product: ", dp_id
try:
client.delete_data_product(dp_id)
except NotFound as ex:
self.fail("existing data product was not found during delete")
# now try to get the deleted dp object
try:
dp_obj = client.read_data_product(dp_id)
except NotFound as ex:
pass
else:
self.fail("deleted data product was found during read")
# now try to delete the already deleted dp object
print "deleting non-existing data product"
try:
client.delete_data_product(dp_id)
except NotFound as ex:
pass
else:
self.fail("non-existing data product was found during delete")
# Shut down container
#container.stop()
#dynamically add tests to the test classes. THIS MUST HAPPEN OUTSIDE THE CLASS
#unit
rim = ResourceImplMetatest(TestDataProductManagementServiceUnit, DataProductManagementService, log)
rim.add_resource_impl_unittests(DataProductImpl)
<file_sep>/ion/services/mi/drivers/uw_bars/test/test_thread.py
#!/usr/bin/env python
__author__ = "<NAME>"
__license__ = 'Apache 2.0'
"""
Update 2012-02-16: The behavior described below is not happening anymore; the
test is now running fine with 'import pyon.util.unit_test' and under the
various launch styles.
(the description of the original behavior follows)
If pyon.util.unit_test is imported, then the thread in this test is NOT
started when this file is run via bin/nosetests or unittest. But it does
run fine when launched (individually) as a regular program via bin/python.
Apparently the pyon.util.unit_test import triggers some internal preparations
in pyon that don't play well with threads (likely related with gevent
monkey-patching).
Just remove the pyon.util.unit_test import, and the test runs fine with any
of the launch methods.
The following two require a ^\ to kill them (the thread is not started).
$ bin/nosetests -sv ion/services/mi/drivers/uw_bars/test/test_thread.py
2012-02-10 13:39:53,238 DEBUG pyon.core.governance.governance_controller GovernanceController.__init__()
2012-02-10 13:39:53,238 DEBUG pyon.core.governance.governance_interceptor GovernanceInterceptor enabled: False
test_simple (ion.services.mi.drivers.uw_bars.test.test_thread.ThreadTest) ... :: _T created
^\
$ bin/python -m unittest ion.services.mi.drivers.uw_bars.test.test_thread
test_simple (ion.services.mi.drivers.uw_bars.test.test_bars_client.DriverTest) ...
DEBUG bars_client 20742 MainThread - ### connecting to 10.180.80.172:2001
DEBUG bars_client 20742 MainThread - ### connected to 10.180.80.172:2001
DEBUG bars_client 20742 MainThread - ### _Recv created.
^\
The following runs fine:
$ bin/python ion/services/mi/drivers/uw_bars/test/test_thread.py
2012-02-10 13:42:32,860 DEBUG pyon.core.governance.governance_controller GovernanceController.__init__()
2012-02-10 13:42:32,860 DEBUG pyon.core.governance.governance_interceptor GovernanceInterceptor enabled: False
:: _T created
:: _T statting to run
:: _T running ...
:: thread started
:: sleeping
:: _T running ...
:: _T running ...
:: ending thread
"""
# uncomment to see the described behaviour
#import pyon.util.unit_test
import unittest
from threading import Thread
import time
from nose.plugins.attrib import attr
import os
@unittest.skipIf(None == os.getenv('run_it'), 'define run_it to run this.')
@attr('UNIT', group='mi')
class _T(Thread):
def __init__(self):
Thread.__init__(self, name="_T")
self._active = True
print ":: _T created"
def end(self):
self._active = False
def run(self):
print ":: _T statting to run"
while self._active:
print ":: _T running ..."
time.sleep(0.5)
class ThreadTest(unittest.TestCase):
def setUp(self):
self.thread = _T()
self.thread.start()
print ":: thread started"
def tearDown(self):
print ":: ending thread"
self.thread.end()
self.thread.join()
def test_simple(self):
print ":: sleeping"
time.sleep(2)
if __name__ == '__main__':
t = ThreadTest('test_simple')
t.run()
| 34ef54f88a7faa25e08e74468fd72fc2fd9cb852 | [
"Python",
"Text"
] | 70 | Python | daf/coi-services | 4a31105d228e1a1a7e9398081634790432ebb618 | fcff3b85a35a8b3da52149f51169003585fb55dd |
refs/heads/master | <file_sep>namespace Main.UI {
export interface IResourceGaugeStyleData {
name: string;
isHorizontal?: boolean;
backgroundWidth?: number;
foregroundWidth?: number;
backgroundHeight?: number;
foregroundHeight?: number;
backgroundOffsetX?: number;
foregroundOffsetX?: number;
backgroundOffsetY?: number;
foregroundOffsetY?: number;
backgroundImageKey?: string;
foregroundImageKey?: string;
backgroundColor?: string;
foregroundColor?: string;
}
export class ResourceGauge implements INamed {
private background: Phaser.Sprite = null;
private foreground: Phaser.Sprite = null;
public constructor(
public name: string,
public x: number,
public y: number,
public style: IResourceGaugeStyleData,
public resource?: Mechanics.Resource,
) {
const bgData = game.add.bitmapData(
style.backgroundWidth,
style.backgroundHeight
);
const fgData = game.add.bitmapData(
style.foregroundWidth,
style.foregroundHeight
);
if (this.style.backgroundColor && this.style.foregroundColor) {
bgData.ctx.beginPath();
fgData.ctx.beginPath();
bgData.ctx.rect(0, 0, 2, 2);
fgData.ctx.rect(0, 0, 2, 2);
bgData.ctx.fillStyle = style.backgroundColor;
fgData.ctx.fillStyle = style.foregroundColor;
bgData.ctx.fill();
fgData.ctx.fill();
this.background = game.add.sprite(
this.x,
this.y,
bgData
);
this.foreground = game.add.sprite(
this.x + this.style.foregroundOffsetX,
this.y + this.style.foregroundOffsetY,
fgData
);
} else if (this.style.backgroundImageKey && this.style.foregroundImageKey) {
this.background = game.add.sprite(
this.x,
this.y,
this.style.backgroundImageKey
);
this.foreground = game.add.sprite(
this.x + this.style.foregroundOffsetX,
this.y + this.style.foregroundOffsetY,
this.style.foregroundImageKey
);
} else {
console.error(`Gauge style ${this.style.name} requires either a bg/fg image key or a bg/fg style. This type of gauge will throw errors.`);
}
this.background.fixedToCamera = true;
this.foreground.fixedToCamera = true;
let bgWidth = 0;
let bgHeight = 0;
let fgWidth = 0;
let fgHeight = 0;
if (this.style.isHorizontal) {
bgHeight = this.style.backgroundHeight;
bgWidth = this.style.backgroundWidth;
fgHeight = this.style.foregroundHeight;
let newWidth: number;
if (resource)
newWidth = (this.resource.current / this.resource.workingMax) * this.style.foregroundWidth;
else
newWidth = 0;
fgWidth = newWidth;
} else {
bgWidth = this.style.backgroundWidth;
bgHeight = this.style.backgroundHeight;
fgWidth = this.style.foregroundWidth;
let newHeight: number;
if (resource)
newHeight = (this.resource.current / this.resource.workingMax) * this.style.foregroundHeight;
else
newHeight = 0;
fgHeight = newHeight;
}
this.background.scale.setTo(bgWidth, bgHeight);
this.foreground.scale.setTo(fgWidth, fgHeight);
}
public bindResource(resource: Mechanics.Resource): void {
this.resource = resource;
this.update();
}
public update(): void {
if (this.style.isHorizontal) {
const newWidth = (this.resource.current / this.resource.workingMax) * this.style.foregroundWidth;
this.foreground.scale.x = newWidth;
} else {
const newHeight = (this.resource.current / this.resource.workingMax) * this.style.foregroundHeight;
this.foreground.scale.y = newHeight;
}
}
}
export class ResourceGaugeFactory {
public styles: IResourceGaugeStyleData[] = [];
public constructor() {
}
public initialize(): void {
const data = game.cache.getJSON('ui-styles');
const gaugeData = data["gauges"];
for (let current of gaugeData) {
this.styles.push(current);
}
}
public create(
name: string,
x: number,
y: number,
style?: string,
resource?: Mechanics.Resource
): ResourceGauge {
let gaugeStyle: IResourceGaugeStyleData;
if (!style) {
if (this.styles.length === 0) {
console.error(`Styles need to be added for Gauges.`);
return null;
}
gaugeStyle = this.styles[0];
} else {
gaugeStyle = this.styles.getByName(style);
if (gaugeStyle == null) {
console.error(`There's no Gauge style named ${style}`);
console.error(`${JSON.stringify(this.styles)}`);
return null;
}
}
const gauge = new ResourceGauge(name, x, y, gaugeStyle, resource);
return gauge;
}
}
}<file_sep>namespace Main.UI {
export interface IUILayoutElement extends INamed {
type: string,
name: string,
x: number,
y: number,
style: string
}
export interface IUILayout extends INamed {
name: string,
elements: IUILayoutElement[]
}
export type ILayoutElement = INamedPhaserText | ResourceGauge
export class Layout {
public elements: ILayoutElement[] = [];
public constructor(layoutKey: string) {
this.generateElements(layoutKey);
}
public getElement(elementKey: string): ILayoutElement {
return <ILayoutElement>this.elements.getByName(elementKey);
}
public generateElements(layoutKey: string): void {
const layoutData = game.cache.getJSON('ui-layouts');
const chosenLayout = <IUILayout>(layoutData['layouts'].getByName(layoutKey));
if (chosenLayout == null) {
console.error(`UI Layout ${layoutKey} doesn't exist in the layouts JSON file.`);
return;
}
for (let current of chosenLayout.elements) {
switch (current.type) {
case "text":
const newText: INamedPhaserText = textFactory.create(
current.name,
current.x,
current.y,
current.style
);
this.elements.push(newText);
break;
case "gauge":
const newGauge: ResourceGauge = resourceGaugeFactory.create(
current.name,
current.x,
current.y,
current.style
);
this.elements.push(newGauge);
break;
default:
console.warn(`Element ${current.name} won't be added, as element type ${current.type} has no generation behavior defined.`);
break;
}
}
}
}
}<file_sep>namespace Main.States {
export class GameState extends Phaser.State {
public map: Services.Map = null;
public player: Entities.Player = null;
public layout: UI.Layout = null;
public mobPool: Entities.MobPool = null;
private npc: Entities.Mob = null;
private testTrigger: Entities.Trigger = null;
public preload(): void {
}
public create(): void {
game.physics.startSystem(Phaser.Physics.ARCADE);
this.map = mapService.loadMap('overworld');
this.mobPool = new Entities.MobPool();
this.player = <Entities.Player>this.mobPool.add('player', 'player', 96, 96);
this.npc = this.mobPool.add('npc', 'npc', 96, 192);
this.testTrigger = new Entities.Trigger(16, 192, 16, 32, this.onEnterSceneChangeTrigger.bind(this));
this.map.elevateOverlayLayer();
this.layout = new UI.Layout('game-ui');
const skillUpLabel: Phaser.Text = <Phaser.Text>(this.layout.getElement('skillUpLabel'));
skillUpLabel.alpha = 0;
skillUpLabel.fixedToCamera = true;
this.player.onSkillUp = this.onPlayerSkillUp.bind(this);
const healthGauge: UI.ResourceGauge = <UI.ResourceGauge>this.layout.getElement('health');
healthGauge.bindResource(this.player.health);
this.player.health.onChange = this.onPlayerHealthChange.bind(this);
const staminaGauge: UI.ResourceGauge = <UI.ResourceGauge>(this.layout.getElement('stamina'));
const playerStamina = this.player.getResourceByName("Stamina");
staminaGauge.bindResource(playerStamina);
playerStamina.onChange = this.onPlayerStaminaChange.bind(this);
cameraService.bindCamera(this.player);
cameraService.fadeIn(() => {});
}
private onEnterSceneChangeTrigger(): void {
if (this.testTrigger.isTriggered)
return;
cameraService.fadeOut(() => {
stateService.load('title');
});
}
private onPlayerSkillUp(skill: Mechanics.SkillLine): void {
const skillUpLabel: Phaser.Text = <Phaser.Text>(this.layout.getElement('skillUpLabel'));
skillUpLabel.setText(`${skill.name} has increased to ${skill.level}`);
skillUpLabel.x = game.canvas.width / 2 - skillUpLabel.width / 2;
skillUpLabel.y = 100
skillUpLabel.fixedToCamera = true;
game.add.tween(skillUpLabel).to(
{alpha: 1},
500,
Phaser.Easing.Linear.None,
true
);
game.time.events.add(3000, () => {
game.add.tween(skillUpLabel).to(
{alpha: 0},
500,
Phaser.Easing.Linear.None,
true
);
});
}
private onPlayerHealthChange(): void {
const healthGauge: UI.ResourceGauge = <UI.ResourceGauge>(this.layout.getElement('health'));
healthGauge.update();
}
private onPlayerStaminaChange(): void {
const staminaGauge: UI.ResourceGauge = <UI.ResourceGauge>(this.layout.getElement('stamina'));
staminaGauge.update();
}
public update(): void {
const deltaTime = this.game.time.physicsElapsed;
this.player.onUpdate(deltaTime);
this.player.checkCollisionWith(this.npc);
this.player.checkCollisionWith(this.map);
this.npc.checkCollisionWith(this.map);
this.testTrigger.checkOverlapsWith(this.player);
}
public render(): void {
}
}
}<file_sep>namespace Main.States {
export class TitleState extends Phaser.State {
public cursors: Phaser.CursorKeys;
public mainMenu: UI.Menu;
public preload(): void {
}
public create(): void {
inputService.initialize();
const toGameState = () => {
cameraService.fadeOut(() => {
stateService.load('game');
});
};
const data = new UI.MenuData(
[
new UI.MenuOptionData('New Game', 8, 240, toGameState),
new UI.MenuOptionData('Continue', 8, 280, toGameState)
],
0
);
this.mainMenu = menuFactory.create(data);
this.mainMenu.grantKeyControl();
}
public update(): void {
}
public shutdown(): void {
this.mainMenu.releaseKeyControl();
}
}
}<file_sep>namespace Main.Services {
export class SceneChangeService {
public mapKey: string = '';
public x: number = 0;
public y: number = 0;
public constructor() {
}
}
}<file_sep>namespace Main.Mechanics {
export class Resource implements INamed {
public current: number;
public workingMax: number;
public onChange: () => void;
public constructor(
public name: string,
public max: number
) {
this.current = this.max;
this.workingMax = this.max;
}
public hasEnough(amount: number): boolean {
return this.current >= amount;
}
public gain(amount: number): void {
const preGain = this.current;
this.current += amount;
if (this.current > this.workingMax)
this.current = this.workingMax;
const postGain = this.current;
if(preGain != postGain)
this.fireChangeEvent();
}
public consume(amount: number): boolean {
if (!this.hasEnough(amount))
return false;
const preConsume = this.current;
this.current -= amount;
if (this.current <= 0)
this.current = 0;
const postConsume = this.current;
if (preConsume != postConsume)
this.fireChangeEvent();
return true;
}
public augment(amount: number): void {
this.workingMax += amount;
if (this.workingMax > this.max)
this.workingMax = this.max;
}
public diminish(amount: number): void {
this.workingMax -= amount;
if (this.workingMax <= 0)
this.workingMax = 0;
if (this.current >= this.workingMax) {
const preDiminish = this.current;
this.current = this.workingMax;
if (this.current < 0)
this.current = 0;
const postDiminish = this.current;
if (preDiminish != postDiminish)
this.fireChangeEvent();
}
}
protected fireChangeEvent(): boolean {
if (!this.onChange)
return false;
this.onChange();
return true;
}
}
export class HealthSystem extends Resource {
public constructor(
public max: number,
public onHealed: () => void,
public onHurt: () => void,
public onDeath: () => void
) {
super("Health", max);
}
public gain(amount: number): void {
if (amount <= 0)
return;
const preHealHP: number = this.current;
this.current += amount;
if (this.current >= this.workingMax)
this.current = this.workingMax;
const postHealHP: number = this.current;
if (preHealHP !== postHealHP) {
this.fireChangeEvent();
this.onHealed();
}
}
public consume(amount: number): boolean {
if (amount <= 0)
return false;
const preHurtHP: number = this.current;
this.current -= amount;
if (this.current <= 0)
this.current = 0;
const postHurtHP: number = this.current;
if (preHurtHP !== postHurtHP) {
this.fireChangeEvent();
this.onHurt();
this.checkForDeath();
return true;
}
return false;
}
public checkForDeath(): void {
if (this.current >= 0)
return;
this.onDeath();
}
public diminish(amount: number): void {
this.workingMax -= amount;
if (this.workingMax > this.current) {
this.current = this.workingMax;
this.fireChangeEvent();
this.onHurt();
this.checkForDeath();
}
}
}
}<file_sep>{
"compilerOptions": {
"target": "es5",
"alwaysStrict": true,
"sourceMap": true,
"outFile": "./fullapp.js",
"typeRoots": [
"./node_modules/phaser-ce/typescript"
]
},
"exclude": [
"assets/maps/*.tsx"
],
"compileOnSave": true
}<file_sep>namespace Main.UI {
export type INamedPhaserTextStyle = Phaser.PhaserTextStyle & INamed;
export type INamedPhaserText = Phaser.Text & INamed;
export class TextFactory {
public styles: INamedPhaserTextStyle[] = [];
public constructor() {
}
public initialize(): void {
const data = game.cache.getJSON('ui-styles');
const styleData = data['text'];
for (let current of styleData) {
this.styles.push(current);
}
}
public create(
name: string,
x: number,
y: number,
text: string,
style?: string
): INamedPhaserText {
let styleData: INamedPhaserTextStyle;
if (!style) {
styleData = JSON.parse(JSON.stringify(this.styles[0]));
} else {
styleData = JSON.parse(JSON.stringify(this.styles.getByName(style)));
}
const newText: INamedPhaserText = game.add.text(x, y, text, styleData);
newText.name = name;
this.setSecondaryStyleData(<Phaser.Text>newText, styleData);
return newText;
}
private setSecondaryStyleData(text: Phaser.Text, style: any): void {
if (style["alpha"]) {
const alpha: number = style["alpha"];
text.alpha = alpha;
}
}
}
}<file_sep>namespace Main.States {
export class InitState extends Phaser.State {
public preload() {
game.load.image('overworld-tiles', 'assets/images/tiles.png');
game.load.tilemap('test-map', 'assets/maps/test-3.json', null, Phaser.Tilemap.TILED_JSON);
game.load.spritesheet('human-template', 'assets/images/human-template.png', 16, 16);
game.load.spritesheet('hero-male', 'assets/images/hero-male.png', 16, 16);
// Used by UI factories
game.load.json('ui-styles', 'assets/ui/styles.json');
// Used to auto-create UIs
game.load.json('ui-layouts', 'assets/ui/layouts.json');
// Used by the Map Service to build maps on the fly without hardcoding every single map.
game.load.json('map-data', 'assets/maps/map-data.json');
// Used by the Entity system to set up mob stats, also without hardcoding every single one.
game.load.json('entity-stats', 'assets/entities/entities.json');
// Used by various Mobs to set up their animations, again without hardcoding every single one.
game.load.json('template-animations', 'assets/animations/template-animations.json');
game.load.json('player-animations', 'assets/animations/player-animations.json');
// Used by the Skill Line factory, to ensure that all mobs have the same skill lines.
game.load.json('skill-line-defaults', 'assets/mechanics/skill-line-defaults.json');
}
public create() {
// Ready any services...
inputService.initialize();
// Ready any factories...
textFactory.initialize();
menuFactory.iniitalize();
resourceGaugeFactory.initialize();
skillLineFactory.initialize();
// Actually start the game proper.
stateService.load('title');
}
public update() {
}
}
}<file_sep>namespace Main.Services {
export type InputControl = (Phaser.Key | Phaser.DeviceButton);
export class InputAxis implements INamed {
public constructor(
public name: string = '',
public positiveBindings: InputControl[],
public negativeBindings: InputControl[]
) {
}
public value(): number {
let result: number = 0;
const checkBindingContribution = (binding: InputControl, addedValue: number): number => {
let contribution: number = 0;
if (binding instanceof Phaser.Key || binding instanceof Phaser.DeviceButton)
if (binding.isDown)
contribution = addedValue;
return contribution;
};
for (let current of this.positiveBindings) {
result += checkBindingContribution(current, 1);
}
for (let current of this.negativeBindings) {
result += checkBindingContribution(current, -1);
}
return result;
}
public isPressed(): boolean {
let result: boolean = false;
const checkBindingState = (binding: InputControl): boolean => {
if (binding instanceof Phaser.Key || binding instanceof Phaser.DeviceButton)
return binding.isDown;
return false;
}
for (let current of this.positiveBindings) {
result = result || checkBindingState(current);
}
for (let current of this.negativeBindings) {
result = result || checkBindingState(current);
}
return result;
}
}
export class InputService {
private cursors: Phaser.CursorKeys;
private pad: Phaser.SinglePad;
public axes: InputAxis[] = [];
public constructor() {
}
// This should only be ran in state create() methods, so that game.input is
// set up.
public initialize(): void {
this.axes.length = 0; // Clear the axes...
this.cursors = game.input.keyboard.createCursorKeys();
// TODO: ...Can we make a factory, and source these bindings from JSON?
this.addAxis(
"horizontal",
[ this.cursors.right ],
[ this.cursors.left ]
);
this.addAxis(
"vertical",
[ this.cursors.down ],
[ this.cursors.up ]
);
this.addAxis(
"dash",
[ game.input.keyboard.addKey(Phaser.KeyCode.SHIFT) ]
);
this.addAxis(
"attack",
[ game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR) ]
);
this.addAxis(
"block",
[ game.input.keyboard.addKey(Phaser.KeyCode.TAB) ]
);
this.addAxis(
"confirm",
[ game.input.keyboard.addKey(Phaser.KeyCode.ENTER) ]
);
this.addAxis(
"cancel",
[ game.input.keyboard.addKey(Phaser.KeyCode.ESC) ]
);
// this.pad = this.game.input.gamepad.pad1;
// this.pad.addCallbacks(this, {
// onConnect: this.addGamepadSupport
// });
}
// public addGamepadSupport(): void {
// const vAxis = this.getAxis('vertical');
// const hAxis = this.getAxis('horizontal');
// const dash = this.getAxis('dash');
// const confirm = this.getAxis('confirm');
// const cancel = this.getAxis('cancel');
// const attack = this.getAxis('attack');
// const block = this.getAxis('block');
// // TODO: Detect common gamepad types, and set the gamepad up as appropriate.
// const dpadUp = this.pad.getButton(Phaser.Gamepad.XBOX360_DPAD_UP);
// const dpadDown = this.pad.getButton(Phaser.Gamepad.XBOX360_DPAD_DOWN);
// const dpadLeft = this.pad.getButton(Phaser.Gamepad.XBOX360_DPAD_LEFT);
// const dpadRight = this.pad.getButton(Phaser.Gamepad.XBOX360_DPAD_RIGHT);
// const dpadA = this.pad.getButton(Phaser.Gamepad.XBOX360_A);
// const dpadB = this.pad.getButton(Phaser.Gamepad.XBOX360_A);
// const dpadX = this.pad.getButton(Phaser.Gamepad.XBOX360_A);
// const dpadY = this.pad.getButton(Phaser.Gamepad.XBOX360_A);
// const dpadL2 = this.pad.getButton(Phaser.Gamepad.XBOX360_LEFT_TRIGGER);
// const dpadR2 = this.pad.getButton(Phaser.Gamepad.XBOX360_RIGHT_TRIGGER);
// vAxis.positiveBindings.push(dpadUp);
// vAxis.negativeBindings.push(dpadDown);
// hAxis.positiveBindings.push(dpadRight);
// hAxis.negativeBindings.push(dpadLeft);
// dash.positiveBindings.push(dpadX);
// confirm.positiveBindings.push(dpadA);
// cancel.positiveBindings.push(dpadB);
// attack.positiveBindings.push(dpadR2);
// block.positiveBindings.push(dpadL2);
// }
public addAxis(
name: string,
positiveBindings?: (Phaser.Key[] | Phaser.DeviceButton[]),
negativeBindings?: (Phaser.Key[] | Phaser.DeviceButton[])
): void {
if (this.getAxis(name) != null) {
console.error(`Axis not registered - ${name} is already registered in the Input Service.`);
return;
}
if (!positiveBindings && !negativeBindings) {
console.error(`Axis ${name} requires at least a positive or a negative binding to be registered.`);
return;
}
if (!positiveBindings)
positiveBindings = [];
if (!negativeBindings)
negativeBindings = [];
const axis: InputAxis = new InputAxis(
name,
positiveBindings,
negativeBindings
);
this.axes.push(axis);
}
public getAxis(name: string): InputAxis {
return <InputAxis>(this.axes.getByName(name));
}
public addHandlerToAxis(
name: string,
positiveHandler?: () => void,
negativeHandler?: () => void
) {
if (!positiveHandler && !negativeHandler) {
console.error(`addHandlerToAxis requires at least a positive or a negative control handler.`);
return;
}
const axis: InputAxis = this.getAxis(name);
if (axis == null) {
console.error(`Axis ${axis.name} has not been registered in the Input Service.`);
return;
}
const bindHandler = (
control: (Phaser.Key | Phaser.DeviceButton),
handler: () => void
) => {
if (control instanceof Phaser.Key) {
control.onDown.add(positiveHandler);
} else if (control instanceof Phaser.DeviceButton) {
control.onDown.add(positiveHandler);
}
};
if (positiveHandler) {
for (let current of axis.positiveBindings) {
bindHandler(current, positiveHandler);
}
}
if (negativeHandler) {
for (let current of axis.negativeBindings) {
bindHandler(current, negativeHandler);
}
}
}
public removeHandlerFromAxis(
name: string,
positiveHandler?: () => void,
negativeHandler?: () => void
): void {
if (!positiveHandler && !negativeHandler) {
console.error(`addHandlerToAxis requires at least a positive or a negative control handler.`);
return;
}
const axis: InputAxis = this.getAxis(name);
if (axis == null) {
console.error(`Axis ${axis.name} has not been registered in the Input Service.`);
return;
}
const removeHandler = (
control: (Phaser.Key | Phaser.DeviceButton),
handler: () => void
) => {
control.onDown.remove(handler);
};
if (positiveHandler)
for (let current of axis.positiveBindings) {
removeHandler(current, positiveHandler);
}
if (negativeHandler)
for (let current of axis.negativeBindings) {
removeHandler(current, negativeHandler);
}
}
}
}<file_sep>namespace Main.Services {
export class StateService {
public states: { key: string, state: any}[] = [];
public constructor(
private game: Phaser.Game
) {
}
public addState(key: string, state: any): void {
this.states.push({
key: key,
state: state
});
}
public readyStates(): void {
for (let current of this.states) {
this.game.state.add(current.key, current.state);
}
}
public startFirstState(): void {
this.game.state.start(this.states[0].key);
}
public load(state: string): void {
this.game.state.start(state, true, false);
}
public overlay(state: string): void {
this.game.state.start(state, false, false);
}
}
}<file_sep>namespace Main.Mechanics {
export enum SkillLineLevelupType {
LINEAR,
EXPONENTIAL,
LOGARITHMIC
}
export class SkillLineLevelupData {
// Programmer's Notes:
// -------------------
// Based on the levelup type, generate a
// function to raise the amount of XP
// required to raise a skill line.
//
// Linear: ttnl = base + (modifier * previous)
// Exponential: ttnl = base + (previous ^ modifier)
// Logarithmic: ttnl = base + previous LOG modifier
public constructor(
public type: SkillLineLevelupType = SkillLineLevelupType.LINEAR,
public base: number = 1,
public modifier: number = 1
) {
}
public generateNextXPTNL(): (previous: number) => number {
switch (this.type) {
case SkillLineLevelupType.LINEAR:
return (previous: number) => this.base + (this.modifier * previous);
case SkillLineLevelupType.EXPONENTIAL:
return (previous: number) => this.base + (previous ^ this.modifier);
case SkillLineLevelupType.LOGARITHMIC:
return (previous: number) => this.base + (previous * Math.log(this.modifier));
default:
console.error(`Unexpected levelup type: ${this.type}`);
return (previous: number) => this.base;
}
}
}
export class SkillLine implements INamed {
public xp: number;
public xpToNextLevel: number;
public level: number;
public constructor(
public name: string,
public description: string,
defaultLevel: number = 1,
defaultXp: number = 0,
defaultXpToNextLevel: number = 5,
public levelupData: SkillLineLevelupData = new SkillLineLevelupData(),
public onLevelUp?: () => void
) {
this.level = defaultLevel;
this.xp = defaultXp;
this.xpToNextLevel = defaultXpToNextLevel;
}
public gainXP(amount: number) {
this.xp += amount;
if (this.xp >= this.xpToNextLevel) {
this.xp = this.xp - this.xpToNextLevel;
this.level++;
console.log(`${this.name} has increased to ${this.level}`);
this.xpToNextLevel = this.levelupData.generateNextXPTNL()(this.xpToNextLevel);
if (this.onLevelUp)
this.onLevelUp();
}
}
public loseXP(amount: number) {
this.xp -= amount;
if (this.xp <= 0)
this.xp = 0;
}
public clone(): SkillLine {
const clone = new SkillLine(
this.name,
this.description,
this.level,
this.xp,
this.xpToNextLevel,
this.levelupData,
this.onLevelUp
);
return clone;
}
}
export class SkillLineFactory {
private skillLines: SkillLine[] = [];
public constructor() {
}
public initialize(): void {
const data = game.cache.getJSON('skill-line-defaults');
for (let current of data['skillLines']) {
const newSkill = new SkillLine(
current['name'],
current['description'],
current['defaultLevel'],
current['defaultXp'],
current['defaultXpToNextLevel']
);
this.skillLines.push(newSkill);
}
}
public generateSkillLines(): SkillLine[] {
const clone: SkillLine[] = [];
for (let current of this.skillLines) {
clone.push(current.clone());
}
return clone;
}
}
}<file_sep>namespace Main.Services {
export class Map {
public layers: Phaser.TilemapLayer[] = [];
public collisionLayer: Phaser.TilemapLayer = null;
public overlayLayer: Phaser.TilemapLayer = null;
public constructor(
public map: Phaser.Tilemap,
public tileSetKey: string,
public tileSize: number,
public tileScale: number
) {
this.map.addTilesetImage(tileSetKey, tileSetKey, tileSize, tileSize);
const firstLayer = this.addLayer(0);
firstLayer.resizeWorld();
}
public addLayer(layerId: number | string): Phaser.TilemapLayer {
const newLayer: Phaser.TilemapLayer = this.map.createLayer(layerId);
newLayer.setScale(this.tileScale, this.tileScale);
this.layers.push(newLayer);
return newLayer;
}
public addCollisionLayer(
layerId: number | string,
firstCollisionTileIndex: number = 1,
lastCollisionTileIndex: number = 1,
collisionGroup?: Phaser.Group
): Phaser.TilemapLayer {
const collisionLayer: Phaser.TilemapLayer = this.addLayer(layerId);
this.map.setCollisionBetween(
firstCollisionTileIndex,
lastCollisionTileIndex,
true,
collisionLayer,
true
);
if (collisionGroup) {
// Assume that a collision group exists,
// and that it has or will have physics and collisions
// set up on it.
collisionGroup.add(collisionLayer);
} else {
game.physics.enable(collisionLayer, Phaser.Physics.ARCADE);
const body = <Phaser.Physics.Arcade.Body>collisionLayer.body;
body.immovable = true;
}
this.collisionLayer = collisionLayer;
return collisionLayer;
}
public addOverlayLayer(
layerId: number | string
): Phaser.TilemapLayer {
const layer = this.addLayer(layerId);
this.overlayLayer = layer;
return layer;
}
public elevateOverlayLayer(): void {
this.overlayLayer.bringToTop();
}
public checkCollisionWith(other: any, onCollide?: () => void): void {
let collidingObject: ICollidableObject;
switch (other.constructor) {
case Entities.Mob:
collidingObject = other.gameObject;
break;
default:
collidingObject = other;
break;
}
game.physics.arcade.collide(this.collisionLayer, collidingObject, onCollide);
}
}
export class MapService {
public constructor(
) {
}
public loadMap(
key: string,
collisionGroup?: Phaser.Group
): Map {
const data: any = game.cache.getJSON('map-data');
const generationData = data['maps'].getByName(key);
// Create the general map from the data...
const tileSize: number = generationData["tileSize"];
const map: Phaser.Tilemap = game.add.tilemap(generationData["key"], tileSize, tileSize);
const result: Map = new Map(map, generationData["tilesetKey"], tileSize, generationData["tileScale"]);
// Build layers from data...
for (let currentLayer of generationData["layers"]) {
const index: number = currentLayer["index"];
switch (currentLayer["type"].toLowerCase()) {
case "collision":
console.log(`Adding layer ${index} as a collision layer...`);
if (!currentLayer["layerName"])
result.addCollisionLayer(
index,
currentLayer["startCollisionIndex"],
currentLayer["endCollisionIndex"],
collisionGroup
);
else
result.addCollisionLayer(
currentLayer["layerName"],
currentLayer["startCollisionIndex"],
currentLayer["endCollisionIndex"],
collisionGroup
);
break;
case "overlay":
result.addOverlayLayer(index);
break;
default:
result.addLayer(index);
break;
}
}
return result;
}
}
}<file_sep>namespace Main {
export interface INamed {
name: string;
}
}<file_sep>namespace Main.Services {
export class SceneService {
public constructor() {
}
public bindCamera(mob: Entities.Mob): void {
game.camera.follow(mob.gameObject.animations.sprite);
}
public pan(x: number, y: number): void {
game.camera.x += x;
game.camera.y += y;
}
public fadeOut(
onComplete: () => void,
durationMs: number = 1000,
fadeColor: number = 0x000000
): void {
const onNextFadeDone = () => {
onComplete();
game.camera.onFadeComplete.removeAll();
};
game.camera.onFadeComplete.add(onNextFadeDone);
game.camera.fade(fadeColor, durationMs);
}
public fadeIn(
onComplete: () => void,
durationMs: number = 1000,
fadeColor: number = 0x000000
): void {
const onNextFadeDone = () => {
onComplete();
game.camera.onFlashComplete.removeAll();
};
game.camera.onFlashComplete.add(onNextFadeDone);
game.camera.flash(fadeColor, durationMs);
}
}
}<file_sep>namespace Main.Entities {
export class Trigger {
public gameObject: Phaser.Sprite = null;
public isTriggered: boolean = false;
public constructor(
public x: number,
public y: number,
public width: number,
public height: number,
public onEnter: (gameObject: Phaser.Sprite, other: ICollidableObject) => void
) {
const spriteData = game.add.bitmapData(width, height).fill(0, 0, 0, 0);
this.gameObject = game.add.sprite(x, y, spriteData);
this.gameObject.scale = new Phaser.Point(gfxMagnification, gfxMagnification);
this.readyPhysics();
}
private readyPhysics(): void {
game.physics.enable(this.gameObject, Phaser.Physics.ARCADE);
this.gameObject.anchor.set(0.5, 0.5);
const body = this.body();
body.immovable = true;
body.bounce.setTo(0);
body.collideWorldBounds = true;
}
public body(): Phaser.Physics.Arcade.Body {
return <Phaser.Physics.Arcade.Body>this.gameObject.body;
}
public checkOverlapsWith(other: any): void {
let collidableObject: ICollidableObject;
switch (other.constructor) {
case Entities.Mob:
case Entities.Player:
collidableObject = <Mob>(other).gameObject;
break;
default:
collidableObject = other;
break;
}
this.isTriggered = game.physics.arcade.overlap(this.gameObject, collidableObject, this.onEnter);
}
}
}<file_sep>interface Array<T> {
getByName: (this: Main.INamed[], name: string) => Main.INamed | null;
}
Array.prototype.getByName = function(name: string) {
let result: Main.INamed = null;
for (let current of this) {
if (current.name !== name)
continue;
result = current;
break;
}
return result;
};<file_sep>namespace Main.Mechanics {
export class ModifiableStat implements INamed {
public scalingModifier: number = 1.0;
public staticModifier: number = 0.0;
public constructor(
public name: string,
public value: number
) {
}
public modifiedValue(): number {
return (this.value * this.scalingModifier) + this.staticModifier;
}
public addBaseValue(baseChange: number): void {
this.value += baseChange;
}
public addScaledEffect(scalingChange: number): void {
this.scalingModifier += scalingChange;
}
public addStaticEffect(staticChange: number): void {
this.scalingModifier += staticChange;
}
public clearModifiers(): void {
this.scalingModifier = 1.0;
this.staticModifier = 0.0;
}
}
}<file_sep>/// <reference path="../node_modules/phaser-ce/typescript/phaser.d.ts" />
namespace Main {
export type ICollidableObject = Entities.Mob
| Entities.Player
| Services.Map
| Phaser.Sprite
| Phaser.Group
| Phaser.Tilemap
| Phaser.TilemapLayer;
export var gfxMagnification: number = 3;
export var game: Phaser.Game = null;
export var mapService: Services.MapService = null;
export var stateService: Services.StateService = null;
export var inputService: Services.InputService = null;
export var cameraService: Services.SceneService = null;
export var sceneChangeService: Services.SceneChangeService = null;
export var menuFactory: UI.MenuFactory = null;
export var textFactory: UI.TextFactory = null;
export var resourceGaugeFactory: UI.ResourceGaugeFactory = null;
export var skillLineFactory: Mechanics.SkillLineFactory = null;
export class App {
private game: Phaser.Game = null;
public constructor() {
this.game = new Phaser.Game(
640, 480,
Phaser.CANVAS,
'content',
null,
false,
false
);
this.registerFactories();
this.registerServices();
this.registerStates();
game = this.game;
this.appStart();
}
private registerServices(): void {
stateService = new Services.StateService(this.game);
inputService = new Services.InputService();
mapService = new Services.MapService();
cameraService = new Services.SceneService();
sceneChangeService = new Services.SceneChangeService();
}
private registerFactories(): void {
menuFactory = new UI.MenuFactory();
textFactory = new UI.TextFactory();
resourceGaugeFactory = new UI.ResourceGaugeFactory();
skillLineFactory = new Mechanics.SkillLineFactory();
// TODO: More factories.
}
private registerStates(): void {
stateService.addState('init', States.InitState);
stateService.addState('title', States.TitleState);
stateService.addState('game', States.GameState);
stateService.readyStates();
}
private appStart(): void {
stateService.startFirstState();
}
}
}
window.onload = () => {
const app = new Main.App();
};<file_sep>namespace Main.Entities {
export enum EntityDirections {
DOWN = 0,
LEFT,
RIGHT,
UP
}
export interface IMobMetaData extends INamed {
name: string,
isPlayerCharacter?: boolean,
imageKey: string,
animationKey: string,
tileSize: number,
aiScript?: string
}
export interface IMobStatData extends INamed {
name: string,
maxHP: number,
resources: {name: string, max: number}[],
stats: {name: string, value: number}[]
}
export class Mob implements INamed {
public isActive: boolean = true;
public mobType: string = '';
public gameObject: Phaser.TileSprite = null;
public direction: EntityDirections = EntityDirections.DOWN;
public health: Mechanics.HealthSystem = null;
public resources: Mechanics.Resource[] = [];
public stats: Mechanics.ModifiableStat[] = [];
public skillLines: Mechanics.SkillLine[] = [];
public onSkillUp: (skill: Mechanics.SkillLine) => void;
public constructor(
public name: string,
x: number,
y: number,
tileSize: number,
imageKey: string,
animationKey: string,
spriteScale: number = 1,
enablePhysics: boolean = true,
private frameRate: number = 8
) {
this.skillLines = skillLineFactory.generateSkillLines();
// Default stats; these should be overwritten by each type of mob.
this.health = new Mechanics.HealthSystem(4, this.onHealed, this.onHurt, this.onDeath);
// Create the actual game object for the mob.
this.gameObject = game.add.tileSprite(x, y, tileSize, tileSize, imageKey);
this.gameObject.scale = new Phaser.Point(spriteScale, spriteScale);
if (enablePhysics) {
this.readyPhysics();
}
// Bind animations...
this.addAnimationsFromFile(animationKey);
}
protected readyPhysics(): void {
game.physics.enable(this.gameObject, Phaser.Physics.ARCADE);
this.gameObject.anchor.set(0.5, 0.5);
const body = this.body();
body.bounce.setTo(0, 0);
body.collideWorldBounds = true;
body.allowDrag = true;
body.angularDrag = 1.0;
}
public body(): Phaser.Physics.Arcade.Body {
return <Phaser.Physics.Arcade.Body>this.gameObject.body;
}
public onHealed(): void {
}
public onHurt(): void {
}
public onDeath(): void {
}
public onUpdate(deltaTime: number): void {
}
public setStatsFromData(
data: IMobStatData,
mobType?: string
): void {
if (mobType)
this.mobType = mobType;
this.health = new Mechanics.HealthSystem(data.maxHP, this.onHealed, this.onHurt, this.onDeath);
for (let current of data.resources) {
const loadedResource = new Mechanics.Resource(
current.name,
current.max
);
this.resources.push(loadedResource);
}
for (let current of data.stats) {
const loadedStat = new Mechanics.ModifiableStat(
current.name,
current.value
);
this.stats.push(loadedStat);
}
}
public addAnimationsFromFile(jsonKey: string): Phaser.Animation[] {
const data = game.cache.getJSON(jsonKey);
const result: Phaser.Animation[] = [];
for (let current of data.animations) {
const newAnimation = this.addAnimation(current['key'], current['frames'], current['isLooped']);
result.push(newAnimation);
}
return result;
}
public getStatByName(name: string): Mechanics.ModifiableStat {
return <Mechanics.ModifiableStat>this.stats.getByName(name);
}
public getSkillLineByName(name: string): Mechanics.SkillLine {
return <Mechanics.SkillLine>this.skillLines.getByName(name);
}
public getResourceByName(name: string): Mechanics.Resource {
return <Mechanics.Resource>this.resources.getByName(name);
}
public addXpForSkill(
xp: number,
skill: string
): void {
const skillLine: Mechanics.SkillLine = this.getSkillLineByName(skill);
if (!skillLine) {
console.error(`Skill line ${skill} does not exist. Can't get XP for that line.`);
return;
}
const preXpLevel = skillLine.level;
skillLine.gainXP(xp);
const postXpLevel = skillLine.level;
if (postXpLevel > preXpLevel) {
if (this.onSkillUp)
this.onSkillUp(skillLine);
}
}
public getLevelForSkill(
skill: string
): number {
const skillLine = this.getSkillLineByName(skill);
if (!skillLine) {
console.error(`Skill line ${skill} does not exist. Can't get XP for that line.`);
return -1;
}
return skillLine.level;
}
public addAnimation(key: string, frames: number[], isLooped: boolean = true): Phaser.Animation {
return this.gameObject.animations.add(key, frames, this.frameRate, isLooped);
}
public checkCollisionWith(other: any, onCollide?: () => void): void {
let collidingObject: ICollidableObject;
switch (other.constructor) {
case Mob:
collidingObject = <Mob>(other).gameObject;
break;
case Services.Map:
collidingObject = <Services.Map>(other).collisionLayer;
break;
default:
collidingObject = other;
break;
}
game.physics.arcade.collide(this.gameObject, collidingObject, onCollide);
}
}
}<file_sep>namespace Main.Entities {
export class MobPool {
private entityData: (IMobMetaData & IMobStatData)[] = []
public mobs: Mob[] = [];
public constructor() {
const rawData = game.cache.getJSON('entity-stats');
this.entityData = rawData['entities'];
}
public getByName(name: string): Mob {
return <Mob>this.mobs.getByName(name);
}
public getFirstInactive(): Mob {
let result: Mob = null;
for (let current of this.mobs) {
if (current.isActive)
continue;
result = current;
break;
}
return result;
}
public add(
name: string,
mobType: string,
x: number,
y: number,
dontOverwriteExisting: boolean = false
): Mob {
let existingEntry = this.getFirstInactive();
if (!existingEntry || dontOverwriteExisting) {
const newEntry = this.create(name, mobType, x, y);
this.mobs.push(newEntry);
return newEntry;
}
else {
existingEntry = this.create(name, mobType, x, y);
return existingEntry;
}
}
private create(
name: string,
mobType: string,
x: number,
y: number
): Mob {
const data: INamed = this.entityData.getByName(mobType);
const mobData: IMobMetaData = <IMobMetaData>data;
const statData: IMobStatData = <IMobStatData>data;
let newMob: Mob;
if (!mobData.isPlayerCharacter) {
newMob = new Mob(
name,
x,
y,
mobData.tileSize,
mobData.imageKey,
mobData.animationKey,
gfxMagnification
);
newMob.setStatsFromData(statData);
} else {
newMob = new Player(
name,
x,
y,
mobData.tileSize,
mobData.imageKey,
mobData.animationKey,
statData,
gfxMagnification
);
}
return newMob;
}
public inactivate(mobName: string): Mob {
const mob: Mob = this.getByName(mobName);
if (!mob) {
console.error(`Can't inactivate mob ${mobName}, as they don't exist in the pool.`);
return;
}
mob.gameObject.alive = false;
}
public remove(mobName: string): void {
const removeMob = this.inactivate(mobName);
const index = this.mobs.indexOf(removeMob);
if (index === -1) {
console.error(`Can't remove ${mobName} from the mob pool as they're not registered in it.`);
return;
}
this.mobs.splice(index, 1);
}
}
}<file_sep>namespace Main.Entities {
export class Player extends Mob {
public constructor(
name: string,
x: number,
y: number,
tileSize: number,
imageKey: string,
animationKey: string,
statData: IMobStatData,
spriteScale: number
) {
super(
name,
x,
y,
tileSize,
imageKey,
animationKey,
spriteScale,
true
);
// Can be sourced from either new game, or save data.
this.setStatsFromData(statData);
}
public onUpdate(deltaTime: number): void {
const hAxis = inputService.getAxis('horizontal').value();
const vAxis = inputService.getAxis('vertical').value();
this.selectAnimation(hAxis, vAxis);
this.performMovement(hAxis, vAxis, deltaTime);
this.resourceRegeneration(deltaTime);
}
private selectAnimation(hAxis: number, vAxis: number): void {
if (hAxis === 0)
if (this.direction === EntityDirections.RIGHT)
this.gameObject.animations.play('idle-right');
else if (this.direction === EntityDirections.LEFT)
this.gameObject.animations.play('idle-left');
if (vAxis === 0)
if (this.direction === EntityDirections.DOWN)
this.gameObject.animations.play('idle-down');
else if (this.direction === EntityDirections.UP)
this.gameObject.animations.play('idle-up');
if (hAxis > 0) {
this.gameObject.animations.play('walk-right');
this.direction = EntityDirections.RIGHT;
} else if (hAxis < 0) {
this.gameObject.animations.play('walk-left');
this.direction = EntityDirections.LEFT;
} else if (vAxis > 0) {
this.gameObject.animations.play('walk-down');
this.direction = EntityDirections.DOWN;
} else if (vAxis < 0) {
this.gameObject.animations.play('walk-up');
this.direction = EntityDirections.UP;
}
}
private performMovement(
hAxis: number,
vAxis: number,
deltaTime: number
): void {
const body = this.body();
const speed = this.getStatByName("speed");
const dashCost = this.getStatByName("Dash Cost");
const stamina = this.getResourceByName("Stamina");
speed.clearModifiers();
if (inputService.getAxis('dash').isPressed()
&& (hAxis !== 0 || vAxis !== 0)
&& stamina.consume(dashCost.modifiedValue() * deltaTime)) {
speed.addScaledEffect(0.6);
this.addXpForSkill(deltaTime, "Conditioning");
}
body.velocity.x = hAxis * speed.modifiedValue();
body.velocity.y = vAxis * speed.modifiedValue();
}
private resourceRegeneration(deltaTime: number): void {
const stamina = this.getResourceByName("Stamina");
const staminaRegen = this.getStatByName("Stamina Regen");
const conditioning = this.getLevelForSkill("Conditioning");
stamina.gain(
staminaRegen.modifiedValue() + ((conditioning / 1000) * 0.25) * deltaTime
);
}
}
}<file_sep>namespace Main.UI {
export class MenuData {
public constructor(
public options: MenuOptionData[],
public defaultOption: number
) {
}
}
export class MenuOptionData {
public constructor(
public optionText: string = '',
public screenX: number = 0,
public screenY: number = 0,
public onSelection: () => void,
public otherData?: Object
) {
}
}
export class Menu {
public isActive: boolean = true;
public currentOption: number = 0;
public constructor(
public data: MenuData,
public labels: Phaser.Text[],
public defaultStyle: Phaser.PhaserTextStyle,
public selectedStyle: Phaser.PhaserTextStyle,
public selectionDelay: number = 250
) {
this.currentOption = this.data.defaultOption;
}
public pause(): void {
this.isActive = false;
}
public activate(): void {
this.isActive = true;
}
private nextOptionHandler(): void {
if (! this.isActive)
return;
this.selectNext();
}
private lastOptionHandler(): void {
if (! this.isActive)
return;
this.selectPrevious();
}
private confirmHandler(): void {
if (! this.isActive)
return;
this.executeSelection();
}
public grantKeyControl(): void {
inputService.addHandlerToAxis(
"vertical",
this.nextOptionHandler.bind(this),
this.lastOptionHandler.bind(this)
);
inputService.addHandlerToAxis(
"confirm",
this.confirmHandler.bind(this)
);
}
public releaseKeyControl(): void {
inputService.removeHandlerFromAxis(
'vertical',
this.nextOptionHandler,
this.lastOptionHandler
);
inputService.removeHandlerFromAxis(
'confirm',
this.confirmHandler
);
}
public selectNext(): void {
if (this.data.options.length <= 1)
return;
this.clearSelectedOption();
this.currentOption++;
if (this.currentOption > this.data.options.length - 1)
this.currentOption = 0;
this.setSelectedOption();
}
public selectPrevious(): void {
if (this.data.options.length <= 1)
return;
console.log('selectPrevious called...');
this.clearSelectedOption();
this.currentOption--;
if (this.currentOption < 0)
this.currentOption = this.data.options.length - 1;
this.setSelectedOption();
}
public executeSelection(): void {
this.data.options[this.currentOption].onSelection();
}
public clearSelectedOption(): void {
this.labels[this.currentOption].setStyle(this.defaultStyle);
}
public setSelectedOption(): void {
this.labels[this.currentOption].setStyle(this.selectedStyle);
}
}
export class MenuFactory {
public defaultStyle: Phaser.PhaserTextStyle;
public selectedStyle: Phaser.PhaserTextStyle;
public constructor() {
}
public iniitalize(): void {
const data = game.cache.getJSON('ui-styles');
this.defaultStyle = data['menu']['default'];
this.selectedStyle = data['menu']['selected'];
}
public create(menuData: MenuData): Menu {
let menuLabels: Phaser.Text[] = [];
let index: number = 0;
for (let current of menuData.options) {
const newText: Phaser.Text = game.add.text(
current.screenX,
current.screenY,
current.optionText
);
newText.mousedown = current.onSelection;
// This causes the options to render with the appropriate styling.
if (index !== menuData.defaultOption)
newText.setStyle(this.defaultStyle);
else
newText.setStyle(this.selectedStyle);
menuLabels.push(newText);
index++;
}
const result: Menu = new Menu(
menuData,
menuLabels,
this.defaultStyle,
this.selectedStyle
);
return result;
}
}
} | c39720bbcd247b7644a7b36c2f1cc08806d6d9fa | [
"TypeScript",
"JSON with Comments"
] | 23 | TypeScript | Asvarduil/ActionRPG | 769c4811fba6e29f3635e39cedcbe895e907401f | 65552f5fbad64cb4a5d993c53909bc39d28b7724 |
refs/heads/master | <repo_name>Bahri-Haythem/Symfony-PROJECT<file_sep>/src/Controller/PostController.php
<?php
namespace App\Controller;
use App\Entity\Post;
use App\Form\PostType;
use App\Repository\PostRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/post", name="post.")
*/
class PostController extends AbstractController
{
/**
* @Route("/", name="index")
*/
public function index(PostRepository $postRepository)
{
// rècuperer tous les posts
$posts = $postRepository->findAll();
return $this->render('post/index.html.twig', [
'posts' => $posts,
]);
}
/**
* @Route("/create", name="create")
*/
public function create(Request $request)
{
//creer un post
$post = new Post();
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
//si on clique sur submit
if ($form->isSubmitted()) {
//on cree le entity manager
$em = $this->getDoctrine()->getManager();
//on ajoute le post a la base
$em->persist($post);
$em->flush();
//affiche de message post created
$this->addFlash("add", "post created");
//redirection vers les posts
return $this->redirect($this->generateUrl("post.index"));
}
return $this->render("post/create.html.twig", [
"form" => $form->createView(),
]);
}
/**
* @Route("/show/{id}", name="show")
*/
public function show(Post $post)
{
//$post = $postRepository->find($id);
//afficher un seul post
return $this->render("post/show.html.twig", [
"post" => $post,
]);
}
/**
* @Route("/delete/{id}", name="remove")
*/
public function remove(Post $post)
{
//on cree le entity manager
$em = $this->getDoctrine()->getManager();
//on supprime le post
$em->remove($post);
//valider la supression dans la base
$em->flush();
//afficher le msg post deleted
$this->addFlash("remove", "post deleted");
return $this->redirect($this->generateUrl("post.index"));
}
}
| 7faef314576618acf07eafa9decfe1dfe4b8ace3 | [
"PHP"
] | 1 | PHP | Bahri-Haythem/Symfony-PROJECT | 6a320799b203e77e0f847b13199d68166357cefe | a5e3cb13e51c58b85db2d4a65619383d06628fff |
refs/heads/master | <file_sep>import React from "react";
import { useSelector } from "react-redux";
import "../css/product.css";
import { Container, Row } from "react-bootstrap";
import Navbarr from "../Components/Navbarr";
import Brand from "../Components/Brand";
import Footerr from "../Components/Footerr";
import movies_product_img from "../image/movies_product.JPG";
import googlenew_img from "../image/googlenew_product.JPG";
import convertmoney_product_img from "../image/convertmoney_product.JPG";
import guessgame_product_img from "../image/guessgame_product.JPG";
import ott_product_img from "../image/ott_product.JPG";
import weather_product_img from "../image/weather_product.JPG";
import todolist_product_img from "../image/todolist_product.JPG";
import goldminer_product_img from "../image/goldminer_product.JPG";
import { Button } from "react-bootstrap";
export default function Product() {
const selector = useSelector(state => state);
return (
<Container fluid={true} className="dashboard-page">
<Row className="brand-navbar">
<Brand />
<Navbarr />
</Row>
<div>Welcome {selector && selector.email}</div>
{/* san pham movies*/}
<section id="work" className="portfolio-mf sect-pt4 route">
<div className="row">
<div className="col-md-6">
<div className="work-box">
<a href={movies_product_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={movies_product_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">Trailer Films</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://movies-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{/* //// google news*/}
<div className="col-md-6">
<div className="work-box">
<a href={googlenew_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={googlenew_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">Google News</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://googlenews-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{/* ///// guessgame*/}
<div className="col-md-6">
<div className="work-box">
<a href={guessgame_product_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={guessgame_product_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">Guess Game</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://guessgame-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{/* ////// convert money*/}
<div className="col-md-6">
<div className="work-box">
<a href={convertmoney_product_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={convertmoney_product_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">Currency Converter</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://convertmoney-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{/* /// ott*/}
<div className="col-md-6">
<div className="work-box">
<a href={ott_product_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={ott_product_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">Rock-Paper-Scissor Game</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://rockpaperscissor-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{/* //// weather*/}
<div className="col-md-6">
<div className="work-box">
<a href={weather_product_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={weather_product_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">Weather</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://weather-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{/* //// todolist*/}
<div className="col-md-6">
<div className="work-box">
<a href={todolist_product_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={todolist_product_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">To Do List</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://todolist-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{/* ///// goldminer*/}
<div className="col-md-6">
<div className="work-box">
<a href={goldminer_product_img} data-lightbox="gallery-mf">
<div className="work-img">
<img src={goldminer_product_img} alt="" className="img-fluid" />
</div>
</a>
<div className="work-content">
<div className="row">
<div className="col-sm-8">
<h2 className="w-title">Catch - Diamond</h2>
<div className="w-more">
<form>
<Button
value="Live Website"
onClick={() =>
window.open("https://gold-miner-dnp.netlify.com/")
}
>
Live Website
</Button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{/* end san pham */}
<Footerr />
</Container>
);
}
<file_sep>import React from "react";
import {Carousel} from 'react-bootstrap'
import slider_first from '../image/slider_first.jpg'
import slider_second from '../image/slider_second.jpg'
import slider_third from '../image/slider_third.jpg'
export default function Carosell() {
return (
);
}
<file_sep>import React from 'react'
import {Navbar} from 'react-bootstrap'
import Brand_logo from '../image/Brand_logo.png'
import '../css/Brand.css'
export default function Brand() {
return (
<Navbar variant="dark">
<Navbar.Brand className="logo-icon" href="#home">
{' Sacred Fire'}
<img
alt=""
src={Brand_logo}
className="d-inline-block align-top img-brand"
/>
</Navbar.Brand>
</Navbar>
)
}
<file_sep>import React from "react";
import { Route, Switch } from "react-router-dom";
import "./App.css";
import Login from "./View/Login";
import Product from "./View/Product";
import Candidates from "./View/Candidates";
import Contact from "./View/Contact";
import AboutMe from "./View/AboutMe";
import "react-loader-spinner/dist/loader/css/react-spinner-loader.css";
function App() {
return (
<Switch>
<Route path="/" exact component={Login}></Route>
<Route path="/login" exact component={Login}></Route>
<Route path="/product" exact component={Product}></Route>
<Route path="/candidates/:id/:edit" exact component={Candidates}></Route>
<Route path="/contact" exact component={Contact}></Route>
<Route path="/aboutMe" exact component={AboutMe}></Route>
</Switch>
);
}
export default App;
<file_sep>import React, { useState, useEffect } from "react";
import {
Card,
Container,
Row,
ListGroup,
ListGroupItem
} from "react-bootstrap";
import { useSelector } from "react-redux";
export default function Candidates() {
const selector = useSelector(state => state);
const [candidates, setCandidates] = useState([]);
console.log("candidata", candidates);
useEffect(() => {
const getCandidates = async () => {
const res = await fetch(`http://localhost:3001/candidates`);
const data = await res.json();
setCandidates(data);
};
getCandidates();
}, []);
const onDeleteHandle = async (id) =>{
const config = {
method: "DELETE",
headers: {'content-type': 'application/json'},
}
fetch(`http://localhost:3001/candidates/` + id,config)
const newData = candidates.filter(candidate=>candidate.id!==id)
setCandidates(newData)
}
return (
<Container>
Welcom {selector && selector.email}
<Row>
{candidates &&
candidates.map(
({
gender,
country,
id,
email,
company,
job_title,
first_name,
last_name,
photo_url
}) => {
return (
<Card className="each-card" key={id}>
<Card.Img
className="img_card"
variant="top"
src={photo_url}
/>
<Card.Body>
<Card.Title>{first_name + " " + last_name}</Card.Title>
<Card.Text>{id}</Card.Text>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroupItem>{gender}</ListGroupItem>
<ListGroupItem>{country}</ListGroupItem>
<ListGroupItem>{email}</ListGroupItem>
<ListGroupItem>{company}</ListGroupItem>
<ListGroupItem>{job_title}</ListGroupItem>
</ListGroup>
<Card.Body>
<Card.Link href={`/candidates/${id}/edit`}>Edit</Card.Link>
<Card.Link href={`/candidates/${id}`} onClick={()=>onDeleteHandle(id)}>Delete</Card.Link>
</Card.Body>
</Card>
);
}
)}
</Row>
</Container>
);
}
<file_sep>import React from "react";
import "../css/Contact.css";
import { Container, Row, Col ,Image} from "react-bootstrap";
import Navbarr from "../Components/Navbarr";
import Brand from "../Components/Brand";
import Footerr from "../Components/Footerr";
import sliderhandholder from '../image/slider-hand-holding.jpg'
// font awsome react
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { library } from "@fortawesome/fontawesome-svg-core";
import { fas, faHandHolding } from "@fortawesome/free-solid-svg-icons";
import {
IconLookup,
IconDefinition,
findIconDefinition
} from "@fortawesome/fontawesome-svg-core";
library.add(fas);
const mapMaker: IconLookup = { prefix: "fas", iconName: "map-marker" };
const MapMakerIconDefinition: IconDefinition = findIconDefinition(mapMaker);
const phoneSquare: IconLookup = { prefix: "fas", iconName: "phone-square" };
const phoneSquareIconDefinition: IconDefinition = findIconDefinition(
phoneSquare
);
const evelop: IconLookup = { prefix: "fas", iconName: "envelope" };
const evelopIconDefinition: IconDefinition = findIconDefinition(evelop);
const CV: IconLookup = { prefix: "fas", iconName: "file-alt" };
const CVIconDefinition: IconDefinition = findIconDefinition(CV);
// end import fontawsome
// import googlemap
// end import googlemap
export default function Contact() {
return (
<Container fluid={true} className="dashboard-page">
{/* navbar */}
<Row className="brand-navbar" id='nav_bar'>
<Brand />
<Navbarr />
</Row>
{/* end navbar */}
<div className="contact-slider-img">
{/* <Image src={sliderhandholder} fluid /> */}
</div>
{/* contact info */}
<Row className="contact-info-map mt-5">
<Col md={6} xs={12}>
<div className="contact-info">
<div className="contact-info-row">
<div className="contact-info-contactWord ">CONTACT</div>
<div className="contact-info-contactSentence">
Never Give Up and Learn More About <br /> Life Values Today.
</div>
<div className="contact-sacredfire-word">Sacred Fire</div>
<div className="mt-5">
<FontAwesomeIcon icon={MapMakerIconDefinition} /> 109/4G, Le Van
Khuong Street, Hiep Thanh ward, Dist 12, Ho Chi Minh City
</div>
<div className="mt-3">
<FontAwesomeIcon icon={phoneSquareIconDefinition} /> (+84)
338019200
</div>
<div className="mt-3">
<FontAwesomeIcon icon={evelopIconDefinition} />{" "}
<EMAIL>
</div>
<div className="mt-3">
<FontAwesomeIcon icon={CVIconDefinition} /> {" "}
<a href="https://phuocduc2020.github.io/" target="_blank" className="contact-cv"> phuocduc2020.github.io</a> (CV)
</div>
</div>
</div>
</Col>
{/* map */}
<Col md={6} xs={12}>
<div className="mapStyles">
<div class="mapouter">
<div class="gmap_canvas">
<iframe
width="100%"
max-width="550px"
height="450px"
id="gmap_canvas"
src="https://maps.google.com/maps?q=19%20HT45%20quan%2012&t=&z=13&ie=UTF8&iwloc=&output=embed"
frameborder="0"
scrolling="no"
marginheight="0"
marginwidth="0"
></iframe>
</div>
</div>
</div>
{/* end map */}
</Col>
</Row>
{/* end contact info */}
{/* footer */}
<Footerr/>
</Container>
// <Container>
// </Container>
);
}
<file_sep>import React from "react";
import "../css/About-me.css";
import { Container, Row, Col } from "react-bootstrap";
import Navbarr from "../Components/Navbarr";
import Brand from "../Components/Brand";
import Footerr from "../Components/Footerr";
import mypic from "../image/mypic.jpg";
export default function AboutMe() {
return (
<Container fluid={true} className="dashboard-page">
{/* navbar */}
<Row className="brand-navbar" id="nav_bar">
<Brand />
<Navbarr />
</Row>
{/* end navbar */}
{/* CV */}
<div className="img-about-cover">
<div className="intro-content">
<div className="table-cell">
<div className="container">
<h1 className="intro-title"><NAME></h1>
<p className="intro-subtitle">Front End Developer</p>
</div>
</div>
</div>
</div>
<Col className="cv">
<div className="cv-table-cell">
<img className="cv" src={mypic} />
{/* <h1><NAME></h1>
<p className="pcv-head">Front End Developer</p> */}
{/* <p className="pcv-head">Computer Science</p> */}
</div>
<Col className="cv-perso-info">
<h1>
<b>Personal Information</b>
</h1>
<p className="pcvperso-info">
Date of birth: 01 April 1992
<br />
Phone: 0338019200 <br />
Email: <EMAIL> <br />
Address: 19 Hiep Thanh Ward, Lê Văn Khương Street, District 12, Hồ
Chí Minh City <br />
Facebook: https://www.facebook.com/duc.nguyen.54738
</p>
<hr />
<Row className="container cvskill">
<Col md={6} xs={12}>
<h1>Skills</h1>
<ul className="cvskill-ul">
<div>
<li>HTML</li>
<li>CSS</li>
<li>Javascript</li>
<li>ReactJS</li>
<li>Photoshop</li>
</div>
<div>
<li>Github</li>
<li>Python</li>
<li>Postgree</li>
<li>Network Configuration</li>
</div>
</ul>
</Col>
<Col md={6} xs={12}>
<h1>About Me</h1>
<p className="skill-aboutme">
I was an application support at an education environment. My
routine job was dealing with third party application to assist
the school. However, I did not absorb clearly what they were
working on code. So that,
</p>
<p>
I decided to join some coding courses and study on my own. Since
taking coding course in CoderSchool, I start improving my
knowledge and being confidence in building websites and
projects.
</p>
<p>
And, I believe the key to making good products is passisonate
and non-stop improving every day.
</p>
</Col>
</Row>
<hr />
<h1>
<b>Education</b>
</h1>
<div className="flip-card-all">
{/* flip carrd saigontech */}
<div className="flip-card col-12 col-md-4">
<div className="flip-card-inner">
<div className="flip-card-front">
<div className="edu-school">
<div className="flip-front-title">
<h2>Saigon Institude of Technology</h2>
<p>Nov. 2011 - Sep. 2016</p>
</div>
<img className="sgtech_img" />
</div>
</div>
<div className="flip-card-back">
<div className="edu-detail">
<ul>
<li>
SaigonTech is an official affiliate of Houston Community
College, Texas, USA
</li>
<li>My major is Networking</li>
<li>
I got Degree of Completion, Mirosoft Server and
Networking
</li>
<li>I got EAL Certificate</li>
</ul>
</div>
</div>
</div>
</div>
{/* end flip card*/}
{/* flip carrd T3H*/}
<div className="flip-card col-12 col-md-4">
<div className="flip-card-inner">
<div className="flip-card-front">
<div className="edu-school">
<div className="flip-front-title">
<h2>CSC Center</h2>
<p>July. 2019 - August. 2019</p>
</div>
<img className="csc_img" />
</div>
</div>
<div className="flip-card-back">
<div className="edu-detail">
<ul>
<li>
<strong>5 weeks for C basic programming</strong>
</li>
<li>
Knowledge: variable, function, array, operator, ,etc.
</li>
<li>
<strong>3 months for Javarscript</strong>
</li>
<ul>
Knowledge:
<li>Build client applications</li>
<li>Build a service application</li>
<li>Interface design with Bootstrap </li>
<li>Use Google Map with JavaScript </li>
<li>Using PDF Forms with JavaScript </li>
<li>Using Graph / Chart in JavaScript </li>
</ul>
</ul>
</div>
</div>
</div>
</div>
{/* end flip card CoderSchool*/}
{/* flip carrd */}
<div className="flip-card col-12 col-md-4">
<div className="flip-card-inner">
<div className="flip-card-front">
<div className="edu-school">
<div className="flip-front-title">
<h2>CoderSchool</h2>
<p>Sep. 2019 - Dep. 2019</p>
</div>
<img className="coder_img" />
</div>
</div>
<div className="flip-card-back">
<div className="edu-detail">
<ul>
<li>HTML & CSS</li>
<li>Javascript</li>
<li>ReactJS</li>
<li>Python</li>
</ul>
</div>
</div>
</div>
</div>
{/* end flip card*/}
</div>
</Col>
</Col>
{/* end CV */}
<Footerr />
</Container>
);
}
<file_sep>import React,{useState} from "react";
import {useHistory} from 'react-router-dom'
import {Container, Row, Form, Button } from "react-bootstrap";
import {useDispatch} from 'react-redux'
export default function Login() {
const [currentUser, setCurrentUser] = useState({})
const history = useHistory()
const dispatch = useDispatch()
const onSubmit = (e) =>{
e.preventDefault()
history.push('/aboutme')
dispatch({type:'SIGN_IN',payload:currentUser})
}
return (
<Container fluid={true} className="container-fluid Login-form-container">
<Row className="Login-form-row">
<Form onSubmit={onSubmit} className="Login-form">
<Form.Text className="Login-form-Logintext">LOGIN</Form.Text>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control onChange={(e)=>setCurrentUser({...currentUser, email: e.target.value})} type="email" placeholder="Enter email" />
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control onChange={(e)=>setCurrentUser({...currentUser, pass: e.target.value})} type="password" placeholder="<PASSWORD>" />
</Form.Group>
<Form.Group controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Remember" />
</Form.Group>
<Button className="Login-form-button" variant="primary" type="submit">
Submit
</Button>
</Form>
</Row>
</Container>
);
}
<file_sep>import React from "react";
import { Navbar, Nav } from "react-bootstrap";
import { Link } from "react-router-dom";
import "../css/Navbarr.css";
export default function Navbarr() {
return (
<Navbar expand="lg" className="navbar-wrap">
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav" className="nav-collapsee">
<Nav className="navbar-wrap-inside mr-auto">
{/* <Link to="/dashboard" className="navbar-linkk">
Home
</Link> */}
<Link to="/aboutMe" className="navbar-linkk">
About
</Link>
<Link to="/product" className="navbar-linkk">
Product
</Link>
<Link to="/login" className="navbar-linkk">
Login
</Link>
<Link to="/contact" className="navbar-linkk">
Contact
</Link>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
| f594ceebc5ad8c5554b199222e75a096eea21610 | [
"JavaScript"
] | 9 | JavaScript | phuocduc/serria-porfolio | 907ef96219279a788538ad8a2f4487b294f7f438 | 82569cc9e36a234010e1c6a97f16d80fbc2a36f6 |
refs/heads/main | <repo_name>alinaroxanapreda/tmx-web<file_sep>/tmx-app/src/components/greet.js
import React from 'react';
class Greet extends React.Component {
constructor(props) {
super(props);
this.state = {val : "awesome written by Alina"}
}
changeValue = () => {
this.setState({val: " wonderful from Alina"})
}
render() {
return(
<div>
<h1>Hello says {this.state.val} World</h1>
<button type="button" onClick={this.changeValue}>Change value</button>
</div>
);
}
}
export default Greet;<file_sep>/tmx-app/src/App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import {Navbar, NavbarBrand} from "reactstrap";
import Menu from './components/menu'
import {PLACES} from './shared/places'
import Greet from './components/greet'
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
places: PLACES
}
}
render() {
return (
<div className="App">
{/*<Navbar color="primary">*/}
{/* <div colorName="container" id="brand">*/}
{/* <NavbarBrand>Incredible Thermomix</NavbarBrand>*/}
{/* </div>*/}
{/*</Navbar>*/}
{/*<Greet/>*/}
{/*<h1>Famous Thermomix Things</h1>*/}
{/*<Menu places={this.state.places}/>*/}
{/*TODO: head cannot appear as a chiald of div*/}
{/*<head>*/}
{/* <meta charSet="utf-8"/>*/}
{/* <meta content="width=device-width, initial-scale=1.0" name="viewport"/>*/}
{/* <title>gătește ușor cu thermomix</title>*/}
{/* <meta content="" name="description"/>*/}
{/* <meta content="" name="keywords"/>*/}
{/* <link href="assets/img/favicon.png" rel="icon"/>*/}
{/* <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon"/>*/}
{/* /!*Google Forms*!/*/}
{/* <link*/}
{/* href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"*/}
{/* rel="stylesheet"/>*/}
{/* <link href="assets/vendor/aos/aos.css" rel="stylesheet"/>*/}
{/* <link href="assets/vendor/bootstrap/css/bootstrap.min.css"*/}
{/* rel="stylesheet"/>*/}
{/* <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css"*/}
{/* rel="stylesheet"/>*/}
{/* <link href="assets/vendor/boxicons/css/boxicons.min.css"*/}
{/* rel="stylesheet"/>*/}
{/* <link*/}
{/* href="assets/vendor/glightbox/css/glightbox.min.css"*/}
{/* rel="stylesheet"/>*/}
{/* <link href="assets/vendor/remixicon/remixicon.css"*/}
{/* rel="stylesheet"/>*/}
{/* <link*/}
{/* href="assets/vendor/swiper/swiper-bundle.min.css"*/}
{/* rel="stylesheet"/>*/}
{/* <link href="assets/css/style.css"*/}
{/* rel="stylesheet"/>*/}
{/*</head>*/}
<body>
<header id="header" class="fixed-top">
<div class="container d-flex align-items-center justify-content-between">
<h1 class="logo"><a href="index.html">gătește ușor cu thermomix</a></h1>
{/*Uncomment below if you prefer to use an image logo -->*/}
{/*<a href="index.html" class="logo"><img src="assets/img/logo.png" alt="" class="img-fluid"></a>-->*/}
<nav id="navbar" class="navbar">
<ul>
<li><a class="nav-link scrollto active" href="#acasa">Acasă</a></li>
<li><a class="nav-link scrollto" href="#paste">Rețete de Paște</a></li>
<li><a class="nav-link scrollto" href="#colectii">Colecții Cookidoo</a></li>
<li><a class="nav-link scrollto" href="#about">Despre Thermomix</a></li>
<li><a class="nav-link scrollto" href="#services">Avantaje și dezavantaje</a></li>
<li><a class="nav-link scrollto" href="#functii">Funcții</a></li>
<li><a class="nav-link scrollto" href="#beneficii">Beneficii</a></li>
{/*<li><a class="nav-link scrollto" href="#contact">Contactează-mă</a></li>*/}
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav>
</div>
</header>
<section id="acasa" class="d-flex align-items-center">
<div class="container position-relative" data-aos="fade-up" data-aos-delay="100">
<div class="row justify-content-center">
<div class="col-xl-7 col-lg-9 text-center">
<h1>thermomix - aparat inteligent de gătire asistată</h1>
<h2>Cea mai mică bucătărie mobilă</h2>
</div>
</div>
<div class="text-center">
<a href="#about" class="btn-get-started scrollto">Începe explorarea</a>
</div>
<div class="row icon-boxes">
<div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0" data-aos="zoom-in"
data-aos-delay="200">
<div class="icon-box">
<div class="icon"><i class="ri-stack-line"></i></div>
<h4 class="title"><a href="">24 în 1 funcții</a></h4>
<p class="description">
Thermomix economisește timp și bani! Câteva dintre ele sunt:</p>
<li>Încălzește la temperatura controlată</li>
<li>Pasare</li>
<li>Mixare</li>
<li>Gătire la abur</li>
<li>Cantărire</li>
<li>Emulsionare</li>
<li>Măcinare</li>
<li>și multe altele</li>
</div>
</div>
<div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0" data-aos="zoom-in"
data-aos-delay="300">
<div class="icon-box">
<div class="icon"><i class="ri-palette-line"></i></div>
<h4 class="title"><a href="">Siguranță pentru rețete proprii</a></h4>
<p class="description">Oferă viteză, siguranță, încredere și oportunitatea bsp;de a
fi creativ.
Bucătării și firmele de catering din toată lumea se bazează pe Thermomix
deoarece economisește
timp, efort și produce rezultate excelente.</p>
</div>
</div>
<div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0" data-aos="zoom-in"
data-aos-delay="400">
<div class="icon-box">
<div class="icon"><i class="ri-command-line"></i></div>
<h4 class="title"><a href="">Conectat la internet</a></h4>
<p class="description">Pe platforma/site-ul web Cookidoo găsim peste 68 000 de
rețete
din întreagă
lume, rețetele pot fi vizualizate pe orice dispozitiv (telefon, tabletă, PC),
dar și
pe tabletă
aparatului.</p>
</div>
</div>
<div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0" data-aos="zoom-in"
data-aos-delay="500">
<div class="icon-box">
<div class="icon"><i class="ri-fingerprint-line"></i></div>
<h4 class="title"><a href="">Planifică meniu și creează listă de cumpărături</a>
</h4>
<p class="description">Platforma de retete Cookidoo ne permite sa cream o lista de
cumparaturi
pentru toate retetele pe care vrem sa le gatim pe o anumita perioada. In cazul
in
care un
ingredient se repede, cantitatile se vor aduna. Lista de cumparaturi poate sa
fie
printata, trimisa pe email, sau putem folosi telefonul la cumparaturi pentru a
sterge de pe
lista ingredientele cumparate.</p>
</div>
</div>
</div>
</div>
</section>
<section id="paste" class="services section-bg">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h3>Cozonac</h3>
<h4>
<p>Rețeta în limba spaniolă de pe Cookidoo</p>
<p><a href="https://cookidoo.international/recipes/recipe/en/r595534">Link Cookidoo Pan
de
Pascua Cozonac (Kozunak)</a></p>
</h4>
<p>Timp de preparare 30 min</p>
<p>Timp total 5h (îl include pe cel de preparare)</p>
</div>
<div class="row">
<div class="col-lg-4 col-md-6 d-flex align-items-stretch" data-aos="zoom-in"
data-aos-delay="100">
<div class="icon-box iconbox-blue">
<div class="icon">
{/*// <!-- <svg width="100" height="100" viewBox="0 0 600 600"-->*/}
{/*// <!-- xmlns="http://www.w3.org/2000/svg">-->*/}
{/*// <!-- <path stroke="none" stroke-width="0" fill="#f5f5f5"-->*/}
{/*// <!-- d="M300,521.0016835830174C376.1290562159157,517.8887921683347,466.0731472004068,529.7835943286574,510.70327084640275,468.03025145048787C554.3714126377745,407.6079735673963,508.03601936045806,328.9844924480964,491.2728898941984,256.3432110539036C474.5976632858925,184.082847569629,479.9380746630129,96.60480741107993,416.23090153303,58.64404602377083C348.86323505073057,18.502131276798302,261.93793281208167,40.57373210992963,193.5410806939664,78.93577620505333C130.42746243093433,114.334589627462,98.30271207620316,179.96522072025542,76.75703585869454,249.04625023123273C51.97151888228291,328.5150500222984,13.704378332031375,421.85034740162234,66.52175969318436,486.19268352777647C119.04800174914682,550.1803526380478,217.28368757567262,524.383925680826,300,521.0016835830174"></path>-->*/}
{/*// <!-- </svg>-->*/}
<img src="assets/img/cozonac.png" class="img-fluid" alt=""/>
<i class="bx bxl-dribbble">Ingrediente</i>
</div>
<p>Aluat</p>
<p> 125g zahăr</p>
<p> 4 coajă de lămâie, după gust</p>
<p> 4 coajă de portocală, după gust</p>
<p> 250g lapte</p>
<p> 20 g drojdie proaspătă presată, mărunțită</p>
<p> 520 g de făînă</p>
<p> 5 gălbenușuri</p>
<p> ½ linguriță de sare</p>
<p> 100 g unt</p>
<p> 1 lingură untură</p>
<p> 1 linguriță vanilie lichidă</p>
<p> 5 lingurițe ulei de floarea soarelui</p>
<br/>
<p> Umplutură</p>
<p> 5 albușuri</p>
<p> 1 vârf de sare</p>
<p> 200 g nuci</p>
<p> 40 g praf de cacao pur</p>
<p> 70g zahăr</p>
<p> 15 g rom</p>
<br/>
<p> Decorare</p>
<p> 2 lingurițe de ulei de floarea soarelui</p>
<p> 1 ou bătut</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="zoom-in"
data-aos-delay="100">
<div class="icon-box iconbox-yellow">
{/*// <div class="icon">-->*/}
{/*// - <svg width="100" height="100" viewBox="0 0 600 600"-->*/}
{/*// xmlns="http://www.w3.org/2000/svg">-->*/}
{/*// <path stroke="none" stroke-width="0" fill="#f5f5f5"-->*/}
{/*// d="M300,503.46388370962813C374.79870501325706,506.71871716319447,464.8034551963731,527.1746412648533,510.4981551193396,467.86667711651364C555.9287308511215,408.9015244558933,512.6030010748507,327.5744911775523,490.211057578863,256.5855673507754C471.097692560561,195.9906835881958,447.69079081568157,138.11976852964426,395.19560036434837,102.3242989838813C329.3053358748298,57.3949838291264,248.02791733380457,8.279543830951368,175.87071277845988,42.242879143198664C103.41431057327972,76.34704239035025,93.79494320519305,170.9812938413882,81.28167332365135,250.07896920659033C70.17666984294237,320.27484674793965,64.84698225790005,396.69656628748305,111.28512138212992,450.4950937839243C156.20124167950087,502.5303643271138,231.32542653798444,500.4755392045468,300,503.46388370962813"></path>-->*/}
{/*// </svg>-->*/}
{/*// <i class="bx bx-layer"></i>-->*/}
{/*// </div>-->*/}
<div class="icon">
<img src="assets/img/cozonac.png" class="img-fluid" alt=""/>
<i class="bx bxl-dribbble">Pregătire aluat</i>
</div>
<p>1. Puneți în bolul de mixare: 120g zahăr, coajă de portocală și lămâie și
pulverizați 30
sec / viteză 10. Scoateți pulberea în un castron și puneți-o deoparte.</p>
<p>2. Puneți laptele în bolul de mixare și activați funcția de încălzire pe TM6 la
50 de
grade, sau încălziți 2 min / 50 ° C / viteză 1 pe alte modele (TM5/TM31).</p>
<p>3. Pentru maia așezați un castron pe capac, cântăriți drojdia mărunțită, 5 g
zahăr și 20
g făînă. Puneți în bolul de mixare 50 g de laptele încălzit la pasul 2 și
adăugați-l în
castron. Se amestecă bine cu o linguriță până când este cremoasă și netedă și se
lasă să
dubleze volumul. Între timp, continuați cu rețeta.</p>
<p>4. Puneți gălbenușurile cu sarea într-un alt vas, bateți ușor și puneți de-o
parte.</p>
<p>5. Adăugați untul, untură de porc și esență de vanilie în vasul de amestecare și
activați
funcția de încălzire pe TM6 la 50 de grade, sau încălziți 2 min / 50 ° C /
viteză 2 pe
alte modele (TM5/TM31).</p>
<p>6. Se amestecă zahărul aromat, făina, amestecul de maia și gălbenușurile bătute
cu sare
și se amestecă 15 sec / viteză 6.</p>
<p>7. Framantati 6 min /spic și adăugați 1 linguriță de ulei prin deschiderea
capacului din
minut în minut. Asezați aluatul de pe suprafața de lucru ușor uns cu ulei,
frământați și
formăți o bilă netedă. Așezați-l într-un vas mare uns, acoperiți cu folie de
plastic și
lăsăți-l să se odihnească timp de 1 oră în cuptor, oprit și cu lumina
aprinsă/cuptorul
setat pe 40 de grade 25 de minute.</p>
<p>8. Luați aluatul pe o parte, ridicați-l, lăsându-l să se întindă și pliați-l pe
sine.
Întoarceți vasul la 90 °, repetați faldul și lăsăți-l să se odihnească 10
minute.
Repetați răsucirea și pliați încă de 2 ori. Așezați aluatul în castron,
acoperiți cu
folie alimentară și lăsăți-l să se odihnească timp de 30 de minute. Între timp,
spălați
bolul de mixare și faceți umplutură.</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="zoom-in"
data-aos-delay="100">
<div class="icon-box iconbox-yellow">
<div class="icon">
<img src="assets/img/cozonac.png" class="img-fluid" alt=""/>
<i class="bx bxl-dribbble">Pregătire umplutură</i>
</div>
<p>9. Așezați fluturașul de batere în bolul de mixare. Puneți alburile și sarea în
bol și
mixati 4 min / viteză 3,5. Scoateți într-un castron și puneți de-o parte.
Scoateți
fluturele de amestecare.</p>
<p>10. Așezați nucile, cacao și zahărul în bolul de amestecare și amestecăți 5 sec /
viteză
7. Cu ajutorul spatulei curățați pereții bolului de mixare.</p>
<p>12. Adăugați rom și albușurile și amestecăți 15 sec / viteză 3. Scoateți în vasul
de
amestecare, terminați de amestecat cu spatulă și puneți-l deoparte.</p>
<p>Asamblare și coacere</p>
<p>Scoateți aluatul de pe suprafața de lucru ușor unsă, aplatizați-l cu mâinile și
tăiați-l
în jumătate. Aplatizați una dintre părți cu mâinile, formând un dreptunghi de
aprox.
35x20 cm. Întindeți suprafața cu jumătate din umplutură, într-un strat de 3 cm
pe una
dintre cele mai lungi părți. Rulați aluatul începând din centru și sigilați bine
capetele. Repetați procesul cu cealaltă jumătate. Așezați pe hârtia de copt cele
două
role în formă de X. Treceți de 2 ori cei 2 cilindri de fiecare parte,
schimbându-i cu
mâna, formând un fel de împletitură și, la final, puneți capetele sub aluat.
Folosind
hârtia, așezați aluatul într-o formă de tort de 2 litri tapetată cu hârtie de
copt,
vopsiți cu ou bătut și lăsăți-l să se odihnească 45 de minute sau până la
dublarea
volumului.</p>
<p>Preîncălziți cuptorul la 160 ° C.</p>
<p>Coaceți timp de 10 minute la 160 ° C, ridicați temperatura la 170 ° C și coaceți
încă 30
de minute. Scoateți din cuptor, lăsăți să stea 15 minute și desfaceți din tavă.
Se lasă
să se răcească complet și se servesc felii.</p>
</div>
</div>
</div>
</div>
</section>
<section id="colectii" class="services section-bg">
<div class="container" data-aos="fade-up">
<div class="section-title">
<div class="section-title">
<h3>Ultima colecție Cookidoo </h3>
<p>în limba romana 🇷🇴</p>
<p><a href="https://cookidoo.international/collection/en/p/col433928">Link Cookidoo
Modul
Fierbere orez</a></p>
<p>Rețete cu timp total de 35 min în medie</p>
</div>
<div class="row">
<div class="col-lg-12 col-md-8 d-flex align-items-stretch" data-aos="zoom-in"
data-aos-delay="100">
<div class="icon-box iconbox-blue">
<div class="icon">
<img src="assets/img/orez.png" class="img-fluid" alt=""/>
<i class="bx bxl-dribbble">Orez</i>
</div>
<br/>
<p>Cu modul Fierbere orez, Thermomixul® tău înlocuiește încă un aparat de
bucătărie.
</p>
<p>Folosește aceste rețete de bază pentru a fierbe perfect orezul și alte
cereale, pe
care să le servești ca
garnitură sau să le amesteci într-o salată.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<main id="main">
<section id="about" class="about">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Despre Thermomix</h2>
<p>Aparat inteligent de gatire asistata Thermomix TM6 - ultima generatie de Thermomix,
un aparat
ce se
produce din 1971</p>
<p>A 6-a generație de Thermomix este adaptată la era digitală, un gadget care se
conectează la
rețeaua
de internet, dar poate fi folosit și fără această conexiune. </p>
</div>
<div class="row content">
<div class="col-lg-6">
<p>
El include un ecran tactil (Touch Screen) color cu o diagonală de 17 cm, funcții
automate și
gătire asistată. Versiunea anterioară a fost îmbunătățită și pe partea de sunet,
TM6
fiind și
mai silențios.
</p>
<ul>
<li><i class="ri-check-double-line"></i>Încălzește la temperatura controlată
</li>
<li><i class="ri-check-double-line"></i>Pasare</li>
<li><i class="ri-check-double-line"></i>Mixare</li>
<li><i class="ri-check-double-line"></i>Gătire la abur</li>
<li><i class="ri-check-double-line"></i>Cantărire</li>
<li><i class="ri-check-double-line"></i>Emulsionare</li>
<li><i class="ri-check-double-line"></i>Măcinare</li>
<li><i class="ri-check-double-line"></i>Cântărire</li>
<li><i class="ri-check-double-line"></i>Amestecare</li>
<li><i class="ri-check-double-line"></i>Bate spume si creme</li>
<li><i class="ri-check-double-line"></i>Mărunțire</li>
<li><i class="ri-check-double-line"></i>Încălzește la temperatura controlată
</li>
<li><i class="ri-check-double-line"></i>Gătire</li>
<li><i class="ri-check-double-line"></i>Gătire lentă (slow cook)</li>
<li><i class="ri-check-double-line"></i>Fermentare</li>
<li><i class="ri-check-double-line"></i>Fierbere</li>
<li><i class="ri-check-double-line"></i>Caramelizare</li>
<li><i class="ri-check-double-line"></i>Prăjire</li>
<li><i class="ri-check-double-line"></i>Sous-vide</li>
<li><i class="ri-check-double-line"></i>Rice-cooker</li>
<li><i class="ri-check-double-line"></i>Îngroșare</li>
<li><i class="ri-check-double-line"></i>Rumenire</li>
<li><i class="ri-check-double-line"></i>Auto-curățare</li>
</ul>
</div>
<div class="col-lg-6 pt-4 pt-lg-0">
<p>Grupul german Vorwerk este pioner in inovatie, asa ca acest aparat conduce pas cu
pas
spre o
reusita sigura in bucatarie, cu ajutorul functiei de
gatire
asistata si a pasilor din reteta afisati pe ecran. Tot ce ramane de facut este
sa
adaugati
ingredientele
sui sa porniti aparatul. Thermomix® are deja setata temperatura si timpul,
parametrii
stabiliti
de
persoane avizate si retetele sunt certificate de grupul nemtesc, Vorwerk. Este o
alternativa
simpla si
rapida, care vine in completarea posibilitatii de folosire in modul manual, cand
putem
sa gatim
retetele
proprii. </p>
<p>Modelul <strong>TM6</strong> este
complet digital si este dotat cu un buton selector unic.
Ce include acest aparat?
- modulul principal cu locasul special pentru bolul de mixare, un orificiu care
asigura
evacuarea
eficienta a lichidelor pe blatul de lucru (in caz de accidente, cand aparatul e
folosit
pe modul
manual), un dispozitiv care detecteaza prezenta capacului bolului e mixare, in
asa fel
incat
aparatul sa
nu porneasca fara prezenta capacului si manerele automate care prind capacul
bolului de
mixare
(o masura
de siguranta prezenta de la modelul anterior)
- un bol de mixare care poate permite gatirea la temperaturi ridicate - 160 de
grade
dotat cu un
cutit
care se invarte in ambele sensuri ale ceasornicului. Modul anti-orar fiind
recomandat
pentru
fierberea
de paste, gemuri, mamaliga si alte amestecari delicate.
- un capac bol de mixare
- un pahar de masurare care nu inchide etans bolul de mixare, Thermomix neavand
functia
de oala
sub
presiune. Acesta permite ridicarea capacului si functioneaza ca o cana gradata,
putand
sa luam
in calcul
densitatea lichidelor atunci cand vrem sa masuram lichide in mililitrii si nu in
grame,
asa cum
masoara
Thermomix toate ingredientele, inclusiv lichidele. Capacul de masurare este
convex si
impreuna
cu
paharul de masurare permite emulsionarea, de exemplu putem sa punem pe capac
ulei ca sa
facem
maioneza,
uleiul picurand treptat in interiorul bolului de mixare.
- un capac anti-strop care se aseaza deasupra capacului bolului de mixare
folosit pentru
rumenire,
gemuri, dar si de fiecare data cand ne cere reteta.
- un fluturas de batere - pentru batut spuma, el asigurand functia de tel
- un cos de inabusire care permite gatirea la abur a orezului, quinoa, linte,
legume,
dar are si
functie
de strecurator si poate ajuta la spalarea delicata a capsunelor/fructelor de
padure
- o spatula cu un guler care permite sa fie introdusa prin orificiul capacului
bolului
de
mixare, astfel
impingand inghetata spre cutite. Spatula se ataseaza cosului de inabusire,
permitand sa
scoatem
cosul de
inabusire incins, astfel obtinand o strecuratoare cu maner.
- o tava Varoma (vapori + aroma) care include un recipient generos in care putem
sa
gatim la
abur legume
voluminoase (broccoli, conopida, vinete, bucati de dovleac), sau o pulpa de
curcan si o
tavita
mai mica
unde putem gati la abur un file de peste, bucati de pui, sau legume mai putin
voluminoase.
</p>
<p>TM6 include o gama mai larga de viteze si temperaturi (de la 37 la 160 grade) si
functia
Turbo
reglabila
intre 0,5 si 2 secunde. Atat bolul cat si Varoma sunt cu 10% mai mari (2,2 si
3,3 litri)
fata de
modelul mai vechi, lansat in 2004, TM31.</p>
<p>Deasemenea, asigura un mai bun control al temperaturilor de gatire, permitand
ajustarea
temperaturii de
gatire la intervale de 1°Celsius.</p>
<p>Afiseaza atat temperatura de gatire cat si temperatura reziduala.</p>
<p><strong>Thermomix</strong> economiseste timp si bani!</p>
<a href="#functii" class="btn-learn-more">Află mai multe</a>
</div>
</div>
</div>
</section>
{/*<!-- ======= Counts Section ======= -->*/}
{/*<!-- <section id="counts" class="counts section-bg">-->*/}
{/*<!-- <div class="container">-->*/}
{/*<!-- <div class="row justify-content-end">-->*/}
{/*<!-- <div class="col-lg-3 col-md-5 col-6 d-md-flex align-items-md-stretch">-->*/}
{/*<!-- <div class="count-box">-->*/}
{/*<!-- <span data-purecounter-start="0" data-purecounter-end="65" data-purecounter-duration="2"-->*/}
{/*<!-- class="purecounter"></span>-->*/}
{/*<!-- <p>Happy Clients</p>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-3 col-md-5 col-6 d-md-flex align-items-md-stretch">-->*/}
{/*<!-- <div class="count-box">-->*/}
{/*<!-- <span data-purecounter-start="0" data-purecounter-end="85" data-purecounter-duration="2"-->*/}
{/*<!-- class="purecounter"></span>-->*/}
{/*<!-- <p>Projects</p>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-3 col-md-5 col-6 d-md-flex align-items-md-stretch">-->*/}
{/*<!-- <div class="count-box">-->*/}
{/*<!-- <span data-purecounter-start="0" data-purecounter-end="30" data-purecounter-duration="2"-->*/}
{/*<!-- class="purecounter"></span>-->*/}
{/*<!-- <p>Years of experience</p>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-3 col-md-5 col-6 d-md-flex align-items-md-stretch">-->*/}
{/*<!-- <div class="count-box">-->*/}
{/*<!-- <span data-purecounter-start="0" data-purecounter-end="20" data-purecounter-duration="2"-->*/}
{/*<!-- class="purecounter"></span>-->*/}
{/*<!-- <p>Awards</p>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </section><!– End Counts Section –>-->*/}
<section id="beneficii" class="about-video">
<div class="container" data-aos="fade-up">
<div class="row">
<div class="col-lg-6 video-box align-self-baseline" data-aos="fade-right"
data-aos-delay="100">
<img src="assets/img/about-video.jpg" class="img-fluid" alt=""
href="https://youtu.be/q88mORoO8Hk" class="glightbox play-btn mb-4"
data-vbtype="video" data-autoplay="true"
/>
</div>
<div class="col-lg-6 pt-3 pt-lg-0 content" data-aos="fade-left" data-aos-delay="100">
<h3>De ce apreciez eu acest aparat?</h3>
<p class="fst-italic">
3 dintre beneficiile lui Thermomix 6
</p>
<p>
Cum poate acest aparat inteligent de gatire asistata sa te ajute?
</p>
<ul>
<li><i class="bx bx-check-double"></i> Rapid și fără stres
<p>Thermomix Te ajuta sa prepari rapid și fără stres aproape orice fel de
mancare,
de la bauturi (smoothie, limonada, cocktail-uri, ciocolata calda si
multe
altele), pana la antreuri, salate, paine, deserturi, dar si meniuri
complete cu
supa si felul principal.</p>
</li>
<li><i class="bx bx-check-double"></i> Diversitate
<p>Te poți inspira din miile de retete de pe platforma Cookidoo, retete din
toate
bucatariile lumii, pe care le poti modifica dupa propriul tau gust</p>
</li>
<li><i class="bx bx-check-double"></i> Multitudine de funcții
<p>Te poate sprijini sa iti inovezi felul de a gati alături de multitudinea
lui de
funcții, cele mai recente fiind gatirea lenta/ slow cooking si gatirea
in pungi
vidate, sau sous vide</p>
</li>
</ul>
</div>
</div>
</div>
</section>
{/*<!-- ======= Clients Section ======= -->*/}
{/*<!-- <section id="clients" class="clients section-bg">-->*/}
{/*<!-- <div class="container">-->*/}
{/*<!-- <div class="row">-->*/}
{/*<!-- <div class="col-lg-2 col-md-4 col-6 d-flex align-items-center justify-content-center"-->*/}
{/*<!-- data-aos="zoom-in">-->*/}
{/*<!-- <img src="assets/img/clients/client-1.png" class="img-fluid" alt="">-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-2 col-md-4 col-6 d-flex align-items-center justify-content-center"-->*/}
{/*<!-- data-aos="zoom-in">-->*/}
{/*<!-- <img src="assets/img/clients/client-2.png" class="img-fluid" alt="">-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-2 col-md-4 col-6 d-flex align-items-center justify-content-center"-->*/}
{/*<!-- data-aos="zoom-in">-->*/}
{/*<!-- <img src="assets/img/clients/client-3.png" class="img-fluid" alt="">-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-2 col-md-4 col-6 d-flex align-items-center justify-content-center"-->*/}
{/*<!-- data-aos="zoom-in">-->*/}
{/*<!-- <img src="assets/img/clients/client-4.png" class="img-fluid" alt="">-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-2 col-md-4 col-6 d-flex align-items-center justify-content-center"-->*/}
{/*<!-- data-aos="zoom-in">-->*/}
{/*<!-- <img src="assets/img/clients/client-5.png" class="img-fluid" alt="">-->*/}
{/*<!-- </div>-->*/}
{/*<!-- <div class="col-lg-2 col-md-4 col-6 d-flex align-items-center justify-content-center"-->*/}
{/*<!-- data-aos="zoom-in">-->*/}
{/*<!-- <img src="assets/img/clients/client-6.png" class="img-fluid" alt="">-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </div>-->*/}
{/*<!-- </section><!– End Clients Section –>-->*/}
<section id="functii" class="testimonials">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Funcții</h2>
<p>Thermomix are 22 de functii in momentul de fata, dar numarul lor creste pentru ca
aparatul
este
conectat la internet. Ultima functie importanta adaugata este cea de fierbator de
oua.</p>
</div>
<div class="testimonials-slider swiper-container" data-aos="fade-up" data-aos-delay="100">
<div class="swiper-wrapper">
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Obtine textura matasoasa perfecta a unui smoothie sanatos, o supa crema
sau
prepara
cocktailuri.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Pasare</h3>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Thermomix ® este unul din cele mai performante si puternice mixere pe
care le-aţi putea avea: clatite perfecte sau budinca Yorkshire intr-un
timp
extrem de
scurt,
compozitii de baza pentru prajituri, biscuiti, patisserie, creme
tartinabile sau
iaurturi.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
{/*<img src="assets/img/testimonials/testimonials-2.jpg" class="testimonial-img"*/}
{/* alt="">-->*/}
<h3>Mixare</h3>
<h4>+ aerare</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Gatirea la aburi este foarte simpla gratie accesoriului Varoma care se
potriveste
perfect pe
capacul bolului de mixare. Alimentele se gatesc la aburi in timp ce
preparati
altceva în
bolul de mixare.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Gatire la abur</h3>
<h4>pe cel mult 4 etaje</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Cu ajutorul cantarului integrat in acest robot de bucatarie, puteti
cantari
orice
ingredient
direct in bolul de mixare. E suficient sa readuceti cantarul la 0
folosind
funcţia Tara,
pentru a putea cantari ingredientele pe masura ce se adauga in bol. Cu
noul
THERMOMIX
TM6,
puteti cantari chiar in timp ce aparatul amesteca sau gateste cu viteza
mica,
deci cu
motorul în funcţiune.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Cantarire</h3>
<h4> Precizie de 1 gram</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Cu Thermomix®, e foarte simplu si usor sa preparati singuri maioneza si
dressing-urile
pentru salate.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Emulsionare</h3>
<h4>Maioneza</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Puteţi macina faina din diferite cereale, cafea la granulaţia dorita,
puteti
rade
parmezanul
si puteţi obtine maximum de aroma, maruntind ierburile aromatice si
macinand
condimente.
Cuburile de gheata pot fi zdrobite in cateva secunde. Chiar si seminţele
marunte
- cum
sunt
cele de mac sau de susan - se pot macina extrem de usor si de repede.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Macinare</h3>
<h4>Faina</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Datorita inteligentei Thermomix ®, cutitul se va roti continuu si,
astfel,
continutul
bolului se va incalzi uniform. Reglati, pur si simplu, Thermomix ® la
viteza cea
mai
mica si
mancarea se va amesteca delicat in timp ce se gateste. Este un mod
minunat de a
ajunge
la
rezultatele asteptate atunci cand gatiti mamaliga, un risotto, o budinca
de
orez, o
crema sau un sos
delicat cum este <em>sosul béchamel.</em>
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
{/*<img src="assets/img/testimonials/testimonials-5.jpg" class="testimonial-img"-->*/}
{/*alt="">-->*/}
<h3>Amestecare</h3>
<h4>Mamaliga</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Cu ajutorul fluturelui de amestecare, puteti bate frisca usor si rapid,
iar
albusurile
se
pot transforma intr-o spuma bogata si matasoasa. E suficient sa montaţi
fluturele de
amestecare pe cutit si reglati o viteza moderata, intre 2 si 4. Viteza 4
fiind
si
maximul la care trebuie folosit acest accesoriu.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Batere spume si creme</h3>
<h4>Frisca</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Robotul de bucatarie THERMOMIX TM6 toaca ceapa, nuci, verdeata, carne,
morcovi,
cartofi
si
multe altele. Selectati viteza doritt, dupa cum vreti ca ingredientele
sa fie
tocate
grosier
sau mai fin. Puteti marunti si o cantitate foarte mica de ingrediente. O
singura
ceapa,
de
exemplu, poate fi tocata în doar 3 secunde!
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Maruntire</h3>
<h4>Toaca</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Datorita acestei functii, puteti obtine cu precizie orice preparat.
Senzorii
integrati
in
bolul de mixare vor mentine temperatura la valoarea dorita. Thermomix ®
poate
încalzi
continutul bolului la temperaturi cuprinse între 37°C şi 160°C.
Controlul
temperaturii
este
asigurat de selectorul de temperatura si prin afisarea temperaturii
exacte pe
ecranul
tactil. Perfect pentru retete delicate cum sunt budincile-crema, sau
pentru
topit
ciocolata
fara sa se taie, dar si pentru prajire. Iar laptele nu va mai fierbe
niciodată
prea
mult,
pentru ca veţi regla temperatura la 90°C.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Incalzestire</h3>
<h4> la temperatura controlata</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Thermomix ® gateste cu precizie, pentru rezultate perfecte de fiecare
data. Spre
deosebire
de o plita traditionala, Thermomix® asigura o temperatura constanta si
exacta,
care se
poate
regla automat, foarte usor, cu ajutorul selectorului de temperatura si a
ecranului
tactil.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Gatire</h3>
<h4> cu precizie</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Functia de framantare reproduce miscarile de manuale ale brutarului
profesionist, cu
rotatia
alternativa a cutitului, in sensul acelor de ceasornic si in sens invers
acelor
de
ceasornic. Aluaturile devin suple si fine: aluaturi dospite - de paine,
pizza -
ori
aluaturi
pentru paste, biscuiti si chiar pentru produse de patiserie si
briose.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Framantare</h3>
<h4>Aluat de cozonac</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Intre 1 si 8 ore la temperatura joasa (70 - 98°C). Se adauga suficient
lichid,
cum ar fi
fond sau sos, cat sa acopere ingredientele si se amesteca cu spatula. Se
selecteaza
timpul
si temperature (in functie de reteta) si se porneste modul Slow Cook.
Thermomix
va gati
ingredientele astfel incat sa fui fragede si suculente. Perfect pentru
carnea
tare (max.
800g).
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Gatire lenta</h3>
<h4>Slow cook</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Pentru iaurt, branzeturi sau aluaturi in vasul Varoma. Timpulul se poate
regal
pana la
12
ore, cu temperature intre 37 si 70°C. Temperatura constanta ajuta si la
fermentarea
direct
in bolul de mixare sau la crearea unei atmosphere calde in vasul Varoma
plasat
deasupra
apei
din bolul de mixare.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Fermentare</h3>
<h4>Iaurt</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Se foloseste pentru a incalzi apa pentru ceai sau pentru a fierbe paste
fainoase. Se
alege
temperatura, iar Thermomix o va incalzi cu precizie anuntand cand este
gata.
Pentru ceai
alb
sau verde se recomanda o temperatura de 80°C, pentru ceai negru la 98°C.
pentru
paste se
recomanda 100°C.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Fierbere</h3>
<h4>temperatura potrivita</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Pentru zahar caramelizat. In functie de temperatura se obtine sirop de
zahar de
diferite
intensitati (pentru fudge, caramel, nougat, simit, toffee), caramel
lichid.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Caramelizare</h3>
<h4>Deserturi</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Ceapa prajita la temperatura ridicata in jumatate din timpul obisnuit.
Savoarea
este
imbunatatita, iar culoare este brun-aurie.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Prajire</h3>
<h4>Ceapa</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Carne, peste, legume si fructe, gatite in pungi vidati de la 0 la 12
ore, la
temperaturi
intre 37 - 98°C pentru fragezime si suculenta.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Sous-vide</h3>
<h4>Temperatura joasa, in pungi vidate</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Orez perfect gatit! Se intoduce orezul in bolul de mixare, se adauga apa
si
mirodenii.
Se
selecteaza modul Rice-cooker si se apasa start. Temperature si timpul de
gatire
sunt
controlate automat.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Rice-cooker</h3>
<h4>Orez cremos</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Se pot rumeni legume si bucati de carne.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Rumenire</h3>
<h4>Temperatura maxima de 160 de grade</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Dupa utilizare, in bol se adauga apa si un strop de detergent lichid. Se
selecteaza una
dintre cele 4 optiuni legate de tipul de murdarire: aluat, universal,
grasime si
rumenire.
Thermomix va detecta cat de murder este bolul si-l va curata in
consecinta
printr-o
incalzire mai lunga daca, de exemplu, daca s-a folosit
pentru caramel va urma o precuratare de cel putin 15 minute.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Auto-curatare</h3>
<h4>sau prespalare</h4>
</div>
</div>
<div class="swiper-slide">
<div class="testimonial-item">
<p>
<i class="bx bxs-quote-alt-left quote-icon-left"></i>
Thermomix tempereaza ciocolata la exact 37°C si poate sa incalzeasca la
temperatura
perfecta si mancarea pentru bebelusi.
<i class="bx bxs-quote-alt-right quote-icon-right"></i>
</p>
<h3>Temperatura joasa</h3>
<h4>Thermomix incalzeste mancarea pentru bebelusi la exact 37°C.</h4>
</div>
</div>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
</section>
<section id="services" class="services section-bg">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Avantaje și dezavantaje</h2>
<p>Thermomix eeconomieste un aparat esențial în bucătăria multor oameni.</p>
<p>Femeile care il folosesc, termomixistele, sunt mândre și entuziasmate de acest aparat
inteligent de gatire
asistata, până la punctul în care fac orice fel de mâncare cu el. <NAME>inta, mai
presus
de toate, mântuirea
celor care nu au reușit niciodată să prăjească un ou prăjit. Trebuie doar să
introduceți
ingredientele, să le
urmați instrucțiunile și <strong>oricine este capabil să facă un fel de mâncare
decent</strong> , oricât de
complex este.
Dar care este succesul acestui aparat inteligent de gatire asistata in bucătărie?
Principalul său avantaj este că este un aliat perfect, atât pentru cei care știu să
gătească, cât și pentru cei
care nu au făcut-o niciodată. Deși este capabil să pregătească tot felul de rețete,
există
unele pe care le face
mai bine decât altele. Indiferent cât de mult ai fi un fan, nu toate sunt avantaje
atunci
când gătești
cu Thermomix , deoarece are și dezavantajele sale.</p>.
</div>
<div class="row">
<div class="col-lg-4 col-md-6 d-flex align-items-stretch" data-aos="zoom-in"
data-aos-delay="100">
<div class="icon-box iconbox-blue">
<div class="icon">
<svg width="100" height="100" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg">
<path stroke="none" stroke-width="0" fill="#f5f5f5"
d="M300,521.0016835830174C376.1290562159157,517.8887921683347,466.0731472004068,529.7835943286574,510.70327084640275,468.03025145048787C554.3714126377745,407.6079735673963,508.03601936045806,328.9844924480964,491.2728898941984,256.3432110539036C474.5976632858925,184.082847569629,479.9380746630129,96.60480741107993,416.23090153303,58.64404602377083C348.86323505073057,18.502131276798302,261.93793281208167,40.57373210992963,193.5410806939664,78.93577620505333C130.42746243093433,114.334589627462,98.30271207620316,179.96522072025542,76.75703585869454,249.04625023123273C51.97151888228291,328.5150500222984,13.704378332031375,421.85034740162234,66.52175969318436,486.19268352777647C119.04800174914682,550.1803526380478,217.28368757567262,524.383925680826,300,521.0016835830174"></path>
</svg>
<i class="bx bxl-dribbble"></i>
</div>
<h4><a href="">Economie de timp</a></h4>
<p>Știm cu toții că gătitul necesită să petrecem o parte importantă a timpului
nostru,
pentru unele feluri de
mâncare mai mult decât pentru altele. Există rețete pe care am vrea să le
facem și
din cauza lipsei de timp
nu
ajungem niciodată să le pregătim. Pregătirea alimentelor este mult mai
rapidă atunci
când o faceți cu acest
robot, mai ales că, odată ce toate ingredientele sunt introduse, mașina este
responsabilă pentru finisarea
acesteia, fără a fi nevoie să fiți în așteptarea amestecării, testării și
modificării punctului de sare. Îl
programați și vă puteți ocupa de a face alte lucruri. În acest fel, nu
trebuie să vă
faceți griji cu privire
la
arderea alimentelor.</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4 mt-md-0"
data-aos="zoom-in"
data-aos-delay="200">
<div class="icon-box iconbox-orange ">
<div class="icon">
<svg width="100" height="100" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg">
<path stroke="none" stroke-width="0" fill="#f5f5f5"
d="M300,582.0697525312426C382.5290701553225,586.8405444964366,449.9789794690241,525.3245884688669,502.5850820975895,461.55621195738473C556.606425686781,396.0723002908107,615.8543463187945,314.28637112970534,586.6730223649479,234.56875336149918C558.9533121215079,158.8439757836574,454.9685369536778,164.00468322053177,381.49747125262974,130.76875717737553C312.15926192815925,99.40240125094834,248.97055460311594,18.661163978235184,179.8680185752513,50.54337015887873C110.5421016452524,82.52863877960104,119.82277516462835,180.83849132639028,109.12597500060166,256.43424936330496C100.08760227029461,320.3096726198365,92.17705696193138,384.0621239912766,124.79988738764834,439.7174275375508C164.83382741302287,508.01625554203684,220.96474134820875,577.5009287672846,300,582.0697525312426"></path>
</svg>
<i class="bx bx-file"></i>
</div>
<h4><a href="">Începătorii pot face rețete complexe</a></h4>
<p>Există tocănițe și rețete pe care nu ai fi îndrăznit niciodată să le
prepari. <strong>Cu Thermomix nu contează
dacă nu aveți experiență de gătit</strong> și că sunteți un adevărat
dezastru
pregătind orice fel de mâncare,
este conceput astfel încât să puteți face orice rețetă, oricât de complicată
ar fi.
Și, de asemenea, astfel
încât să iasă așa cum o vedeți în fotografie. Trebuie doar să urmați fiecare
pas pe
măsură ce îl marcați. Fie că
gătește, gătește sau prepară mâncăruri tradiționale, începătorii au
posibilitatea de
a face rețete complexe. Pe
lângă shake-uri sănătoase, pot fi preparate preparate elaborate și rețete
mai
specifice pentru cei alergici la
gluten sau lactoză.</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4 mt-lg-0"
data-aos="zoom-in"
data-aos-delay="300">
<div class="icon-box iconbox-pink">
<div class="icon">
<svg width="100" height="100" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg">
<path stroke="none" stroke-width="0" fill="#f5f5f5"
d="M300,541.5067337569781C382.14930387511276,545.0595476570109,479.8736841581634,548.3450877840088,526.4010558755058,480.5488172755941C571.5218469581645,414.80211281144784,517.5187510058486,332.0715597781072,496.52539010469104,255.14436215662573C477.37192572678356,184.95920475031193,473.57363656557914,105.61284051026155,413.0603344069578,65.22779650032875C343.27470386102294,18.654635553484475,251.2091493199835,5.337323636656869,175.0934190732945,40.62881213300186C97.87086631185822,76.43348514350839,51.98124368387456,156.15599469081315,36.44837278890362,239.84606092416172C21.716077023791087,319.22268207091537,43.775223500013084,401.1760424656574,96.891909868211,461.97329694683043C147.22146801428983,519.5804099606455,223.5754009179313,538.201503339737,300,541.5067337569781"></path>
</svg>
<i class="bx bx-tachometer"></i>
</div>
<h4><a href="">Diversitate de retete</a></h4>
<p>Pe platforma/site-ul web Cookidoo găsim peste 68 000 de rețete din întreagă
lume,
rețetele
pot fi vizualizate pe orice dispozitiv (telefon, tabletă, PC), dar și pe
tabletă
aparatului.</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="zoom-in"
data-aos-delay="100">
<div class="icon-box iconbox-yellow">
<div class="icon">
<svg width="100" height="100" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg">
<path stroke="none" stroke-width="0" fill="#f5f5f5"
d="M300,503.46388370962813C374.79870501325706,506.71871716319447,464.8034551963731,527.1746412648533,510.4981551193396,467.86667711651364C555.9287308511215,408.9015244558933,512.6030010748507,327.5744911775523,490.211057578863,256.5855673507754C471.097692560561,195.9906835881958,447.69079081568157,138.11976852964426,395.19560036434837,102.3242989838813C329.3053358748298,57.3949838291264,248.02791733380457,8.279543830951368,175.87071277845988,42.242879143198664C103.41431057327972,76.34704239035025,93.79494320519305,170.9812938413882,81.28167332365135,250.07896920659033C70.17666984294237,320.27484674793965,64.84698225790005,396.69656628748305,111.28512138212992,450.4950937839243C156.20124167950087,502.5303643271138,231.32542653798444,500.4755392045468,300,503.46388370962813"></path>
</svg>
<i class="bx bx-layer"></i>
</div>
<h4><a href="">Totul în bucătăria ta</a></h4>
<p>În general, pentru a pregăti o rețetă avem nevoie de mai multe ustensile de
bucătărie, cum ar fi tigaia, cratița,
friteuza, mixerul, masina de paine. Acest aparat inteligent are totul
încorporat,
astfel încât poate fi folosit
pentru a prăji, a
găti sau a rumeni mâncarea, fără a fi nevoie să o transportați. De asemenea,
are o
cântare integrată, astfel
încât să puteți cântări toate ingredientele. De parcă nu ar fi suficient,
acesta
încorporează și funcția de
blender și tocător.</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="zoom-in"
data-aos-delay="200">
<div class="icon-box iconbox-red">
<div class="icon">
<svg width="100" height="100" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg">
<path stroke="none" stroke-width="0" fill="#f5f5f5"
d="M300,532.3542879108572C369.38199826031484,532.3153073249985,429.10787420159085,491.63046689027357,474.5244479745417,439.17860296908856C522.8885846962883,383.3225815378663,569.1668002868075,314.3205725914397,550.7432151929288,242.7694973846089C532.6665558377875,172.5657663291529,456.2379748765914,142.6223662098291,390.3689995646985,112.34683881706744C326.66090330228417,83.06452184765237,258.84405631176094,53.51806209861945,193.32584062364296,78.48882559362697C121.61183558270385,105.82097193414197,62.805066853699245,167.19869350419734,48.57481801355237,242.6138429142374C34.843463184063346,315.3850353017275,76.69343916112496,383.4422959591041,125.22947124332185,439.3748458443577C170.7312796277747,491.8107796887764,230.57421082200815,532.3932930995766,300,532.3542879108572"></path>
</svg>
<i class="bx bx-slideshow"></i>
</div>
<h4><a href="">Nu servește ca cuptor</a></h4>
<p>Este adevărat că are multe funcții, deși dacă trebuie să va ganditi la un
minus este
lipsa de coacere. Rețetele
care
necesită finisare în cuptor, cum ar fi lasagna, după terminarea întregului
proces de
preparare, trebuie
introduse în cuptor pentru a termina gătitul. Actualul model ajunge la
temperatura
de 160 de grade Celsius,
reusind astfel sa si rumenreasca alimentele, dar cele doua preparate pe care
nu le
poate realiza datorita
temperaturii maxime la care ajunge sunt: popcosnul si cartofii prajiti.</p>
</div>
</div>
<div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="zoom-in"
data-aos-delay="300">
<div class="icon-box iconbox-teal">
<div class="icon">
<svg width="100" height="100" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg">
<path stroke="none" stroke-width="0" fill="#f5f5f5"
d="M300,566.797414625762C385.7384707136149,576.1784315230908,478.7894351017131,552.8928747891023,531.9192734346935,484.94944893311C584.6109503024035,417.5663521118492,582.489472248146,322.67544863468447,553.9536738515405,242.03673114598146C529.1557734026468,171.96086150256528,465.24506316201064,127.66468636344209,395.9583748389544,100.7403814666027C334.2173773831606,76.7482773500951,269.4350130405921,84.62216499799875,207.1952322260088,107.2889140133804C132.92018162631612,134.33871894543012,41.79353780512637,160.00259165414826,22.644507872594943,236.69541883565114C3.319112789854554,314.0945973066697,72.72355303640163,379.243833228382,124.04198916343866,440.3218312028393C172.9286146004772,498.5055451809895,224.45579914871206,558.5317968840102,300,566.797414625762"></path>
</svg>
<i class="bx bx-arch"></i>
</div>
<h4><a href="">"Amprenta persoanala"</a></h4>
<p>Este evident că atingerea personală se poate pierde atunci când faceți o
rețetă în
acest aparat inteligent, cu
toate ca el doar va sugereaza cantitatile, lasandu-va posibilitatea sa
alegeti cat
zahar, de exempl, sa
adaugati. Poate fi considerata mai putin probabila dorinta de a adăuga
condimente în ceea ce privește aroma pe care doriți să o aibă atunci cand
gatiti
retetele prestabilite. La fel
se întâmplă cu anumite alimente, cum ar fi
o paella. În funcție de locul în care îl faceți, acesta va ieși cu o aromă
diferită,
fie că este vorba de foc de
lemne, sticlă ceramică sau foc de gaz. Acest lucru se pierde cu Thermomix si
trebuie
sa tineti cont ca gustul va
fi acelasi de fiecare data cand o sa gatiti reteta, lucru care este un
avantaj
pentru restaurante.</p>
</div>
</div>
</div>
</div>
</section>
</main>
<footer id="footer">
<div class="footer-top">
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-6 footer-contact">
<h3>gătește ușor cu thermomix</h3>
<p>
Str. <NAME>, nr 32<br/>
Otopeni, jud. Ilfov<br/>
Romania <br/><br/>
<strong>Telefon: </strong>+40 723809147<br/>
<strong>Email: </strong><EMAIL><br/>
</p>
</div>
<div class="col-lg-2 col-md-6 footer-links">
<h4>Link-uri utile</h4>
<ul>
<li><i class="bx bx-chevron-right"></i> <a href="#">Acasă</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#paste">Rețetă de Paște</a>
</li>
<li><i class="bx bx-chevron-right"></i> <a href="#colectii">Colecții
Cookidoo</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#about">Despre Thermomix</a>
</li>
<li><i class="bx bx-chevron-right"></i> <a href="#services">Avantaje și
dezavantaje</a>
</li>
{/*<li><i class="bx bx-chevron-right"></i> <a href="#contact">Contactează-mă</a></li>-->*/}
</ul>
</div>
<div class="col-lg-3 col-md-6 footer-links">
<h4>Serviciile oferite</h4>
<ul>
<li><i class="bx bx-chevron-right"></i> <a href="#">Prezentare online</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#">Prezentare față în față
acasă la
dvs</a>
</li>
<li><i class="bx bx-chevron-right"></i> <a href="#">Prezentare față în față la
sediul
Thermomix, din Băneasa</a></li>
<li><i class="bx bx-chevron-right"></i> <a href="#">Ajutor permanent pe perioada
utilizarii</a>
</li>
<li><i class="bx bx-chevron-right"></i> <a href="#">Recomandări de rețete</a>
</li>
</ul>
</div>
//todo
{/*<div class="col-lg-4 col-md-6 footer-newsletter">*/}
{/* <h4>Primește vești despre Thermomix</h4>*/}
{/* <p>Îți vom trimite rețete, noutăți despre Cookidoo și Thermomix</p>*/}
{/* <form action="" method="post">-->*/}
{/* <input type="email" name="email"><input type="submit" value="Înscrie-te">*/}
{/* </form>*/}
{/*</div>*/}
</div>
</div>
</div>
<div class="container d-md-flex py-4">
<div class="me-md-auto text-center text-md-start">
<div class="copyright">
© Copyright <strong><span>OnePage</span></strong>. Toate drepturile rezervate.
</div>
<div class="credits">
Realizat de <a href="https://alinapreda.ro/">Alina Preda</a>
</div>
</div>
<div class="social-links text-center text-md-right pt-3 pt-md-0">
<a href="https://www.facebook.com/gatesteusorthermomix/" class="facebook"><i
class="bx bxl-facebook"></i></a>
<a href="https://www.instagram.com/gateste.usor.cu.thermomix/" class="instagram"><i
class="bx bxl-instagram"></i></a>
{/*<a href="#" class="linkedin"><i class="bx bxl-linkedin"></i></a>-->*/}
</div>
</div>
</footer>
<div id="preloader"></div>
<a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i
class="bi bi-arrow-up-short"></i></a>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<script src="assets/vendor/purecounter/purecounter.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</div>
)
}
}
export default App;
<file_sep>/README.md
# tmx-web
A React app for a website
| e698df5107620df0c2fed29c9c9ebf34cc3f1b1e | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | alinaroxanapreda/tmx-web | 2147c538c4a21c58404334e31dd4bcb541161981 | 7029433789498bf484cafd5148bc09402f7fe838 |
refs/heads/master | <file_sep># Message Wall
The wall is a basic message board type page where after loging in or registering they can post messages for everyone to see. Users can also comment on messages and delete messages they wrote. Created to work one some of the CRUD functions.
__Built With:__
* C#
* ASP.NET Core
* MySQL
* Boostrap
* HTML/CSS

<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TheWall.Models;
namespace TheWall.Controllers
{
public class WallController : Controller
{
private readonly DbConnector _dbConnector;
public WallController(DbConnector connect) {
_dbConnector = connect;
}
[HttpGet]
[Route("Wall")]
public IActionResult Wall() {
ViewBag.Errors = TempData["Errors"];
// Get user's name
int? UserId = HttpContext.Session.GetInt32("id");
string IdQuery = ("SELECT * FROM users WHERE id = '"+UserId+"'");
var GrabId = _dbConnector.Query(IdQuery);
ViewBag.User = GrabId;
// Get message info
string MessageQuery = "SELECT messages.id, CONCAT(users.first_name, ' ', users.last_name) AS message_author, messages.created_at, messages.user_id, messages.message FROM messages JOIN users on users.id = messages.user_id ORDER BY messages.id DESC";
var allMessages = _dbConnector.Query(MessageQuery);
ViewBag.AllMessages = allMessages;
string CommentQuery = $"SELECT comments.message_id, CONCAT(users.first_name, ' ',users.last_name) AS comment_author, comments.created_at, comments.comment FROM comments JOIN users ON users.id = comments.user_id JOIN messages ON messages.id = comments.message_id";
var allComments = _dbConnector.Query(CommentQuery);
ViewBag.AllComments = allComments;
return View("Wall");
}
[HttpPost]
[Route("post_message")]
public IActionResult post_message(Message model) {
int? UserId = HttpContext.Session.GetInt32("id");
List<string> allErrors = new List <string>();
if (ModelState.IsValid) {
string query = $"INSERT INTO messages (message, created_at, updated_at, user_id) VALUES ('"+model.message+"', NOW(), NOW(), '"+UserId+"')";
_dbConnector.Execute(query);
return RedirectToAction("Wall");
}
foreach (var i in ModelState.Values) {
if (i.Errors.Count > 0) {
allErrors.Add(i.Errors[0].ErrorMessage.ToString());
}
}
TempData["Errors"] = allErrors;
return RedirectToAction("Wall");
}
[HttpPost]
[Route("post_comment/{id}")]
public IActionResult post_comment(Comment model) {
int? UserId = HttpContext.Session.GetInt32("id");
List<string> allErrors = new List <string>();
if (ModelState.IsValid) {
// string MessageQuery = $"SELECT * FROM messages where id = '"+model.id+"'";
string query = $"INSERT INTO comments (comment, created_at, updated_at, message_id, user_id) VALUES ('"+model.comment+"', NOW(), NOW(), '"+model.id+"', '"+UserId+"')";
_dbConnector.Execute(query);
return RedirectToAction("Wall");
}
// If validiation fails
foreach (var i in ModelState.Values) {
if (i.Errors.Count > 0) {
allErrors.Add(i.Errors[0].ErrorMessage.ToString());
}
}
TempData["Errors"] = allErrors;
return RedirectToAction("Wall");
}
[HttpPost]
[Route("delete_post/{id}")]
public IActionResult delete_post(Comment model) {
string DeleteQuery = $"DELETE FROM comments WHERE message_id = '"+model.id+"'";
_dbConnector.Execute(DeleteQuery);
string query = $"DELETE FROM messages WHERE id = '"+model.id+"'";
_dbConnector.Execute(query);
return RedirectToAction("Wall");
}
[HttpPost]
[Route("delete_comment/{id}")]
public IActionResult delete_comment(Comment model) {
string query = $"DELETE FROM comments WHERE id = '"+model.id+"'";
_dbConnector.Execute(query);
return RedirectToAction("Wall");
}
}
}
<file_sep>using System.ComponentModel.DataAnnotations;
namespace TheWall.Models
{
public class Comment : BaseEntity
{
[Required]
public string comment { get; set; }
[Required]
public int id { get; set; }
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace TheWall.Models
{
public class Message : BaseEntity
{
[Key]
public int message_id { get; set; }
[Key]
public int comments_message_id { get; set; }
[Required]
public string message { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TheWall.Models;
using Microsoft.AspNetCore.Http;
namespace TheWall.Controllers
{
public class LoginRegController : Controller
{
private readonly DbConnector _dbConnector;
public LoginRegController(DbConnector connect) {
_dbConnector = connect;
}
[HttpGet]
[Route("")]
public IActionResult LoginReg()
{
ViewBag.Errors = TempData["Errors"];
return View("LoginReg");
}
[HttpPost]
[Route("Register")]
public IActionResult Register(RegisterUser model) {
List<string> allErrors = new List <string>();
if(ModelState.IsValid) {
// string UserQuery = ("SELECT * FROM users WHERE Email = '"+model.email+"'");
// var CheckForUser = _dbConnector.Query(UserQuery);
// if (CheckForUser != null) {
// allErrors.Add("Email already in use");
// TempData["Errors"] = allErrors;
// return RedirectToAction("LoginReg");
// }
// else {
string query = $"INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES ('"+model.first_name+"', '"+model.last_name+"', '"+model.email+"', '"+model.password+"', NOW(), NOW())";
_dbConnector.Execute(query);
// Grab user id
string IdQuery = ("SELECT id FROM users WHERE Email = '"+model.email+"'");
var GrabId = _dbConnector.Query(IdQuery);
HttpContext.Session.SetInt32("id", (int)GrabId[0]["id"]);
return RedirectToAction("Success");
// }
}
foreach (var i in ModelState.Values) {
if (i.Errors.Count > 0) {
allErrors.Add(i.Errors[0].ErrorMessage.ToString());
}
}
TempData["Errors"] = allErrors;
return RedirectToAction("LoginReg");
}
[HttpPost]
[Route("Login")]
public IActionResult Login(LoginUser model) {
List<string> allErrors = new List <string>();
if(ModelState.IsValid) {
string UserQuery = ("SELECT * FROM users WHERE Email = '"+model.Email+"'");
var CheckForUser = _dbConnector.Query(UserQuery);
// Check if user exists
if (CheckForUser != null) {
string PasswordQuery = ("SELECT Password FROM users WHERE Email = '"+model.Email+"'");
var CheckPassword = _dbConnector.Query(PasswordQuery);
// Check for correct password
if (model.Password == (string)CheckPassword[0]["Password"]) {
// Grab user id
string IdQuery = ("SELECT id FROM users WHERE Email = '"+model.Email+"'");
var GrabId = _dbConnector.Query(UserQuery);
HttpContext.Session.SetInt32("id", (int)GrabId[0]["id"]);
return RedirectToAction("Success");
}
else {
allErrors.Add("Incorrect password");
TempData["Errors"] = allErrors;
}
}
}
// ViewBag.Errors = ModelState.Values;
foreach (var i in ModelState.Values) {
if (i.Errors.Count > 0) {
allErrors.Add(i.Errors[0].ErrorMessage.ToString());
}
}
TempData["Errors"] = allErrors;
return RedirectToAction("LoginReg");
}
[HttpGet]
[Route("Success")]
public IActionResult Success()
{
System.Console.WriteLine("SUCCESS");
return RedirectToAction("Wall", "Wall");
}
}
}
| af190ea143afc38c99f1f27b4932bcb9f1e856ab | [
"Markdown",
"C#"
] | 5 | Markdown | Ziyal/TheWall | d3110fe6208941598c984b84fc607010df57a951 | e7b3a73fa0784bdaef8848a11662b9187e8b710e |
refs/heads/master | <file_sep>import math
from statistics import mean
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print "Name:", self.lastName + ",", self.firstName
print "ID:", self.idNumber
class Student(Person):
# Class Constructor
#
# Parameters:
# firstName - A string denoting the Person's first name.
# lastName - A string denoting the Person's last name.
# id - An integer denoting the Person's ID number.
# scores - An array of integers denoting the Person's test scores.
#
# Write your constructor here
def __init__(self, firstName, lastName, idNumber, scores):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
self.scores = scores
def calculate(self):
print "self.scores :",self.scores
print "len(self.scores):",len(self.scores)
print "sum(self.scores) :",sum(self.scores)
avg=sum(self.scores)/len(self.scores)
# avg=mean(self.scores)
print avg
if 90 <= self.scores <= 100:
return 'O'
elif 80 <= self.scores < 90:
return 'E'
elif 70 <= self.scores < 80:
return 'A'
elif 55 <= self.scores < 70:
return 'P'
elif 40 <= self.scores < 55:
return 'D'
elif self.scores < 40:
return 'T'
print "self.scores :",self.scores
# Function Name: calculate
# Return: A character denoting the grade.
#
# Write your function here
line = raw_input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
# numScores = int(raw_input()) # not needed for Python
scores = map(int, raw_input().split())
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print "Grade:", s.calculate()
# Actual:
def calculate(self):
avg = int(sum(self.scores) / len(self.scores))
if 90 <= avg <= 100:
return 'O'
elif 80 <= avg < 90:
return 'E'
elif 70 <= avg < 80:
return 'A'
elif 55 <= avg < 70:
return 'P'
elif 40 <= avg < 55:
return 'D'
elif avg < 40:
return 'T'
<file_sep># Write a function that takes in a string of one or more words, and returns the same string, but with all five
# or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters
# and spaces. Spaces will be included only when more than one word is present.
# Examples:
# spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") =>
# returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"
# test.assert_equals(spin_words("Welcome"), "emocleW")
def spin_words1(sentence):
l=[]
for x in sentence.split():
if len(x) >4:
l.append(x[::-1])
else:
l.append(x)
return ' '.join(X for X in l)
def spin_words2(sentence):
# Your code goes here
return " ".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(" ")])
def spin_words3(sentence):
return ' '.join(word if len(word)<5 else word[::-1] for word in sentence.split())
print spin_words1("Welcome to the jungle")
print spin_words2("Welcome to the jungle")
print spin_words3("Welcome to the jungle")<file_sep># # Input Format
# #
# # The first line contains an integer,N , total number of rows in the table.
# # Each of the N subsequent lines contains 2 space-separated strings denoting a person's first name and email ID, respectively.
# #
# # Constraints
# #
# # Each of the first names consists of lower case letters a-z only.
# # Each of the email IDs consists of lower case letters a-z,@ and . only.
# # The length of the first name is no longer than 20.
# # The length of the email ID is no longer than 50.
# #
# # Output Format
# #
# # Print an alphabetically-ordered list of first names for every user with a gmail account. Each name must be printed on a new line.
# #
# # Sample Input
# #
# # 6
# # riya <EMAIL>
# # julia <EMAIL>
# # julia <EMAIL>
# # julia <EMAIL>
# # samantha <EMAIL>
# # tanya <EMAIL>
# #
# # Sample Output
# #
# # julia
# # julia
# # riya
# # samantha
# # tanya
#
#
# #!/bin/python
# import sys
# import re
# N = int(raw_input().strip())
# dict={}
# for a0 in xrange(N):
# firstName,emailID = raw_input().strip().split(' ')
# dict[firstName]=emailID
# print dict
# # [firstName,emailID] = [str(firstName),str(emailID)]
# # print "firstName :",firstName
# # print "emailID :",emailID
# # for x in dict.values():
# # print dict.values()
# # if re.match('[a-z]+<EMAIL>',x):
# # print True
# # print dict.keys()
import re
N = int(raw_input().strip())
abc=[]
for a0 in xrange(N):
firstName,emailID = raw_input().strip().split(' ')
firstName,emailID = [str(firstName),str(emailID)]
if re.match('[a-z.]+@<EMAIL>', emailID):
abc.append(firstName)
abc.sort()
print abc
print '\n'.join(abc)
# Online Answer:
import re
arr = []
n = int(input())
for i in range(n):
data = str(raw_input()).split(" ")
name = data[0]
email = data[1]
if re.search(".+@gmail\.com$", email):
arr.append(name)
arr.sort()
for name in arr:
print(name)
# 6
# riya <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# samantha <EMAIL>
# tanya <EMAIL>
# EXTRA TEST CASES
# INPUT:
# 30
# riya <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# samantha <EMAIL>
# tanya <EMAIL>
# riya <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# samantha <EMAIL>
# tanya <EMAIL>
# riya <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# samantha <EMAIL>
# tanya <EMAIL>
# riya <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# julia <EMAIL>
# samantha <EMAIL>
# tanya <EMAIL>
# riya <EMAIL>
# priya <EMAIL>
# preeti <EMAIL>
# alice <EMAIL>
# alice <EMAIL>
# alice <EMAIL>
#
#
# OUTPUT:
# alice
# alice
# julia
# julia
# julia
# julia
# preeti
# priya
# riya
# riya
# samantha
# samantha
# tanya
# tanya<file_sep># n=int(raw_input("Enter n:"))
# phone={}
# for x in range(n):
# a=raw_input("Enter name and number: ")
# print a.split()[0]
# print a.split()[1]
# phone[a.split()[0]]=a.split()[1]
# print phone
# # print x.split()[0],x.split()[1]
# # dict(x.split()[0])=x.split()[1]
# abc=raw_input("")
# for y in phone.keys():
# print y+"="+phone.get(y)
# else:
# "Not Found"
n=int(raw_input(""))
phone={}
for x in range(n):
a=raw_input("")
#print a.split()[0]
#print a.split()[1]
phone[a.split()[0]]=int(a.split()[1])
#print phone
# print x.split()[0],x.split()[1]
# dict(x.split()[0])=x.split()[1]
for z in range(n):
y=raw_input("")
if y in phone.keys():
print str(y)+"="+str(phone.get(y))
else:
print "Not found"
n=int(raw_input(""))
phone={}
for x in range(n):
a=raw_input("").split(" ")
phone[a[0]]=int(a[1])
for z in range(n):
name=raw_input()
if name in phone:
phone1 = phone[name]
print(name + "=" + str(phone1))
else:
print("Not found")
#actual answer
num = int(input())
phone_book = {}
for i in range(0, num):
entry = str(raw_input()).split(" ")
name = entry[0]
phone = int(entry[1])
phone_book[name] = phone
for j in range(0, num):
name = str(raw_input())
if name in phone_book:
phone = phone_book[name]
print(name + "=" + str(phone))
else:
print("Not found")<file_sep># n sorted array of int
# a=[1,4,10,2,3]
# 2nd highest no
# dont use sort and loop through only once
# a=[1,4,10,2,3]
# max_no= max(a)
# a.remove(max_no)
# print max(a)
# n=len(a)
# for i in range(n):
# while i!=n-1:
# if a[i] > a[i+1]:
# a[i],a[i+1]=a[i+1],a[i]
# print a[n-2]
cur=[2000,500,100,50,20,10,5,2]
amount=2553
#split it with minimum no of notes
count=[0,0,0,0,0,0,0,0]
for i,j in zip(cur,count):
if amount>=i:
j=amount//i
amount=amount-j*i
print (i,j)
print "%s cant be splitted further"%amount
<file_sep># If the book is returned on or before the expected return date, no fine will be charged (i.e.: fine=0).
# If the book is returned after the expected return day but still within the same calendar month and year as the
# expected return date,fine=15 Hackos x the no of days late.
# If the book is returned after the expected return month but still within the same calendar year as the expected
# return date, the fine=500 Hackos x the no of months late .
# If the book is returned after the calendar year in which it was expected, there is a fixed fine of 10000 hackos.
#a=actual e=expected
a=raw_input().split(" ")
print a
e=raw_input().split(" ")
print e
# print e.split(" ")
# print e.split(" ")[0]
# if a[0]>=e[0] and a[1]==e[1] and a[2]==e[2]:
# # fine=0
# # else:
# fine=15 * (int(a[0])-int(e[0]))
#
# elif a[1]>=e[1] and a[2]==e[2]:
# # fine=0
# # else:
# fine=500*((int(a[1])-int(e[1])))
#
# elif a[2]==e[2]:
# # fine=0
# # else:
# fine=10000
#
# print fine
#
# # print date_fine
# # print month_fine
# # total_fine=date_fine + month_fine
# # print total_fine
if int(a[2])<int(e[2]):
fine=0
elif int(a[2])>int(e[2]):
fine=10000
elif int(a[1])>int(e[1]):
fine=500*((int(a[1])-int(e[1])))
elif int(a[0])>int(e[0]):
fine=15*((int(a[0])-int(e[0])))
else:
fine=0
print fine
<file_sep>class Difference:
def __init__(self, a):
self.__elements = a
def computeDifference(self):
# self.maximumDifference=0
# for x in self.__elements:
# self.maximumDifference=abs(x-self.maximumDifference)
# print self.maximumDifference
self.max=max(self.__elements)
self.min=min(self.__elements)
self.maximumDifference=abs(self.max-self.min)
_ = raw_input()
a = [int(e) for e in raw_input().split(' ')]
d = Difference(a)
d.computeDifference()
print d.maximumDifference
#Actual Solution:
#self.maximumDifference = max(a) - min(a)
<file_sep>arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
# print arr
# print ("\n *******************************")
sum_arr=[]
# def calc_sum():
# print arr[0][0]+arr[0][1]+arr[0][2]+arr[1][1]+arr[2][0]+arr[2][1]+arr[2][2]
for n in range(4):
for m in range(4):
sum=arr[n][m]+arr[n][m+1]+arr[n][m+2]+arr[n+1][m+1]+arr[n+2][m]+arr[n+2][m+1]+arr[n+2][m+2]
sum_arr.append(sum)
# print sum_arr
print max(sum_arr)
# 1 2 3 4 5 6
# 1 2 3 4 5 6
# 1 2 3 4 5 6
# 1 2 3 4 5 6
# 1 2 3 4 5 6
# 1 2 3 4 5 6
# for arr_i in xrange(6):
# print arr_i
# for arr_i in range(6):
# print arr_i<file_sep># Write a function that takes an integer as input, and returns the number of bits that are equal to one in the
# binary representation of that number. You can guarantee that input is non-negative.
# Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
# test.assert_equals(countBits(0), 0);
# test.assert_equals(countBits(4), 1);
# test.assert_equals(countBits(7), 3);
# test.assert_equals(countBits(9), 2);
# test.assert_equals(countBits(10), 2);
from collections import Counter
def countBit(n):
a=Counter(bin(n))
if "1" in a:
return a.get("1")
return 0
def countBits(n):
return bin(n).count("1")
print countBits(0)
print countBits(4)
print countBits(7)
print countBits(9)
print countBits(10)<file_sep># # My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest.
# I am the one who establishes the list so I told him: "Don't worry any more, I will modify the order of the list". It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits.
# For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers?
# Example:
# "56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99"
# When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9), it comes before as a string.
# All numbers in the list are positive numbers and the list can be empty.
# Notes
# it may happen that the input string have leading, trailing whitespaces and more than a unique whitespace between two consecutive numbers
# Don't modify the input
# For C: The result is freed.
# Test.it("Basic tests")
# Test.assert_equals(order_weight("103 123 4444 99 2000"), "2000 103 123 4444 99")
# Test.assert_equals(order_weight("2000 10003 1234000 44444444 9999 11 11 22 123"), "11 11 2000 10003 22 123 1234000 44444444 9999")
dt={}
def order_weight(strng):
for x in strng:
res=0
for i in x:
res = res + int(i)
dt[x]=res
# print dt
a=sorted(dt.items(),key = lambda x: (x[1],x[0]))
print [x[0] for x in a]
# return ' '.join(x[0] for x in dt)
dt=[]
def order_weight(strng):
for x in strng.split():
res=0
for i in x:
res = res + int(i)
dt.append((x,res))
# print dt
dt.sort(key = lambda x: (x[1],x[0]))
# print dt[3][0]
return ' '.join(x[0] for x in dt)
# order_weight("103 123 4444 99 2000")
# print order_weight("2000 10003 1234000 44444444 9999 11 11 22 123")
################################
def order_weight(_str):
return ' '.join(sorted(sorted(_str.split(' ')), key=lambda x: sum(int(c) for c in x)))
################################3
def sum_string(s):
sum = 0
for digit in s:
sum += int(digit)
return sum
def order_weight(strng):
# your code
initial_list = sorted(strng.split())
result = " ".join(sorted(initial_list, key=sum_string))
return result<file_sep>S = raw_input().strip()
try:
S=int(S)
print S
except ValueError:
print "Bad String"<file_sep># To introduce the problem think to my neighbor who drives a tanker truck. The level indicator is down and
# he is worried because he does not know if he will be able to make deliveries. We put the truck on a horizontal
# ground and measured the height of the liquid in the tank.
# Fortunately the tank is a perfect cylinder and the vertical walls on each end are flat.
# The height of the remaining liquid is h, the diameter of the cylinder is d, the total volume is
# vt (h, d, vt are positive or null integers). You can assume that h <= d.
# Could you calculate the remaining volume of the liquid? Your function tankvol(h, d, vt) returns an
# integer which is the truncated result (e.g floor) of your float calculation.
# Examples:
# tankvol(40,120,3500) should return 1021 (calculation gives about: 1021.26992027)
# tankvol(60,120,3500) should return 1750
# tankvol(80,120,3500) should return 2478 (calculation gives about: 2478.73007973)<file_sep># Let us begin with an example:
# A man has a rather old car being worth $2000. He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one.
# He thinks he can save $1000 each month but the prices of his old car and of the new one decrease of 1.5 percent per month. Furthermore this percent of loss increases by 0.5 percent at the end of every two months. Our man finds it difficult to make all these calculations.
# Can you help him?
# How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over?
# Parameters and return of function:
# parameter (positive int or float, guaranteed) startPriceOld (Old car price)
# parameter (positive int or float, guaranteed) startPriceNew (New car price)
# parameter (positive int or float, guaranteed) savingperMonth
# parameter (positive float or int, guaranteed) percentLossByMonth
# nbMonths(2000, 8000, 1000, 1.5) should return [6, 766] or (6, 766)
# where 6 is the number of months at the end of which he can buy the new car and 766 is the nearest integer to 766.158 (rounding 766.158 gives 766).
# Note:
# Selling, buying and saving are normally done at end of month. Calculations are processed at the end of each considered month but if, by chance from the start, the value of the old car is bigger than the value of the new one or equal there is no saving to be made, no need to wait so he can at the beginning of the month buy the new car:
# nbMonths(12000, 8000, 1000, 1.5) should return [0, 4000]
# nbMonths(8000, 8000, 1000, 1.5) should return [0, 0]
def car(cash,price,saving,per):
month=0
tot=0
while price>tot+cash:
month+=1
cash=cash-((cash*(per))/100)
# cash+=saving
# saving+=savisavingng
tot+=saving
# tot+=cash
price = price-((price*(per))/100)
if month%2==0 and month!=0:
per+=0.5
print month,per
print tot,cash,price,saving,per,month,tot-price
else:
return month,cash+tot-price
print car(2000, 8000, 1000, 1.5)<file_sep>S="Hacker"
len(S)
# for i in range(0,len(S-1)):
# print S[::2]
print S[::2]
print S[1::2]
S=raw_input("Enter a String")
odd=[]
even=[]
for i in range(len(S)):
print i
while i:
if i==0:
even.append(S[0])
elif i%2==0:
even.append(S[i])
elif i%2!=0:
odd.append(S[i])
print odd
print even
#Actual Answer
# Enter your code here. Read input from STDIN. Print output to STDOUT
M=int(raw_input("Enter a Name"))
for i in range(M):
S=raw_input("")
print S[::2]+" "+S[1::2]
<file_sep># Define a function that takes one integer argument and returns logical value true or false depending on if the integer is a prime.
# Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
# Assumptions
# You can assume you will be given an integer input.
# You can not assume that the integer will be only positive. You may be given negative numbers as well (or 0).
# There are no fancy optimizations required, but still the most trivial solutions might time out. Try to find a solution which does not loop all the way up to n.
# @Test.describe("Basic")
# def basic():
# @Test.it("Basic tests")
# def basic_tests():
# Test.assert_equals(is_prime(0), False, "0 is not prime")
# Test.assert_equals(is_prime(1), False, "1 is not prime")
# Test.assert_equals(is_prime(2), True, "2 is prime")
# Test.assert_equals(is_prime(73), True, "73 is prime")
# Test.assert_equals(is_prime(75), False, "75 is not prime")
# Test.assert_equals(is_prime(-1), False, "-1 is not prime")
# @Test.it("Test prime")
# def test_prime():
# Test.assert_equals(is_prime(3), True, "3 is not prime");
# Test.assert_equals(is_prime(5), True, "5 is not prime");
# Test.assert_equals(is_prime(7), True, "7 is prime");
# Test.assert_equals(is_prime(41), True, "41 is prime");
# Test.assert_equals(is_prime(5099), True, "5099 is prime");
# @Test.it("Test not prime")
# def test_not_prime():
# Test.assert_equals(is_prime(4), False, "4 is not prime");
# Test.assert_equals(is_prime(6), False, "6 is not prime");
# Test.assert_equals(is_prime(8), False, "8 is prime");
# Test.assert_equals(is_prime(9), False, "9 is prime");
# Test.assert_equals(is_prime(45), False, "45 is not prime");
# Test.assert_equals(is_prime(-5), False, "-5 is not prime");
# Test.assert_equals(is_prime(-8), False, "-8 is not prime");
# Test.assert_equals(is_prime(-41), False, "-41 is not prime");
import math
def is_prime(num):
# if
if num > 1:
for n in range(2,int(math.sqrt(num))+1):
# for n in range(2,int(math.ceil(math.sqrt(num)))+1):
# for n in range(2,(num/2)+1):
# for y in range(2,(n/2)+1):
# if n % y==0:
# return False
if num % n==0:
return False
return True
return False
print is_prime(-5)
print is_prime(9)
print is_prime(524287)
print int(math.sqrt(10))
print is_prime(2147483647)
# -*- coding: utf-8 -*-
def is_prime(num):
import math
# There's only one even prime: 2
if num < 2 : return False
if num == 2 : return True
if num %2 == 0: return False
"""
Property:
Every number n that is not prime has at least one prime divisor p
such 1 < p < square_root(n)
"""
root = int(math.sqrt(num))
# We know there's only one even prime, so with that in mind
# we're going to iterate only over the odd numbers plus using the above property
# the performance will be improved
for i in xrange(3, root+1, 2):
if num % i == 0: return False
return True<file_sep># Count the number of Duplicates
# Write a function that will return the count of distinct case-insensitive alphabetic characters and
# numeric digits that occur more than once in the input string. The input string can be assumed to contain
# only alphabets (both uppercase and lowercase) and numeric digits.
# Example
# "abcde" -> 0 # no characters repeats more than once
# "aabbcde" -> 2 # 'a' and 'b'
# "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)
# "indivisibility" -> 1 # 'i' occurs six times
# "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
# "aA11" -> 2 # 'a' and '1'
# "ABBA" -> 2 # 'A' and 'B' each occur twice
# test.assert_equals(duplicate_count("abcde"), 0)
# test.assert_equals(duplicate_count("abcdea"), 1)
# test.assert_equals(duplicate_count("indivisibility"), 1)
from collections import Counter
def duplicate_count(text):
print text
a={}
for x in text:
if x in a:
a[x]+=1
else:
a[x]=1
print a
z=Counter(text)
print len(z)
print z.values()
# count = sum(1 for e in z.values() if e is not 1)
count = sum(1 for e in Counter(text.lower()).values() if e is not 1)
print count
# print (lambda v: z.values()>0)#, z.values()))
# print len(lambda v: z.values()>0)#, z.values()))
duplicate_count("abcd ABCD")
def duplicate_count(s):
return len([c for c in set(s.lower()) if s.lower().count(c)>1])<file_sep># Most football fans love it for the goals and excitement. Well, this Kata doesn't.
# You are to handle the referee's little notebook and count the players who were sent off for fouls and misbehavior.
# The rules: Two teams, named "A" and "B" have 11 players each; players on each team are numbered from 1 to 11.
# Any player may be sent off the field by being given a red card. A player can also receive a yellow warning card,
# which is fine, but if he receives another yellow card, he is sent off immediately (no need for a red card in
# that case). If one of the teams has less than 7 players remaining, the game is stopped immediately by the referee,
# and the team with less than 7 players loses.
# A card is a string with the team's letter ('A' or 'B'), player's number, and card's color ('Y' or 'R')
# all concatenated and capitalized. e.g the card 'B7Y' means player #7 from team B received a yellow card.
# The task: Given a list of cards (could be empty), return the number of remaining players on each team at
# the end of the game (as a tuple of 2 integers, team "A" first). If the game was terminated by the referee
# for insufficient number of players, you are to stop the game immediately, and ignore any further possible cards.
# Note for the random tests: If a player that has already been sent off receives another card - ignore it.
# test.assert_equals(men_still_standing([]),(11,11))
# test.assert_equals(men_still_standing(["A4Y", "A4Y"]),(10,11))
# test.assert_equals(men_still_standing(["A4Y", "A4R"]),(10,11))
# test.assert_equals(men_still_standing(["A4Y", "A5R", "B5R", "A4Y", "B6Y"]),(9,10))
# test.assert_equals(men_still_standing(["A4R", "A4R", "A4R"]),(10,11))
# test.assert_equals(men_still_standing(["A4R", "A6R", "A8R", "A10R", "A11R"]),(6,11))
dica={}
dicb={}
def men_still_standing(cards):
for x in cards:
dica[x]=1
print dica
print men_still_standing(["A4R", "A6R", "A8R", "A10R", "A11R"])<file_sep># Take the following IPv4 address: 172.16.58.3
# This address has 4 octets where each octet is a single byte (or 8 bits).
# 1st octet 128 has the binary representation: 10000000
# 2nd octet 32 has the binary representation: 00100000
# 3rd octet 10 has the binary representation: 00001010
# 4th octet 1 has the binary representation: 00000001
# So 172.16.58.3 == 10000000.00100000.00001010.00000001
# Because the above IP address has 32 bits, we can represent it as the unsigned 32 bit number: 2149583361
# Complete the function that takes an unsigned 32 bit number and returns a string representation of its IPv4 address.
# Examples
# 2149583361 ==> "172.16.58.3"
# 32 ==> "0.0.0.32"
# 0 ==> "0.0.0.0"
# Test.assert_equals(int32_to_ip(2154959208), "172.16.58.3")
# Test.assert_equals(int32_to_ip(0), "0.0.0.0")
# Test.assert_equals(int32_to_ip(2149583361), "172.16.58.3")
def int32_to_ip(int32):
n='00001011'
m=32
bi='{0:2b}'.format(int(2149583361))
a=0
print bi
print int(n,2)
print bin(32)
di='{0:2b}'.format(int(a)).strip().zfill(32)
# di='{0:2b}'.format(int(a)).strip()#.zfill(32)
# di=di.rjust(9, '0')
print "di :",di
di=di.zfill(32)
print di.zfill(32),type(di)
print '{0:32d}'.format(int(32))
print di[0:8]
print int(di[0:8],2)
print int(di[24:32],2)
print '{}.{}.{}.{}'.format(int(di[0:8],2),int(di[8:16],2),int(di[16:24],2),int(di[24:32],2))
print '%d.%d.%d.%d'%(int(di[0:8],2),int(di[8:16],2),int(di[16:24],2),int(di[24:32],2))
int32_to_ip(5)
def int32_to_ip(int32):
bi='{0:2b}'.format(int32).strip().zfill(32)
return '{}.{}.{}.{}'.format(int(bi[0:8],2),int(bi[8:16],2),int(bi[16:24],2),int(bi[24:32],2))
# print int32_to_ip(5)
def int32_to_ip(int32):
return '{}.{}.{}.{}'.format(*int32.to_bytes(4, 'big'))
print int32_to_ip(5)
from ipaddress import IPv4Address
from ipaddress import ip_address
def int32_to_ip(int32):
return str(IPv4Address(int32))
# print int32_to_ip(5)
<file_sep># #!/bin/python
#
# # import sys
# # import counter
# #
# # n = int(raw_input("Enter no: ").strip())
# # print n
# # print bin(n)
# # a=str("{0:b}".format(n))
# # print a
# # print len(str(a))
# # print counter.Counter(str("{0:b}".format(n)))
# # count =1
# #
# # for x in range(len(str(a))):
# # print x
# # if x==0 and a[x]=="1":
# # count=1
# # elif a[x]=="1" and a[x-1]=="1":
# # count+=1
# # else:
# # count=1
# # print "count :",count
#
#
# num = int(input())
#
# result = 0
# maximum = 0
#
# while num > 0:
# if num % 2 == 1:
# result += 1
# if result > maximum:
# maximum = result
#
# else:
# result = 0
# num //= 2
# # print (num //= 2)
#
# print(maximum)
n = int(input())
max_one_count = 0
one_count = 0
while n != 0: #15!=0 #
factor = n // 2 #15//2=7 7//2=3 3//2=1 1//2=0 0//2=0
# print "factor :",factor
remainder = n - (2 * factor) #15-(2*7)==1 7-(2*3)==1 3-(2*1)==1 1-(2*0)==1 0-(2*0)==0
# print "remainder :",remainder
n = factor #n=7 n=3 n=1 n=0 n=0
if remainder == 1:
one_count += 1
max_one_count = max(max_one_count, one_count)
else:
one_count = 0
print(max_one_count)
#15==1111;
print 15//2
print 1//2
print 0//2<file_sep>########################################################################################
# from __future__ import division
#
# print 7/3 # 2 if no import #2.333 import import from future
########################################################################################
# import keyword
# s = ["for","geeksforgeeks","elif","elseif","nikhil","assert","shambhavi","True","False","akshat","akash","break","ashty","lambda","suman","try"]
# for x in s:
# if keyword.iskeyword(x):
# print ( x + " is a python keyword")
# else:
# print ( x + " is not a python keyword")
#
# print (keyword.kwlist)
########################################################################################
# print False == 0 #True
# print True == 1
# print True + True + True
# print True + False + False
# assert 5 < 3, "5 is not smaller than 3"
########################################################################################
# for letter1 in 'geeksforgeeks':
# if letter1 == 'e' or letter1 == 's':
# continue
# print 'Current Letter1 :', letter1
# var = 10
########################################################################################
# for letter2 in 'geeksforgeeks':
# # break the loop as soon it sees 'e'
# # or 's'
# if letter2 == 'e' or letter2 == 's':
# break
# print 'Current Letter2 :', letter2
########################################################################################
# for letter3 in 'geeksforgeeks':
# pass
# print 'Last Letter :', letter3
########################################################################################
# for i in 'geeksforgeeks':
# print i,
#
# print ("\r")
# print "anildileep\rdileep"
# #dileepleep
# print "anildileep\fdileep"
# #anildileep
# # dileep
# print (' ' is '')
# print (' ' is ' ')
# print ('ab' is ' ')
# print ({} is {})
########################################################################################
# a = 10
# def read():
# print (a)
# def mod1():
# global a
# a = 5
# def mod2():
# a = 15
# read()
# mod1()
# read()
# mod2()
# read()
########################################################################################
# def simpleGeneratorFun():
# yield 1
# yield 2
# yield 3
# # Driver code to check above generator function
# for value in simpleGeneratorFun():
# print(value)
#
# def nextSquare():
# i = 1
# while True:
# yield i * i
# i += 1 # Next execution resumes
# # from this point
# for num in nextSquare():
# if num > 100:
# break
# print(num)
########################################################################################
# # Create a new dictionary
# d = dict() # or d = {}
# d['xyz'] = 123
# d['abc'] = 345
# print d
# print d.keys()
# print d.values()
# for i in d:
# print "%s %s" % (i, d[i])
# for index, value in enumerate(d):
# print index, value, d[value]
# print 'xyz' in d
# del d['xyz']
# print "xyz" in d
# print d
########################################################################################
# def cube(x):
# return x**2
# print "MAP EXAMPLES"
# cubes = map(cube, range(10))
# print cubes
# print "LAMBDA EXAMPLES"
# print (lambda x: x**2,5)
# print (lambda x: x**2)(5)
# print (lambda x, y: x * y)(3, 4)
# print "FILTER EXAMPLE"
# special_cubes = filter(lambda x: x > 9 and x < 60, cubes)
# print special_cubes
# x = [2, 3, 4, 5, 6]
# y = []
# for v in x:
# print v%2
# if v % 2:
# y += [v * 5]
# print y
# x = [2, 3, 4, 5, 6]
# y = map(lambda v: v * 5, filter(lambda u: u % 2, x))
# print y
########################################################################################
# try,except and else
# def AbyB(a , b):
# try:
# c = ((a+b) / (a-b))
# except ZeroDivisionError:
# print "a/b result in 0"
# else:
# print c
# AbyB(2.0, 3.0)
# AbyB(3.0, 3.0)
########################################################################################
# try:
# print "try"
# raise NameError("Hi there") # Raise Error
# except NameError:
# print "Except"
# print "An exception"
# raise
########################################################################################
# # A Python program to to return multiple
# # values from a method using class
# class Test:
# def __init__(self):
# self.str = "geeksforgeeks"
# self.x = 20
# # This function returns an object of Test
# def fun():
# return Test()
# # Driver code to test above method
# t = fun()
# print(t.str)
# print(t.x)
#
#
# # A Python program to to return multiple
# # values from a method using tuple
# # This function returns a tuple
# def fun():
# str = "geeksforgeeks"
# x = 20
# return str, x; # Return tuple, we could also
# # write (str, x)
# # Driver code to test above method
# str, x = fun() # Assign returned tuple
# print(str)
# print(x)
#
#
# # A Python program to to return multiple
# # values from a method using list
# # This function returns a list
# def fun():
# str = "geeksforgeeks"
# x = 20
# return [str, x];
# # Driver code to test above method
# list = fun()
# print(list)
#
#
# # A Python program to to return multiple
# # values from a method using dictionary
# # This function returns a dictionary
# def fun():
# d = dict();
# d['str'] = "GeeksforGeeks"
# d['x'] = 20
# return d
# # Driver code to test above method
# d = fun()
# print(d)
########################################################################################
# Print The File Path Of Imported Modules.
# import os
# import socket
#
# print(os)
# print(socket)
########################################################################################
# Checking if two words are anagrams
# from collections import Counter
# def is_anagram(str1, str2):
# return Counter(str1) == Counter(str2)
#
# print(is_anagram('geek', 'eegk'))
# print(is_anagram('geek', 'peek'))
########################################################################################
# a = [[1, 2], [3, 4], [5, 6]]
# # Convert it to a single list without using any loops.
# # Output:- [1, 2, 3, 4, 5, 6]
#
# import itertools
# list(itertools.chain.from_iterable(a))
# # [1, 2, 3, 4, 5, 6]
########################################################################################
# # Python code to demonstrate the use of 'sys' module
# # for command line arguments
# import sys
# # command line arguments are stored in the form
# # of list in sys.argv
# argumentList = sys.argv
# print argumentList
# # Print the name of file
# print sys.argv[0]
# # Print the first argument after the name of file
# print sys.argv[1]
########################################################################################
# import sys
# from math import factorial
#
# print factorial(int(sys.argv[1]))
# print factorial(5)
########################################################################################
# Variable Arguments args(*) and kwargs(**) Both ‘args’ and ‘kwargs’ are used to get arbitrary number of arguments in a function.
# args will give us all the function parameters in the form of a list and kwargs will give us all the keyword arguments except for those corresponding to formal parameter as dictionary.
#
# # Python program to illustrate the use of args which
# # multiplies all the values given to the function as parameter
#
#
# def multiplyAll(*values):
# mul = 1
#
# # values(args) will be in the form of tuple
# print values
# print "Type = ", type(values)
#
# # Multiplying the all the parameters and return the result
# for i in values:
# mul = mul * i
#
# return mul
#
#
# # Driver program to test above function
#
# # Multiply two numbers using above function
# ans = multiplyAll(1, 2)
# print "The multiplication of 1 and 2 is ", ans
#
# # Multiply 5 numbers using above function
# ans = multiplyAll(3, 4, 5, 6, 7)
# print "The multiplication of 3 to 7 is ", ans
# Note that args are denoted by using a single star and kwargs are denoted by two stars before the formal parameters in the function.
# Program to illustrate the use of kwargs in Python
# # Function that print the details of a student
# # The number of details per student may vary
# def printDetails(**details):
# # Variable 'details' contains the details in the
# # form of dictionary
# print "Parameter details contains"
# print details
# print "Type = ", type(details)
#
# # Print first name
# print "First Name = ", details['firstName']
#
# # Print the department of student
# print "Department = ", details['department']
# print "" # Extra line break
#
#
# # Driver program to test above function
#
# # Calling the function with three arguments
# printDetails(firstName="Nikhil",
# rollNumber="007",
# department="CSE")
#
# # Calling the function with two arguments
# printDetails(firstName="Abhay",
# department="ECE")
# Please note that if you are using both args and kwargs in a function then the args parameter must precede before the kwarg parameters.
# Example:
# # Function containing both args and kwargs
# def cheeseshop(kind, *arguments, **keywords):
# print "-- Do you have any", kind, "?"
# print "-- I'm sorry, we're all out of", kind
# for arg in arguments:
# print arg
# print "-" * 40
# keys = sorted(keywords.keys())
# for kw in keys:
# print kw, ":", keywords[kw]
#
#
# # Driver program to test above function
# cheeseshop("Burger", "It's very funny, sir.",
# "It's really very, VERY funny, sir.",
# shopkeeper='<NAME>',
# client="<NAME>",
# sketch="Cheese Shop Sketch")<file_sep># The rgb() method is incomplete. Complete the method so that passing in RGB decimal values will result in a hexadecimal representation being returned.
# The valid decimal values for RGB are 0 - 255. Any (r,g,b) argument values that fall out of that range should be rounded to the closest valid value.
# The following are examples of expected output values:
# rgb(255, 255, 255) # returns FFFFFF
# rgb(255, 255, 300) # returns FFFFFF
# rgb(0,0,0) # returns 000000
# rgb(148, 0, 211) # returns 9400D3
# test.assert_equals(rgb(0,0,0),"000000", "testing zero values")
# test.assert_equals(rgb(1,2,3),"010203", "testing near zero values")
# test.assert_equals(rgb(255,255,255), "FFFFFF", "testing max values")
# test.assert_equals(rgb(254,253,252), "FEFDFC", "testing near max values")
# test.assert_equals(rgb(-20,275,125), "00FF7D", "testing out of range values")
def rgb(r, g, b):
op=''
if r < 0:op+='00'
elif r>255:op+='FF'
else:op+='{0:02X}'.format(int(r))
if g < 0:op+='00'
elif g>255:op+='FF'
else:op+='{0:02X}'.format(int(g))
if b< 0:op+='00'
elif b>255:op+='FF'
else:op+='{0:02X}'.format(int(b))
return op
print rgb(-20,275,125)
def rgb(r, g, b):
round = lambda x: min(255, max(x, 0))
return ("{:02X}" * 3).format(round(r), round(g), round(b))
def limit(num):
if num < 0:
return 0
if num > 255:
return 255
return num
def rgb(r, g, b):
return "{:02X}{:02X}{:02X}".format(limit(r), limit(g), limit(b))<file_sep># A stream of data is received and needs to be reversed.
# Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:
# 11111111 00000000 00001111 10101010
# (byte1) (byte2) (byte3) (byte4)
# should become:
# 10101010 00001111 00000000 11111111
# (byte4) (byte3) (byte2) (byte1)
# The total number of bits will always be a multiple of 8.
# The data is given in an array as such:
# [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]
# data1 = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]
# data2 = [1,0,1,0,1,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]
# test.assert_equals(data_reverse(data1),data2)
# data3 = [0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,1]
# data4 = [0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0]
# test.assert_equals(data_reverse(data3),data4)
def data_reverse(data):
# print len(data)/8
n=[]
for i in range((len(data)/8),0,-1):
# print data[8*(i-1):8*(i)]
# print ''.join(data[8*(i-1):8*(i)])
# ''.join(str(data[8*(i-1):8*i]))
n.extend(data[8*(i-1):8*i])
# print [x for x in n[::-1]]
print n
# return [(data[8*(i-1):8*i] for i in range((len(data)/8),0,-1)]
print data_reverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0])
def data_reverse(data):
res = []
for i in range(len(data)-8, -1, -8):
res.extend(data[i:i+8])
return res
def data_reverse(data):
return [b for a in xrange(len(data) - 8, -1, -8) for b in data[a:a + 8]]<file_sep># Task:
# Given an array of strings, reverse them and their order in such way that their length stays the same as the length of the original inputs.
# Example:
# Input: {"I", "like", "big", "butts", "and", "I", "cannot", "lie!"}
# Output: {"!", "eilt", "onn", "acIdn", "ast", "t", "ubgibe", "kilI"}
# Test.assert_equals(
# reverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]),
# ["!", "eilt", "onn", "acIdn", "ast", "t", "ubgibe", "kilI"]
# )
# Test.assert_equals(
# reverse(["?kn", "ipnr", "utotst", "ra", "tsn", "iksr", "uo", "yer", "ofebta", "eote", "vahu", "oyodpm", "ir", "hsyn", "amwoH"]),
# ["How", "many", "shrimp", "do", "you", "have", "to", "eat", "before", "your", "skin", "starts", "to", "turn", "pink?"]
# )
def reversed(a):
rev=''.join(a)
rev=rev[::-1]
og=[]
for i in a:
og.append(len(i))
# print og
new=[]
start,end=0,0
for i in og:
start,end=end,i+end
new.append(rev[start:end])
return new
def reverse1(a):
s=reversed(''.join(a))
print s
return [''.join(next(s) for _ in w) for w in a]
def reverse(a):
s = ''.join(a)[::-1]
print s
l, x = [], 0
print l,x
for i in a:
l.append(s[x:x+len(i)])
x += len(i)
return l
print reverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"])
print reverse(["?kn", "ipnr", "utotst", "ra", "tsn", "iksr", "uo", "yer", "ofebta", "eote", "vahu", "oyodpm", "ir", "hsyn", "amwoH"])<file_sep># In this example you have to validate if a user input string is alphanumeric. The given string is not nil, so you don't have to check that.
# The string has the following conditions to be alphanumeric:
# At least one character ("" is not valid)
# Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9
# No whitespaces/underscore
# test.assert_equals(alphanumeric("hello_world"), False)
# test.assert_equals(alphanumeric("PassW0rd"), True)
# test.assert_equals(alphanumeric(" "), False)
# test.assert_equals(alphanumeric("a"), True)
import string
def alphanumeric(string):
print string.isalnum()
alphanumeric("hello_world")
alphanumeric("PassW0rd")
alphanumeric(" ")
alphanumeric("a")<file_sep>class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print current.data,
current = current.next
def insert(self, head, data):
# Complete this method
new_node = data
current = head
print "new_node :",new_node
print "current :",current
# while current.data!=None:
# while new_node!=None:
while current!=None:
current = current.next
print "current :",current
print "current.data :", current.data
print "current.next :", current.next
current.next = new_node
###########solution 1:
if head is None:
head = Node(data)
else:
curr = head
while curr.next:
curr = curr.next
curr.next = Node(data)
return head
###########solution 1 end:
###########solution 2:
# new_node = Node(data)
# if (head == None):
# head = new_node
# else:
# temp = head
# while (temp.next != None):
# temp = temp.next
# temp.next = new_node
#
# return head
###########solution 2 end:
mylist= Solution()
T=int(raw_input())
head=None
for i in range(T):
data=int(raw_input())
head=mylist.insert(head,data)
mylist.display(head);
<file_sep># # *
# # * *
# # * * *
# # * * * *
# # n=4
# # for i in range(1,n+1):
# # for j in range(1,n-i+1):
# # print " ",
# # for k in range(1,i+1):
# # print "* ",
# # print "\n"
# # for x in range(n-1,0,-1):
# # for j in range(1,n-x+1):
# # print " ",
# # for k in range(1,x+1):
# # print "* ",
# # print "\n"
# # import sys
# # print "#"*15
# # n=4
# # for i in range(1,n+1):
# # for j in range(1,n-i+1):
# # print " ",
# # # sys.stdout.write(" ")
# # for k in range(1,i+1):
# # print "* ",
# # # sys.stdout.write("* ")
# # print "\n"
# # print "#"*15
# # n=4
# # for x in range(n,0,-1):
# # for j in range(1,n-x+1):
# # print " ",
# # for k in range(1,x+1):
# # print "* ",
# # print "\n"
# # print "#"*15
# # n=4
# # for x in range(n,0,-1):
# # for j in range(1,n-x+1):
# # print " ",
# # for k in range(1,x+1):
# # print "*",
# # print "\n"
# # print "#"*15
# # n=4
# # for x in range(n,0,-1):
# # for k in range(1,x+1):
# # print "*",
# # for j in range(1,n-x+1):
# # print " ",
# # print "\n"
# # print "#"*15
# # n=4
# # for x in range(n,0,-1):
# # for k in range(1,x+1):
# # print str(x),
# # for j in range(1,n-x+1):
# # print " ",
# # print "\n"
# # print "#"*15
# # n=["a","b","c","d"]
# # for x in range(1,len(n)+1):
# # for j in range(1,len(n)-x+1):
# # print " ",
# # for k in range(1,x+1):
# # print str(n[x-1])+" ",
# # print "\n"
# # for x in range(len(n)-1,0,-1):
# # for j in range(1,len(n)-x+1):
# # print " ",
# # for k in range(1,x+1):
# # print str(n[x-1])+" ",
# # print "\n"
# # print "#"*15
# # n=["a","b","c","d"]
# # for x in range(len(n),0,-1):
# # for j in range(1,len(n)-x+1):
# # print " ",
# # for k in range(1,x+1):
# # print str(n[x-1])+" ",
# # print "\n"
# # print "#"*15
# # # n=4
# # # for x in range(1,n+1):
# # # for y in range(x):
# # # print x
# # def palindrome(N):
# # for x in range(N,0,-1):
# # for j in range(1,N+1):
# # print "#",
# # for i in range(1, N + 1):
# # print(int('1' * i)**2)
# # print '\n'
# # # palindrome(5)
# # n=9
# # for i in range(1,n+1):
# # print " "*(n-i)+str(int('1' * i)**2)
# # for i in range(n-1,0,-1):
# # print " "*(n-i)+str(int('1' * i)**2)
# # n=9
# # for i in range(1,n):
# # print ((n-i)*' '+i*'* ')
# # for j in range(n-2,0,-1):
# # print ((n-j)*' '+j*'* ')
# # n=["a","b","c","d"]
# # for x in range(len(n)):
# # print ' '.join(x for x in n[0:x+1] + n[x::-1])
# # # # for x in range(len(n),0,-1):
# # # for j in range(1,len(n)-x+1):
# # # print " ",
# # # for k in range(1,x+1):
# # # print str(n[x-1])+" ",
# # # print "\n"
# # # for i in range(1,n):
# # # print ((n-i)*' '+i*'* ')
# # n=5
# # for i in range(1,n):
# # print ((n-i)*' '+i*'* ')
# # for i in range(1,n):
# # print ((n-i)*''+i*'*')
# # for i in range(1,n):
# # print ((n-i)*' '+i*'*')
# # for i in range(0,n):
# # print (" "*i+"* "*(n-i))
# # stl=4
# # for i in range(stl):
# # print '*'*stl
# # for i in range(6):
# # for j in range(3):
# # print '*',
# # print '\n'
# # for i in range(10):
# # for j in range(i+1):
# # print j,
# # print '\n'
# # n=1
# # for i in range(0,5):
# # for j in range(0,i+1):
# # print n,
# # n=n+1
# # print '\n'
# # n=65
# # for i in range(0,7):
# # for j in range(0,i+1):
# # conv=chr(n)
# # print conv,
# # n=n+1
# # print '\n'
# # l1=[1,5,6,9,11]
# # l2=[1,5,6,9,11,15]
# # s1=len(l1)
# # s2=len(l2)
# # res=[]
# # i,j=0,0
# # while i<s1 and j<s2:
# # if l1[i] < l2[j]:
# # res.append(l1[i])
# # i+=1
# # else:
# # res.append(l2[j])
# # j+=1
# # res=res+l1[i:]+l2[j:]
# # print res
# # x = [1,2,3,4]
# # f = [1,11,22,33,44,3,4]
# # res = list(set(x+f))
# # print(res)
# # l1 = [1,2,3,4]
# # l2 = [1,11,22,33,44,3,4]
# # res = []
# # i,j=0,0
# # while i<len(l1) and j<len(l2):
# # if l1[i] in res:
# # i+=1
# # else:
# # res.append(l1[i])
# # # i+=1
# # if l2[j] in res:
# # j+=1
# # else:
# # res.append(l2[j])
# # # j+=1
# # print res
# # n = 3
# # list_1 = [1, 2, 3, 4, 5, 6]
# # list_1 = (list_1[len(list_1) - n:len(list_1)] + list_1[0:len(list_1) - n])
# # print(list_1)
# # n = 4
# # list_1 = [1, 2, 3, 4, 5, 6, 1, 7]
# # list_2 = [5, 6, 1, 7, 1, 2, 3, 4]
# # list_1 = (list_1[-n:] + list_1[:-n])
# # print list_1
# # print list_2.index(1)
# # n=-(2+1)
# # list3 = (list_2[-n:] + list_2[:-n])
# # print list3
# # print list3 == list_1
# # print list3.pop(1)
# # print list3.remove(1)
# l=[1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0]
# print len(l)
# count0=len(l)-l.index(0)
# print "count0 :",count0
# l=[1,2,3,4,5,6,7]
# print l[-3]
# dic={}
# l=[1,2,3,4,5,6,7,8,9,11,12,13,45,46,123,8,21,3,5,31,2,5,321,41,1,5,2,6,4,123]
# for x in l:
# if x not in dic:
# dic[x]=1
# else:
# dic[x]+=1
# print "dic :",dic
# def myFun(*args, **kwargs):
# for arg in args:
# print arg
# for key, value in kwargs.items():
# print ("%s == %s" %(key, value))
# # Driver code
# myFun("Hi", first ='Geeks', mid ='for', last='Geeks')
# class A:
# def names(self, n = 'Rahul'):
# self.name = n
# return self.name
# class B(A):
# def __init__(self, roll):
# self.roll = roll
# object = B(23)
# print object.roll
# print object.names()
import copy
# initializing list 1
li1 = [1, 2,[3,5], 4]
print id(li1)
# using deepcopy to deep copy
li2 = copy.deepcopy(li1)
# original elements of list
print ("The original elements before deep copying")
for i in range(0,len(li1)):
print "li1[%s] :"%i,li1[i]#,end=" ")
print("\r")
# adding and element to new list
li2[2][0] = 7
print "li2 :",li2,li1,id(li1),id(li2)
# Change is reflected in l2
print ("The new list of elements after deep copying ")
for i in range(0,len( li1)):
print "li2[%s] :"%i,li2[i]#,end=" ")
print("\r")
print ("The original elements after deep copying")
for i in range(0,len( li1)):
print "li1[%s] :"%i,li1[i]#,end=" ")
print("\r")
li3 = copy.copy(li1)
li3[2][0] = 9
print "li3 :",li3,li1,id(li1),id(li3)
# Change is reflected in l2
print ("The new list of elements after copying ")
for i in range(0,len( li1)):
print "li3[%s] :"%i,li3[i]#,end=" ")
print("\r")
# Change is NOT reflected in original list
# as it is a deep copy
print ("The original elements after copying")
for i in range(0,len( li1)):
print "li1[%s] :"%i,li1[i]#,end=" ") <file_sep>t=int(raw_input("Lectures"))
for i in range(t):
n=raw_input("Students/Cancel").split(" ")
a=raw_input("Time").split(" ")
count = 0
for j in range(int(n[0])):
if int(a[j])<=0:
count+=1
if count>=int(n[1]):
print "YES"
else:
print "NO"
# print('5')
# print('4 3')
# print('-1 -3 4 2')
# print('5 2')
# print('0 -1 2 1 4')
# print('4 3')
# print('-1 -3 4 2')
# print('5 2')
# print('0 -1 2 1 4')
# print('4 3')
# print('-1 -3 4 0')<file_sep>n=int(raw_input("Enter no.of enteries : "))
phoneBook={}
for i in range(n):
# raw_input("Enter name and phone number with a spcae between them:")
a=raw_input("Enter name and phone number with a spcae between them:").split(' ')
phoneBook[a[0]]=a[1]
print a
print a[0]
# print phoneBook
query=raw_input()
print phoneBook.get(query)
if query in phoneBook.keys():
print query+"="+phoneBook.get(query)
else:
print "Not Found"<file_sep>import sys
if __name__ == "__main__":
meal_cost = float(raw_input().strip())
tip_percent = int(raw_input().strip())
tax_percent = int(raw_input().strip())
total = int(round(meal_cost + ((meal_cost * tip_percent) / 100) + ((meal_cost * tax_percent) / 100)))
# total=int(round(total))
print (total)<file_sep># Find the 2nd largest integer in array If the array has no 2nd largest integer then return nil.
# Reject all non integers elements and then find the 2nd largest integer in array
# find_2nd_largest([1,2,3]) => 2
# find_2nd_largest([1,1,1,1,1]) => nil because all elements are same. Largest no. is 1. and there is no 2nd largest no.
# find_2nd_largest([1,'a','2',3,3,4,5,'b']) => 4 as after rejecting non integers array will be [1,3,3,4,5]
# Largest no. is 5. and 2nd largest is 4.
# Return nil if there is no 2nd largest integer. Take care of big numbers as well
# test.describe("Example Tests")
# test.assert_equals(find_2nd_largest([1,2,3]), 2)
# test.assert_equals(find_2nd_largest([1,1,1,1,1,1,1]), None)
# test.assert_equals(find_2nd_largest([1,'a','2',3,3,4,5,'b']),4)
# test.assert_equals(find_2nd_largest([1,'a','2',3,3,3333333333333333333334,
# 544444444444444444444444444444,'b']),3333333333333333333334)
def find_2nd_largest(arr):
# arr=list(set(arr))
if len(set(arr))==1:
return None
else:
arr1=[x for x in arr if not type(x)==str ]
l=arr1[0]
l2=None
print l,l2,arr,arr1
for x in arr1[1:]:
print "x,l,l2 :",x,l,l2
# print x
if long(x)>long(l):#: and type(x)!=str :
l2=l
l=long(x)
elif l2 == None or long(l2)<long(x):
l2=long(x)
return l,l2
# print find_2nd_largest([1,2,3])
# print find_2nd_largest([1,1,1,1,1,1,1])
# print find_2nd_largest([1,'a','2',3,3,4,5,'b','b'])
# print find_2nd_largest([1,'a','2',3,3,3333333333333333333334,544444444444444444444444444444,'b'])
print find_2nd_largest(['k', 'A', 14844, 'T', 75663, 93592, 2254, 'j', 'f', 15919, 99054, '1', 'A', 91192, 76485, 'n', 'W', 84194, 'r', 53906])
print find_2nd_largest(['W', 99633, 19141, 91590, 'r', 43539, 33036, 'O', 86486, 'O', 'C', '5', 27723, 83160, 30571, 'I', 'Q', 'C', 'I', 53004])
# a=[1,'a','2',3,3,3333333333333333333334,544444444444444444444444444444,'b']
# for x in a:
# print type(x)
print long(99633)<long(91590)
# print long(3333333333333333333334)
# print long(4)
def find_2nd_largest(arr):
arr = sorted(i for i in set(arr) if type(i) != str)
return arr[-2] if len(arr) > 1 else None
print find_2nd_largest([1,'a','2',3,3,3333333333333333333334,544444444444444444444444444444,'b'])
print find_2nd_largest(['W', 99633, 19141, 91590, 'r', 43539, 33036, 'O', 86486, 'O', 'C', '5', 27723, 83160, 30571, 'I', 'Q', 'C', 'I', 53004])
<file_sep># Notes Count
# def countCurrency(amount):
# notes = [2000, 500, 200, 100, 50, 20, 10, 5]
# notes_dict={2000:0, 500:0, 200:0, 100:0, 50:0, 20:0, 10:0, 5:0, 1:0}
# for i in notes:
# if amount >=i:
# j=amount // i
# amount = amount - (j * i)
# print i,amount
# notes_dict[i]=j
# print "%s can't be divided further"%amount
# print notes_dict
# amount = 868
# countCurrency(amount)
# Factorial
# def fac(n):
# result=1
# for i in range(n,0,-1):
# result=result*i
# print result
# # fac(1)
# fac(5)
# Fibonacci:
# def fib(n):
# a,b=0,1
# for i in range(n):
# a,b=b,b+a
# print a
# fib(10)
# Fibonacci using generators:
# def fib(n):
# a,b=0,1
# for i in range(n):
# a,b=b,b+a
# yield "{}:{}".format(i+1,a)
# for item in fib(10):
# print item
# Palindrome:
# def pal(s):
# st=str(s)
# rev_st=st[::-1]
# if st==rev_st:
# print "Palindrome"
# else:
# print "Not palindrome"
# pal(1)
# pal(123)
# pal(12321)
# pal("anil")
# pal("malayalam")
# Star Pattern 1:
# n=4
# for i in range(n,0,-1):
# print "*"*i
# Star Pattern 2:
# n=4
# for i in range(n,0,-1):
# print str(i)*i
# Index of element:
# a=["This","is","sequence","of",5]
# def find_index(s):
# print a.index(s)
# find_index(5)
# find_index("is")
# Reverse String:
# s="My name is Anil"
# l=s.split()
# print ' '.join(l[::-1])
# Pyg Latin:
# s="My name is Anil"
# l=s.split()
# for i in l:
# print ''.join(i[1:])+i[0]+'ay',
# First 10 prime numbers:
# n=100
# l=[]
# for num in range(n):
# if num > 1 and len(l)<10:
# for i in range(2,num):
# if (num % i) == 0:
# break
# else:
# l.append(num)
# print(num),
# Prime number > 5000:
# lower=5000
# upper=6000
# l=[]
# for num in range(lower,upper):
# if num > lower and len(l)<10:
# for i in range(2,num):
# if (num % i) == 0:
# break
# else:
# l.append(num)
# print(num),
# Pattern :
# l=[1,2,3,4,5]
# # print l
# for i in range(len(l),0,-1):
# # print i,"*************"
# # for j in range(i,len(l)):
# # pass
# print ''.join(str(x) for x in l[0:i])+''.join(str(x-i) for x in l[i:len(l)])
# Palindrome Substring
# def palindromes(text):
# text = text.lower()
# results = []
# for i in range(len(text)):
# # print "i :",i,"#######"
# for j in range(0, i):
# chunk = text[j:i + 1]
# # print chunk+" : "+chunk[::-1]
# if chunk == chunk[::-1]:
# results.append(chunk)
# # print results
# return text.index(max(results, key=len)), results
# print palindromes("forgeekskeegfor")
# def pypart2(n):
# k = 2*n - 2
# for i in range(0, n):
# for j in range(0, k):
# print " " ,
# k = k - 2
# for j in range(0, i+1):
# print("* ","")
# print("\r")
# n = 5
# pypart2(n)
# def ispangram(str):
# alphabet = "abcdefghijklmnopqrstuvwxyz"
# for char in alphabet:
# if char not in str.lower():
# return False
# return True
# # Driver code
# string = 'the quick brown fox jumps over the lazy dog'
# if(ispangram(string) == True):
# print("Yes")
# else:
# print("No")
# import string
# alphabet = set(string.ascii_lowercase)
# def ispangram(string):
# return set(string.lower()) >= alphabet
# # Driver code
# string = "The quick brown fox ;? /jmps over the lazy dog"
# if(ispangram(string) == True):
# print("Yes")
# else:
# print("No")
# import string
# alphabet = set(string.ascii_lowercase)
# def ispangram(str):
# print set(alphabet),set(str),set(alphabet) - set(str)
# return not set(alphabet) - set(str)
# # Driver code
# string = 'the quick brown fox jumps over ;the lazy dog'
# if(ispangram(string) == True):
# print("Yes")
# else:
# print("No")
# import itertools
# import string
# alphabet = set(string.ascii_lowercase)
# def ispangram(str):
# return sum(1 for i in set(str) if 96 < ord(i) <= 122) == 26
# # Driver code
# string = 'the quick brown fox jumps over the lazy dog'
# if(ispangram(string) == True):
# print("Yes")
# else:
# print("No")
# import json
# # a Python object (dict):
# x = {
# "name": "John",
# "age": 30,
# "city": "New York"
# }
# # convert into JSON:
# y = json.dumps(x)
# # the result is a JSON string:
# print(y)
# print(type(y))
# import json
# # some JSON:
# x = '{ "name":"John", "age":30, "city":"New York"}'
# # parse x:
# y = json.loads(x)
# # the result is a Python dictionary:
# print(y["age"]),type(y)
# x = {"name": "John","age": 30,"city": "New York","status":None}
# print x,type(x)
# a=[1,2,3,4,5,6,7,8,9]
# b=[3,7,9]
# c=[]
# for x in a:
# if x in b:
# pass
# else:
# c.append(x)
# print c
# # BUBBLESORT
# d=[7,2,6,4,9,1,3,10,5,8]
# # d.sort()
# print "BEFORE SORTING :",d
# n=len(d)
# for i in range(n):
# for j in range(0,n-i-1):
# if d[j]>d[j+1]:
# d[j],d[j+1]=d[j+1],d[j]
# print d
# print "AFTER SORTING :",d
# #SELECTION SORT
# d=[7,2,6,4,9,1,3,10,5,8]
# print "BEFORE SORTING :",d
# for i in range(len(d)):
# min_idx=i
# for j in range(i+1,len(d)):
# if d[min_idx]>d[j]:
# min_idx=j
# d[i],d[min_idx]=d[min_idx],d[i]
# print d
# print "AFTER SORTING :",d
# Get Key of Dictionary using Value:
mydict = {'george':16,'amber':19}
print "mydict.values()).index(16) :",list(mydict.values()).index(16)
print list(mydict.keys())
print list(mydict.keys())[list(mydict.values()).index(16)]
l=[1,2,3,4,5]
ld={}
for i in l:
<file_sep>#!/bin/python
import sys
N = int(raw_input().strip())
if N%2!=0:
print "Weird"
elif N%2==0 and N in range(2,6):
print "Not Weird"
elif N%2==0 and N in range(6,21):
print "Weird"
elif N%2==0 and N>20:
print "Not Weird"<file_sep>sum=8
l=[1,3,5,4,7,6,9,2,8]
res=[]
for i in range(len(l)):
for j in range(0,len(l)):
if l[i]+l[j]==sum:
print l[i],l[j]
break
<file_sep># import java.io.*;
# import java.util.*;
#
# interface AdvancedArithmetic{
# int divisorSum(int n);
# }
# class Calculator implements AdvancedArithmetic {
# public int divisorSum(int n) {
# int sum = n;
# for (int i = 1; i <= n/2; i++) {
# if (n % i == 0)
# sum += i;
# }
# return sum;
# }
# }
#
# class Solution {
#
# public static void main(String[] args) {
# Scanner scan = new Scanner(System.in );
# int n = scan.nextInt();
# scan.close();
#
# AdvancedArithmetic myCalculator = new Calculator();
# int sum = myCalculator.divisorSum(n);
# System.out.println("I implemented: " + myCalculator.getClass().getInterfaces()[0].getName() );
# System.out.println(sum);
# }
# }
divisible_list=[]
user_input=int(raw_input("Enter the number :"))
print "user_input :",user_input
for i in range (1,user_input+1):
# print i
if user_input%i==0:
divisible_list.append(i)
print "divisible_list :",divisible_list
print "sum(divisible_list) :", sum(divisible_list)
<file_sep>T=int(raw_input("Enter Test cases: "))
for i in range(T):
data = int(input("Print the number: "))
print "data :",data
for x in range(2,data+1):
if data==1:
print "Number is not prime"
if data%x==0 and x<data:
print "Number is not prime"
break
elif data==x:
print "prime"
break
#ACTUAL ANSWER:
# from math import sqrt
#
# T = int(input())
#
# def isPrime(n):
# for i in range(2, int(sqrt(n))+1):
# if n % i is 0:
# return False
# return True
#
# for _ in range(T):
# n = int(input())
#
# if n >= 2 and isPrime(n):
# print("Prime")
# else:
# print("Not prime")<file_sep>#!/bin/python
A=1
B=2
print A&B
t = int(raw_input().strip())
for a0 in xrange(t):
n,k = raw_input().strip().split(' ')
n,k = [int(n),int(k)]
S=set(range(1,n+1))
# for i in range(1,int(n)+1):
# S.add(i)
# print S
# print len(S)
# for i in len(S):
# while i:
and_list=[]
for i in S:
for j in range(i,len(S)+1):
if i!=j:
if i&j<k:
and_list.append(i&j)
# print "and_list :",and_list
print max(and_list)
# ONLINE ANSWER:
# #!/bin/python3
# import sys
# t = int(input().strip())
# for a0 in range(t):
# n,k = input().strip().split(' ')
# n,k = [int(n),int(k)]
# print(k-1 if ((k-1) | k) <= n else k-2)<file_sep>def array_left_rotation(a, n, k):
for i in range(k):
temp=a[0]
a=a[1:]
a.append(temp)
for i in a:
# print i
# print type(i)
# print ''.join(str(i)),
print i,
n, k = map(int, raw_input().strip().split(' '))
a = list(map(int, raw_input().strip().split(' ')))
answer = array_left_rotation(a, n, k)
# print(*answer, sep=' ')
#
# a=[1 ,2, 3]
# print a
# temp=a[0]
# a=a[1:]
# print a
# a.append(temp)
# print a
# PYTHON 2 Solution
# def array_left_rotation(a, n, k):
# return a[k:n] + a[:k]
#
# n, k = map(int, raw_input().strip().split(' '))
# a = list(map(int, raw_input().strip().split(' ')))
# answer = array_left_rotation(a, n, k)
# print ' '.join(str(i) for i in answer),
# PYTHON 3 Solution
# def array_left_rotation(a, n, k):
# return a[k:n] + a[:k]
#
# n, k = map(int, input().strip().split(' '))
# a = list(map(int, input().strip().split(' ')))
# answer = array_left_rotation(a, n, k)
# print(*answer, sep=' ')<file_sep>class Calculator():
def power(self,no1,no2):
# try:
if no1>0 and no2>0:
return no1**no2
else:
# except Exception:# as e:
raise Exception("n and p should be non - negative")
myCalculator=Calculator()
T=int(raw_input())
for i in range(T):
n,p = map(int, raw_input().split())
try:
ans=myCalculator.power(n,p)
print ans
except Exception,e:
print e
#Actual Answer:
# class Calculator:
# def power(self, n, p):
# if n < 0 or p < 0:
# raise Exception("n and p should be non-negative")
# return pow(n, p)
# class Calculator():
# def power(self,n,p):
# if n<0 or p<0:
# raise Exception("n and p should be non-negative")
# else:
# return n**p<file_sep># Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently they can be guessed due to common cultural references. You can get your passphrases stronger by different means. One is the following:
# choose a text in capital letters including or not digits and non alphabetic characters,
# shift each letter by a given number but the transformed letter must be a letter (circular shift),
# replace each digit by its complement to 9,
# keep such as non alphabetic and non digit characters,
# downcase each letter in odd position, upcase each letter in even position (the first character is in position 0),
# reverse the whole result.
# #Example:
# your text: "BORN IN 2015!", shift 1
# 1 + 2 + 3 -> "CPSO JO 7984!"
# 4 "CpSo jO 7984!"
# 5 "!4897 Oj oSpC"
# With longer passphrases it's better to have a small and easy program. Would you write it?
# test.assert_equals(play_pass("I LOVE YOU!!!", 1), "!!!vPz fWpM J")
# test.assert_equals(play_pass("MY GRANMA CAME FROM NY ON THE 23RD OF APRIL 2015", 2),
# "4897 NkTrC Hq fT67 GjV Pq aP OqTh gOcE CoPcTi aO")
strs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' #use a string like this, instead of ord()
# print strs[(strs.index(i) + shift) % 26]
def play_pass(s, n):
a=[]
for i in s:
if i.isdigit():
a.append(str(9-int(i)))
elif i.isalpha():
y=strs[(strs.index(i) + n) % 26]
print "y :",y
# a.append(chr((ord(i)+n) % 26))
a.append(y)
else:
a.append(i)
# print a
for i in range(len(a)):
# if i == 0 and a[i].isalpha():
# a[i]=a[i].upper()
# else:
# if i%2==0 and a[i].isalpha():
# a[i]=a[i].upper()
# elif i%2!=0 and a[i].isalpha():
# a[i]=a[i].lower()
# print a.index(i)
if i%2==0:a[i]=a[i].upper()
else:a[i]=a[i].lower()
return ''.join(x for x in a[::-1])
# print ord('a'),ord('A'),ord('z'),ord('Z')
print play_pass("I LOVE YOU!!!", 1)
print play_pass("MY GRANMA CAME FROM NY ON THE 23RD OF APRIL 2015", 2)
<file_sep># Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
# For example:
# persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4
# # and 4 has only one digit.
# persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
# # 1*2*6 = 12, and finally 1*2 = 2.
# persistence(4) => 0 # Because 4 is already a one-digit number.
# persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4
# # and 4 has only one digit
# persistence(999) # returns 4, because 9*9*9=729, 7*2*9=126,
# # 1*2*6=12, and finally 1*2=2
# persistence(4) # returns 0, because 4 is already a one-digit number
# Test.it("Basic tests")
# Test.assert_equals(persistence(39), 3)
# Test.assert_equals(persistence(4), 0)
# Test.assert_equals(persistence(25), 2)
# Test.assert_equals(persistence(999), 4)
global c
c=0
def persistences(m):
# global c
c=0
i=1
while m>=10:
for n in str(m):
i=i*int(n)
# i = i - 1
print c,i,n
print "*"*50
# persistences(m)
print "m,i :",m,i
# if len(str(i))!=1:
# persistence(i)
# elif len(str(i))==1:
# print "hi"
# return c
##########################################################33
def get_digits(num):
digits = []
while num:
num, digit = divmod(num, 10)
digits.append(digit)
return digits
def multiply_all(digits):
multiplier = 1
while digits:
multiplier *= digits.pop()
return multiplier
def persistence(num):
count = 0
while num >= 10:
num = multiply_all(get_digits(num))
count += 1
return count
###############################################################
import operator
def persistence(n):
i = 0
while n>=10:
n=reduce(operator.mul,[int(x) for x in str(n)],1)
i+=1
return i
#############################################################
def persistence(n):
nums = [int(x) for x in str(n)]
sist = 0
while len(nums) > 1:
newNum = reduce(lambda x, y: x * y, nums)
nums = [int(x) for x in str(newNum)]
sist = sist + 1
return sist
####################################################
def persistencey(n):
n = str(n)
count = 0
while len(n) > 1:
p = 1
for i in n:
p *= int(i)
n = str(p)
count += 1
return count
print persistence(39)
print persistence(4)
print persistence(25)
print persistencey(999)<file_sep># from abc import ABCMeta, abstractmethod
# class Book:
# __metaclass__ = ABCMeta
# def __init__(self,title,author):
# self.title=title
# self.author=author
# @abstractmethod
# def display(self):
# pass
#
# #Write MyBook class
# class MyBook(Book):
# def __init__(self,title,author,price):
# # self.title=title
# # self.author=author
# super().__init__(title, author)
# self.price=int(price)
# def display(self):
# # super(self).display()
# print "Title: %s"%self.title
# print "Author: %s"%self.author
# print "Price: %s"%self.price
#
# title=raw_input()
# author=raw_input()
# price=int(raw_input())
# new_novel=MyBook(title,author,price)
# new_novel.display()
# from abc import ABCMeta, abstractmethod
#
#
# class Book(object, metaclass=ABCMeta):
# def __init__(self, title, author):
# self.title = title
# self.author = author
#
# @abstractmethod
# def display(self): pass
#
#
# class MyBook(Book):
# def __init__(self, title, author, price):
# super().__init__(title, author)
# self.price = price
#
# def display(self):
# print("Title: " + self.title + "\nAuthor: " + self.author + "\nPrice: " + str(self.price))
#
#
# title = input()
# author = input()
# price = int(input())
# new_novel = MyBook(title, author, price)
# new_novel.display()
from abc import ABCMeta, abstractmethod
class Book():
__metaclass__ = ABCMeta
def __init__(self, title, author):
self.title = title
self.author = author
@abstractmethod
def display(self):
pass
# Write MyBook class
class MyBook(Book):
def __init__(self, title, author, price):
super(Book).__init__(title, author)
self.price = price
def display(self):
print("Title:", self.title)
print("Author:", self.author)
print("Price:", self.price)
title = raw_input()
author = raw_input()
price = int(raw_input())
new_novel = MyBook(title, author, price)
new_novel.display()
# Java code:
# import java.util. *;
# abstract class Book {
# String title;
# String author;
#
# Book(String title, String author) {
# this.title = title;
# this.author = author;
# }
#
# abstract void display();
# }
# class MyBook extends Book
# {
# int price;
# MyBook(String t , String a , int p)
# {
# super(t,a);
# this.price =p;
# }
# void display()
# {
# System.out.println("Title: "+title);
# System.out.println("Author: "+author);
# System.out.println("Price: "+price);
# }
# }
# public class Solution {
#
# public static void main(String[] args) {
# Scanner scanner = new Scanner(System.in );
# String title = scanner.nextLine();
# String author = scanner.nextLine();
# int price = scanner.nextInt();
# scanner.close();
#
# Book book = new MyBook(title, author, price);
# book.display();
# }
# }<file_sep>def countingValleys(n, s):
valley=0
count=0
# print s
# print s.index("D")
# print s.index("U")
# high = 0
# for i in s[s.index("D")::]:
# if i == "D":
# count-=1
# else:
# count+=1
# print "count :",count
for i in s:
if i == "U":
count+=1
else:
count -=1
if count == 0 and i =="U":
valley+=1
print valley
if __name__ == '__main__':
# n = int(raw_input())
# s = raw_input()
n=8
s="UDDDUDUU" #1
# s="DDUUUUDD" #1
s="DDUUDDUDUUUD" #2
result = countingValleys(n, s)
# print "result :",result
<file_sep>import sys
class Solution:
# Two instance variables: one for your stack, and one for your queue
def __init__(self):
self.stack = []
self.queue = []
# A char popCharacter() method that pops and returns the character at the top of the stack instance variable.
def popCharacter(self):
print "popCharacter"
print "self.stack :", self.stack
print "self.queue :", self.queue
return self.stack.pop()
# A void pushCharacter(char ch) method that pushes a character onto a stack.
def pushCharacter(self, char):
self.stack.append(char)
print "pushCharacter"
print "self.stack :",self.stack
print "self.queue :", self.queue
# A char dequeueCharacter() method that dequeues and returns the first character in queue the instance variable.
def dequeueCharacter(self):
print "dequeueCharacter"
char = self.queue[0]
print "char :",char
self.queue = self.queue[1:]
print "self.stack :", self.stack
print "self.queue :", self.queue
return char
# A void enqueueCharacter(char ch) method that enqueues a character in the queue instance variable.
def enqueueCharacter(self, char):
self.queue.append(char)
print "enqueueCharacter"
print "self.stack :", self.stack
print "self.queue :", self.queue
# read the string s
s = raw_input("Enter String : ")
# Create the Solution class object
obj = Solution()
l = len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
print "i :",i
obj.pushCharacter(s[i])
obj.enqueueCharacter(s[i])
isPalindrome = True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
print "l/2 :",l/2
for i in range(l / 2):
if obj.popCharacter() != obj.dequeueCharacter():
isPalindrome = False
break
# finally print whether string s is palindrome or not.
if isPalindrome:
sys.stdout.write("The word, " + s + ", is a palindrome.")
else:
sys.stdout.write("The word, " + s + ", is not a palindrome.")<file_sep># Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it,
# is to score a throw according to these rules. You will always be given an array with five six-sided dice values.
# Three 1's => 1000 points
# Three 6's => 600 points
# Three 5's => 500 points
# Three 4's => 400 points
# Three 3's => 300 points
# Three 2's => 200 points
# One 1 => 100 points
# One 5 => 50 point
# A single die can only be counted once in each roll. For example, a "5" can only count as part of a triplet
# (contributing to the 500 points) or as a single 50 points, but not both in the same roll.
# Example scoring
# Throw Score
# --------- ------------------
# 5 1 3 4 1 50 + 2 * 100 = 250
# 1 1 1 3 1 1000 + 100 = 1100
# 2 4 4 5 4 400 + 50 = 450
# # TODO: Replace examples and use TDD development by writing your own tests
# # These are some of the methods available:
# # test.expect(boolean, [optional] message)
# # test.assert_equals(actual, expected, [optional] message)
# # test.assert_not_equals(actual, expected, [optional] message)
# # You can use Test.describe and Test.it to write BDD style test groupings
# test.describe("Example Tests")
# test.it("Example Case")
# test.assert_equals( score( [2, 3, 4, 6, 2] ), 0)
# test.assert_equals( score( [4, 4, 4, 3, 3] ), 400)
# test.assert_equals( score( [2, 4, 4, 5, 4] ), 450)
from collections import Counter
def score(dice):
a=Counter(dice)
print a.keys()
print a.values()
print a.items()
for i,j in a.items():
print j/3,j%3
score([2, 3, 4, 6, 2, 2, 3, 4, 6, 2])
<file_sep>n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
print arr
arr=arr[::-1]
print arr
for n in arr:
print n,<file_sep># import java.util.*;
#
# class Printer <T> {
# //Write your code here
#
# static <E> void printArray( E[] inputArray)
# {
# for( E e : inputArray)
# {
# System.out.println(""+e);
# }
#
# }
# }
#
# public
#
#
# class Generics {
#
# public static void main(String args[]){
# Scanner scanner = new Scanner(System.in );
# int n = scanner.nextInt();
# Integer[] intArray = new Integer[n];
# for (int i = 0; i < n; i++) {
# intArray[i] = scanner.nextInt();
# }
#
# n = scanner.nextInt();
# String[] stringArray = new String[n];
# for (int i = 0; i < n; i++) {
# stringArray[i] = scanner.next();
# }
#
# Printer < Integer > intPrinter = new Printer < Integer > ();
# Printer < String > stringPrinter = new Printer < String > ();
# intPrinter.printArray( intArray );
# stringPrinter.printArray( stringArray );
# if (Printer.
#
#
# class .getDeclaredMethods().length > 1){
#
#
# System.out.println("The Printer class should only have 1 method named printArray.");
# }
# }
# }
s=raw_input("Enter input: ")
a=s.split(" ")
print a
a.sort()
print a<file_sep>def jumpingOnClouds(c):
count=0
# current=c[i]
for i in range(len(c)):
pointer=i
while pointer
print i,c[i]
if c[i]==0 and c[i+2]==0:
count+=1
pointer+=2
# if i == 0:
# print "hii"
# n = int(raw_input())
# c = map(int, raw_input().rstrip().split())
# c=[0, 0, 1, 0, 0, 1, 0] #4
c=[0, 0, 0, 0, 1, 0] #3
jumpingOnClouds(c)
<file_sep># Write a function last that accepts a list and returns the last element in the list.
# If the list is empty:
# In languages that have a built-in option or result type (like OCaml or Haskell), return an empty option
# In languages that do not have an empty option, just return None
# @test.describe('Sample Tests')
# def fixed_tests():
# @test.it('Sample Test Cases')
# def sample_tests():
# test.assert_equals( last([1,2,3]), 3, "last([1,2,3]) == 3")
# test.assert_equals( last([]), None, "last( [] ) == None")
def last(lst):
if lst==[]:
return None
return lst[::-1][0]
print last([1,2,3])<file_sep># Given an array of ones and zeroes, convert the equivalent binary value to an integer.
# Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
# Examples:
# Testing: [0, 0, 0, 1] ==> 1
# Testing: [0, 0, 1, 0] ==> 2
# Testing: [0, 1, 0, 1] ==> 5
# Testing: [1, 0, 0, 1] ==> 9
# Testing: [0, 0, 1, 0] ==> 2
# Testing: [0, 1, 1, 0] ==> 6
# Testing: [1, 1, 1, 1] ==> 15
# Testing: [1, 0, 1, 1] ==> 11
# Test.describe("One's and Zero's")
# Test.it("Example tests")
# Test.assert_equals(binary_array_to_number([0,0,0,1]), 1)
# Test.assert_equals(binary_array_to_number([0,0,1,0]), 2)
# Test.assert_equals(binary_array_to_number([1,1,1,1]), 15)
# Test.assert_equals(binary_array_to_number([0,1,1,0]), 6)
def binary_array_to_number(arr):
return int(''.join(str(x) for x in arr),2)
print binary_array_to_number([1,1,1,1])<file_sep># Some numbers have funny properties. For example:
# 89 --> 8 + 9 = 89 * 1
# 695 --> 6 + 9 + 5= 1390 = 695 * 2
# 46288 --> 4 + 6+ 2 + 8 + 8 = 2360688 = 46288 * 51
# Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
# we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n.
# In other words:
# Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
# If it is the case we will return k, if not return -1.
# Note: n and p will always be given as strictly positive integers.
# your codedig_pow(89, 1)
# dig_pow(89, 1) should return 1 since 8 + 9 = 89 = 89 * 1
# dig_pow(92, 1) should return -1 since there is no k such as 9 + 2 equals 92 * k
# dig_pow(695, 2) should return 2 since 6 + 9 + 5= 1390 = 695 * 2
# dig_pow(46288, 3) should return 51 since 4 + 6+ 2 + 8 + 8 = 2360688 = 46288 * 51
def dig_pow(n, p):
result=0
for i in str(n):
result+=int(i)**p
p+=1
# print result
if result%n==0:
return result/n
# else:
return -1
# ACTUAL
def dig_pow(n, p):
s = 0
for i,c in enumerate(str(n)):
print "i,c :",i,c
s += pow(int(c),p+i)
return s/n if s%n==0 else -1
print dig_pow(89, 1)
print dig_pow(92, 1)
print dig_pow(46288, 3)
print dig_pow(695, 2)<file_sep># Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)
# HH = hours, padded to 2 digits, range: 00 - 99
# MM = minutes, padded to 2 digits, range: 00 - 59
# SS = seconds, padded to 2 digits, range: 00 - 59
# The maximum time never exceeds 359999 (99:59:59)
# You can find some examples in the test fixtures.
# Test.assert_equals(make_readable(0), "00:00:00")
# Test.assert_equals(make_readable(5), "00:00:05")
# Test.assert_equals(make_readable(60), "00:01:00")
# Test.assert_equals(make_readable(86399), "23:59:59")
# Test.assert_equals(make_readable(359999), "99:59:59")
def make_readables(seconds):
HH=(seconds-(seconds%3600))/3600
MM=(seconds-(HH*3600))/60
SS=(seconds%60)
print "%02d:%02d:%02d"%(HH,MM,SS)
def make_readable(s):
return '{:02}:{:02}:{:02}'.format(s / 3600, s / 60 % 60, s % 60)
print make_readable(8)
print make_readable(359)
print make_readable(359998)
print 608%3600
print 359999%3600
<file_sep>#!/bin/python
def factorial(n):
result=1
while n>0:
result=result*n
n-=1
return result
if __name__ == "__main__":
n = int(raw_input().strip())
result = factorial(n)
print result<file_sep>#!/bin/python
import sys
n = int(raw_input("Enter Number : ").strip())
print "\nusing for\n"
for i in range(1,11):
op=n*i
# i+=1
print "%s x %s = %s"%(n,i,op)
print "\nusing while\n"
j=1
while 1<=j<=10:
opt = n * i
print "%s x %s = %s" % (n, j, opt)
j += 1<file_sep>#!/bin/python
import sys
n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
# Write Your Code Here
count=0
for y in range(n - 1):
for i in range(n-1):
if a[i]<a[i+1]:
pass
else:
tmp=a[i]
a[i]=a[i+1]
a[i+1]=tmp
count+=1
print "Array is sorted in %s swaps." %count
print "First Element: %s" %a[0]
print "Last Element: %s" %a[n-1]
<file_sep>import sys
def factorial(n):
xyz=1
for i in range(n):
xyz = xyz * (n - 1)
# i += 1
print "i :",i
print "xyz :",xyz
# Complete this function
if __name__ == "__main__":
n = int(raw_input().strip())
result = factorial(n)
print result<file_sep>#!/bin/python
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
dic={}
def sockMerchant(n, ar):
pairs=0
for i in ar:
if i not in dic:
dic[i]=1
else:
dic[i]+=1
print "dic :",dic
for i in dic.values():
pairs+=i//2
return pairs
if __name__ == '__main__':
n = int(raw_input("Enter no of inputs :"))
ar = map(int, raw_input("Enter the pairs :").rstrip().split())
result = sockMerchant(n, ar)
print "result :",result<file_sep># Create a function args_count, that returns the count of passed argument
# args_count(1, 2, 3) -> 3
# args_count(1, 2, 3, 10) -> 4
# test.describe("Basic tests")
# test.assert_equals(args_count(100), 1)
# test.assert_equals(args_count(100, 2, 3), 3)
# test.assert_equals(args_count(32, a1=12), 2)
# test.assert_equals(args_count(), 0)
def args_count(*args,**kwargs):
return len(kwargs)+len(args)
print args_count(32, a1=12) | 44578317fdd1dfb2572760ba46dc46f353fafdf6 | [
"Python"
] | 57 | Python | anildn14/online_coding | 6d1c6c317c5e9f8708470a419e680b00582982d8 | 80f6caaffaa6db3a8423384e792808dbd2b0f3ab |
refs/heads/master | <repo_name>jaisingh12/transport_company<file_sep>/src/com/javatpoint/DbConn.java
package com.javatpoint;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConn {
public static Connection getConnection() throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = IBM1046.daytonoh.ncr.com)(PORT = 1521)) (CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME=CLTE))) ",
"socom_custom", "castor");
return con;
}
}
<file_sep>/Db_Scripts/dbExecute.sql
set echo off verify off showmode off feedback off;
prompt
connect socom_custom/castor@testdb;
spool C:\Teamcity\TMS\DB_logs\dbExecute.log
prompt "Kill all active sessions for testdb"
DECLARE
cur_stmt VARCHAR(2000);
BEGIN
FOR sid_ser IN (SELECT sid, serial# from v$session where username= upper('testdb'))
LOOP
cur_stmt := 'ALTER SYSTEM KILL SESSION '''||sid_ser.sid||','||sid_ser.serial#||''' IMMEDIATE';
dbms_output.put_line(cur_stmt);
EXECUTE IMMEDIATE cur_stmt;
END LOOP;
END;
/
select * from tinstall;
spool off
exit;
| 128249ecc479fe1d702bfdd48d98ad235b18459d | [
"Java",
"SQL"
] | 2 | Java | jaisingh12/transport_company | d1a9fa52e19a0f58108a819edd58b2c84ae6fb7f | 8414589acc3a0b5f2cebae553f43c63a43a176bf |
refs/heads/master | <repo_name>wodis/AndroidWebSocket<file_sep>/app/src/main/java/com/openwudi/androidwebsocket/model/ImageOpt.java
package com.openwudi.androidwebsocket.model;
/**
* Created by diwu on 17/5/24.
*/
public class ImageOpt {
//灰色
private boolean gray;
public boolean isGray() {
return gray;
}
public void setGray(boolean gray) {
this.gray = gray;
}
}
| f335c883368caeeb875c2a012899f95cb34b10a4 | [
"Java"
] | 1 | Java | wodis/AndroidWebSocket | 6cec90578750ac6a8f4728c089f2ff10308c8163 | 0889f5c6c113aadcde2226fed6ba9e311c8a4319 |
refs/heads/master | <file_sep>import { Pokemon } from "./pokemon"
import { AttackOrder } from "./battle"
import {Attack} from "./attack";
const charizardAttacks = [new Attack("ThunderPunch", 75, 100),
new Attack("Scratch", 40, 100),
new Attack("Inferno", 100, 50)]
const pikachuAttacks = [new Attack("ThunderShock", 40, 100),
new Attack("Slam", 80, 75)],
new Attack("Feint", 30, 100)]
const onixAttacks = [new Attack("IronTail", 100, 75),
new Attack("Bind", 15, 85)],
new Attack("Double-Edge", 120, 100)]
let charizard = new Pokemon("Charizard", 78, 84, 100, 78, 109, 85, 100, charizardAttacks);
let pikachu = new Pokemon("Pikachu", 35, 55, 100, 40, 50, 50, 90, pikachuAttacks);
let onix = new Pokemon("Onix", 35, 45, 100, 160, 30, 45, 70, onixAttacks);
console.log('Charizard : ', charizard);
console.log('Pikachu created : ', pikachu);
console.log('Which strikes first ? :', AttackOrder.firstStriker(charizard, onix).name);
pikachu.attack(onix, pikachu.attackList[1]);
console.log('Pikachu attacks Onix');
console.log(pikachu, onix);<file_sep>import { Attack, computeDamage } from "./attack";
import { randomNum } from "./auxFuncs";
export class Pokemon {
name: string
HP: number
level: number
attackPower: number
defense: number
speedAttack: number
speedDefense: number
speed: number
attackList: Attack[]
constructor(name: string, HP: number, attackPower: number, level: number, defense: number,
speedAttack: number, speedDefense: number, speed: number, attackList: Attack[]) {
this.name = name
this.HP = HP
this.attackPower = attackPower
this.level = level
this.defense = defense
this.speedAttack = speedAttack
this.speedDefense = speedDefense
this.speed = speed
this.attackList = attackList
}
attack(targetPokemon: Pokemon, attack: Attack) {
let accuracyPokemon = randomNum(101);
if(attack.acc > accuracyPokemon)
targetPokemon.HP -= computeDamage(this, targetPokemon, attack);
}
hitsMoveOrMisses(attack: Attack): boolean {
return randomNum(99) <= attack.acc;
}
}<file_sep>import { Pokemon } from "../src/pokemon"
describe('Test src/pokemon.ts', () => {
it('should return Pikachu as the expected starting pokemon', () => {
let pikachu = new Pokemon("Pikachu", 100, 274, 400, 209, 179);
let dracaufeu = new Pokemon("Dracaufeu", 100, 360, 299, 267, 255);
expect(wichPokemonStarts(pikachu, dracaufeu)).toEqual(pikachu);
})
it('should return Dracaufeu as the expected starting pokemon', () => {
let pikachu = new Pokemon("Pikachu", 100, 274, 279, 209, 179);
let dracaufeu = new Pokemon("Dracaufeu", 100, 360, 299, 267, 255);
expect(wichPokemonStarts(pikachu, dracaufeu)).toEqual(dracaufeu);
})
it('should Dracaufeu take damage from Pikachu', () => {
let pikachu = new Pokemon("Pikachu", 100, 274, 279, 209, 179);
let dracaufeu = new Pokemon("Dracaufeu", 100, 360, 299, 267, 255);
pikachu.attack(dracaufeu);
expect(dracaufeu.health).toBe(317);
})
});<file_sep>import { Pokemon } from "./pokemon"
export class Battle {
pokemonA: Pokemon
pokemonB: Pokemon
constructor(pokemonA: Pokemon, pokemonB: Pokemon) {
this.pokemonA = pokemonA
this.pokemonB = pokemonB
}
export function firstStriker(pokemonA: Pokemon, pokemonB: Pokemon): Pokemon {
return pokemonA.speed > pokemonB.speed ? pokemonA : pokemonB;
}
}<file_sep>import { Pokemon } from "./pokemon";
export class Attack {
name: string;
power: number;
acc: number;
constructor(name: string, power: number, acc: number) {
this.name = name;
this.power = power;
this.acc = acc;
}
}
export function computeDamage(attackingPokemon: Pokemon, pokemonDefense: Pokemon, attack: Attack) {
return Math.floor(Math.floor(Math.floor(2 * attackingPokemon.level / 5 + 2)
* attackingPokemon.attackPower * attack.power / pokemonDefense.defense)
/ 50) + 2;
} | d202f88c529f4f057a0ff070b2387a33d306b346 | [
"TypeScript"
] | 5 | TypeScript | eboucher/typescript-warmup | f81639089f0d455f2603d1a5854eb95e9be90525 | 5383fbd86f9fa53800d9affb91655cb233dbe486 |
refs/heads/master | <repo_name>chippawah/RTFM<file_sep>/js/loginCtrl.js
angular.module('rtfm').controller('loginCtrl', function($scope, userService){
$scope.login = function(){
userService.loginUser($scope.user);
$scope.user = {}
}
})<file_sep>/js/userService.js
angular.module('rtfm').service('userService', function($firebaseAuth, fb, $state){
var ref = new Firebase(fb.url);
var authObj = $firebaseAuth(ref);
this.register = function(newUser){
return authObj.$createUser(newUser)
.then(function(userData){
console.log(userData);
authObj.$authWithPassword(newUser)
.then(function(authData){
$state.go('threads')
})
})
}
this.loginUser = function(userObj) {
return authObj.$authWithPassword(userObj)
.then(function(authData){
console.log('Authdata', authData)
$state.go('threads')
}).catch(function(err){
console.log("Error authenticating:", err);
})
}
this.logoutUser = function(){
return authObj.$unauth()
}
this.getUser = function(){
var authData = authObj.$getAuth()
console.log(authData)
if(authData){
console.log('User is authenticated')
} else {
console.log('No user authentication!')
}
return authData
}
authObj.$onAuth(function(authData){
if(!authData){
if($state){
$state.go('login');
}
}
})
})<file_sep>/js/threadCtrl.js
angular.module('rtfm').controller('threadCtrl', function($scope, $firebaseObject, threadData, commentData, $firebaseArray, userService, $state){
if(!userService.getUser()){
$state.go('login')
}
var thread = $firebaseObject(threadData);
thread.$bindTo($scope, 'thread');
$scope.comments = $firebaseArray(commentData)
$scope.addComment = function(){
$scope.comments.$add($scope.newComment);
$scope.newComment = {}
}
}) | 694b234143e5e4fa03bf6930501c1e20200282bc | [
"JavaScript"
] | 3 | JavaScript | chippawah/RTFM | 04a7329035264dbc7717e2ec51cb6150a0099d84 | e5fb20e523f7e290db998f5841e98ccf4eba7840 |
refs/heads/master | <file_sep><?php get_header(); ?>
<section id="portfolio" class="bg-light-gray">
<div class="container">
<div class="row">
<?php
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$big = 999999999;
$query = new WP_Query(
array(
'post_type' => 'video',
'posts_per_page' => 2,
'paged' => $paged,
)
);
if ( have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
<div class="col-md-4 col-sm-5 portfolio-item">
<?php the_content(); ?>
<div class="portfolio-caption">
<h4><?php the_title(); ?></h4>
<p class="text-muted"><i class="fa fa-tag"></i> <?php the_field( 'area_code' ); ?></p>
</div>
</div>
<?php } }
?>
</div>
</div>
</section>
<?php echo call_to_action(); ?>
<section>
<div class="container">
<div class="row">
<div class="col-md-8">
<?php
echo paginate_links(
array(
'total' => $query->max_num_pages,
'prev_text' => 'Previous',
'next_text' => 'Next',
'show_all' => true,
'type' => 'plain',
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'type' => 'list',
)
); ?>
</div>
</div>
</div>
</section>
<?php get_footer(); ?><file_sep>/*!
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
//Add nav-link class to navigation links
$('.navbar-nav').find('a').addClass('nav-link');
//Add about-qmk-p class to numbered paragraphs
$('.about-qmk').find('p').addClass('about-qmk-p');
$('.page-numbers').addClass('pagination');
$('.edit-profile').on('click', function() {
if($('#user-edit').hasClass('cancel')) {
$('.card-body').find('.user-profile').attr('readonly', 'readonly');
$('.cancel').removeClass('cancel').addClass('edit-profile').html('Edit Profile');
} else {
$('.card-body').find('.user-profile').removeAttr('readonly').focus();
$('.edit-profile').removeClass('edit-profile').addClass('cancel').html('Cancel');
}
});
// $('.cancel').on('click', function() {
// $('.card-body').find('.user-profile').attr('readonly', 'readonly');
// $('.cancel').html('Edit Profile');
// });
$('.delete-profile').on('click', function() {
location.reload();
window.location.href = 'http://localhost:3000/';
});
//Search
class Search {
//Initiate the object
constructor() {
this.addSearchHTML();
this.resultsDiv = $('#artists-search_results');
this.openForm = $('.search-input_field');
this.closeForm = $('.search-overlay__close');
this.searchOverlay = $('.search-overlay');
this.searchField = $('#search-term');
this.events();
this.typingTimer;
this.previousValue;
this.isSpinnerVisible = false;
this.isOverlayOpen = false;
}
//Events
events() {
this.openForm.on('click', this.openOverlay.bind(this));
this.closeForm.on('click', this.closeOverlay.bind(this));
this.searchField.on('keyup', this.typingLogic.bind(this));
$('.delete-profile').on('click', this.deleteProflle);
}
//Methods
deleteProflle(e) {
var thisProfile = $(e.target).parents('.modal-footer');
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader( 'X-WP-Nonce', qmkData.nonce );
},
type: "DELETE",
url: qmkData.root_url + "/wp-json/wp/v2/users/" + thisProfile.data('id') + "?reassign=0&force=true",
error: (response) => {
console.log('Not deleted');
console.log(response);
},
success: (response) => {
console.log('Deleted');
console.log(response);
}
});
}
typingLogic() {
if (this.searchField.val() != this.previousValue) {
clearTimeout(this.typingTimer);
if (this.searchField.val() ) {
if (!this.isSpinnerVisible) {
this.resultsDiv.html('<div class="spinner-loader"></div>');
this.isSpinnerVisible = true;
}
this.typingTimer = setTimeout(this.getResults.bind(this), 750);
} else {
this.resultsDiv.html('');
this.isSpinnerVisible = false;
}
}
this.previousValue = this.searchField.val();
}
getResults() {
$.getJSON( qmkData.root_url + "/wp-json/wp/v2/users?search=" + this.searchField.val(), users => {
this.resultsDiv.html(`
${users.length ? '<div class="portfolio-item">' : '<p>Sorry, we couldn\'t find any creative matching your search.</p>' }
${users.map(item =>
`<div class="col-md-4 col-sm-5 creative-search__result" id="artists-search_results">
<a href="#${item.custom_fields.nickname}" class="portfolio-link" data-toggle="modal">
<img src="${item.custom_fields.profile_image}" class="img-responsive" alt="51">
<div class="portfolio-caption mt-2">
<h4>${item.custom_fields.nickname}</h4>
<p class="text-muted"><i class="fa fa-tag"></i> ${item.custom_fields.artform}</p>
</div>
</a>
</div>`).join('')}
${users.length ? '</div>' : '' }
`);
this.isSpinnerVisible = false;
}
);
}
openOverlay() {
this.searchOverlay.addClass('search-overlay--active');
$('body').addClass('body-no-scroll');
this.searchField.val('');
setTimeout( () => this.searchField.focus(), 301);
console.log("our open method just ran");
this.isOverlayOpen = true;
}
closeOverlay() {
this.searchOverlay.removeClass('search-overlay--active');
$('body').removeClass('body-no-scroll');
console.log("our close method just ran");
this.isOverlayOpen = false;
}
addSearchHTML() {
$('body').append(`
<div class="search-overlay">
<div class="search-overlay__top mb-5">
<div class="container">
<i class="fa fa-search search-overlay__icon" aria-hidden="true"></i>
<input type="text" id="search-term" class="search-term" placeholder="Type here to search artists">
<i class="fa fa-window-close search-overlay__close" aria-hidden="true"></i>
</div>
</div>
<div class="container">
<div class="row" id="artists-search_results">
</div>
</div>
</div>
`);
}
}
var searchQuery = new Search();<file_sep><?php
if ( is_user_logged_in()) {
wp_redirect( esc_url( site_url( '/' ) ) );
}
get_header();
?>
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="card card-body bg-light md-5 login-register">
<?php
if ( have_posts() ):
while (have_posts() ):
the_post();
$email = ( ! empty( $_POST['email'] ) ) ? sanitize_email( $_POST['email'] ) : '';
$password = ( ! empty( $_POST['password'] ) ) ? sanitize_text_field( $_POST['password'] ) : '';
?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<?php echo login_user(); ?>
<div class="form-group">
<label for="email">Email <strong>*</strong></label>
<input type="email" autocomplete="email" class="form-control <?php echo (!empty($email_error)) ? 'is-invalid' : ''; ?>" name="email" value="<?php echo ( isset( $_POST['email'] ) ? $email : null ); ?>">
<span class="invalid-feedback"><?php echo $email_error; ?></span>
</div>
<div class="form-group">
<label for="password">Password <strong>*</strong></label>
<input type="password" autocomplete="password" class="form-control <?php echo (!empty($login_error)) ? 'is-invalid' : ''; ?>" name="password" value="<?php echo ( isset( $_POST['password'] ) ? $password : null ); ?>">
<span class="invalid-feedback"><?php echo $login_error; ?></span>
</div>
<div class="form-row">
<div class="col">
<input type="submit" class="btn btn-primary mb-2" name="login" value="Login" />
</div>
<div class="col">
<a href="<?php echo esc_url( site_url( 'register' ) ); ?>" class="login-link" title="Register">Don't have an account? Register</a>
</div>
</div>
<div class="form-group text-center mb-0">
<a class="login-link" href="<?php echo wp_lostpassword_url(); ?>" title="Change Password">Change Password</a>
</div>
</form>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
</div>
</div>
<?php get_footer(); ?>
<file_sep><?php
/**
* Plugin Name: QMK User Registration Form
* Description: Register new users with custom registration fields
* Version: 1.0.0
* Author: Tebu
* Author URI: https://www.creativegemini.co.za
*/
//Set custom user data
function set_user_registration_data()
{
if ( isset( $_POST['submit'] ) ) {
validating_user_input(
$_POST['username'],
$_POST['password'],
$_POST['first_name'],
$_POST['last_name'],
$_POST['biography'],
$_POST['email'],
$_POST['area_code'],
$_POST['artform']
);
//Sanitize user data
global $username, $password, $area_code, $artform, $biography, $first_name, $last_name, $email;
$username = sanitize_user( $_POST['username'] );
$password = esc_attr( $_POST['password'] );
$area_code = intval( $_POST['area_code'] );
$artform = sanitize_text_field( $_POST['artform'] );
$biography = esc_textarea( $_POST['biography'] );
$first_name = sanitize_text_field( $_POST['first_name'] );
$last_name = sanitize_text_field( $_POST['last_name'] );
$email = sanitize_email( $_POST['email'] );
/**
* Call complete_registration fumction to create the user
* only when no WP_Error is not found
*/
complete_user_registration(
$username,
$password,
$area_code,
$artform,
$biography,
$first_name,
$last_name,
$email
);
qmk_registration_form(
$username,
$password,
$area_code,
$artform,
$biography,
$first_name,
$last_name,
$email
);
}
}
function qmk_registration_form( $username, $password, $area_code, $artform, $biography, $first_name, $last_name, $email )
{
echo '
<style>
div {margin-bottom: 2px}
input {margin-bottom: 4px}
</style>';
echo '
<form action=" '. $_SERVER['REQUEST_URI'] . '" method="post">
<div class="form-row">
<div class="col">
<label for="first_name">First Name <strong>*</strong></label>
<input type="text" class="form-control" name="first_name" value="' . ( isset( $_POST['first_name'] ) ? $first_name : null ) . '">
</div>
<div class="col">
<label for="last_name">Last Name <strong>*</strong></label>
<input type="text" class="form-control" name="last_name" value="' . ( isset( $_POST['last_name'] ) ? $last_name : null ) . '">
</div>
</div>
<div class="form-group">
<label for="username">Username<strong>*</strong></label>
<input type="text" class="form-control" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '">
</div>
<div class="form-group">
<label for="password">Password <strong>*</strong></label>
<input type="password" class="form-control" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '">
</div>
<div class="form-group">
<label for="email">Email <strong>*</strong></label>
<input type="email" class="form-control" name="email" value="' . ( isset( $_POST['email'] ) ? $email : null ) . '">
</div>
<div class="form-group">
<label for="biography">Biography <strong>*</strong></label>
<textarea class="form-control" name="biography">' . ( isset( $_POST['biography'] ) ? $biography : null ) . '</textarea>
</div>
<div class="form-row form-group">
<div class="col">
<label for="areacode">Area Code <strong>*</strong></label>
<input class="form-control" type="number" name="area_code" value="' . ( isset( $_POST['area_code'] ) ? $area_code : null ) . '">
</div>
<div class="col">
<label for="artform">Artform<strong>*</strong></label></label>
<input class="form-control" type="text" name="artform" value="' . ( isset( $_POST['artform'] ) ? $artform : null ) . '">
</div>
</div>
<input type="submit" class="btn btn-primary mb-2" name="submit" value="Register" />
</form>';
}
//Validating and sanitizing user input
function validating_user_input( $username, $password, $area_code, $artform, $biography, $first_name, $last_name, $email )
{
//Counter for area code length
function countDigit($n)
{
$count = 0;
while ($n != 0)
{
$n = round($n / 10);
++$count;
}
return $count;
}
// Driver code
$n = 3452;
global $reg_errors;
$reg_errors = new WP_Error();
//Check all the fields have been field
if ( empty( $username ) || empty( $password ) || empty( $area_code ) || empty( $artform ) || empty( $biography ) || empty( $first_name ) || empty( $last_name ) || empty( $email ) ) {
$reg_errors->add( 'field', 'Make sure you fill all the form fields' );
}
//Check if username already exists
if ( username_exists( $username ) ) {
$reg_errors->add( 'user_name', 'Eish, someone is already using that username here! Try another one.' );
}
//Check if username provided is valid
if ( ! validate_username( $username ) ) {
$reg_errors->add( 'username_invalid', 'Please register a valid username' );
}
//Check if password is not less than 5 characters
if ( 5 > strlen( $password ) ) {
$reg_errors->add( 'password', 'Your password must be more than 5 characters long.' );
}
//Check if email is valid
if ( ! is_email( $email ) ) {
$reg_errors->add( 'email_invalid', 'Enter a valid email.' );
}
//Check if the email is already registered
if ( email_exists( $email ) ) {
$reg_errors->add( 'email', 'Seems like there\'s someone already registered with this email address.' );
}
//Check if area code is not less than and not more than 4 characters long
if ( trim( $_POST['area_code'] ) < countDigit($n) && trim( $_POST['area_code'] ) > countDigit($n) ) {
$Reg_errors->add( 'area_code_error', 'Your area code should be ' . countDigit($n) . ' digits long.' );
}
//Loop through the errors and show individual error
if ( is_wp_error( $reg_errors ) ) {
foreach ( $reg_errors->get_error_messages() as $error ) {
echo '<div class="alert alert-danger" role="alert">';
echo '<strong>Error: </strong>';
echo $error . '<br />';
echo '</div>';
}
}
}
//User registration
function complete_user_registration()
{
global $reg_errors, $username, $password, $area_code, $artform, $biography, $first_name, $last_name, $email;
if ( 1 > count( $reg_errors->get_error_messages() ) ) {
$userdata = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => $<PASSWORD>,
'first_name' => $first_name,
'last_name' => $last_name,
'description' => $biography,
);
$user = wp_insert_user( $userdata );
echo 'Nice, your registration is complete. Click <a href="' . esc_url( site_url() ) . '/wp_login.php">here to login</a>.';
}
}
//Register a new shortcode [qmk_register_form]
function register_qmk_shortcode()
{
ob_start();
set_user_registration_data();
return ob_get_clean();
}
add_shortcode( 'qmk_form', 'register_qmk_shortcode' );<file_sep><?php
wp_redirect( esc_url( wp_logout() ) );
wp_redirect( esc_url( site_url( '/' ) ) );
?><file_sep><?php get_header(); ?>
<div class="container">
<div class="col-md-12 col-xl-12 text-center">
<section class="terms">
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
}
}
the_content();
?>
</section>
</div> <!-- col-md-12 text-center -->
</div> <!-- container -->
<?php get_footer(); ?><file_sep><footer>
<div class="container">
<div class="row">
<div class="col-md-12">
<?php
wp_nav_menu(
array(
'theme_location' => 'footer_menu',
)
);
?>
</div>
</div>
</div>
<div class="site-info col-md-12">
<span class="site-title">
<small><?php echo bloginfo( 'name' ); ?> © <?php echo date( 'Y' ); ?></small>
</span>
</div>
</footer>
<?php wp_footer(); ?>
</body>
</html>
<file_sep><?php
/**
* Adding the theme's stylesheets and scripts
*
* @since 1.0.0
*/
function add_qmk_theme_scripts()
{
//styles and fonts
wp_enqueue_style( 'bootstrap', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', array(), '4.3.1', 'all' );
wp_enqueue_style( 'font-awesome', '//stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', array(), '4.7', 'all' );
wp_enqueue_style( 'style', get_stylesheet_uri(), array(), '1.0.0', 'all' );
//Scripts
wp_enqueue_script( 'jquery-scripts', get_template_directory_uri() . '/js/jquery.js', array(), '1.11.1', true );
wp_enqueue_script( 'bootstrap-js', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', '', '4.3.1', true );
wp_enqueue_script( 'classie', get_template_directory_uri() . '/js/classie.js', '', '3.3.6', true );
wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main.js', '', '1.0.0', true );
wp_register_script( 'profile', get_template_directory_uri() . '/js/UserProfile.js', array('jquery'), '1.0.0', true );
wp_enqueue_script( 'profile' );
wp_enqueue_script( 'animateHeader', get_template_directory_uri() . '/js/cbpAnimatedHeader.min.js', '', '1.0.0', true );
wp_localize_script( 'main', 'qmkData', array(
'root_url' => get_site_url(), 'nonce' => wp_create_nonce('wp_rest')
));
wp_enqueue_media();
}
add_action( 'wp_enqueue_scripts', 'add_qmk_theme_scripts' );
/**
* Adding features supported by this theme
*
* @since 1.0.0
*/
function add_qmk_theme_features()
{
add_theme_support( 'custom-logo' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'custom-header' );
add_theme_support( 'custom-background' );
add_theme_support( 'title-tag' );
register_nav_menus(
array(
'primary_menu' => 'Primary Menu',
'login_register_menu' => 'User Menu',
'footer_menu' => 'Footer Menu',
)
);
}
add_action( 'after_setup_theme', 'add_qmk_theme_features' );
/**
* Redirect subscriber user from admin
* to front page
*/
function redirect_subscriber_to_homepage()
{
$qmkCurrentUser = wp_get_current_user();
if ( count( $qmkCurrentUser->roles) == 1 AND $qmkCurrentUser->roles[0] == 'subscriber' ) {
wp_redirect( esc_url( site_url( '/' ) ) );
exit;
}
}
add_action( 'admin_init', 'redirect_subscriber_to_homepage' );
/**
* Remove admin bar if
* User is a subscriber
*/
function remove_admin_bar_for_subscribers()
{
if ( ! current_user_can( 'manage_options' ) ) {
show_admin_bar( false );
}
}
add_action( 'wp_loaded', 'remove_admin_bar_for_subscribers' );
function qmk_adjust_queries($query)
{
$query->set( 'posts_per_page', 2 );
}
add_action( 'pre_get_posts', 'qmk_adjust_queries' );
/**
* Change logo url on the default login page
* to point qmk home page
*/
function qmk_header_url()
{
return esc_url( site_url( '/' ) );
}
add_filter( 'login_headerurl', 'qmk_header_url' );
/**
* Load custom style to the login page
*/
function qmk_login_scripts()
{
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'login_enqueue_scripts', 'qmk_login_scripts' );
/**
* Load custom style to the login page
*/
function qmk_login_page_title()
{
return 'Register Your Profile - ' . get_bloginfo( 'name' );
}
add_filter( 'login_title', 'qmk_login_page_title' );
/**
* Change logo url on the default login page
* to point qmk home page
*/
function qmk_header_title()
{
return get_bloginfo( 'name' );
}
add_filter( 'login_headertitle', 'qmk_header_title' );
/**
* Adding customization options for QMK
* @since 1.0.0
*/
function add_qmk_customization( $wp_customize )
{
/**
* Creating a section for the footer that can be customised
*/
$wp_customize->add_section(
'call_to_action_section', array(
'title' => __( 'Call to Action', 'qmk' )
)
);
/**
* Settings for customizing the copyright
*/
$wp_customize->add_setting(
'call_to_action', array(
'default' => '',
'transport' => 'refresh',
)
);
$wp_customize->add_control(
'call_to_action_control', array(
'label' => __( 'Text', 'qmk' ),
'section' => 'call_to_action_section',
'settings' => 'call_to_action',
'type' => 'text',
)
);
/**
* Settings for customizing the copyright
*/
$wp_customize->add_setting(
'cta_btn', array(
'default' => '',
'transport' => 'refresh',
)
);
$wp_customize->add_control(
'cta_btn_control', array(
'label' => __( 'Button Text', 'qmk' ),
'section' => 'call_to_action_section',
'settings' => 'cta_btn',
'type' => 'text',
)
);
}
add_action( 'customize_register', 'add_qmk_customization' );
/**
* Call to action
*/
function call_to_action()
{
if ( ! is_user_logged_in() ) {
?>
<section class="cta-section">
<div class="container">
<div class="col-md-12 cl-xs-6 cta">
<span class="push-col-sm-12" style="font-family: Hobo Std;"><?php echo get_theme_mod('call_to_action', 'Call to action goes here'); ?><br></span>
<span class="cta-btn"><a href="<?php echo esc_url( site_url( '/register/' ) ); ?>" class="page-scroll btn btn-sm" style="position:relative; font-family: Hobo Std;"><?php echo get_theme_mod('cta_btn', 'Place text here'); ?></a></span>
</div>
</div>
</section>
<?php } }
//A new registration form
add_action( 'register_form', 'qmk_register_form' );
function qmk_register_form()
{
$validate_user = new QMK_User();
$first_name = $validate_user->validate_first_name();
$last_name = $validate_user->validate_last_name();
$username = $validate_user->validate_username();
$password = $validate_user->validate_password();
$email = $validate_user->validate_email();
$biography = $validate_user->validate_biography();
$area_code = $validate_user->validate_area_code();
$artform = $validate_user->validate_artform();
$phone_number = $validate_user->validate_phone_number();
?>
<div class="form-row form-group">
<div class="col">
<label for="first_name"><?php _e( 'First Name', 'qmk' ) ?> <strong>*</strong></label>
<input type="text" name="first_name" id="first_name" class="form-control" value="<?php echo esc_attr( $first_name ); ?>" size="25" /></label>
</div>
<div class="col">
<label for="last_name"><?php _e( 'Last Name', 'qmk' ) ?> <strong>*</strong></label>
<input type="text" name="last_name" id="last_name" class="form-control" value="<?php echo esc_attr( $last_name ); ?>" size="25" /></label>
</div>
</div>
<div class="form-group">
<label for="username">Username <strong>*</strong></label>
<input type="text" class="form-control" name="username" value="<?php echo ( isset( $_POST['username'] ) ? $username : null ); ?>">
</div>
<div class="form-group">
<label for="password">Password <strong>*</strong></label>
<input type="password" class="form-control" name="password" value="<?php echo ( isset( $_POST['password'] ) ? $password : null ); ?>">
</div>
<div class="form-group">
<label for="email">Email <strong>*</strong></label>
<input type="email" class="form-control" name="email" value="<?php echo ( isset( $_POST['email'] ) ? $email : null ); ?>">
</div>
<div class="form-group">
<label for="phone_number">Phone Number <strong>*</strong></label>
<input type="tel" class="form-control" name="phone_number" min="10" maxlength="10" value="<?php echo ( isset( $_POST['phone_number'] ) ? $phone_number : null ); ?>">
</div>
<div class="form-group">
<label for="biography">Biography <strong>*</strong></label>
<textarea class="form-control" name="biography" maxlength="140"><?php echo ( isset( $_POST['biography'] ) ? $biography : null ); ?></textarea>
</div>
<div class="form-row form-group">
<div class="col">
<label for="area_code"><?php _e( 'Area Code', 'qmk' ) ?> <strong>*</strong></label>
<input type="number" name="area_code" id="area_code" class="form-control" value="<?php echo esc_attr( $area_code ); ?>" size="25" />
</div>
<div class="col">
<label for="artform">What do you do? <strong>*</strong></label>
<input class="form-control" type="text" name="artform" value="<?php echo ( isset( $_POST['artform'] ) ? $artform : null ); ?>">
</div>
</div>
<div class="form-row">
<div class="col">
<input type="submit" class="btn btn-primary mb-2" name="submit" value="Register" />
</div>
<div class="col">
<a href="<?php echo esc_url( site_url( 'login' ) ); ?>" class="login-link" title="Login">Already registered? Login</a>
</div>
</div>
<?php
}
/**
* Perform automatic login.
*/
function login_user() {
global $login_error;
global $email_error;
if (isset($_POST['login'])) {
$login_data = array();
$login_data['user_login'] = sanitize_email($_POST['email']);
$login_data['user_password'] = esc_attr($_POST['<PASSWORD>']);
$user = wp_signon( $login_data );
if ( ! email_exists( sanitize_email($_POST['email']) ) ) {
$email_error = 'Email is incorrect';
}
if ( is_wp_error( $user ) ) {
$login_error = $user->get_error_message();
}else {
wp_clear_auth_cookie();
do_action('wp_login', $user->ID);
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID, true);
$redirect_to = esc_url( site_url( 'profile' ) );
wp_safe_redirect($redirect_to);
exit;
}
}
}
// Run before the headers and cookies are sent.
add_action( 'after_setup_theme', 'login_user' );
//Save user meta on registration.
add_action( 'user_register', 'qmk_user_register' );
function qmk_user_register( $user_id ) {
if ( ! empty( $_POST['area_code'] ) ) {
update_user_meta( $user_id, 'area_code', intval( $_POST['area_code'] ) );
}
if ( ! empty( $_POST['artform'] ) ) {
update_user_meta( $user_id, 'artform', sanitize_text_field( $_POST['artform'] ) );
}
if ( ! empty( $_POST['profile_image'] ) ) {
update_user_meta( $user_id, 'profile_image', sanitize_text_field( $_POST['profile_image'] ) );
}
}
class QMK_User{
public function validate_first_name()
{
if ( ! empty( $_POST['first_name'] ) ) {
return sanitize_text_field( $_POST['first_name'] );
} else {
return '';
}
}
public function validate_last_name()
{
if ( ! empty( $_POST['last_name'] ) ) {
return sanitize_text_field( $_POST['last_name'] );
} else {
return '';
}
}
public function validate_username()
{
if ( ! empty( $_POST['username'] ) ) {
return sanitize_text_field( $_POST['username'] );
} else {
return '';
}
}
public function validate_password()
{
if ( ! empty( $_POST['password'] ) ) {
return sanitize_text_field( $_POST['password'] );
} else {
return '';
}
}
public function validate_email()
{
if ( ! empty( $_POST['email'] ) ) {
return sanitize_email( $_POST['email'] );
} else {
return '';
}
}
public function validate_biography()
{
if ( ! empty( $_POST['biography'] ) ) {
return sanitize_textarea_field( $_POST['biography'] );
} else {
return '';
}
}
public function validate_area_code()
{
if ( ! empty( $_POST['area_code'] ) ) {
return intval( $_POST['area_code'] );
} else {
return '';
}
}
public function validate_artform()
{
if ( ! empty( $_POST['artform'] ) ) {
return sanitize_text_field( $_POST['artform'] );
} else {
return '';
}
}
public function validate_profile_image()
{
if ( ! empty( $_POST['profile_image'] ) ) {
return sanitize_text_field( $_POST['profile_image'] );
} else {
return '';
}
}
public function validate_image()
{
if ( ! empty( $_POST['image'] ) ) {
return sanitize_text_field( $_POST['image'] );
} else {
return '';
}
}
public function validate_image1()
{
if ( ! empty( $_POST['image1'] ) ) {
return sanitize_text_field( $_POST['image1'] );
} else {
return '';
}
}
public function validate_facebook()
{
if ( ! empty( $_POST['facebook'] ) ) {
return esc_url_raw( $_POST['facebook'] );
} else {
return '';
}
}
public function validate_instagram()
{
if ( ! empty( $_POST['instagram'] ) ) {
return esc_url_raw( $_POST['instagram'] );
} else {
return '';
}
}
public function validate_twitter()
{
if ( ! empty( $_POST['twitter'] ) ) {
return esc_url_raw( $_POST['twitter'] );
} else {
return '';
}
}
public function validate_youtube()
{
if ( ! empty( $_POST['youtube'] ) ) {
return esc_url_raw( $_POST['youtube'] );
} else {
return '';
}
}
public function validate_soundcloud()
{
if ( ! empty( $_POST['soundcloud'] ) ) {
return esc_url_raw( $_POST['soundcloud'] );
} else {
return '';
}
}
public function validate_website()
{
if ( ! empty( $_POST['website'] ) ) {
return esc_url_raw( $_POST['website'] );
} else {
return '';
}
}
public function validate_behance()
{
if ( ! empty( $_POST['behance'] ) ) {
return esc_url_raw( $_POST['behance'] );
} else {
return '';
}
}
public function validate_phone_number()
{
if ( ! empty( $_POST['phone_number'] ) ) {
return intval( $_POST['phone_number'] );
} else {
return '';
}
}
}
global $user_id;
function update_user()
{
$user_id = get_current_user_id();
$validate_user = new QMK_User();
$first_name = $validate_user->validate_first_name();
$last_name = $validate_user->validate_last_name();
$username = $validate_user->validate_username();
$password = $validate_user->validate_password();
$email = $validate_user->validate_email();
$biography = $validate_user->validate_biography();
$area_code = $validate_user->validate_area_code();
$artform = $validate_user->validate_artform();
$profile_image = $validate_user->validate_profile_image();
$image = $validate_user->validate_image();
$image1 = $validate_user->validate_image1();
$facebook = $validate_user->validate_facebook();
$instagram = $validate_user->validate_instagram();
$twitter = $validate_user->validate_twitter();
$youtube = $validate_user->validate_youtube();
$soundcloud = $validate_user->validate_soundcloud();
$website = $validate_user->validate_website();
$behance = $validate_user->validate_behance();
$phone_number = $validate_user->validate_phone_number();
if (isset($_POST['update'])) {
$username = $username;
$last_name = $last_name;
$first_name = $first_name;
$password = <PASSWORD>;
$email = $email;
$biography = $biography;
$area_code = $area_code;
$artform = $artform;
$profile_image = $profile_image;
$image = $image;
$image1 = $image1;
$facebook = $facebook;
$instagram = $instagram;
$twitter = $twitter;
$youtube = $youtube;
$soundcloud = $soundcloud;
$behance = $behance;
$website = $website;
$phone_number = $phone_number;
$user_id = wp_update_user(
array(
'ID' => $user_id,
'user_pass' => <PASSWORD>,
'nickname' => $username,
'first_name' => $first_name,
'last_name' => $last_name,
'description' => $biography,
'user_email' => $email,
)
);
if ( ! empty( $area_code && wp_get_current_user() ) ) {
update_user_meta( $user_id, 'area_code', intval( $_POST['area_code'] ) );
}
if ( ! empty( $artform ) ) {
update_user_meta( $user_id, 'artform', sanitize_text_field( $_POST['artform'] ) );
}
if ( ! empty( $image ) ) {
update_user_meta( $user_id, 'image', sanitize_text_field( $_POST['image'] ) );
}
if ( ! empty( $profile_image ) ) {
update_user_meta( $user_id, 'profile_image', sanitize_text_field( $_POST['profile_image'] ) );
}
if ( ! empty( $image1 ) ) {
update_user_meta( $user_id, 'image1', sanitize_text_field( $_POST['image1'] ) );
}
if ( ! empty( $phone_number ) ) {
update_user_meta( $user_id, 'phone_number', intval( $_POST['phone_number'] ) );
}
echo $phone_number;
/**
* Adding/updating user social media links
*
* Whether empty or not
*/
update_user_meta( $user_id, 'facebook', esc_url_raw( $_POST['facebook'] ) );
update_user_meta( $user_id, 'instagram', esc_url_raw( $_POST['instagram'] ) );
update_user_meta( $user_id, 'twitter', esc_url_raw( $_POST['twitter'] ) );
update_user_meta( $user_id, 'youtube', esc_url_raw( $_POST['youtube'] ) );
update_user_meta( $user_id, 'soundcloud', esc_url_raw( $_POST['soundcloud'] ) );
update_user_meta( $user_id, 'behance', esc_url_raw( $_POST['behance'] ) );
update_user_meta( $user_id, 'website', esc_url_raw( $_POST['website'] ) );
if ( is_wp_error( $user_id ) ) {
$login_error = $user_id->get_error_message();
} else {
$success = '<div class="alert alert-success" role="alert">Your profile has been updated successfully.</div>';
echo $success;
}
}
}
function show_social_icons()
{
$args = array(
'number' => 1,
'include' => get_current_user_id(),
'key' => 'ID',
array(
'meta_key' => 'instagram'
),
array(
'meta_key' => 'facebook'
),
array(
'meta_key' => 'twitter'
),
array(
'meta_key' => 'youtube'
),
array(
'meta_key' => 'soundcloud'
),
array(
'meta_key' => 'behance'
),
array(
'meta_key' => 'website'
),
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->get_results() ) ) {
foreach ( $user_query->get_results() as $user ) {
if (!empty($user->facebook)) {
echo '<li><a href="'. $user->facebook .'"><i class="fa fa-facebook"></i></a></li>';
}
if (!empty($user->instagram)) {
echo '<li><a href="'. $user->instagram .'"><i class="fa fa-instagram"></i></a></li>';
}
if (!empty($user->twitter)) {
echo '<li><a href="'. $user->twitter .'"><i class="fa fa-twitter"></i></a></li>';
}
if (!empty($user->youtube)) {
echo '<li><a href="'. $user->youtube .'"><i class="fa fa-youtube"></i></a></li>';
}
if (!empty($user->soundcloud)) {
echo '<li><a href="'. $user->soundcloud .'"><i class="fa fa-soundcloud"></i></a></li>';
}
if (!empty($user->behance)) {
echo '<li><a href="'. $user->behance .'"><i class="fa fa-behance"></i></a></li>';
}
if (!empty($user->website)) {
echo '<li><a href="'. $user->website .'"><i class="fa fa-globe"></i></a></li>';
}
}
}
}
function filter_media( $query ) {
// admins get to see everything
if ( current_user_can( 'upload_files' ) )
$query['subscriber'] = get_current_user_id();
return $query;
}
function qmk_filter_media( $query ) {
// admins get to see everything
if (!current_user_can('manage_options'))
$query['author'] = get_current_user_id();
return $query;
}
add_filter('ajax_query_attachments_args', 'qmk_filter_media');
function slug_get_user_meta_cb( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ] );
}
add_action( 'rest_api_init', 'qmk_rest_meta_fields_query');
function qmk_rest_meta_fields_query() {
register_rest_field( 'user',
'custom_fields',
array(
'get_callback' => 'slug_get_user_meta_cb',
'schema' => null,
)
);
}
add_filter( 'rest_user_query', 'prefix_remove_has_published_posts_from_wp_api_user_query', 10, 2 );
/**
* Removes `has_published_posts` from the query args so even users who have not
* published content are returned by the request.
*
* @see https://developer.wordpress.org/reference/classes/wp_user_query/
*
* @param array $prepared_args Array of arguments for WP_User_Query.
* @param WP_REST_Request $request The current request.
*
* @return array
*/
function prefix_remove_has_published_posts_from_wp_api_user_query( $prepared_args, $request ) {
unset( $prepared_args['has_published_posts'] );
return $prepared_args;
}
if ( is_user_logged_in() && isset( $_GET['delete'] ) ) {
add_action( 'init', 'remove_logged_in_user' );
}
function remove_logged_in_user() {
// Verify that the user intended to take this action.
if ( ! wp_verify_nonce( 'delete_account' ) ) {
return;
}
require_once(ABSPATH.'wp-admin/includes/user.php' );
$current_user = wp_get_current_user();
wp_delete_user( $current_user->ID );
}
<file_sep><?php get_header(); ?>
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-12 mx-auto">
<div class="card card-body bg-light md-5 login-register">
<?php
if ( have_posts() ):
while (have_posts() ):
the_post();
?>
<h2 class="mb-2"><?php the_title(); ?></h2>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<?php get_template_part( './inc/form', 'validate' ); ?>
<?php echo qmk_register_form(); ?>
</form>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
</div>
</div>
<?php get_footer(); ?>
<file_sep><?php
if ( !get_current_user_id() ) {
wp_redirect( site_url('/') );
}
get_header();
$user_id = get_current_user_id();
$args = array(
'key' => $user_id,
'value' => 'user_login',
'number' => '1',
'include' => $user_id
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->get_results() ) ) {
foreach ( $user_query->get_results() as $user ) {
$registered = $user->user_registered;
$registered_date = date('F Y', strtotime( $registered ));
//If user profile image is not empty
if ( isset( $user->profile_image ) ) {
$image = $user->profile_image;
} else {
$image = 'http://www.qmk.co.za/wp-content/uploads/2018/12/banner.jpg';
}
?>
<section class="bg--secondary space--sm">
<div class="container">
<div class="row">
<div class="col-lg-4">
<div class="card card-body boxed boxed--lg boxed--border profile-border__box">
<div class="text-block text-center">
<input type="hidden" name="profile_image" value="">
<img src="<?php echo $image; ?>" alt="<?php echo $user->nickname; ?>'s profile picture" title="<?php echo $user->nickname; ?>'s profile picture" class="artist-thumb">
<span class="card-title artist-name"><strong><?php echo $user->nickname; ?></strong></span>
<span class="badge badge-primary artform-label"><?php echo $user->artform; ?></span>
<span class="label">Kaffy since <?php echo $registered_date; ?></span>
</div>
<hr>
<div class="text-block text-center">
<ul class="list-inline social-buttons">
<?php echo show_social_icons(); ?>
</ul>
</div>
</div>
</div>
<div class="accordion col-lg-8" id="qmk-accordion">
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-link pl-0" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Profile
</button>
<button class="btn btn-link pl-0 edit-profile" id="user-edit" type="button">
Edit Profile
</button>
</h2>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#qmk-accordion">
<div class="card-body">
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<div class="form-row form-group">
<div class="col">
<label class="user-profile-title">First Name</label>
<input type="text" class="form-control user-profile" name="first_name" value="<?php echo $user->first_name; ?>" readonly>
</div>
<div class="col">
<label class="user-profile-title">Last Name</label>
<input type="text" class="form-control user-profile" name="last_name" value="<?php echo $user->last_name; ?>" readonly>
</div>
</div>
<div class="form-row form-group">
<div class="col">
<label class="user-profile-title">Username</label>
<input type="text" class="form-control user-profile" name="username" value="<?php echo $user->nickname; ?>" readonly>
</div>
<div class="col">
<label for="email" class="user-profile-title">Email</label>
<input type="email" class="form-control user-profile" name="email" value="<?php echo $user->user_email; ?>" readonly>
</div>
</div>
<div class="form-group col-md-3 pl-0">
<label for="phone_number">Phone Number</label>
<input type="tel" class="form-control user-profile" name="phone_number" min="10" max="10" value="<?php echo $user->phone_number; ?>" readonly>
</div>
<div class="form-group">
<label for="biography" class="user-profile-title">Biography</label>
<textarea class="form-control user-profile" name="biography" maxlength="140" readonly><?php echo $user->description; ?></textarea>
</div>
<div class="form-row form-group">
<div class="col">
<label for="area_code" class="user-profile-title"><?php _e( 'Area Code', 'qmk' ) ?></label>
<input type="number" name="area_code" id="area_code" class="form-control user-profile" value="<?php echo $user->area_code; ?>" size="25" readonly />
</div>
<div class="col">
<label for="artform" class="user-profile-title">Artform</label>
<input class="form-control user-profile" type="text" name="artform" value="<?php echo $user->artform; ?>" readonly>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h2 class="mb-0">
<button class="btn btn-link collapsed pl-0" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Artwork
</button>
</h2>
</div>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#qmk-accordion">
<div class="card-body">
<div class="image-holder">
<img src="<?php echo $user->profile_image; ?>" alt="<?php echo $user->nickname; ?>'s profile picture">
</div>
<div class="custom-file mb-3 mt-1">
<input type="hidden" id='profile-image' name="profile_image">
<input type="file" id="upload-button" name="image" class="custom-file-input" onChange="displayImage(this)" value="">
<label class="custom-file-label" for="customFile">Choose profile picture</label>
</div>
<div class="image-holder">
<img src="<?php echo $user->image; ?>" onClick="triggerClick()" id="">
</div>
<div class="custom-file mb-3 mt-1">
<input type="hidden" id='artwork-image' name="image">
<input type="file" id='upload-artwork' name="artwork-image" class="custom-file-input">
<label class="custom-file-label" for="customFile">Choose your first image</label>
</div>
<div class="image-holder">
<img src="<?php echo $user->image1; ?>" id="">
</div>
<div class="custom-file mt-1">
<input type="hidden" id='artwork-image1' name="image1">
<input type="file" id="upload-artwork1" name="artwork-image1" class="custom-file-input" id="customFile" value="<?php echo $user->image1; ?>">
<label class="custom-file-label" for="customFile">Choose your second image</label>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button class="btn btn-link collapsed pl-0" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Links
</button>
</h2>
</div>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#qmk-accordion">
<div class="card-body">
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">Facebook</span>
</div>
<input type="text" name="facebook" class="form-control user-profile pl-1" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Insert link starting with http" value="<?php echo $user->facebook; ?>" readonly>
</div>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">Instagram</span>
</div>
<input type="text" name="instagram" class="form-control user-profile pl-1" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Insert link starting with http" value="<?php echo $user->instagram; ?>" readonly>
</div>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">Twitter</span>
</div>
<input type="text" name="twitter" class="form-control user-profile pl-1" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Insert link starting with http" value="<?php echo $user->twitter; ?>" readonly>
</div>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">YouTube</span>
</div>
<input type="text" name="youtube" class="form-control user-profile pl-1" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Insert link starting with http" value="<?php echo $user->youtube; ?>" readonly>
</div>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">SoundCloud</span>
</div>
<input type="text" name="soundcloud" class="form-control user-profile pl-1" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Insert link starting with http" value="<?php echo $user->soundcloud; ?>" readonly>
</div>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">Behance</span>
</div>
<input type="text" name="behance" class="form-control user-profile pl-1" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Insert link starting with http" value="<?php echo $user->behance; ?>" readonly>
</div>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">Website</span>
</div>
<input type="text" name="website" class="form-control user-profile pl-1" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Insert link starting with http" value="<?php echo $user->website; ?>" readonly>
</div>
</div>
</div>
<div class="form-row form-button-group">
<div class="col">
<input type="submit" class="btn btn-primary mb-2" name="update" value="UPDATE" />
<button type="button" class="btn btn-danger float-right mb-2" data-toggle="modal" data-target="#delete-modal">Delete Profile</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<?php
}
} ?>
<!-- Modal -->
<div class="modal fade" id="delete-modal" tabindex="-1" role="dialog" aria-labelledby="delete-modalLabel" aria-hidden="true">
<div class="container">
<div class="row">
<div class="modal-dialog col-md-6" role="document">
<div class="modal-content">
<div class="modal-header alert-danger">
<h5 class="modal-title font-weight-bolder" id="delete-modalLabel">Delete Profile</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>You are about to permanently delete your profile. If you are sure you want to do this, click Delete. Otherwise click Cancel.</p>
</div>
<div class="modal-footer" data-id="<?php echo $user->ID; ?>">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" name="delete" class="btn btn-danger delete-profile">Delete</button>
</div>
</div>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
<file_sep><?php get_header(); ?>
<div class="container">
<div class="col-md-12 col-xl-12 text-center">
<section class="bg-light-gray">
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
}
}
?>
<div class="wp-search-container">
<form action="<?php echo esc_url( site_url( '/search/' ) ); ?>" method="get">
<input type="search" name="s">
<input type="submit" value="Search">
</form>
</div>
</section>
<?php echo call_to_action(); ?>
</div> <!-- col-md-12 text-center -->
</div> <!-- container -->
<?php get_footer(); ?>
<file_sep># qmk
Web development project for Question Mark Kaffy (QMK) that is built on WordPress.
<file_sep>function makeReadable() {
$('.card-body').find('.user-profile').removeAttr('readonly');
$('.edit-profile').addClass('cancel').html('Cancel');
}
<file_sep><?php
$first_name = ( ! empty( $_POST['first_name'] ) ) ? sanitize_text_field( $_POST['first_name'] ) : '';
$last_name = ( ! empty( $_POST['last_name'] ) ) ? sanitize_text_field( $_POST['last_name'] ) : '';
$username = ( ! empty( $_POST['username'] ) ) ? sanitize_text_field( $_POST['username'] ) : '';
$password = ( ! empty( $_POST['password'] ) ) ? sanitize_text_field( $_POST['password'] ) : '';
$email = ( ! empty( $_POST['email'] ) ) ? sanitize_email( $_POST['email'] ) : '';
$biography = ( ! empty( $_POST['biography'] ) ) ? sanitize_textarea_field( $_POST['biography'] ) : '';
$area_code = ( ! empty( $_POST['area_code'] ) ) ? intval( $_POST['area_code'] ) : '';
$artform = ( ! empty( $_POST['artform'] ) ) ? sanitize_text_field( $_POST['artform'] ) : '';
$phone_number = ( ! empty( $_POST['phone_number'] ) ) ? intval( $_POST['phone_number'] ) : '';
function countDigit($n)
{
$count = 0;
while ($n != 0)
{
$n = round($n / 10);
++$count;
}
return $count;
}
// Driver code
$n = 3452;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$reg_errors = new WP_Error();
if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) {
$reg_errors->add( 'first_name_error', sprintf('<strong>%s</strong>: %s',__( 'Error', 'qmk' ),__( 'You must include a first name.', 'qmk' ) ) );
}
if ( empty( $_POST['last_name'] ) || ! empty( $_POST['last_name'] ) && trim( $_POST['last_name'] ) == '' ) {
$reg_errors->add( 'last_name_error', sprintf('<strong>%s</strong>: %s',__( 'Error', 'qmk' ),__( 'You must include a last name.', 'qmk' ) ) );
}
if ( empty( $_POST['area_code'] ) || ! empty( $_POST['area_code'] ) && trim( $_POST['area_code'] ) == '' ) {
$reg_errors->add( 'area_code_error', sprintf('<strong>%s</strong>: %s',__( 'Error', 'qmk' ),__( 'You must include your area code.', 'qmk' ) ) );
}
if ( strlen( $_POST['area_code'] ) < countDigit($n) || strlen( $_POST['area_code'] ) > countDigit($n) ) {
$reg_errors->add( 'area_code_error', sprintf('<strong>%s</strong>: %s',__( 'Error', 'qmk' ),__( 'Your area code should be ' . countDigit($n) . ' digits long.', 'qmk' ) ) );
}
//Check all the fields have been field
if ( empty( $username ) || empty( $password ) || empty( $area_code ) || empty( $artform ) || empty( $biography ) || empty( $first_name ) || empty( $last_name ) || empty( $email ) ) {
$reg_errors->add( 'field', sprintf('<strong>%s</strong>: %s',__( 'Error', 'qmk' ),__( 'Make sure you fill all the form fields', 'qmk' ) ) );
}
//Check if username already exists
if ( username_exists( $username ) ) {
$reg_errors->add( 'user_name', sprintf( '<strong>%s</strong>: %s', __( 'Error', 'qmk' ),__( 'Eish, someone is already using that username here! Try another one.', 'qmk' )) );
}
//Check if username provided is valid
if ( ! validate_username( $username ) ) {
$reg_errors->add( 'username_invalid', sprintf( '<strong>%s</strong>: %s', __( 'Error', 'qmk' ), __( 'Please register a valid username', 'qmk' ) ) );
}
//Check if password is not less than 5 characters
if ( 5 > strlen( $password ) ) {
$reg_errors->add( 'password', sprintf( '<strong>%s</strong>: %s', __( 'Error', 'qmk' ), __( 'Your password must be more than 5 characters long.', 'qmk' ) ) );
}
if ( 10 > intval( $phone_number ) && 10 < intval ($phone_number) ) {
$reg_errors->add( 'phone_number', sprintf( '<strong>%s</strong>: %s', __( 'Error', 'qmk' ), __( 'Your phone number must start with a 0 and 10 numbers long.', 'qmk' ) ) );
}
//Check if email is valid
// if ( ! is_email( $email ) ) {
// $reg_errors->add( 'email_invalid', 'Enter a valid email.' );
// }
//Check if the email is already registered
if ( email_exists( $email ) ) {
$reg_errors->add( 'email', sprintf( '<strong>%s</strong>: %s', __( 'Error', 'qmk' ), __( 'Seems like there\'s someone already registered with this email address.', 'qmk' ) ) );
}
//Looping through the errors and showing individual errors
if ( is_wp_error( $reg_errors ) ) {
foreach ( $reg_errors->get_error_messages() as $error ) {
echo '<div class="alert alert-danger" role="alert">';
echo $error . '<br />';
echo '</div>';
}
}
if ( 1 > count( $reg_errors->get_error_messages() ) ) {
$userdata = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => <PASSWORD>,
'first_name' => $first_name,
'last_name' => $last_name,
'description' => $biography,
'display_name' => $username,
);
$user = wp_insert_user( $userdata );
echo '
<div class="alert alert-success" role="alert">
Your registration has been successful. Please click here to <a href="' . esc_url( site_url( 'login' ) ) . '"> login</a>.
</div>
';
exit;
}
}
<file_sep><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset=" <?php bloginfo( 'charset'); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<?php wp_head(); ?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top" <?php body_class( 'index' ); ?>>
<nav class="navbar navbar-dark navbar-expand-lg navbar-fixed-top">
<div class="container nav-container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<?php the_custom_logo(); ?>
</div>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Custom Menu -->
<?php
if ( !is_user_logged_in() ) {
wp_nav_menu(
array(
'container_id' => 'bs-example-navbar-collapse-1',
'container_class' => 'collapse navbar-collapse justify-content-end',
'menu_class' => 'nav navbar-nav navbar-right',
'theme_location' => 'login_register_menu',
)
);
} else {
wp_nav_menu(
array(
'container_id' => 'bs-example-navbar-collapse-1',
'container_class' => 'collapse navbar-collapse justify-content-end',
'menu_class' => 'nav navbar-nav navbar-right',
'theme_location' => 'Primary',
)
);
echo '<li class="menu-item logout"><a href=" ' . wp_logout_url( home_url() ) . '" class="nav-link">Logout</a></li>';
}
?>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Header -->
<header style="background-image: url(<?php header_image(); ?>);">
<div class="container">
<div class="intro-text">
<?php
while (have_posts()):
the_post();
?>
<div class="intro-lead-in"><?php the_field( 'showcase_and_discover' ); ?></div>
<div class="intro-heading"><?php bloginfo( 'description' ); ?><br>
<small><?php the_field( 'creatives_places_lifestyle' ); ?></small></div>
<?php endwhile; ?>
<div class="col-md-12">
<ul class="list-group list-group-horizontal list-inline social-buttons">
<?php
$args = array(
'role' => 'Administrator',
'meta_key' => 'facebook',
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->get_results() ) ) {
foreach ( $user_query->get_results() as $user ) {
$registered = $user->user_registered;
$registered_date = date('F Y', strtotime( $registered ));
?>
<li><a href="<?php echo $user->facebook; ?>"><i class="fa fa-facebook"></i></a>
</li>
<li><a href="<?php echo $user->instagram; ?>"><i class="fa fa-instagram"></i></a>
</li>
<li><a href="<?php echo $user->youtube; ?>"><i class="fa fa-youtube"></i></a>
</li>
<li><a href="<?php echo $user->soundcloud; ?>"><i class="fa fa-soundcloud"></i></a>
</li>
<?php }} ?>
</ul>
</div>
</div>
</div>
</header><file_sep><?php
function add_qmk_custom_post_types()
{
register_post_type(
'slider', array(
'public' => true,
'supports' => array(
'thumbnail',
'editor',
),
'labels' => array(
'name' => 'Slider',
'add_new_item' => 'Add Slide',
'edit_item' => 'Edit Slide',
'all_items' => 'All Slides',
'Singular' => 'Slide',
),
'menu_icon' => 'dashicons-images-alt2',
)
);
register_post_type(
'video', array(
'public' => true,
'supports' => array(
'editor',
'title',
),
'labels' => array(
'name' => 'videos',
'add_new_item' => 'Add video',
'edit_item' => 'Edit video',
'all_items' => 'All videos',
'Singular' => 'video',
),
'menu_icon' => 'dashicons-admin-media',
)
);
register_post_type(
'video', array(
'public' => true,
'supports' => array(
'editor',
'title',
'custom-fields',
),
'labels' => array(
'name' => 'Videos',
'add_new_item' => 'Add Video',
'edit_item' => 'Edit Video',
'all_items' => 'All Videos',
'Singular' => 'Video',
),
'menu_icon' => 'dashicons-video-alt2',
)
);
register_post_type(
'profile', array(
'show_in_rest' => true,
'public' => true,
'supports' => array(
'editor',
'title',
'custom-fields',
'thumbnail',
),
'labels' => array(
'name' => 'Profile',
'add_new_item' => 'Add Profile',
'edit_item' => 'Edit Profile',
'all_items' => 'All Profiles',
'Singular' => 'Profile',
),
'menu_icon' => 'dashicons-admin-users',
)
);
}
add_action( 'init', 'add_qmk_custom_post_types' );<file_sep><?php get_header(); ?>
<!-- Portfolio Grid Section -->
<?php $user_id = get_current_user_id(); ?>
<section class="search-section">
<div class="container">
<div class="row">
<div class="input-group mb-3 col-md-6 search-input_field">
<input type="text" class="form-control search-input_field" placeholder="Search for creatives here" aria-label="Search for artists here" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-primary" type="button" id="button-addon2">Search</button>
</div>
</div>
</div>
</div>
</section>
<section id="portfolio" class="bg-light-gray">
<div class="container">
<div class="row">
<?php
$big = 999999999;
$number = 10;
$paged = ( get_query_var( 'page' ) ) ? absint( get_query_var( 'page' ) ) : 1;
$offset = ($paged - 1) * $number;
$users = get_users();
$query = get_users('&offset='.$offset.'&number='.$number);
$total_users = count($users);
$total_query = count($query);
$total_pages = ceil($total_users / $number) + 1;
$args = array(
'value' => 'user_login',
'orderby' => 'registered',
'order' => 'DESC',
'number' => 2,
'paged' => $paged,
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->get_results() ) ) {
foreach ( $user_query->get_results() as $user ) {
$registered = $user->user_registered;
$registered_date = date('F Y', strtotime( $registered ));
//If user profile image is not empty
if ( isset( $user->profile_image ) ) {
$image = $user->profile_image;
} else {
$image = 'http://www.qmk.co.za/wp-content/uploads/2018/12/banner.jpg';
}
?>
<div class="col-md-4 col-sm-5 portfolio-item">
<a href="#<?php echo $user->nickname; ?>" class="portfolio-link" data-toggle="modal">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<p><?php echo wp_trim_words( $user->description, 20 ); ?></p>
</div>
</div>
<img src="<?php echo $image; ?>" class="img-responsive" alt="<?php echo get_post_thumbnail_id(); ?>">
</a>
<div class="portfolio-caption mt-2">
<a href="#portfolioModal1" class="portfolio-link" data-toggle="modal"><h4><?php echo $user->nickname; ?></h4></a>
<p class="text-muted"><i class="fa fa-tag"></i> <?php echo $user->artform; ?></p>
</div>
</div>
<?php }} ?>
<?php wp_reset_postdata(); ?>
</div>
</div>
</section>
<?php call_to_action(); ?>
<section>
<div class="container">
<div class="row">
<div class="col-md-7">
<?php
if ($total_users > $total_pages) {
$current_page = max(1, get_query_var('page'));
echo paginate_links(array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => 'page/%#%/',
'current' => $current_page,
'total' => $total_pages,
'prev_next' => false,
'type' => 'list',
));
} else {
echo 'No creatives found.';
}
?>
</div>
</div>
</div>
</section>
<section>
<div class="container">
<?php echo paginate_links(); ?>
</div>
</section>
<?php get_footer(); ?>
<!-- Modal -->
<?php
$args = array(
'value' => 'user_login',
'orderby' => 'registered',
'order' => 'DESC',
array(
'meta_key' => 'instagram'
),
array(
'meta_key' => 'facebook'
),
array(
'meta_key' => 'twitter'
),
array(
'meta_key' => 'youtube'
),
array(
'meta_key' => 'soundcloud'
),
array(
'meta_key' => 'behance'
),
array(
'meta_key' => 'website'
),
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->get_results() ) ) {
foreach ( $user_query->get_results() as $user ) {
$registered = $user->user_registered;
$registered_date = date('F Y', strtotime( $registered ));
//If user profile image is not empty
if ( isset( $user->profile_image ) ) {
$image = $user->profile_image;
} else {
$image = 'http://www.qmk.co.za/wp-content/uploads/2018/12/banner.jpg';
}
?>
<div class="modal fade" id="<?php echo $user->nickname; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="container">
<div class="row">
<div class="modal-dialog" role="document">
<div class="col-md-8 modal-offset">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center" id="exampleModalLabel"><?php echo $user->nickname; ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<span class="badge badge-primary artform-label artform-label-home"><?php echo $user->artform; ?></span>
<img class="img-responsive img-centered" src="<?php echo $image; ?>" alt="" class="mb-2" />
<p><?php echo $user->description; ?></p>
<p><strong>Follow <?php echo $user->nickname; ?></strong></p>
<div class="text-block text-center social">
<ul class="list-inline social-buttons">
<?php
if (!empty($user->facebook)) {
echo '<li><a href="'. $user->facebook .'"><i class="fa fa-facebook"></i></a></li>';
}
if (!empty($user->instagram)) {
echo '<li><a href="'. $user->instagram .'"><i class="fa fa-instagram"></i></a></li>';
}
if (!empty($user->twitter)) {
echo '<li><a href="'. $user->twitter .'"><i class="fa fa-twitter"></i></a></li>';
}
if (!empty($user->youtube)) {
echo '<li><a href="'. $user->youtube .'"><i class="fa fa-youtube"></i></a></li>';
}
if (!empty($user->soundcloud)) {
echo '<li><a href="'. $user->soundcloud .'"><i class="fa fa-soundcloud"></i></a></li>';
}
if (!empty($user->behance)) {
echo '<li><a href="'. $user->behance .'"><i class="fa fa-behance"></i></a></li>';
}
if (!empty($user->website)) {
echo '<li><a href="'. $user->website .'"><i class="fa fa-globe"></i></a></li>';
}
?>
</ul>
</div>
<ul class="list-inline text-cente">
<li>Since: <?php echo $registered_date; ?></li>
<li>Area code: <?php echo $user->area_code; ?></li>
</ul>
</div>
<?php
if ( $user_id != $user->ID ) { ?>
<div class="modal-footer btn-group btn-group-sm">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<?php } else {
?>
<div class="modal-footer btn-group btn-group-sm">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<a href="<?php echo esc_url( site_url( '/profile/' ) ); ?>" class="btn btn-primary">Edit Profile</a>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php }} ?><file_sep><?php get_header(); ?>
<div class="container">
<div class="col-md-12 col-xl-12 text-center">
<section class="about-qmk">
<?php while ( have_posts() ): the_post(); ?>
<h2 class="section-heading"><?php $title = get_the_title(); echo ucwords($title); ?></h2>
<?php the_content(); ?>
</section>
<section class="video-embed">
<div class="col-md-8 center-block embed-responsive embed-responsive-16by9">
<?php the_field( 'video_link' ); ?>
</div>
<?php endwhile; ?>
</section>
<div id="qmk-carousel" class="carousel slide carousel-fade" data-ride="carousel">
<ol class="carousel-indicators">
<?php
$count = 0;
$i = 0;
$slider = new WP_Query(
array(
'post_type' => 'slider',
'post_per_page' => -1,
)
);
while ( $slider->have_posts() ) {
$slider->the_post();
$count = $count + 1;
?>
<li class="" data-target="#qmk-carousel-indicators" data-slide-to="<?php echo $count; ?>"></li>
<?php } ?>
</ol>
<div class="carousel-inner col-md-8">
<?php
while ( $slider->have_posts() ) {
$slider->the_post();
?>
<div class="carousel-item <?php if ($i == 0) echo 'active'; ?>">
<img class="d-block" src="<?php the_post_thumbnail_url(); ?>" alt="<?php echo get_post_thumbnail_id(); ?>" width="720px" height="300">
</div>
<?php $i++;?>
<?php wp_reset_postdata(); ?>
<?php } ?>
</div>
<p><a class="carousel-control-prev" href="#qmk-carousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#qmk-carousel" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</p>
</div>
<div class="col-md-12 text-center soundcloud-audio">
<?php the_field( 'soundcloud_audio' ); ?>
</div>
<section id="about-qmk">
<div class="container">
<div class="row">
<?php while ( have_posts() ): the_post(); ?>
<div class="col-lg-12 text-center">
<h2 class="section-heading"><?php the_title(); ?></h2>
<p class="about-qmk-p"><?php the_field( 'heading_three' ); ?></p>
<p class="hobo-form"><?php the_field( 'services_heading' ); ?></p>
<div class="media">
<?php
$slider = new WP_Query(
array(
'post_type' => 'service',
'post_per_page' => 2,
'order' => 'ASC',
'post__in' => array(67, 70)
)
);
while ( $slider->have_posts() ) {
$slider->the_post();
?>
<div class="media-body col-12-12">
<h4 class="media-heading hobo-form"><?php the_title(); ?></h4>
<?php the_content(); ?>
</div>
<?php wp_reset_postdata(); ?>
<?php } ?>
</div>
<div class="media">
<?php
$slider = new WP_Query(
array(
'post_type' => 'service',
'post_per_page' => 2,
'order' => 'ASC',
'post__in' => array(68, 71)
)
);
while ( $slider->have_posts() ) {
$slider->the_post();
?>
<div class="media-body col-md-12">
<h4 class="media-heading hobo-form"><?php the_title(); ?></h4>
<?php the_content(); ?>
</div>
<?php wp_reset_postdata(); ?>
<?php } ?>
</div>
<div class="media">
<?php
$slider = new WP_Query(
array(
'post_type' => 'service',
'post_per_page' => 2,
'order' => 'ASC',
'post__in' => array(69, 72)
)
);
while ( $slider->have_posts() ) {
$slider->the_post();
?>
<div class="media-body col-md-12">
<h4 class="media-heading hobo-form"><b><?php the_title(); ?></b></h4>
<?php the_content(); ?>
</div>
<?php wp_reset_postdata(); ?>
<?php } ?>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
</section>
<section id="contact" class="section-quote">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<p class="hobo-form"><?php (the_field( 'request_quote' )); ?></p>
</div>
</div>
</div>
</section>
<?php echo call_to_action(); ?>
</div> <!-- col-md-12 text-center -->
</div> <!-- container -->
<?php get_footer(); ?> | b2a0d23fa250a9f6d68b73fc51b6b2d826496609 | [
"JavaScript",
"Markdown",
"PHP"
] | 18 | PHP | tebu-ho/qmk | b69f8e68412eadc3fc7b906266b5f588b3f8f5ae | 023da19a91056cdb8adb23670790c6d31c3e36d2 |
refs/heads/master | <repo_name>astoria-tech/slack-exporter<file_sep>/README.md
# Astoria Digital's Slack Exporter
A script which exports the history (including replies) of all the public and private channels a bot is in.
## Usage
1. Create a bot in your Slack workspace (with all the bot scope permissions)
1. Add the bot to any private channel you want to export (public channels will be joined automatically)
1. Run `pip install pipenv`
1. Run `pipenv install`
1. Run `SLACK_TOKEN=<PASSWORD>token pipenv run python slack_export.py`
<file_sep>/slack_export.py
#!/usr/bin/env python
import os
import json
import sys
import time
from slack_sdk import WebClient
from tqdm import tqdm
SLACK_TOKEN = os.getenv('SLACK_TOKEN')
def main():
print('ASTORIA DIGITAL SLACK EXPORTER\n')
api = WebClient(token=SLACK_TOKEN)
# Gather all the channels
channels = []
for page in api.conversations_list(types='public_channel,private_channel',
exclude_archived=True):
channels += page.data['channels']
for i, channel in enumerate(channels):
# Print which channel we're processing
print(f'> {i + 1}/{len(channels)}: {channel["name"]} ')
sys.stdout.flush()
# Try to join the channel
try:
api.conversations_join(channel=channel['id'])
except Exception:
pass
# Gather all the messages on the channel
messages = []
for page in api.conversations_history(channel=channel['id'], limit=1000):
messages += page.data['messages']
time.sleep(1)
# Go through all the messages and add any replies
total_replies = 0
for message in tqdm(messages, ncols=80):
message['replies'] = []
if 'reply_count' in message:
for page in api.conversations_replies(channel=channel['id'], ts=message['ts']):
message['replies'] += page.data['messages']
time.sleep(1)
total_replies += len(message['replies'])
# Save the output to a file
with open(f'archive/{channel["name"]}.json', 'w') as f:
json.dump(messages, f)
# Print how many messages we processed
print(f'{len(messages) + total_replies} messages gathered\n')
if __name__ == "__main__":
main()
| fbf5c1a61d33f1d91fe903f545543c0986c56e17 | [
"Markdown",
"Python"
] | 2 | Markdown | astoria-tech/slack-exporter | 9a57ac6af0f14ebb46d628c4a5c0f83496c4bab7 | 1acf53ee8b07791cf30567e457c5f75b19ca498e |
refs/heads/master | <file_sep>int P_WINDOW=128;
double P_L0=58;
double P_L1=50;
double P_L2=74;
double P_BETA=4;
<file_sep>#ifndef CONTROLLER_HH
#define CONTROLLER_HH
#include <cstdint>
#include <pthread.h>
/* Congestion controller interface */
class Controller
{
private:
bool debug_; /* Enables debugging output */
public:
/* Add member variables here */
float window_size_float;
float window_size_float_active = 0;
float window_size_float_passive = 0;
int senddelay = 500;
double est_time = 0;
double link_status = 0;
double link_throughput = 0;
/* Public interface for the congestion controller */
/* You can change these if you prefer, but will need to change
the call site as well (in sender.cc) */
/* Default constructor */
Controller( const bool debug );
/* Get current window size, in datagrams */
unsigned int window_size( void );
/* A datagram was sent */
void datagram_was_sent( const uint64_t sequence_number,
const uint64_t send_timestamp );
/* An ack was received */
void ack_received( const uint64_t sequence_number_acked,
const uint64_t send_timestamp_acked,
const uint64_t recv_timestamp_acked,
const uint64_t timestamp_ack_received );
void ack_received_delay_threshold( const uint64_t sequence_number_acked,
const uint64_t send_timestamp_acked,
const uint64_t recv_timestamp_acked,
const uint64_t timestamp_ack_received );
void ack_received_delay_threshold_varied_target( const uint64_t sequence_number_acked,
const uint64_t send_timestamp_acked,
const uint64_t recv_timestamp_acked,
const uint64_t timestamp_ack_received );
void ack_received_prediction( const uint64_t sequence_number_acked,
const uint64_t send_timestamp_acked,
const uint64_t recv_timestamp_acked,
const uint64_t timestamp_ack_received );
/* How long to wait (in milliseconds) if there are no acks
before sending one more datagram */
unsigned int timeout_ms( void );
int send_counter=0;
int recv_counter=0;
uint64_t* send_time_list=NULL;
uint64_t* recv_time_list=NULL;
double* delay_list=NULL;
};
#endif
<file_sep>#include <iostream>
#include <unistd.h>
#include <math.h>
#include <malloc.h>
#include <time.h>
#include "controller.hh"
#include "timestamp.hh"
#include "parameter.hh"
using namespace std;
/* Default constructor */
Controller::Controller( const bool debug )
: debug_( debug ), window_size_float(20.0)
{
}
/* Get current window size, in datagrams */
unsigned int Controller::window_size( void )
{
/* Default: fixed window size of 100 outstanding datagrams */
unsigned int the_window_size = 5;
if ( debug_ ) {
cerr << "At time " << timestamp_ms()
<< " window size is " << the_window_size << endl;
}
return max((unsigned int)floor(window_size_float),(unsigned int)1);
//return the_window_size;
}
/* A datagram was sent */
void Controller::datagram_was_sent( const uint64_t sequence_number,
/* of the sent datagram */
const uint64_t send_timestamp )
/* in milliseconds */
{
/* Default: take no action */
if(this->send_time_list == NULL)
{
this->send_time_list = (uint64_t*)malloc(sizeof(uint64_t)*65536*2);
this->send_counter = 0;
}
//this->send_time_list[this->send_counter ++] = send_timestamp;
this->send_time_list[this->send_counter ++] = timestamp_ms();
//printf("%lu %lud\n",sequence_number, send_timestamp);
usleep(senddelay); // sleep 500 microsecond
if ( debug_ ) {
cerr << "At time " << send_timestamp
<< " sent datagram " << sequence_number << endl;
}
}
template<typename type> double Mean(type * ptr, int n)
{
double ret = 0;
double decay = 1.0;
double decay_sum = 0;
for(int i = n-1; i>=0; i--)
{
ret = ret + ptr[i] * decay;
decay_sum+=decay;
decay *= 0.97;
}
return ret/(decay_sum);
}
double Std(double* ptr, int n)
{
double ret = 0;
double mean = Mean(ptr,n);
for(int i = 0; i<n; i++) ret = ret + (ptr[i] - mean)*(ptr[i] - mean);
return sqrt(ret/n);
}
template<typename type> double dir(type* ptr, int n)
{
double ret = 0;
type mmax = 0;
type mmin = 0;
if(n <2) return 1000;
for(int i = 0; i<n-1; i++)
{
ret = ret + ptr[i+1] - ptr[i];
if(ptr[i+1]-ptr[i] > mmax) mmax = ptr[i+1] - ptr[i];
if(ptr[i+1]-ptr[i] < mmin) mmin = ptr[i+1] - ptr[i];
}
return (ret)/(n-1);
}
double dir_exp(double* ptr, int n)
{
double ret = 0;
double w = 1.0;
double sum = 0.0;
double p = 1.2;
for(int i = 0; i<n-1; i++)
{
ret = ret + (ptr[i+1]-ptr[i])*w;
sum = sum + w;
w = w * p;
}
return ret/sum;
}
double dir_power(double* ptr, int n)
{
double ret = 0;
double w = 1.0;
double sum = 0.0;
double p = 0.1;
for(int i = 0; i<n-1; i++)
{
ret = ret + (ptr[i+1]-ptr[i])*w;
sum = sum + w;
w = w + p;
}
return ret/sum;
}
double throughput_est(uint64_t* t, int n)
{
uint64_t delta = t[n-1] - t[0];
//TODO prediction
return n/((double)delta)*1000;
}
void Controller::ack_received_prediction( const uint64_t sequence_number_acked,
/* what sequence number was acknowledged */
const uint64_t send_timestamp_acked,
/* when the acknowledged datagram was sent (sender's clock) */
const uint64_t recv_timestamp_acked,
/* when the acknowledged datagram was received (receiver's clock)*/
const uint64_t timestamp_ack_received )
/* when the ack was received (by sender) */
{
//static uint64_t old_delay = 0;
uint64_t delay = timestamp_ack_received - send_timestamp_acked;
static double* delay_list = NULL;
static double* window_list = NULL;
static uint64_t * ack_time_stamps = NULL;
static int * time_window_count = NULL;
static int counter = 0;
if(delay_list == NULL)
{
delay_list = (double*)malloc(sizeof(double)*65536*2);
}
if(window_list == NULL)
{
window_list = (double*)malloc(sizeof(double)*65536*2);
}
if(ack_time_stamps == NULL)
{
ack_time_stamps = (uint64_t*)malloc(sizeof(uint64_t)*65536*2);
}
if(time_window_count == NULL)
{
time_window_count = (int*)malloc(sizeof(int)*65536*2);
}
#include "parameter.hh"
int window = P_WINDOW;
double w_old_avg = 0;
double w_ins = 40;
double w_target = 0;
double d_avg = 0;
double mean_pf = 0;
double mean_nf = 0;
double feedback_pos = 0;
double feedback_neg = 0;
double feedback_avg = 0;
double beta;
static uint64_t TimeWindow = 20; // ms
beta = P_BETA / 100.0;
delay_list[counter] = delay;
window_list[counter] = w_ins;
ack_time_stamps[counter] = timestamp_ack_received;
time_window_count[counter] = 0;
int cur_win = window;
int cur_win_old = 0;
if(counter>window*3)
{
cur_win = 0;
while(cur_win_old < window*2 - 1)
{
if(timestamp_ack_received - ack_time_stamps[counter - cur_win-1] < TimeWindow)
cur_win ++;
if(timestamp_ack_received - ack_time_stamps[counter - cur_win_old -1] < TimeWindow * 2)
cur_win_old ++;
else break;
}
if(cur_win > window) cur_win = window;
time_window_count[counter] = cur_win;
w_old_avg = Mean(window_list + counter - (cur_win+1)*2+1, cur_win+1); // FIXME
d_avg = Mean(delay_list + counter - cur_win, cur_win+1);
double mean_tp = P_L0;
mean_pf = min(max((mean_tp*2-d_avg)/mean_tp,0.0),2.0);
mean_nf = 1.0 + max((d_avg-mean_tp)/mean_tp,-1.0);
feedback_pos = mean_pf;
feedback_neg = mean_nf;
feedback_avg = -max(d_avg - P_L1, 0.0) * feedback_neg - min(d_avg - P_L2, 0.0) * feedback_pos;
w_target = max(w_old_avg + beta * feedback_avg , 0.0);
w_ins = w_target;
}
delay_list[counter] = delay;
window_list[counter] = w_ins;
ack_time_stamps[counter] = timestamp_ack_received;
counter ++;
if(counter < 2)
printf("L1 %.2f L2 %.2f BETA %.2f\n",P_L1, P_L2, beta);
window_size_float += min(w_ins - window_size_float,1.0);
if ( debug_ ) {
cerr << "At time " << timestamp_ack_received
<< " received ack for datagram " << sequence_number_acked
<< " (send @ time " << send_timestamp_acked
<< ", received @ time " << recv_timestamp_acked << " by receiver's clock)"
<< endl;
}
}
/* An ack was received */
void Controller::ack_received( const uint64_t sequence_number_acked,
/* what sequence number was acknowledged */
const uint64_t send_timestamp_acked,
/* when the acknowledged datagram was sent (sender's clock) */
const uint64_t recv_timestamp_acked,
/* when the acknowledged datagram was received (receiver's clock)*/
const uint64_t timestamp_ack_received )
/* when the ack was received (by sender) */
{
/* Default: take no action */
if(this->recv_time_list == NULL)
{
this->recv_time_list = (uint64_t*)malloc(sizeof(uint64_t)*65536*2);
this->recv_counter = 0;
}
if(this->delay_list == NULL)
{
this->delay_list = (double*)malloc(sizeof(double)*65536*2);
}
this->recv_time_list[this->recv_counter] = timestamp_ack_received;
this->delay_list[this->recv_counter++] = timestamp_ack_received - send_timestamp_acked;
ack_received_prediction(sequence_number_acked, send_timestamp_acked, recv_timestamp_acked, timestamp_ack_received);
//if((int64_t)timestamp_ack_received - (int64_t)send_timestamp_acked > 60)
// window_size_float *= 0.97;
//else
// window_size_float += 2.0/window_size_float;
if ( debug_ ) {
cerr << "At time " << timestamp_ack_received
<< " received ack for datagram " << sequence_number_acked
<< " (send @ time " << send_timestamp_acked
<< ", received @ time " << recv_timestamp_acked << " by receiver's clock)"
<< endl;
}
}
/* How long to wait (in milliseconds) if there are no acks
before sending one more datagram */
unsigned int Controller::timeout_ms( void )
{
//return 50; /* timeout of 0.05 second */
return 50; /* timeout of 0.05 second */
}
| a7cba8955d02b3c97ecf6fef05557ecd26f0d281 | [
"C++"
] | 3 | C++ | songtaohe/sourdough | 5bad0fb2b85a2d16965d2e04b23e6c1bf60fbff5 | 57a804a977bcd81ce11c6d682049a9b57c325445 |
refs/heads/master | <file_sep>## Stream - Find First Vowel
Sample that find the first char vowel, after a consonant, where it is predecessor to a vowel and does not repeat itself in the rest of the stream.
Using the Stream interface methods:
```
public boolean hasNext() {
return position < input.length();
}
public char getNext() {
char ret = chars[position];
position++;
return ret;
}
```
### Running
Execute the java main function on class `StreamFindFirstVowel`.
<file_sep>package com.douglastenn.stream.impl;
import com.douglastenn.stream.Stream;
public class StreamImpl implements Stream {
private String input;
private int position;
private char chars[];
public StreamImpl(String input) {
this.input = input;
this.chars = input.toCharArray();
}
@Override
public boolean hasNext() {
return position < input.length();
}
@Override
public char getNext() {
char ret = chars[position];
position++;
return ret;
}
}
<file_sep>package com.douglastenn.util;
import com.douglastenn.exception.NotFoundCharException;
import com.douglastenn.stream.impl.StreamImpl;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.core.IsEqual.equalTo;
public class StreamUtilTest {
private StreamUtil streamUtil = new StreamUtil();
@Test
public void test_firstVowel_withEndedVowel() {
StreamImpl stream = new StreamImpl("aAbBABacafe");
char c = this.streamUtil.findFirstVowel(stream);
assertThat(c, equalTo('e'));
}
@Test
public void test_firstChar_Succeed() {
StreamImpl stream = new StreamImpl("aAbBEeEyiEeooO");
char c = this.streamUtil.findFirstVowel(stream);
assertThat(c, equalTo('i'));
}
@Test(expected = NotFoundCharException.class)
public void test_firstChar_WithOnlyConsonant() {
StreamImpl stream = new StreamImpl("yyyyyyyyyyyyyyyyy");
char c = this.streamUtil.findFirstVowel(stream);
}
@Test(expected = NotFoundCharException.class)
public void test_firstChar_withEmptyString() {
StreamImpl stream = new StreamImpl("");
char c = this.streamUtil.findFirstVowel(stream);
}
} | 5a4b8edd33460bf9d97302df2013517aa9c61621 | [
"Markdown",
"Java"
] | 3 | Markdown | douglastenn-zz/stream-find-first-vowel | 3dec33f481f07e7919a873fae02150894f559202 | 47aa7f8da6af9a14a55632fc3a40427971842711 |
refs/heads/develop | <repo_name>schulz3000/msgpack.wcf<file_sep>/src/MsgPack.Wcf/MsgPackOperationBehavior.cs
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
using System.Xml;
namespace MsgPack.Wcf
{
internal class MsgPackOperationBehavior : DataContractSerializerOperationBehavior
{
/// <summary>
/// Create a new MsgPackOperationBehavior instance
/// </summary>
/// <param name="operation"></param>
public MsgPackOperationBehavior(OperationDescription operation)
: base(operation)
{
}
/// <summary>
/// Creates a MsgPack serializer
/// </summary>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="ns"></param>
/// <param name="knownTypes"></param>
public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
=> XmlMsgPackSerializer.Create(type);
}
}
<file_sep>/src/MsgPack.CoreWcf/XmlMsgPackSerializer.cs
using MsgPack.Serialization;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
namespace MsgPack.CoreWcf
{
internal class XmlMsgPackSerializer : XmlObjectSerializer
{
private readonly Type targetType;
/// <summary>
/// Attempt to create a new serializer for the given model and type
/// </summary>
/// <param name="type"></param>
/// <returns>A new serializer instance if the type is recognised by the model; null otherwise</returns>
public static XmlMsgPackSerializer Create(Type type)
=> new XmlMsgPackSerializer(type);
/// <summary>
/// Creates a new serializer for the given model and type
/// </summary>
/// <param name="type"></param>
public XmlMsgPackSerializer(Type type)
{
targetType = type ?? throw new ArgumentOutOfRangeException(nameof(type));
}
/// <summary>
/// Ends an object in the output
/// </summary>
/// <param name="writer"></param>
public override void WriteEndObject(XmlDictionaryWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
writer.WriteEndElement();
}
/// <summary>
/// Begins an object in the output
/// </summary>
/// <param name="writer"></param>
/// <param name="graph"></param>
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
writer.WriteStartElement(MSGPACK_ELEMENT);
}
private const string MSGPACK_ELEMENT = "msgpack";
private const string COMPRESS_ATTRIBUTE_NAME = "cmp";
/// <summary>
/// Writes the body of an object in the output
/// </summary>
/// <param name="writer"></param>
/// <param name="graph"></param>
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (graph == null)
{
writer.WriteAttributeString("nil", bool.TrueString);
}
else
{
using var ms = new MemoryStream();
byte[] buffer;
var serializer = MessagePackSerializer.Get(targetType);
serializer.Pack(ms, graph);
if (ms.Length > 150)
{
buffer = Compressor.Compress(ms);
writer.WriteAttributeString(COMPRESS_ATTRIBUTE_NAME, "1");
}
else
{
buffer = ms.ToArray();
}
writer.WriteBase64(buffer, 0, buffer.Length);
}
}
/// <summary>
/// Indicates whether this is the start of an object we are prepared to handle
/// </summary>
/// <param name="reader"></param>
public override bool IsStartObject(XmlDictionaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
reader.MoveToContent();
return reader.NodeType == XmlNodeType.Element
&& MSGPACK_ELEMENT.Equals(reader.Name, StringComparison.Ordinal);
}
/// <summary>
/// Reads the body of an object
/// </summary>
/// <param name="reader"></param>
/// <param name="verifyObjectName"></param>
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
var isCompressed = "1".Equals(reader.GetAttribute(COMPRESS_ATTRIBUTE_NAME), StringComparison.Ordinal);
reader.MoveToContent();
bool isSelfClosed = reader.IsEmptyElement;
bool isNil = bool.TrueString.Equals(reader.GetAttribute("nil"), StringComparison.Ordinal);
reader.ReadStartElement(MSGPACK_ELEMENT);
// explicitly null
if (isNil)
{
if (!isSelfClosed)
{
reader.ReadEndElement();
}
return null;
}
var serializer = MessagePackSerializer.Get(targetType);
if (isSelfClosed) // no real content
{
return serializer.Unpack(Stream.Null);
}
using var ms = new MemoryStream(reader.ReadContentAsBase64());
try
{
if (isCompressed)
{
using var unzip = Compressor.Decompress(ms);
return serializer.Unpack(unzip);
}
return serializer.Unpack(ms);
}
finally
{
reader.ReadEndElement();
}
}
}
}
<file_sep>/src/MsgPack.Wcf/MsgPackBehaviorExtension.cs
#if !COREFX
using System;
using System.ServiceModel.Configuration;
namespace MsgPack.Wcf
{
/// <summary>
/// Configuration element to swap out DatatContractSerilaizer with the XmlMsgPackSerializer for a given endpoint.
/// </summary>
/// <seealso cref="MsgPackEndpointBehavior"/>
public class MsgPackBehaviorExtension : BehaviorExtensionElement
{
/// <summary>
/// Gets the type of behavior.
/// </summary>
public override Type BehaviorType => typeof(MsgPackEndpointBehavior);
/// <summary>
/// Creates a behavior extension based on the current configuration settings.
/// </summary>
/// <returns>The behavior extension.</returns>
protected override object CreateBehavior() => new MsgPackEndpointBehavior();
}
}
#endif<file_sep>/src/MsgPack.CoreWcf/MsgPackBehaviorAttribute.cs
using CoreWCF;
using CoreWCF.Channels;
using CoreWCF.Description;
using CoreWCF.Dispatcher;
using System;
using System.Collections.ObjectModel;
namespace MsgPack.CoreWcf
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public sealed class MsgPackBehaviorAttribute : Attribute, IOperationBehavior, IServiceBehavior
{
void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}
void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
IOperationBehavior innerBehavior = new MsgPackOperationBehavior(operationDescription);
innerBehavior.ApplyClientBehavior(operationDescription, clientOperation);
}
void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
IOperationBehavior innerBehavior = new MsgPackOperationBehavior(operationDescription);
innerBehavior.ApplyDispatchBehavior(operationDescription, dispatchOperation);
}
void IOperationBehavior.Validate(OperationDescription operationDescription)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
var serviceBehavior = new MsgPackBehavior() as IServiceBehavior;
serviceBehavior.ApplyDispatchBehavior(serviceDescription, serviceHostBase);
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
}
<file_sep>/src/MsgPack.Wcf.Core.SampleClient/Program.cs
using ServiceReference;
using System;
using System.Threading.Tasks;
namespace MsgPack.Wcf.Core.SampleClient
{
internal static class Program
{
private static async Task Main(string[] args)
{
var client = new ServiceClient();
client.Endpoint.EndpointBehaviors.Add(new MsgPackEndpointBehavior());
Console.WriteLine(await client.GetDataAsync(1));
Console.WriteLine((await client.GetDataUsingDataContractAsync(new CompositeType { BoolValue = true, StringValue = "Hello World" })).StringValue);
Console.WriteLine((await client.GetCollectionUsingDataContractAsync(new CompositeType { BoolValue = true, StringValue = "Hello World" })).Count);
Console.ReadKey();
}
}
}
<file_sep>/src/MsgPack.CoreWcf.SampleClient/Program.cs
using System;
using System.ServiceModel;
using MsgPack.Wcf;
namespace MsgPack.CoreWcf.SampleClient
{
internal static class Program
{
private static void Main(string[] args)
{
var factory = new ChannelFactory<IService>(new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/basichttp"));
factory.Endpoint.EndpointBehaviors.Add(new MsgPackEndpointBehavior());
factory.Open();
var channel = factory.CreateChannel();
Console.WriteLine(channel.GetData(1));
Console.WriteLine(channel.GetDataUsingDataContract(new CompositeType { BoolValue = true, StringValue = "Hello World" }).StringValue);
Console.WriteLine(channel.GetCollectionUsingDataContract(new CompositeType { BoolValue = true, StringValue = "Hello World" }).Count);
factory.Close();
Console.ReadKey();
}
}
}
<file_sep>/README.md
# msgpack.wcf
msgpack-cli based serializer for WCF
based on <NAME> protobuf-net ServiceModel code
## Builds
[](https://ci.appveyor.com/project/schulz3000/msgpack-wcf/branch/develop)
[](https://github.com/schulz3000/msgpack.wcf/actions/workflows/dotnet.yml)
## Nuget
[](https://www.nuget.org/packages/msgpack.wcf)
## Frameworks
- DotNet >= 3.5
- NetStandard >= 1.1
## Usage
### Serverside
``` csharp
//Add behavior in config
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="MsgPackBehaviorConfig">
<MsgPackSerialization/>
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="MsgPackSerialization" type="MsgPack.Wcf.MsgPackBehaviorExtension, MsgPack.Wcf, Version=1.0.0.0, Culture=neutral, PublicKeyToken=645f937616845218"/>
</behaviorExtensions>
</extensions>
<service name="MsgPack.Wcf.SampleHost.Service">
<endpoint address="http://localhost:6360/Service.svc" binding="basicHttpBinding" behaviorConfiguration="MsgPackBehaviorConfig"
name="basicHttpMsgPack" contract="MsgPack.Wcf.SampleHost.IService" />
</service>
</system.serviceModel>
```
### Clientside
``` csharp
//Add behavior in Code
var client = new ServiceClient();
client.Endpoint.EndpointBehaviors.Add(new MsgPackEndpointBehavior());
//Alternative add behavior in config
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="MsgPackBehaviorConfig">
<MsgPackSerialization/>
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="MsgPackSerialization" type="MsgPack.Wcf.MsgPackBehaviorExtension, MsgPack.Wcf, Version=1.0.0.0, Culture=neutral, PublicKeyToken=645f937616845218"/>
</behaviorExtensions>
</extensions>
<client>
<endpoint address="http://localhost:6360/Service.svc" binding="basicHttpBinding"
contract="ServiceReference.IService"
name="basicHttpMsgPack" behaviorConfiguration="MsgPackBehaviorConfig"/>
</client>
</system.serviceModel>
```<file_sep>/src/MsgPack.CoreWcf.SampleHost/Program.cs
using CoreWCF.Configuration;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace MsgPack.Wcf.Core.SampleHost
{
internal static class Program
{
private static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
host.Run();
}
private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => options.ListenLocalhost(8080))
.UseNetTcp(8808)
.UseStartup<Startup>();
}
}
<file_sep>/src/MsgPack.CoreWcf/MsgPackBehavior.cs
using CoreWCF;
using CoreWCF.Channels;
using CoreWCF.Description;
using CoreWCF.Dispatcher;
using System.Collections.ObjectModel;
namespace MsgPack.CoreWcf
{
public class MsgPackBehavior : IEndpointBehavior, IServiceBehavior
{
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
=> ReplaceDataContractSerializerOperationBehavior(endpoint);
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
=> ReplaceDataContractSerializerOperationBehavior(endpoint);
void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (var endpoint in serviceDescription.Endpoints)
{
ReplaceDataContractSerializerOperationBehavior(endpoint);
}
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
private static void ReplaceDataContractSerializerOperationBehavior(ServiceEndpoint serviceEndpoint)
{
foreach (OperationDescription operationDescription in serviceEndpoint.Contract.Operations)
{
ReplaceDataContractSerializerOperationBehavior(operationDescription);
}
}
private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description)
{
if (!description.OperationBehaviors.Contains(typeof(DataContractSerializerOperationBehavior)))
{
return;
}
var dcsOperationBehavior = (DataContractSerializerOperationBehavior)description.OperationBehaviors[typeof(DataContractSerializerOperationBehavior)];
if (dcsOperationBehavior != null)
{
description.OperationBehaviors.Remove(dcsOperationBehavior);
var newBehavior = new MsgPackOperationBehavior(description);
newBehavior.MaxItemsInObjectGraph = dcsOperationBehavior.MaxItemsInObjectGraph;
description.OperationBehaviors.Add(newBehavior);
}
}
}
}<file_sep>/src/MsgPack.Wcf.SampleHost/IService.cs
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace MsgPack.Wcf.SampleHost
{
[ServiceContract]
public interface IService
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
List<CompositeType> GetCollectionUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType
{
[DataMember]
public bool BoolValue { get; set; }
[DataMember]
public string StringValue { get; set; }
}
}
<file_sep>/src/MsgPack.CoreWcf.SampleHost/Startup.cs
using CoreWCF;
using CoreWCF.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using MsgPack.CoreWcf;
namespace MsgPack.Wcf.Core.SampleHost
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddServiceModelServices();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseServiceModel(builder =>
{
builder
.AddService<Service>()
.AddServiceEndpoint<Service, IService>(new BasicHttpBinding(), "/basichttp")
.AddServiceEndpoint<Service, IService>(new NetTcpBinding(), "/nettcp")
.ConfigureServiceHostBase<Service>(config =>
{
//foreach (var endpoint in config.Description.Endpoints)
//{
// endpoint.EndpointBehaviors.Add(new MsgPackBehavior());
//}
});
});
}
}
}
<file_sep>/src/MsgPack.CoreWcf/Compressor.cs
using System.IO;
using System.IO.Compression;
namespace MsgPack.CoreWcf
{
internal static class Compressor
{
public static byte[] Compress(Stream inputStream)
{
inputStream.Position = 0;
using var zipms = new MemoryStream();
using var gzip = new GZipStream(zipms, CompressionMode.Compress);
inputStream.CopyTo(gzip);
return zipms.ToArray();
}
public static Stream Decompress(Stream inputStream)
{
inputStream.Position = 0;
var zipms = new MemoryStream();
using var gzip = new GZipStream(inputStream, CompressionMode.Decompress);
gzip.CopyTo(zipms);
zipms.Position = 0;
return zipms;
}
}
}
<file_sep>/src/MsgPack.Wcf/StreamExtensions.cs
using System.IO;
namespace MsgPack.Wcf
{
#if NET35
internal static class StreamExtensions
{
public static void CopyTo(this Stream sourceStream, Stream targetStream)
{
const int bufferLength = 81920;
var buffer = new byte[bufferLength];
int read;
while ((read = sourceStream.Read(buffer, 0, bufferLength)) != 0)
{
targetStream.Write(buffer, 0, read);
}
}
}
#endif
}
<file_sep>/src/MsgPack.Wcf.SampleHost/Service.svc.cs
using System;
using System.Collections.Generic;
namespace MsgPack.Wcf.SampleHost
{
public class Service : IService
{
public List<CompositeType> GetCollectionUsingDataContract(CompositeType composite)
{
var list = new List<CompositeType>();
for (int i = 0; i < 10; i++)
{
list.Add(composite);
}
return list;
}
public string GetData(int value)
=> $"You entered: {value}";
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException(nameof(composite));
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
<file_sep>/src/MsgPack.Wcf/MsgPackEndpointBehavior.cs
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
#if COREFX
using System.Linq;
#endif
namespace MsgPack.Wcf
{
public class MsgPackEndpointBehavior : IEndpointBehavior
{
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
=> ReplaceDataContractSerializerOperationBehavior(endpoint);
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
=> ReplaceDataContractSerializerOperationBehavior(endpoint);
void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
{
}
private static void ReplaceDataContractSerializerOperationBehavior(ServiceEndpoint serviceEndpoint)
{
foreach (OperationDescription operationDescription in serviceEndpoint.Contract.Operations)
{
ReplaceDataContractSerializerOperationBehavior(operationDescription);
}
}
#if COREFX
private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description)
{
var dcsOperationBehavior = (DataContractSerializerOperationBehavior)description.OperationBehaviors[typeof(DataContractSerializerOperationBehavior)];
if (dcsOperationBehavior != null)
{
description.OperationBehaviors.Remove(dcsOperationBehavior);
var newBehavior = new MsgPackOperationBehavior(description);
newBehavior.MaxItemsInObjectGraph = dcsOperationBehavior.MaxItemsInObjectGraph;
description.OperationBehaviors.Add(newBehavior);
}
}
#else
private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description)
{
var dcsOperationBehavior = description.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dcsOperationBehavior != null)
{
description.Behaviors.Remove(dcsOperationBehavior);
var newBehavior = new MsgPackOperationBehavior(description);
newBehavior.MaxItemsInObjectGraph = dcsOperationBehavior.MaxItemsInObjectGraph;
description.Behaviors.Add(newBehavior);
}
}
#endif
}
}<file_sep>/src/MsgPack.Wcf.SampleClient/Program.cs
using System;
using MsgPack.Wcf.Classic.SampleClient.ServiceReference;
namespace MsgPack.Wcf.SampleClient
{
internal static class Program
{
private static void Main(string[] args)
{
var client = new ServiceClient();
client.Endpoint.EndpointBehaviors.Add(new MsgPackEndpointBehavior());
Console.WriteLine(client.GetData(1));
Console.WriteLine(client.GetDataUsingDataContract(new CompositeType { BoolValue=true, StringValue = "Hello World" }).StringValue);
Console.WriteLine(client.GetCollectionUsingDataContract(new CompositeType { BoolValue = true, StringValue = "Hello World" }).Count);
Console.ReadKey();
}
}
}
| e3b1624303e0de7a1a4d4a4de592f16aabbec073 | [
"Markdown",
"C#"
] | 16 | C# | schulz3000/msgpack.wcf | e092415bb053230eea5b167ed217aa70366b9e0a | 81e7eeedb5c7543a7cc65bf4c2a4fc7c603c3c6a |
refs/heads/master | <file_sep># Diffie-Hellman-Key-Exchange-via-UDP-Sockets
Implementing and Establishing the secure channel between two parties using Diffie-Hellman Key Exchange
- Alice stands for Host(Server)
- Bob stands for Client
#Usage :
- Run server and client in seperate terminal windows.
-to run server
$ cd Alice
$ javac Host.java SetUp.java;java Host
-to run client
$cd Bob
$ javac Client.java ClientSetUp.java;java Client <port-number>
# Note
Please run the server first.*
When the client is run while there is no serve listening at the given <port-number>, the program will throw ConnectException.*
<file_sep>/**
* This is just a testing and playing around with Sha-1 Hash,
* which is required for my CS Assignment
* In real world, do not ever use SHA-1 as a hashing technique.
* It is not secure anymore.
*/
import java.io.BufferedReader;
import java.io.DataInputStream;
class Host {
private static final String RECEIVE_TEXT_COLOR = "\u001B[36m"; // cyan
public static final String SEND_TEXT_COLOR = "\u001B[35m"; // purple
private static final String DEFAULT_COLOR = "\u001B[0m"; // default color
private static final String ERROR_TEXT_COLOR = "\u001B[31m"; // red
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Usage: java Host <port-number>");
System.exit(1);
}
int PORT = Integer.parseInt(args[0]);
SetUp setUp = new SetUp(PORT);
setUp.readConfigs();
setUp.initConnection();
setUp.performHandShake();
// start background thread for receiving messages from client
//setUp.start();
BufferedReader kb_bufferedReader = setUp.getKeyBoardBufferedReader();
DataInputStream inputStream = setUp.getInputStream();
System.out.print(SEND_TEXT_COLOR + "\n" + SEND_TEXT_COLOR);
while (true) {
String s_message = "";
String r_message = "";
while ( !kb_bufferedReader.ready() ) {
while ( inputStream.available() > 0 ) {
// receive message
r_message = setUp.receiveMessage();
if (r_message != null) {
System.out.print(RECEIVE_TEXT_COLOR + "Client : "+ r_message + RECEIVE_TEXT_COLOR);
System.out.print(SEND_TEXT_COLOR+"\n\n"+SEND_TEXT_COLOR);
if (r_message.equals("exit"))
setUp.terminateConnection();
}
else {
// reject message
System.out.println(ERROR_TEXT_COLOR + "MESSAGE REJECTED" + ERROR_TEXT_COLOR);
System.out.println(SEND_TEXT_COLOR);
}
}
}
if (kb_bufferedReader.ready()) {
s_message = kb_bufferedReader.readLine();
setUp.sendMessage(s_message);
}
if (s_message.equals("exit"))
break;
}
System.out.println(DEFAULT_COLOR);
setUp.terminateConnection();
}
}
| 32f9e76a12725bde3a529ac47e04cb21aa7bdc86 | [
"Markdown",
"Java"
] | 2 | Markdown | lazyKT/UDP-Sockets-with-Diffie-Hellman-Key-Exchange | e21d3a7b4037cd0fda13da4e07c9ec2ae2003ba3 | c75ef59c1485075977aadb0c30ad7358c7695712 |
refs/heads/master | <repo_name>AlucardxTepes/RxJavaRetrofitTest<file_sep>/app/src/main/java/ado/com/ember/rxretrofittest/MainActivity.java
package ado.com.ember.rxretrofittest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final String BASE_URL = "https://api.learn2crack.com/";
private RecyclerView mRecyclerView;
private CompositeDisposable mCompositeDisposable;
private DataAdapter mAdapter;
private ArrayList<AndroidVersion> mAndroidAVersionList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCompositeDisposable = new CompositeDisposable();
initRecyclerView();
requestJson();
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
mCompositeDisposable.dispose();
}
}
private void initRecyclerView() {
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(layoutManager);
}
private void requestJson() {
ApiService apiService = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService.class);
mCompositeDisposable.add(apiService.findAll()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::initAdapter, this::showError)
);
}
private void initAdapter(List<AndroidVersion> androidVersions) {
mAndroidAVersionList = (ArrayList<AndroidVersion>) androidVersions;
mAdapter = new DataAdapter(new ArrayList<>(androidVersions));
mRecyclerView.setAdapter(mAdapter);
}
private void showError(Throwable throwable) {
Toast.makeText(this, throwable.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
throwable.printStackTrace();
}
}
| a79ded8c56504516b7fb3caa4e1f2115ff5df64c | [
"Java"
] | 1 | Java | AlucardxTepes/RxJavaRetrofitTest | 976cbb167374ca522e200bc1ed5f21fc2b385258 | 5f39fab5efbdf099e5b2f4ede366da2652ad7adc |
refs/heads/master | <file_sep>#!/usr/bin/env bash
set -e
set -u
export DEBIAN_FRONTEND=noninteractive
# Install the kernel sources before the guest additions to guarantee that
# we can compile the kernel module.
apt-get install -q -y linux-headers-amd64
<file_sep>#!/usr/bin/env bash
set -e
set -u
export DEBIAN_FRONTEND=noninteractive
readonly PKGS=(
ssh-askpass
clang-3.6
clang-format-3.5
gfortran
git
libblas-dev
liblapack-dev
libpython3-dev
libpython-dev
python3
python3-matplotlib
python3-numpy
python3-scipy
python-matplotlib
python-scipy
resolvconf
ruby
unzip
)
# Set up the backports repo.
cat > /etc/apt/sources.list.d/backports.list <<EOT
deb http://http.debian.net/debian jessie-backports main
EOT
# Set up the LLVM repo.
cat > /etc/apt/sources.list.d/llvm-3.6.list <<EOT
deb http://llvm.org/apt/jessie/ llvm-toolchain-jessie-3.6 main
deb-src http://llvm.org/apt/jessie/ llvm-toolchain-jessie-3.6 main
EOT
# Enable user namespace for sandboxing.
cat > /etc/sysctl.d/99-enable-user-namespaces.conf <<EOT
kernel.unprivileged_userns_clone = 1
EOT
# Accept the LLVM GPG key so we can install their packages.
wget -O - http://llvm.org/apt/llvm-snapshot.gpg.key | apt-key add -
# Install all the packages that we need/want.
apt-get update
for pkg in "${PKGS[@]}"; do
apt-get install -y -f --force-yes "$pkg"
done
mkdir /tmp/image-making/ -p
wget -qO /tmp/image-making/installer.sh https://github.com/bazelbuild/bazel/releases/download/0.5.2/bazel-0.5.2-installer-linux-x86_64.sh
bash /tmp/image-making/installer.sh && rm -r /tmp/image-making
<file_sep>Requirements
--------------------------------------------------------------------------------
1. Install Vagrant <https://www.vagrantup.com/downloads.html>
1. Install VirtualBox and VirtualBox Extension Pack
<https://www.virtualbox.org/wiki/Downloads>.
1. Add `vagrant` and `VBoxManage` to your PATH.
- This is most likely already done by the installation binaries.
It's added to the system path.
- To test this, type these commands in a terminal:
~$ vagrant --version
Vagrant 1.8.1
~$ VBoxManage --version
5.0.14r105127
- You may need to log out and back in for the path modifications to take
effect.
Usage
--------------------------------------------------------------------------------
1. Clone this repository onto your computer somewhere.
git clone https://github.com/valkyrierobotics/dev-environment.git
1. Go into the directory and build the VM.
vagrant up
1. Some errors during the `vagrant up` process can be addressed by
re-provisioning the vagrant box. This is useful if, for example, an
`apt-get` invocation timed out and caused the provisioning process to abort.
vagrant provision
1. Once built, reboot the VM so it starts the GUI properly.
vagrant reload
1. You can then log in and open a terminal. The username and password are both
`<PASSWORD>`.
1. At this point, you should be able to see "299 Virtual Environment" in the
list of VMs in VirtualBox. Go to the settings of "299 Virtual Environment"
to customize options such as increasing video memory or number of CPUs.
1. Download the code.
git clone https://github.com/valkyrierobotics/mass.git
cd mass
1. Once connected to the robot's radio through wifi, ssh in to verify
authenticity of the connection. Press ENTER for password.
ssh admin@10.2.99.2
Building and Deploying To Robot
--------------------------------------------------------------------------------
1. After making any chances, build the code for the RoboRIO.
bazel build //y2017/download_stripped --cpu=roborio -- $(cat NO_BUILD_ROBORIO)
1. Deploy code to RoboRIO.
bazel run //y2017/download_stripped --cpu=roborio -- 10.2.99.2
| 8470727cbe2fab46e9d581cd061e05a7c7f8aa45 | [
"Markdown",
"Shell"
] | 3 | Shell | minhoolee/dev-environment | 3128fc84ccfe903ec4404ef8da2a9a8092b11fda | 34710359be24aa86a421d4a09ab0c3da073fa328 |
refs/heads/master | <repo_name>eyamil/hack-n-forth<file_sep>/README.md
# hack-n-forth
Intended for sharing of scripts. Although XSS is typically considered a vulnerability, it has the potential to make chat applications like IRC and http://hack.chat/ uniquely interactive. In Hack-N-Forth, I can have a (trusted) user push Javascript over to me. The script gets executed parallely in both of our browsers, letting us do things like collaboratively browse a webpage (by spawning an iframe in each window and casting over each user's mouse and key events to be replicated in each iframe).
<file_sep>/client.js
// Run straightaway:
// Load socket.io:
var socketSC = document.createElement('script');
socketSC.type = 'text/javascript';
socketSC.src = 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.js';
document.head.appendChild(socketSC);
// Load JQuery for an evil hack:
var JQ = document.createElement('script');
JQ.type = 'text/javascript';
JQ.src = 'https://code.jquery.com/jquery-3.1.0.min.js';
document.head.appendChild(JQ);
// Load CSS:
var css = document.createElement('link');
css.rel = 'stylesheet';
css.type = 'text/css';
css.href = '/client.css';
document.head.appendChild(css);
// Run on window load:
window.onload = function () {
const USER = window.prompt('Nickname:'); // Get the user's nickname. Eventually there should be a "middle var step" that allows socket to check for name collisions before going through.
// MSGBody setup:
var msgbody = document.createElement('article');
document.body.appendChild(msgbody);
msgbody.className = 'hnf_msgcontainer';
var msgs = document.createElement('div');
msgbody.appendChild(msgs);
msgs.className = 'hnf_msgs';
// Socket setup:
var socket = io.connect();
recieve = function(data) {
$(msgs).append(data); // Evil hax lie here
//msgbody.innerHTML += data; <-- Useful without JQuery, as if you do document.body.innerHTML += stuff, you lose the "onkeydown" event.
document.body.scrollTop = 1e99;
}
socket.on('data', recieve);
send = function(data) {
socket.emit('data', data);
}
// Textarea Creation:
var textbox = document.createElement('textarea');
document.body.appendChild(textbox);
function EnterKey(e) {
if(e.keyCode == 13 && !e.shiftKey) {
send('<div class="hnf_msgbox"><span class="nick">' + USER + ' </span><pre class="text">' + e.target.value + '<pre></div>');
e.target.value = '';
}
}
textbox.onkeyup = EnterKey;
textbox.className = 'hnf_sendbox';
}
<file_sep>/server.js
// Webserver Setup:
var fs = require('fs');
var http = require('http');
const PORT = process.env.PORT || 3300;
function handleRequest(request, response){
// Favicon handling:
if (request.url == '/favicon.ico') {
response.writeHead(200, {'Content-Type': 'image/x-icon'});
var FaviconStream = fs.createReadStream(__dirname + '/favicon.ico');
FaviconStream.pipe(response);
}
// Serve client.js:
else if (request.url == '/client.js') {
response.writeHead(200, {'Content-Type': 'application/javascript'});
var JSStream = fs.createReadStream(__dirname + '/client.js');
JSStream.pipe(response);
}
// Serve client.css:
else if (request.url == '/client.css') {
response.writeHead(200, {'Content-Type': 'text/css'});
var JSStream = fs.createReadStream(__dirname + '/client.css');
JSStream.pipe(response);
}
// Other Routing:
else {
// Write the page HTML (as bare-bones as can be. The meat is injected via client.js)
response.write('<html>');
response.write('<head>');
response.write('<script src="client.js"></script>');
response.write('<title>' + request.url + '</title>');
response.write('</head>');
response.write('<body>');
response.write('</body>');
response.write('</html>');
response.end();
console.log(request.url);
}
}
var WebServer = http.createServer(handleRequest);
WebServer.listen(PORT, function(){
console.log("HTTP server listening on: http://localhost:%s", PORT);
});
// Sockets setup:
var ws = require('socket.io')(WebServer);
ws.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('data', function (data) {
ws.emit('data', data);
});
});
| 01db23a6e072548e3109b0fe28eb566c94643770 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | eyamil/hack-n-forth | 4c11e84db0e6de7369feb37f5b8b18354596a459 | a723e4f136db31335d1350ed0d5b4d2bfef238fa |
refs/heads/master | <file_sep>'use strict';
(function() {
var buttonShowHotels = document.querySelector('.show-hotels');
var formSearchHotel = document.querySelector('.dates-and-people');
var fieldArrival = formSearchHotel.querySelector('#arrival');
var fieldAdults = formSearchHotel.querySelector('#adults');
var fieldChildren = formSearchHotel.querySelector('#children');
var iconPlus = formSearchHotel.querySelectorAll('.icon-plus');
var iconMinus = formSearchHotel.querySelectorAll('.icon-minus');
var buttonSearch = formSearchHotel.querySelector('.blue-btn');
function clickButton(evt) {
evt.preventDefault();
formSearchHotel.classList.toggle('dates-and-people-appearance');
fieldArrival.focus();
fieldAdults.value = localStorage.getItem('adults') || 2;
fieldChildren.value = localStorage.getItem('children') || 0;
}
function clickIconPlus(evt) {
if (evt.target.htmlFor === 'adults') {
if (+fieldAdults.value < 10) {
fieldAdults.value++;
} else {
return;
}
}
if (evt.target.htmlFor === 'children') {
if (+fieldChildren.value < 10) {
fieldChildren.value++;
} else {
return;
}
}
}
function clickIconMinus(evt) {
if (evt.target.htmlFor === 'adults') {
if (+fieldAdults.value > 0) {
fieldAdults.value--;
if (+fieldAdults.value <= 10) {
fieldAdults.classList.remove('field-error');
}
} else {
return;
}
}
if (evt.target.htmlFor === 'children') {
if (+fieldChildren.value > 0) {
fieldChildren.value--;
if (+fieldChildren.value <= 10) {
fieldChildren.classList.remove('field-error');
}
} else {
return;
}
}
}
function inputData(evt) {
var goodNumber = /^\d+$/.exec(evt.target.value);
if (!goodNumber || +goodNumber[0] > 10) {
evt.target.classList.add('field-error');
} else {
evt.target.classList.remove('field-error');
}
}
function submitForm(evt) {
if (fieldAdults.classList.contains('field-error') || fieldChildren.classList.contains('field-error')) {
evt.preventDefault();
}
localStorage.setItem('adults', fieldAdults.value);
localStorage.setItem('children', fieldChildren.value);
}
function hideForm(evt) {
if (evt.keyCode === 27 && formSearchHotel.classList.contains('dates-and-people-appearance')) {
formSearchHotel.classList.remove('dates-and-people-appearance');
}
}
formSearchHotel.addEventListener('submit', submitForm);
buttonShowHotels.addEventListener('click', clickButton);
fieldAdults.addEventListener('input', inputData);
fieldChildren.addEventListener('input', inputData);
window.addEventListener('keydown', hideForm);
[].forEach.call(iconMinus, function(item) {
item.addEventListener('click', clickIconMinus);
});
[].forEach.call(iconPlus, function(item) {
item.addEventListener('click', clickIconPlus);
});
})();
| acd0db7da78957118526627a89e2f7a6e60f447a | [
"JavaScript"
] | 1 | JavaScript | htmlacademy-htmlcss/199714-sedona | d74f20f8b55224bd73af09f6952c5d5352acf1e5 | 78fbaa1ccd3698d6b5ddfa03e78a48bdcd37ffb3 |
refs/heads/main | <file_sep>package kg.turar.arykbaev.sokoban.model
import kg.turar.arykbaev.sokoban.utils.*
import kg.turar.arykbaev.sokoban.viewer.Viewer
import java.io.BufferedReader
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStreamReader
class LevelFile : Level {
private val listOfLevels: Array<String>
private val viewer: Viewer
private var currentLevelIndex: Int
constructor(viewer: Viewer) {
this.viewer = viewer
listOfLevels = arrayOf("level1.sok", "level2.sok", "level3.sok")
currentLevelIndex = 0
}
override fun getLevel(levelNumber: Int): Array<IntArray> {
currentLevelIndex = levelNumber - 1
return when (levelNumber) {
LEVEL_1 -> getDesktopFromFile(listOfLevels[0])
LEVEL_2 -> getDesktopFromFile(listOfLevels[1])
LEVEL_3 -> getDesktopFromFile(listOfLevels[2])
else -> ArrayHelper.getDefaultDesktop()
}
}
private fun getDesktopFromFile(fileName: String): Array<IntArray> {
var letterFromFile = ""
try {
val assetManager = viewer.assets
val inputStream = assetManager.open("levels/$fileName")
val input = BufferedReader(InputStreamReader(inputStream))
while (true) {
val unicode = input.read()
val symbol = unicode.toChar()
if (symbol in '0'..'9' || symbol == '\n') {
letterFromFile += symbol
}
if (unicode == -1) {
break
}
}
} catch (fne: FileNotFoundException) {
println(fne)
} catch (ioe: IOException) {
println(ioe)
}
return ArrayHelper.letterToArray(letterFromFile)
}
override fun nextLevel(): Array<IntArray> {
if (currentLevelIndex < listOfLevels.size - 1) {
currentLevelIndex++
}
return getLevel(currentLevelIndex + 1)
}
override fun getLevelsNumber(): Int {
return listOfLevels.size
}
override fun setLevelNumber(levelNumber: Int) {
currentLevelIndex = levelNumber - 1
}
override fun isLastLevel(): Boolean {
return listOfLevels.size - 1 <= currentLevelIndex
}
override fun getCurrentLevelNumber(): Int {
return currentLevelIndex + 1
}
override fun restartLevel(): Array<IntArray> {
return getLevel(currentLevelIndex + 1)
}
override fun getDifficulty(): String {
return DIFFICULTY_MIDDLE
}
}<file_sep>package kg.turar.arykbaev.sokoban.model
interface Level {
fun getLevel(levelNumber: Int): Array<IntArray>
fun nextLevel(): Array<IntArray>
fun restartLevel(): Array<IntArray>
fun getLevelsNumber(): Int
fun setLevelNumber(levelNumber: Int)
fun isLastLevel(): Boolean
fun getCurrentLevelNumber(): Int
fun getDifficulty(): String
}<file_sep>package kg.turar.arykbaev.sokoban.controller
import android.view.*
import kg.turar.arykbaev.sokoban.R
import kg.turar.arykbaev.sokoban.model.Model
import kg.turar.arykbaev.sokoban.utils.DIFFICULTY_EASY
import kg.turar.arykbaev.sokoban.utils.DIFFICULTY_HARD
import kg.turar.arykbaev.sokoban.utils.DIFFICULTY_MIDDLE
import kg.turar.arykbaev.sokoban.utils.Direction
import kg.turar.arykbaev.sokoban.viewer.Viewer
public class Controller : View.OnTouchListener, View.OnClickListener {
private val model: Model
private lateinit var gestureDetector: GestureDetector
constructor(viewer: Viewer) {
model = Model(viewer)
}
fun initDetector(viewer: Viewer) {
gestureDetector = GestureDetector(viewer, GestureDetectorListener(this))
}
fun initMenu(menu: Menu) {
model.initMenu(menu)
model.setLevelListToMenu()
}
fun getModel(): Model {
return model
}
override fun onTouch(view: View, event: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(event)
}
fun swipeDown() {
model.updateGamer(Direction.DOWN)
model.move(Direction.DOWN)
}
fun swipeUp() {
model.updateGamer(Direction.UP)
model.move(Direction.UP)
}
fun swipeLeft() {
model.updateGamer(Direction.LEFT)
model.move(Direction.LEFT)
}
fun swipeRight() {
model.updateGamer(Direction.RIGHT)
model.move(Direction.RIGHT)
}
fun onOptionsItemSelectedHandler(item: MenuItem) {
when (item.itemId) {
R.id.menu_easy -> {
model.setLevelByteCode()
model.setDifficulty(DIFFICULTY_EASY)
}
R.id.menu_middle -> {
model.setLevelFile()
model.setDifficulty(DIFFICULTY_MIDDLE)
}
R.id.menu_hard -> {
model.setLevelServer()
model.setDifficulty(DIFFICULTY_HARD)
}
R.id.menu_refresh -> {
model.restartLevel()
}
R.id.menu_level -> {
return
}
R.id.menu_difficulty -> {
return
}
else -> {
model.setNewLevel(item.itemId)
model.checkMenuItem(item.itemId)
}
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.next_level -> model.nextLevel()
R.id.play_again -> model.restartLevel()
}
model.dismissDialog()
}
fun setSavedDesktop(difficulty: String?, levelNumber: Int, letterDesktop: String?) {
model.setSavedDesktop(difficulty, levelNumber, letterDesktop)
}
fun getDifficulty(): String {
return model.getDifficulty()
}
fun getLevelNumber(): Int {
return model.getLevelNumber()
}
fun getLetterDesktop(): String {
return model.getLetterDesktop()
}
}<file_sep>package kg.turar.arykbaev.sokoban.model
import kg.turar.arykbaev.sokoban.utils.*
class LevelByteCode : Level {
private val listOfLevels: Array<Int>
private var currentLevelIndex: Int
constructor() {
listOfLevels = arrayOf(LEVEL_1, LEVEL_2, LEVEL_3)
currentLevelIndex = 0
}
private fun getFirstDesktop(): Array<IntArray> {
val desktop = arrayOf(
intArrayOf(2, 2, 2, 2, 2, 2),
intArrayOf(2, 0, 0, 1, 0, 2),
intArrayOf(2, 3, 2, 2, 2, 2),
intArrayOf(2, 0, 2),
intArrayOf(2, 0, 2),
intArrayOf(2, 4, 2),
intArrayOf(2, 2, 2)
)
return desktop
}
private fun getSecondDesktop(): Array<IntArray> {
val desktop = arrayOf(
intArrayOf(2, 2, 2, 2, 2, 2),
intArrayOf(2, 1, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 3, 4, 2),
intArrayOf(2, 0, 4, 3, 0, 2),
intArrayOf(2, 2, 2, 2, 2, 2)
)
return desktop
}
private fun getThirdDesktop(): Array<IntArray> {
val desktop = arrayOf(
intArrayOf(2, 2, 2, 2, 2, 2),
intArrayOf(2, 1, 0, 0, 0, 2, 2),
intArrayOf(2, 0, 3, 3, 0, 0, 2),
intArrayOf(2, 0, 2, 4, 0, 4, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 2, 2, 2, 2, 2, 2)
)
return desktop
}
override fun getLevel(levelNumber: Int): Array<IntArray> {
currentLevelIndex = levelNumber - 1
when (levelNumber) {
LEVEL_1 -> return getFirstDesktop()
LEVEL_2 -> return getSecondDesktop()
LEVEL_3 -> return getThirdDesktop()
else -> return ArrayHelper.getDefaultDesktop()
}
}
override fun nextLevel(): Array<IntArray> {
if (currentLevelIndex < listOfLevels.size - 1) {
currentLevelIndex++
}
return getLevel(currentLevelIndex + 1)
}
override fun restartLevel(): Array<IntArray> {
return getLevel(currentLevelIndex + 1)
}
override fun getLevelsNumber(): Int {
return listOfLevels.size
}
override fun setLevelNumber(levelNumber: Int) {
currentLevelIndex = levelNumber - 1
}
override fun isLastLevel(): Boolean {
return listOfLevels.size - 1 <= currentLevelIndex
}
override fun getCurrentLevelNumber(): Int {
return listOfLevels[currentLevelIndex]
}
override fun getDifficulty(): String {
return DIFFICULTY_EASY
}
}<file_sep>package kg.turar.arykbaev.sokoban.viewer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import kg.turar.arykbaev.sokoban.R
import kg.turar.arykbaev.sokoban.canvas.CanvasSokoban
import kg.turar.arykbaev.sokoban.controller.Controller
import kg.turar.arykbaev.sokoban.utils.DESKTOP
import kg.turar.arykbaev.sokoban.utils.DIFFICULTY
import kg.turar.arykbaev.sokoban.utils.Direction
import kg.turar.arykbaev.sokoban.utils.LEVEL
class Viewer : AppCompatActivity {
private val controller: Controller
private lateinit var canvas: CanvasSokoban
private lateinit var dialog: AlertDialog
constructor() {
controller = Controller(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
canvas = CanvasSokoban(this, controller.getModel())
canvas.setOnTouchListener(controller)
setContentView(canvas)
controller.initDetector(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.level_menu, menu)
controller.initMenu(menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
controller.onOptionsItemSelectedHandler(item)
return true
}
fun showWinDialog(){
val builder = AlertDialog.Builder(this)
val view = View.inflate(this, R.layout.congratulations_dialog_layout, null)
builder.setView(view)
val next = view.findViewById<Button>(R.id.next_level)
val restart = view.findViewById<Button>(R.id.play_again)
next.setOnClickListener(controller)
restart.setOnClickListener(controller)
dialog = builder.create()
dialog.setCancelable(true)
dialog.show()
}
fun showLastLevelWinDialog() {
val builder = AlertDialog.Builder(this)
val view = View.inflate(this, R.layout.last_level_dialog_layout, null)
builder.setView(view)
val restart = view.findViewById<Button>(R.id.play_again)
restart.setOnClickListener(controller)
dialog = builder.create()
dialog.setCancelable(true)
dialog.show()
}
fun dismissDialog() {
dialog.dismiss()
}
fun setTitle(title: String) {
this.title = title
}
fun updateDesktop() {
canvas.updateDesktop()
}
fun update() {
canvas.update()
}
fun updateGamer(direction: Direction) {
canvas.updateGamer(direction)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
val difficulty = savedInstanceState.getString(DIFFICULTY)
val levelNumber = savedInstanceState.getInt(LEVEL)
val letter = savedInstanceState.getString(DESKTOP)
controller.setSavedDesktop(difficulty, levelNumber, letter)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(DIFFICULTY, controller.getDifficulty())
outState.putInt(LEVEL, controller.getLevelNumber())
outState.putString(DESKTOP, controller.getLetterDesktop())
}
}<file_sep>include ':app'
rootProject.name = "Sokoban"<file_sep>package kg.turar.arykbaev.sokoban.utils
class ArrayHelper {
companion object {
fun letterToArray(newLetter: String): Array<IntArray> {
val letter = removeUnnecessaryNewLine(newLetter)
var row = 1
for (element in letter) {
if (element == '\n') {
row += 1
}
}
val array = Array(row) { IntArray(0) }
var column = 0
var index = 0
for (i in letter.indices) {
val symbol = letter[i]
if (symbol == '\n') {
array[index] = IntArray(column)
index += 1
column = 0
} else {
column += 1
}
}
array[index] = IntArray(column)
var arrayIndexX = 0
var arrayIndexY = 0
for (element in letter) {
if (element == '\n') {
arrayIndexX += 1
arrayIndexY = 0
} else {
array[arrayIndexX][arrayIndexY] = Character.getNumericValue(element)
arrayIndexY += 1
}
}
return array
}
fun getDefaultDesktop(): Array<IntArray> {
val desktop = arrayOf(
intArrayOf(2, 2, 2, 2, 2, 2, 2, 2),
intArrayOf(2, 4, 3, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 1, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 0, 0, 0, 0, 0, 0, 2),
intArrayOf(2, 2, 2, 2, 2, 2, 2, 2)
)
return desktop
}
fun arrayToLetter(desktop: Array<IntArray>): String {
var letter = ""
for (row in desktop) {
for (i in row) {
letter += i.toString()
}
letter += '\n'
}
return letter
}
private fun removeUnnecessaryNewLine(letter: String): String {
var newLetter = ""
var isNumber = false
for (i in letter.indices) {
if (isNumber && letter[i] == '\n' && i < letter.lastIndex - 1) {
newLetter += letter[i]
}
if (letter[i] != '\n') {
newLetter += letter[i]
isNumber = true
} else {
isNumber = false
}
}
return newLetter
}
}
}<file_sep>package kg.turar.arykbaev.sokoban.viewer
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import kg.turar.arykbaev.sokoban.R
class StartActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start)
supportActionBar?.hide()
val button = findViewById<Button>(R.id.button_easy)
button.setOnClickListener {
val intent = Intent(this, Viewer::class.java)
startActivity(intent)
finish()
}
}
}<file_sep>package kg.turar.arykbaev.sokoban.controller
import android.view.GestureDetector
import android.view.MotionEvent
import kg.turar.arykbaev.sokoban.utils.SWIPE_MIN_DISTANCE
import kg.turar.arykbaev.sokoban.utils.SWIPE_THRESHOLD_VELOCITY
import kotlin.math.abs
class GestureDetectorListener : GestureDetector.SimpleOnGestureListener {
private val controller: Controller
constructor(controller: Controller) {
this.controller = controller
}
override fun onDown(e: MotionEvent?): Boolean {
return true
}
override fun onFling(
event1: MotionEvent,
event2: MotionEvent,
velocityX: Float,
velocityY: Float
): Boolean {
val valueX: Float = event2.x - event1.x
val valueY: Float = event2.y - event1.y
if (abs(valueX) > abs(valueY)) {
if (abs(valueX) > SWIPE_MIN_DISTANCE && abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if (valueX > 0) {
swipeRight()
} else {
swipeLeft()
}
}
} else if (abs(valueY) > SWIPE_MIN_DISTANCE && abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
if (valueY > 0) {
swipeDown()
} else {
swipeUp()
}
}
return super.onFling(event1, event2, velocityX, velocityY)
}
private fun swipeDown() {
controller.swipeDown()
}
private fun swipeUp() {
controller.swipeUp()
}
private fun swipeLeft() {
controller.swipeLeft()
}
private fun swipeRight() {
controller.swipeRight()
}
}<file_sep>package kg.turar.arykbaev.sokoban.utils
const val DESKTOP_EMPTY = 0
const val DESKTOP_GAMER = 1
const val DESKTOP_WALL = 2
const val DESKTOP_BOX = 3
const val DESKTOP_POINT = 4
const val SWIPE_MIN_DISTANCE = 30
const val SWIPE_THRESHOLD_VELOCITY = 200
const val LEVEL_1 = 1
const val LEVEL_2 = 2
const val LEVEL_3 = 3
const val DIFFICULTY = "difficulty"
const val LEVEL = "level"
const val DESKTOP = "desktop"
const val DIFFICULTY_EASY = "Easy"
const val DIFFICULTY_MIDDLE = "Middle"
const val DIFFICULTY_HARD = "Hard"
<file_sep>package kg.turar.arykbaev.sokoban.model
import android.widget.Toast
import kg.turar.arykbaev.sokoban.utils.*
import kg.turar.arykbaev.sokoban.viewer.Viewer
class LevelServer : Level {
private val viewer: Viewer
private val listOfLevels: Array<Int>
private var currentLevelIndex: Int
constructor(viewer: Viewer) {
this.viewer = viewer
listOfLevels = arrayOf(LEVEL_1, LEVEL_2, LEVEL_3)
currentLevelIndex = 0
}
override fun getLevel(levelNumber: Int): Array<IntArray> {
currentLevelIndex = levelNumber - 1
when (levelNumber) {
LEVEL_1 -> return getDesktopFromServer(listOfLevels[0])
LEVEL_2 -> return getDesktopFromServer(listOfLevels[1])
LEVEL_3 -> return getDesktopFromServer(listOfLevels[2])
else -> return ArrayHelper.getDefaultDesktop()
}
}
private fun getDesktopFromServer(levelNumber: Int): Array<IntArray> {
val connectToServer = ConnectToServer(levelNumber.toString())
connectToServer.go()
val letter = connectToServer.getLetter()
if (letter.isEmpty()) {
Toast.makeText(viewer, "Server problems", Toast.LENGTH_SHORT).show()
return ArrayHelper.getDefaultDesktop()
}
return ArrayHelper.letterToArray(letter)
}
override fun nextLevel(): Array<IntArray> {
if (currentLevelIndex < listOfLevels.size - 1) {
currentLevelIndex++
}
return getLevel(currentLevelIndex + 1)
}
override fun getLevelsNumber(): Int {
return listOfLevels.size
}
override fun setLevelNumber(levelNumber: Int) {
currentLevelIndex = levelNumber - 1
}
override fun isLastLevel(): Boolean {
return listOfLevels.size - 1 <= currentLevelIndex
}
override fun getCurrentLevelNumber(): Int {
return currentLevelIndex + 1
}
override fun restartLevel(): Array<IntArray> {
return getLevel(currentLevelIndex + 1)
}
override fun getDifficulty(): String {
return DIFFICULTY_HARD
}
}<file_sep>package kg.turar.arykbaev.sokoban.canvas
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.view.View
import kg.turar.arykbaev.sokoban.R
import kg.turar.arykbaev.sokoban.model.Model
import kg.turar.arykbaev.sokoban.utils.*
import kg.turar.arykbaev.sokoban.viewer.Viewer
class CanvasSokoban : View {
private val model: Model
private val viewer: Viewer
private var desktop: Array<IntArray>
private var rowMaxSize: Int
private var columnMaxSize: Int
private var gamer: Drawable
private val wall: Drawable
private val point: Drawable
private val box: Drawable
private val empty: Drawable
private var isChanged: Boolean
private var cellSize: Int
private var x: Int
private var y: Int
private var startX: Int
private var startY: Int
constructor(viewer: Viewer, model: Model) : super(viewer) {
this.model = model
this.viewer = viewer
setBackgroundColor(viewer.getColor(R.color.backColor))
desktop = model.getDesktop()
rowMaxSize = model.getRowMaxSize()
columnMaxSize = model.getColumnMaxSize()
isChanged = false
cellSize = 0
x = 0
y = 0
startX = 0
startY = 0
gamer = viewer.getDrawable(R.drawable.gamer)!!
box = viewer.getDrawable(R.drawable.box)!!
wall = viewer.getDrawable(R.drawable.wall)!!
point = viewer.getDrawable(R.drawable.point)!!
empty = viewer.getDrawable(R.drawable.empty)!!
}
fun updateGamer(direction: Direction) {
when (direction) {
Direction.LEFT -> gamer = viewer.getDrawable(R.drawable.gamer_left)!!
Direction.RIGHT -> gamer = viewer.getDrawable(R.drawable.gamer_right)!!
Direction.UP -> gamer = viewer.getDrawable(R.drawable.gamer_up)!!
Direction.DOWN -> gamer = viewer.getDrawable(R.drawable.gamer)!!
else -> gamer = viewer.getDrawable(R.drawable.gamer)!!
}
}
fun updateDesktop() {
resetValue()
desktop = model.getDesktop()
}
private fun resetValue() {
isChanged = false
cellSize = 0
x = 0
y = 0
startX = 0
startY = 0
rowMaxSize = model.getRowMaxSize()
columnMaxSize = model.getColumnMaxSize()
}
override fun onDraw(canvas: Canvas) {
if (!isChanged) {
if (width < height) {
setDesktopResolutionPortrait()
} else {
setDesktopResolutionLandscape()
}
isChanged = true
}
x = startX
y = startY
for (row in desktop) {
for (i in row) {
when (i) {
DESKTOP_GAMER -> {
gamer.setBounds(x, y, x + cellSize, y + cellSize)
gamer.draw(canvas)
}
DESKTOP_WALL -> {
wall.setBounds(x, y, x + cellSize, y + cellSize)
wall.draw(canvas)
}
DESKTOP_BOX -> {
box.setBounds(x, y, x + cellSize, y + cellSize)
box.draw(canvas)
}
DESKTOP_POINT -> {
point.setBounds(x, y, x + cellSize, y + cellSize)
point.draw(canvas)
}
DESKTOP_EMPTY -> {
empty.setBounds(x, y, x + cellSize, y + cellSize)
empty.draw(canvas)
}
}
x += cellSize
}
x = startX
y += cellSize
}
}
private fun setDesktopResolutionPortrait() {
if (rowMaxSize != 0 && columnMaxSize != 0) {
if (height < (width / columnMaxSize) * rowMaxSize) {
cellSize = height / rowMaxSize
startX = (width / 2) - cellSize * (columnMaxSize / 2)
startY = 0
} else {
cellSize = width / columnMaxSize
startX = 0
startY = (height / 2) - cellSize * (rowMaxSize / 2)
}
}
}
private fun setDesktopResolutionLandscape() {
if (rowMaxSize != 0 && columnMaxSize != 0) {
if (width < (height / rowMaxSize) * columnMaxSize) {
cellSize = width / columnMaxSize
startX = 0
startY = (height / 2) - cellSize * (rowMaxSize / 2)
} else {
cellSize = height / rowMaxSize
startX = (width / 2) - cellSize * (columnMaxSize / 2)
startY = 0
}
}
}
fun update() {
invalidate()
}
}<file_sep>package kg.turar.arykbaev.sokoban.model
import android.view.Menu
import kg.turar.arykbaev.sokoban.R
import kg.turar.arykbaev.sokoban.utils.*
import kg.turar.arykbaev.sokoban.viewer.Viewer
class Model {
private val viewer: Viewer
private var desktop: Array<IntArray>
private var pointIndexX: IntArray
private var pointIndexY: IntArray
private var gamerPosIndexX: Int
private var gamerPosIndexY: Int
private var rowMaxSize: Int
private var columnMaxSize: Int
private var pointNumber: Int
private var levelNumber: Int
private var difficulty: String
private var level: Level
private lateinit var menu: Menu
constructor(viewer: Viewer) {
this.viewer = viewer
gamerPosIndexX = 0
gamerPosIndexY = 0
rowMaxSize = 0
columnMaxSize = 0
pointNumber = 0
levelNumber = LEVEL_1
difficulty = DIFFICULTY_EASY
pointIndexX = IntArray(0)
pointIndexY = IntArray(0)
level = LevelByteCode()
desktop = level.getLevel(LEVEL_1)
setGamerPositionAndCountPoint()
setPointsPosition()
}
fun setSavedDesktop(difficulty: String?, levelNumber: Int, letterDesktop: String?) {
this.difficulty = difficulty ?: DIFFICULTY_EASY
this.levelNumber = levelNumber
when (difficulty) {
DIFFICULTY_EASY -> level = LevelByteCode()
DIFFICULTY_MIDDLE -> level = LevelFile(viewer)
DIFFICULTY_HARD -> level = LevelServer(viewer)
else -> level = LevelByteCode()
}
desktop = if (letterDesktop != null) {
ArrayHelper.letterToArray(letterDesktop)
} else {
level.getLevel(levelNumber)
}
level.setLevelNumber(levelNumber)
updateDesktop()
}
private fun startLevel(levelNumber: Int) {
desktop = level.getLevel(levelNumber)
updateDesktop()
}
fun restartLevel() {
desktop = level.restartLevel()
updateDesktop()
}
fun nextLevel() {
desktop = level.nextLevel()
updateDesktop()
checkMenuItem(level.getCurrentLevelNumber())
viewer.setTitle("Level ${level.getCurrentLevelNumber()}")
}
private fun updateDesktop() {
resetValues()
setGamerPositionAndCountPoint()
setPointsPosition()
viewer.updateDesktop()
viewer.update()
}
private fun resetValues() {
gamerPosIndexX = 0
gamerPosIndexY = 0
rowMaxSize = 0
columnMaxSize = 0
pointNumber = 0
}
private fun setGamerPositionAndCountPoint() {
for (i in desktop.indices) {
for (j in desktop[i].indices) {
if (desktop[i][j] == DESKTOP_GAMER) {
gamerPosIndexX = i
gamerPosIndexY = j
}
if (desktop[i][j] == DESKTOP_POINT) {
pointNumber++
}
}
if (desktop[i].size > columnMaxSize) columnMaxSize = desktop[i].size
}
rowMaxSize = desktop.size
}
private fun setPointsPosition() {
pointIndexX = IntArray(pointNumber)
pointIndexY = IntArray(pointNumber)
var index = 0
for (i in desktop.indices) {
for (j in desktop[i].indices) {
if (desktop[i][j] == DESKTOP_POINT) {
pointIndexX[index] = i
pointIndexY[index] = j
index++
}
}
}
}
fun move(direction: Direction) {
if (isCollision(direction)) {
moveBox(direction)
}
moveGamer(direction)
checkPoint()
winChecker()
viewer.update()
}
private fun isCollision(direction: Direction): Boolean {
when (direction) {
Direction.LEFT -> if (desktop[gamerPosIndexX][gamerPosIndexY - 1] == DESKTOP_BOX) return true
Direction.UP -> if (desktop[gamerPosIndexX - 1][gamerPosIndexY] == DESKTOP_BOX) return true
Direction.RIGHT -> if (desktop[gamerPosIndexX][gamerPosIndexY + 1] == DESKTOP_BOX) return true
Direction.DOWN -> if (desktop[gamerPosIndexX + 1][gamerPosIndexY] == DESKTOP_BOX) return true
}
return false
}
private fun moveBox(direction: Direction) {
when (direction) {
Direction.LEFT -> moveBoxToLeft()
Direction.RIGHT -> moveBoxToRight()
Direction.UP -> moveBoxToUp()
Direction.DOWN -> moveBoxToDown()
}
}
private fun moveGamer(direction: Direction) {
when (direction) {
Direction.LEFT -> moveLeft()
Direction.RIGHT -> moveRight()
Direction.UP -> moveUp()
Direction.DOWN -> moveDown()
}
}
private fun checkPoint() {
for (i in pointIndexX.indices) {
if (desktop[pointIndexX[i]][pointIndexY[i]] == DESKTOP_EMPTY) {
desktop[pointIndexX[i]][pointIndexY[i]] = DESKTOP_POINT
}
}
}
private fun winChecker() {
for (i in pointIndexX.indices) {
if (desktop[pointIndexX[i]][pointIndexY[i]] != DESKTOP_BOX) {
return
}
}
if (!level.isLastLevel()) {
viewer.showWinDialog()
} else {
viewer.showLastLevelWinDialog()
}
}
private fun moveLeft() {
if (isNotWallOrBox(Direction.LEFT, gamerPosIndexX, gamerPosIndexY)) {
desktop[gamerPosIndexX][gamerPosIndexY] = DESKTOP_EMPTY
desktop[gamerPosIndexX][--gamerPosIndexY] = DESKTOP_GAMER
}
}
private fun moveRight() {
if (isNotWallOrBox(Direction.RIGHT, gamerPosIndexX, gamerPosIndexY)) {
desktop[gamerPosIndexX][gamerPosIndexY] = DESKTOP_EMPTY
desktop[gamerPosIndexX][++gamerPosIndexY] = DESKTOP_GAMER
}
}
private fun moveUp() {
if (isNotWallOrBox(Direction.UP, gamerPosIndexX, gamerPosIndexY)) {
desktop[gamerPosIndexX][gamerPosIndexY] = DESKTOP_EMPTY
desktop[--gamerPosIndexX][gamerPosIndexY] = DESKTOP_GAMER
}
}
private fun moveDown() {
if (isNotWallOrBox(Direction.DOWN, gamerPosIndexX, gamerPosIndexY)) {
desktop[gamerPosIndexX][gamerPosIndexY] = DESKTOP_EMPTY
desktop[++gamerPosIndexX][gamerPosIndexY] = DESKTOP_GAMER
}
}
private fun moveBoxToLeft() {
if (isNotWallOrBox(Direction.LEFT, gamerPosIndexX, gamerPosIndexY - 1)) {
desktop[gamerPosIndexX][gamerPosIndexY - 1] = DESKTOP_EMPTY
desktop[gamerPosIndexX][gamerPosIndexY - 2] = DESKTOP_BOX
}
}
private fun moveBoxToRight() {
if (isNotWallOrBox(Direction.RIGHT, gamerPosIndexX, gamerPosIndexY + 1)) {
desktop[gamerPosIndexX][gamerPosIndexY + 1] = DESKTOP_EMPTY
desktop[gamerPosIndexX][gamerPosIndexY + 2] = DESKTOP_BOX
}
}
private fun moveBoxToUp() {
if (isNotWallOrBox(Direction.UP, gamerPosIndexX - 1, gamerPosIndexY)) {
desktop[gamerPosIndexX - 1][gamerPosIndexY] = DESKTOP_EMPTY
desktop[gamerPosIndexX - 2][gamerPosIndexY] = DESKTOP_BOX
}
}
private fun moveBoxToDown() {
if (isNotWallOrBox(Direction.DOWN, gamerPosIndexX + 1, gamerPosIndexY)) {
desktop[gamerPosIndexX + 1][gamerPosIndexY] = DESKTOP_EMPTY
desktop[gamerPosIndexX + 2][gamerPosIndexY] = DESKTOP_BOX
}
}
private fun isNotWallOrBox(direction: Direction, x: Int, y: Int): Boolean {
when (direction) {
Direction.LEFT -> if (y < 1 || desktop[x][y - 1] == DESKTOP_WALL || desktop[x][y - 1] == DESKTOP_BOX) return false
Direction.UP -> if (x < 1 || desktop[x - 1][y] == DESKTOP_WALL || desktop[x - 1][y] == DESKTOP_BOX) return false
Direction.RIGHT -> if (y > columnMaxSize - 3 || desktop[x][y + 1] == DESKTOP_WALL || desktop[x][y + 1] == DESKTOP_BOX) return false
Direction.DOWN -> if (x > rowMaxSize - 3 || desktop[x + 1][y] == DESKTOP_WALL || desktop[x + 1][y] == DESKTOP_BOX) return false
}
return true
}
fun getDesktop(): Array<IntArray> {
return desktop
}
fun getColumnMaxSize(): Int {
return columnMaxSize
}
fun getRowMaxSize(): Int {
return rowMaxSize
}
fun setLevelByteCode() {
level = LevelByteCode()
startLevel(LEVEL_1)
levelNumber = LEVEL_1
setLevelListToMenu()
}
fun setLevelFile() {
level = LevelFile(viewer)
startLevel(LEVEL_1)
levelNumber = LEVEL_1
setLevelListToMenu()
}
fun setLevelServer() {
level = LevelServer(viewer)
startLevel(LEVEL_1)
levelNumber = LEVEL_1
setLevelListToMenu()
}
fun initMenu(menu: Menu) {
this.menu = menu
}
fun setLevelListToMenu() {
val subLevelMenu = menu.findItem(R.id.menu_level).subMenu
subLevelMenu.clear()
for (i in 1..level.getLevelsNumber()) {
subLevelMenu.add(0, i, Menu.NONE, "${level.getDifficulty()} level $i")
}
subLevelMenu.setGroupCheckable(0, true, true)
setCheckDifficultyItem()
checkMenuItem(levelNumber)
viewer.setTitle("Level $levelNumber")
}
private fun setCheckDifficultyItem() {
when (difficulty) {
DIFFICULTY_EASY -> checkMenuItem(R.id.menu_easy)
DIFFICULTY_MIDDLE -> checkMenuItem(R.id.menu_middle)
DIFFICULTY_HARD -> checkMenuItem(R.id.menu_hard)
else -> checkMenuItem(R.id.menu_easy)
}
}
fun setDifficulty(difficulty: String) {
this.difficulty = difficulty
this.levelNumber = LEVEL_1
}
fun setNewLevel(itemId: Int) {
startLevel(itemId)
viewer.setTitle("Level ${level.getCurrentLevelNumber()}")
}
fun checkMenuItem(id: Int) {
val item = menu.findItem(id)
item.isChecked = true
}
fun dismissDialog() {
viewer.dismissDialog()
}
fun updateGamer(direction: Direction) {
viewer.updateGamer(direction)
}
fun getDifficulty(): String {
return level.getDifficulty()
}
fun getLevelNumber(): Int {
return level.getCurrentLevelNumber()
}
fun getLetterDesktop(): String {
return ArrayHelper.arrayToLetter(desktop)
}
}<file_sep>package kg.turar.arykbaev.sokoban.model
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.Socket
class ConnectToServer : Thread {
private val message: String
private var letter: String
constructor(message: String) {
this.message = message
letter = ""
}
fun go() {
start()
try {
join(2000)
} catch (ie: InterruptedException) {
println(ie)
}
}
override fun run() {
send(message)
}
private fun send(number: String) {
try {
println("Start send.")
val socket = Socket("localhost", 8080)
val outputStream = ObjectOutputStream(socket.getOutputStream())
val inputStream = ObjectInputStream(socket.getInputStream())
outputStream.writeUTF(number)
outputStream.flush()
println("End send.")
val line: String = inputStream.readUTF()
letter = line
println(line)
println("--------------------------")
outputStream.close()
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
fun getLetter(): String {
return letter
}
} | e6451683ec97b9f09f5ae161976624127ad2b376 | [
"Kotlin",
"Gradle"
] | 14 | Kotlin | turararykbaev/Sokoban | 85e24cd5ddd44330b47e80b209b7a1e3527665c8 | ce65df9a7b49822820b9f4f782766da03fe06512 |
refs/heads/master | <file_sep># yarn dev
FROM node:10.23.0
# make the 'app' folder the current working directory
WORKDIR /app/
# copy project files and folders to the current working directory (i.e. 'app' folder)
COPY . .
# expose port 3000 to the host
EXPOSE 3000
CMD ["sh", "start_dev.sh"]<file_sep>#!/bin/bash
# https://docs.npmjs.com/cli/cache
npm cache verify
# install project dependencies
npm install
npm install --save nuxt
# generate static
# npm run generate
# run the development server
npm run dev | cc337e5e8f4d9a2c18f53520055df1a839b58362 | [
"Dockerfile",
"Shell"
] | 2 | Dockerfile | liubomyrgavryliv/powercat | 6a21beab8f2753fc194cd9a2ca932d25cc0f8688 | 8176fa10513511c1c278509a193ea56e333b2427 |
refs/heads/main | <repo_name>jameesjohn/vanilla-router<file_sep>/src/router.js
class RouterException extends Error {
constructor(message) {
super();
this.message = message;
this.name = 'Router Exception';
}
}
/**
*
* @param {{routes: {path: string, element: HTMLElement, name: string, elementPath: string}[], rootUrl: string, entry: HTMLElement, mode: string}}
*/
function Router({ routes, entry, mode, rootUrl = '/' }) {
// Prune the root URL. Rules: The Root URL should start with a '/' but not end with a '/'.
if (!rootUrl.startsWith('/')) rootUrl = `/${rootUrl}`;
if (rootUrl.endsWith('/')) rootUrl = rootUrl.substring(0, rootUrl.length - 1);
rootUrl = location.origin + rootUrl;
const ROUTER_NAME_ATTRIBUTE = 'data-router-name';
const URL_CHANGE_EVENT = 'urlchange';
let currentRouteEntry = null;
if (!Array.isArray(routes) || routes.length === 0) {
throw new RouterException('Invalid routes array provided');
}
if (!entry || !(entry instanceof HTMLElement)) {
throw new RouterException(
'Invalid entry point for app. Entry point must be a valid HTML element'
);
}
if (!mode) {
mode = 'hash';
}
function inHistoryMode() {
return mode === 'history';
}
function setupListeners() {
entry.addEventListener(URL_CHANGE_EVENT, handleUrlChange);
addEventListener('popstate', handlePopState);
}
/**
* Handle initial setup and bootstrapping of the page.
*/
function handleInitialLoad() {
currentRouteEntry = getCurrentLocationRoute();
// Empty the page initially.
entry.innerHTML = '';
fetchAndShowElement(currentRouteEntry);
// showElement(currentRouteEntry.element);
}
/**
*
* @param {{path: string, element: HTMLElement|undefined, name: string, elementPath: string|undefined}} routeEntry
*/
function fetchAndShowElement(routeEntry) {
if (routeEntry.element) {
showElement(routeEntry.element);
return;
}
if (routeEntry.elementPath) {
if (!routeEntry.elementPath.startsWith('/'))
routeEntry.elementPath = `/${routeEntry.elementPath}`;
fetch(`${rootUrl}${routeEntry.elementPath}`)
.then((response) => response.text())
.then((response) => {
const parser = new DOMParser();
const newDocument = parser.parseFromString(response, 'text/html');
mapLinksToRoutes(newDocument);
// Store it here so we don't fetch it again in the future.
routeEntry.element = newDocument.body.firstElementChild;
showElement(routeEntry.element);
});
return;
}
throw new RouterException(
'Route entry must have either an element or a path to an element'
);
}
/**
* Handle native pop state triggered by the browser.
* @param {PopStateEvent} evt
*/
function handlePopState(evt) {
evt.preventDefault();
entry.dispatchEvent(
new CustomEvent(URL_CHANGE_EVENT, {
detail: {
current: getCurrentLocationRoute(),
previous: currentRouteEntry,
},
})
);
currentRouteEntry = getCurrentLocationRoute();
}
/**
* Go through all the links and map them to appropriate routes.
* @param {Document} document
*/
function mapLinksToRoutes(document) {
const linksToMap = document.querySelectorAll(`a[${ROUTER_NAME_ATTRIBUTE}]`);
linksToMap.forEach((linkElement) => {
const routeName = linkElement.getAttribute(ROUTER_NAME_ATTRIBUTE);
const routeEntry = routes.find((route) => route.name === routeName);
if (!routeEntry) {
throw new RouterException(`No route found with name: "${routeName}"`);
}
linkElement.href = getRouteHref(routeEntry);
linkElement.addEventListener('click', (e) => {
e.preventDefault();
handleLinkClick(linkElement, routeEntry);
});
});
}
/**
*
* @param {HTMLAnchorElement} linkElement
* @param {{path: string, element: HTMLElement, name: string, elementPath: string}} routeEntry
*/
function handleLinkClick(linkElement, routeEntry) {
pushState(routeEntry, linkElement.href);
}
/**
* Get the href property for the route entry.
* @param {{path: string, element: HTMLElement, name: string, elementPath: string}} routeEntry
*/
function getRouteHref(routeEntry) {
if (inHistoryMode()) {
return rootUrl + routeEntry.path;
}
return `#${routeEntry.path.substring(1)}`;
}
/**
* Wrapper over history.pushState. This function dispatches the
* URL_CHANGE_EVENT, and updates the current route entry before
* calling history.pushState appropriately.
* @param {{path: string, element: HTMLElement, name: string, elementPath: string}} routeEntry
* @param {string} url
*/
function pushState(routeEntry, url) {
const previousRouteEntry = getCurrentLocationRoute();
if (previousRouteEntry === routeEntry) {
// User clicked on a URL to the current location.
return;
}
entry.dispatchEvent(
new CustomEvent(URL_CHANGE_EVENT, {
detail: {
current: routeEntry,
previous: previousRouteEntry,
},
})
);
currentRouteEntry = routeEntry;
history.pushState({}, routeEntry.name, url);
}
/**
* Handle the URL change event. This function displays the next page
* and hides the page being left.
* @param {CustomEvent} evt
*/
function handleUrlChange(evt) {
fetchAndShowElement(evt.detail.current);
const previouslyRenderedElement = evt.detail.previous.element;
if (previouslyRenderedElement) {
hideElement(previouslyRenderedElement);
}
}
/**
* Show a specific element.
* @param {HTMLElement} element
*/
function showElement(element) {
entry.appendChild(element);
}
/**
* Hide a specific element.
* @param {HTMLElement} element
*/
function hideElement(element) {
entry.removeChild(element);
}
/**
* Get the current route which the user is on.
*/
function getCurrentPath() {
if (inHistoryMode()) {
const currentPathname = location.pathname;
const rootPathname = new URL(rootUrl).pathname;
const path = currentPathname.substring(rootPathname.length);
return path;
}
return location.hash || '#';
}
/**
* Get the route associated with a particular path.
* @param {string} path
*/
function getRouteEntryFromPath(path) {
if (path.startsWith('#')) {
path = `/${path.substring(1)}`;
}
return routes.find((route) => route.path === path);
}
function getCurrentLocationRoute() {
return getRouteEntryFromPath(getCurrentPath());
}
handleInitialLoad();
mapLinksToRoutes(document);
setupListeners();
/**
* Go to a specific named route.
* @param {string} name - Name of the route to visit.
*/
this.visit = function (routeName) {
const route = routes.find(({ name }) => name === routeName);
if (!route) {
throw new RouterException(
`Unable to find route with name: '${routeName}'`
);
}
pushState(route, getRouteHref(route));
};
/**
* Go back one step in the route history.
*/
this.back = function () {
history.back();
};
/**
* Go to a specific point in history.
* @param {Number} number
*/
this.go = function (number) {
const validatedNumber = Number(number);
if (Number.isNaN(validatedNumber)) {
throw new RouterException(
`Parameter passed must be a number, ${typeof number} received.`
);
}
history.go(validatedNumber);
};
}
<file_sep>/README.md
# Vanilla Router
This is a simple router that can be used in vanilla javascript projects. If you are building a simple website without frameworks and you want to get SPA (Single Page Application) routing similar to what is available in Vue or React, you'd probably want to check this out.
## Usage
The router is initialized by creating a new Router object.
```javascript
const router = new Router({
routes: [
{ path: '/', elementPath: '/homeComponent.html', name: 'home' },
{ path: '/about', elementPath: '/aboutComponent.html', name: 'about' },
],
entry: document.querySelector('main'),
mode: 'history',
rootUrl: 'examples/multi_file_components/',
});
```
And in your HTML, you can create links to each page using the data-router attributes.
```html
<a href="" data-router-name="first">First Page</a>
<a href="" data-router-name="second">Second Page</a>
<a href="" data-router-name="third">Third Page</a>
```
## Config Object
When instantiating the router class, you are required to provide a configuration object.
The object must contain the following properties.
1. routes - This is an array of routes to be parsed by the router.
2. entry - The entry point of the router. This is where all the routed components would be mounted.
3. mode - History or hash. Specifies if the url should be hashed or not. Defaults to hash.
4. rootUrl - The base URL for the page. Defaults to the page origin if not specified.
### Defining Routes
Routes are perhaps the most important piece of the config object.
Each route requires the following properties.
- path: Path specifies the URL for the route entry. This property is required as we would not be able to modify the URL without it.
- element: Element is a reference to the element to be routed. This property is not required and should only be used if the components to be routed are contained in one page as opposed to single HTML files.
- elementPath: This property is used when components are single filed. It specifies the location of the component with relative to the rootURL.
- name: This property is used to name the routes. It is required and is also used in the HTML when specifying route links.
## Examples
Examples can be found in the `/examples` directory.
<file_sep>/examples/multi_file_components/index.js
const router = new Router({
routes: [
{ path: '/', elementPath: '/homeComponent.html', name: 'home' },
{ path: '/about', elementPath: '/aboutComponent.html', name: 'about' },
],
entry: document.querySelector('main'),
mode: 'history',
rootUrl: 'examples/multi_file_components/',
});
| b7c7f5a3cf46ee9e9d860ee485f6097d3cc49a84 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jameesjohn/vanilla-router | 13000fd356148e702d051d6e3820121fbb9a676e | d90fd8f7ab367f98d45cf9da1df95dfeff279166 |
refs/heads/master | <file_sep>Moesort
=======
Sort items by stroke count or Bopomofo (Zhuyin) sequence.
Powered by [MoeDict](https://moedict.tw) API.
License
-------
BSD License.
<file_sep>import requests
cache = {}
def get_definition(char):
if char not in cache:
response = requests.get('https://www.moedict.tw/uni/{}'.format(char))
cache[char] = response.json()
return cache[char]
def radical_sort(arr):
def radical_key(chars):
buf = ''
for char in chars:
defs = get_definition(char)
buf += '{:02d}'.format(defs.get('stroke_count', 0))
return buf
return sorted(arr, key=radical_key)
def bopomofo_sort(arr):
def bopomofo_key(chars):
buf = ''
for char in chars:
defs = get_definition(char)
if 'heteronyms' in defs:
buf += defs['heteronyms'][0]['bopomofo'].ljust(4)
else:
buf += ' ' * 4
return buf
return sorted(arr, key=bopomofo_key)
| 6ce62bafd6277eee3b29d79d3204e03d7942fcef | [
"Markdown",
"Python"
] | 2 | Markdown | rschiang/moesort | 3a33f9b50c3b34ce890bb1cab1816a85ecf74b99 | b791bb43a678791ffbad6661fb3006dca6aacb99 |
refs/heads/master | <repo_name>EvgenyGusarov/django-fias<file_sep>/fias/fields/__init__.py
#coding: utf-8
from __future__ import unicode_literals, absolute_import
from .uuid import UUIDField
from .address import AddressField, ChainedAreaField
<file_sep>/fias/urls.py
#coding: utf-8
from __future__ import unicode_literals, absolute_import
from django.conf.urls import patterns, url
from fias.views import (SuggestAddressViewStepByStep,
SuggestBySphinx,
GetAreasListView)
urlpatterns = patterns('',
url(r'^suggest_sbs', SuggestAddressViewStepByStep.as_view(), name='suggest_step_by_step'),
url(r'^suggest_sphinx', SuggestBySphinx.as_view(), name='suggest_by_sphinx'),
url(r'^get_areas_list', GetAreasListView.as_view(), name='get_areas_list'),
)
| f11552ac019acd3f96ddd445da69b19db23e1777 | [
"Python"
] | 2 | Python | EvgenyGusarov/django-fias | eef17265a8ec6721a0420728d40e797fee051338 | 5752ce415771f368dcfc5373cba7d95f1af1e197 |
refs/heads/master | <file_sep>self.__precacheManifest = [
{
"revision": "6cdb9b0faa6a7aafebfe",
"url": "/static/css/main.c573bd15.chunk.css"
},
{
"revision": "6cdb9b0faa6a7aafebfe",
"url": "/static/js/main.6cdb9b0f.chunk.js"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.42ac5946.js"
},
{
"revision": "21db27ba221c38008547",
"url": "/static/css/2.b9982b2f.chunk.css"
},
{
"revision": "21db27ba221c38008547",
"url": "/static/js/2.21db27ba.chunk.js"
},
{
"revision": "60c866748ff15f5b347fdba64596b1b1",
"url": "/static/media/open-sans-latin-300.60c86674.woff2"
},
{
"revision": "521d17bc9f3526c690e8ada6eee55bec",
"url": "/static/media/open-sans-latin-300.521d17bc.woff"
},
{
"revision": "8a648ff38ded89ea15916e84529d62d3",
"url": "/static/media/open-sans-latin-300italic.8a648ff3.woff"
},
{
"revision": "db70d0b9cb27ada1a260a2b35e756b8b",
"url": "/static/media/open-sans-latin-400italic.db70d0b9.woff"
},
{
"revision": "cffb686d7d2f4682df8342bd4d276e09",
"url": "/static/media/open-sans-latin-400.cffb686d.woff2"
},
{
"revision": "bf2d0783515b7d75c35bde69e01b3135",
"url": "/static/media/open-sans-latin-400.bf2d0783.woff"
},
{
"revision": "987032ea5d57c93d8da215678eae3b86",
"url": "/static/media/open-sans-latin-400italic.987032ea.woff2"
},
{
"revision": "06bbd3188b34820cd83a0e0b3d0a6f57",
"url": "/static/media/open-sans-latin-300italic.06bbd318.woff2"
},
{
"revision": "1cd5320f8937d337b61d5117cf9d7b28",
"url": "/static/media/open-sans-latin-600.1cd5320f.woff"
},
{
"revision": "223a277bd88d8a90c8cdf24cda0ad5f5",
"url": "/static/media/open-sans-latin-600.223a277b.woff2"
},
{
"revision": "d08c09f2f169f4a6edbcf8b8d1636cb4",
"url": "/static/media/open-sans-latin-700.d08c09f2.woff2"
},
{
"revision": "4950a7205f0b5cefe41fc03ac346e236",
"url": "/static/media/open-sans-latin-600italic.4950a720.woff2"
},
{
"revision": "623e3205570002af47fc2b88f9335d19",
"url": "/static/media/open-sans-latin-700.623e3205.woff"
},
{
"revision": "c02f5da6e82e1efe0b45841bfd49ce37",
"url": "/static/media/open-sans-latin-700italic.c02f5da6.woff2"
},
{
"revision": "6b3973ffe02bb6a8be0f8453506ec032",
"url": "/static/media/open-sans-latin-800italic.6b3973ff.woff2"
},
{
"revision": "72e19cbb0e38c6773a<PASSWORD>",
"url": "/static/media/open-sans-latin-700italic.72e19cbb.woff"
},
{
"revision": "aaeffaf205b9bbb09920089a14dbe9e8",
"url": "/static/media/open-sans-latin-800.aaeffaf2.woff2"
},
{
"revision": "79b58175343190550489efe46a7f1138",
"url": "/static/media/open-sans-latin-800italic.79b58175.woff"
},
{
"revision": "c6aa0c4a601fb6ac66f8253fa594dff5",
"url": "/static/media/open-sans-latin-800.c6aa0c4a.woff"
},
{
"revision": "318ea1ada4102c0704a0637228dcad03",
"url": "/static/media/open-sans-latin-600italic.318ea1ad.woff"
},
{
"revision": "a50c381443e6993188ed9cc4b6806866",
"url": "/static/media/merriweather-latin-300.a50c3814.woff2"
},
{
"revision": "9deeb422b65afb1daacc039296bb3640",
"url": "/static/media/merriweather-latin-300italic.9deeb422.woff"
},
{
"revision": "2c73b119ad85e697123658b8a091ff83",
"url": "/static/media/merriweather-latin-300.2c73b119.woff"
},
{
"revision": "f936cb550d4dcd769f75c453207ac5e6",
"url": "/static/media/merriweather-latin-400.f936cb55.woff2"
},
{
"revision": "5c9a23d08e2c851e5a25795b940acd4f",
"url": "/static/media/merriweather-latin-400italic.5c9a23d0.woff2"
},
{
"revision": "ab0616e6d856817eff54eb8c5e1664e4",
"url": "/static/media/merriweather-latin-400.ab0616e6.woff"
},
{
"revision": "0ab4b54f3b1e8b14cf755970fde8ce35",
"url": "/static/media/merriweather-latin-400italic.0ab4b54f.woff"
},
{
"revision": "1636f13a52ca3f0eb8784c9c57f62082",
"url": "/static/media/merriweather-latin-700.1636f13a.woff2"
},
{
"revision": "8b0db67123584893c6591accbc51640c",
"url": "/static/media/merriweather-latin-700italic.8b0db671.woff2"
},
{
"revision": "a<PASSWORD>",
"url": "/static/media/merriweather-latin-900italic.a26a8168.woff2"
},
{
"revision": "cc<PASSWORD>",
"url": "/static/media/merriweather-latin-700.cc673c94.woff"
},
{
"revision": "46631a9aab93dec3ed34f429dd1a5646",
"url": "/static/media/merriweather-latin-900.46631a9a.woff2"
},
{
"revision": "db42a3f34378e69ef5aebb6717f1f33e",
"url": "/static/media/merriweather-latin-900italic.db42a3f3.woff"
},
{
"revision": "513649f5b9ba4675cff15cf3f7ad4f2a",
"url": "/static/media/merriweather-latin-700italic.513649f5.woff"
},
{
"revision": "a0528570caa2c785891308ce604d8db7",
"url": "/static/media/merriweather-latin-900.a0528570.woff"
},
{
"revision": "bd410cbf8c272acd<PASSWORD>",
"url": "/static/media/merriweather-latin-300italic.bd410cbf.woff2"
},
{
"revision": "7a3446294cc<PASSWORD>462f2c<PASSWORD>",
"url": "/index.html"
}
];<file_sep># WikiLite
The current view of Wikipedia on browser is very eye-straining. So I thought why not make it look minimalistic? So I made this app from scratch. WikiLite is made wth React.js & Tailwind CSS. Wikilite utilizes public Wikipedia API to fetch data from Wiki and presents it on the viewport. Nowadays, due to COVID19 crisis, we, specially students like me, are doing our studies from home, to be honest if we get stuck at any point, we prefer Wikipedia. But when we try to surf any article or question/answer on Wikipedia, the default theme look is not very suitable for going through & moreover makes us feel bored. So, Wikilite is the perfect solution for Wikipedia for mobile users. This app is still in development as I will be making this React app into a React-SPWA. Wikilite is hosted on Netlify for now. Fork my repo & free to drop a star if you ❤️ it :)
##### Inspiration
* https://www.pinterest.com/pin/719872321667377276/
* https://www.behance.net/gallery/75870375/Wikipedia-Imagination
| f0bf969a65e99c64f0cadc18987940ac0669f123 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Neilblaze/WikiLite | 00cbe14f987359fc70644c782e10f3034314c08b | b9f85c431a79b3bf6aca9abaa35d34e4ca38418c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.