branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>928902646/Gymnast<file_sep>/app/src/main/java/com/gymnast/view/home/view/GuideActivity.java package com.gymnast.view.home.view; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.home.HomeActivity; import com.gymnast.view.home.adapter.ViewPagerAdapter; import java.util.ArrayList; /** * Created by Cymbi on 2016/9/7. */ public class GuideActivity extends ImmersiveActivity implements ViewPager.OnPageChangeListener { private ViewPager vp; private TextView boot_in; private ArrayList<View> views; private ViewPagerAdapter vpAdapter; private ImageView[] dots; private int[] ids = { R.id.iv1, R.id.iv2, R.id.iv3 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.guide); initViews(); initDots(); } private void initViews() { LayoutInflater inflater = LayoutInflater.from(this); views = new ArrayList<View>(); views.add(inflater.inflate(R.layout.activity_boot_a, null)); views.add(inflater.inflate(R.layout.activity_boot_b, null)); views.add(inflater.inflate(R.layout.activity_boot_c, null)); vpAdapter = new ViewPagerAdapter(views, this); vp = (ViewPager) findViewById(R.id.viewpager); vp.setAdapter(vpAdapter); boot_in = (TextView) views.get(2).findViewById(R.id.boot_in); boot_in.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(GuideActivity.this, HomeActivity.class); startActivity(i); finish(); } }); vp.setOnPageChangeListener(this); } private void initDots() { dots = new ImageView[views.size()]; for (int i = 0; i < views.size(); i++) { dots[i] = (ImageView) findViewById(ids[i]); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { for (int i = 0; i < ids.length; i++) { if (position == i) { dots[i].setImageResource(R.mipmap.login_point_selected); } else { dots[i].setImageResource(R.mipmap.login_point); } } } @Override public void onPageScrollStateChanged(int state) { } } <file_sep>/app/src/main/java/com/gymnast/utils/InputWatcherUtil.java package com.gymnast.utils; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Created by zzqybyb19860112 on 2016/9/4. */ public class InputWatcherUtil implements TextWatcher { private Button mBtnClear; private EditText mEtContainer ; private TextView tvConfirm ; private TextView tvCancel ; /** * * @param btnClear 清空按钮 可以是button的子类 * @param etContainer edittext */ public InputWatcherUtil(Button btnClear, EditText etContainer, TextView tvConfirm, TextView tvCancel) { if (btnClear == null || etContainer == null||tvConfirm==null||tvCancel==null) { throw new IllegalArgumentException("请确保btnClear和etContainer不为空"); } this.mBtnClear = btnClear; this.mEtContainer = etContainer; this.tvConfirm=tvConfirm; this.tvCancel=tvCancel; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!TextUtils.isEmpty(s) && !s.toString().trim().equals("")) { if (mBtnClear != null) { mBtnClear.setVisibility(View.VISIBLE); tvConfirm.setVisibility(View.VISIBLE); tvCancel.setVisibility(View.GONE); mBtnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mEtContainer != null) { mEtContainer.setText(""); mBtnClear.setVisibility(View.GONE); tvConfirm.setVisibility(View.GONE); tvCancel.setVisibility(View.VISIBLE); } } }); } } else { if (mBtnClear != null) { mBtnClear.setVisibility(View.GONE); tvConfirm.setVisibility(View.GONE); tvCancel.setVisibility(View.VISIBLE); } } } @Override public void afterTextChanged(Editable s) { } } <file_sep>/app/src/main/java/com/gymnast/view/picker/SlideDateTimeListener.java package com.gymnast.view.picker; import java.util.Date; public abstract class SlideDateTimeListener{ public abstract void onDateTimeSet(Date date); public void onDateTimeCancel() { } } <file_sep>/app/src/main/java/com/gymnast/data/hotinfo/HotInfoServiceImpl.java package com.gymnast.data.hotinfo; import com.gymnast.App; import com.gymnast.data.net.HotInfoApi; import com.gymnast.data.net.Result; import com.gymnast.utils.RetrofitUtil; import rx.Observable; /** * Created by fldyown on 16/6/30. */ public class HotInfoServiceImpl implements HotInfoService { HotInfoApi api; public HotInfoServiceImpl() { api = RetrofitUtil.createApi(App.getContext(), HotInfoApi.class); } @Override public Observable<Result<HotInfoData>> getAllHotInfo() { return api.getAllHotInfo(); } } <file_sep>/app/src/main/java/com/gymnast/view/personal/contact/PersonFenSiActivity.java package com.gymnast.view.personal.contact; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.Handler; import android.os.Message; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.GetUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.personal.activity.PersonalOtherHomeActivity; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class PersonFenSiActivity extends ImmersiveActivity implements SwipeRefreshLayout.OnRefreshListener{ private ListView lvRightLetters; private SideBar sideBar; private TextView dialog; private FansAdapter adapter; private ClearEditText ceFilterEdit; private String token; private String id; /** * 汉字转换成拼音的类 */ private CharacterParser characterParser; private List<SortModel> SourceDateList; /** * 根据拼音来排列ListView里面的数据类 */ private PinyinComparator pinyinComparator; private ImageView ivFenSiBack; public static final int HANDLE_DATAS=1; ArrayList<Bitmap> bitmaps=new ArrayList<>(); ArrayList<String> nickNames=new ArrayList<>(); ArrayList<String> avatars=new ArrayList<>(); ArrayList<Integer> UserIdList=new ArrayList<>(); private SwipeRefreshLayout swipeRefresh; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANDLE_DATAS: initView(); adapter.notifyDataSetChanged(); swipeRefresh.setRefreshing(false); break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_attention); getInfo(); setView(); /** * 解决listview和swipeRefreshLayout滑动冲突问题 */ lvRightLetters.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { boolean enable = false; if(lvRightLetters != null && lvRightLetters.getChildCount() > 0){ // check if the first item of the list is visible boolean firstItemVisible = lvRightLetters.getFirstVisiblePosition() == 0; // check if the top of the first item is visible boolean topOfFirstItemVisible = lvRightLetters.getChildAt(0).getTop() == 0; // enabling or disabling the refresh layout enable = firstItemVisible && topOfFirstItemVisible; } swipeRefresh.setEnabled(enable); } }); getData(); } private void getData() { new Thread(new Runnable() { @Override public void run() { String uri= API.BASE_URL+"/v1/my/attention/to"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("accountId",id); String result= GetUtil.sendGetMessage(uri,params); try { JSONObject object=new JSONObject(result); JSONArray data=object.getJSONArray("data"); for (int i=0;i<data.length();i++){ JSONObject obj=data.getJSONObject(i); String nickname=obj.getString("nickname"); String avatar=obj.getString("avatar"); int id=obj.getInt("id"); avatars.add(API.IMAGE_URL+avatar); nickNames.add(nickname); UserIdList.add(id); } for (int i=0;i<avatars.size();i++){ Bitmap bitmap= PicUtil.getImageBitmap(avatars.get(i)); bitmaps.add(bitmap); } handler.sendEmptyMessage(HANDLE_DATAS); } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void getInfo() { SharedPreferences share = getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token=share.getString("Token",""); id = share.getString("UserId",""); } private void setView() { sideBar = (SideBar) findViewById(R.id.sidrbar); dialog = (TextView) findViewById(R.id.tvDialog); lvRightLetters = (ListView) findViewById(R.id.lvRightLetters); ivFenSiBack = (ImageView) findViewById(R.id.ivFenSiBack); ceFilterEdit = (ClearEditText) findViewById(R.id.ceFilterEdit); swipeRefresh=(SwipeRefreshLayout)findViewById(R.id.swipeRefresh); RefreshUtil.refresh(swipeRefresh,this); swipeRefresh.setOnRefreshListener(this); } public void initView() { // 实例化汉字转拼音类 characterParser = CharacterParser.getInstance(); pinyinComparator = new PinyinComparator(); sideBar.setTextView(dialog); // 设置右侧触摸监听 sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() { @Override public void onTouchingLetterChanged(String s) { // 该字母首次出现的位置 int position = adapter.getPositionForSection(s.charAt(0)); if (position != -1) { lvRightLetters.setSelection(position); } } }); lvRightLetters.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i=new Intent(PersonFenSiActivity.this, PersonalOtherHomeActivity.class); SortModel sortModel=SourceDateList.get(position); i.putExtra("UserID",sortModel.getId()); startActivity(i); } }); SourceDateList = filledData(nickNames); // 根据a-z进行排序源数据 Collections.sort(SourceDateList, pinyinComparator); adapter = new FansAdapter(this, SourceDateList, FansAdapter.TYPE_CONCERN); lvRightLetters.setAdapter(adapter); // 根据输入框输入值的改变来过滤搜索 ceFilterEdit.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // 当输入框里面的值为空,更新为原来的列表,否则为过滤数据列表 filterData(s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); ivFenSiBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /** * 为ListView填充数据 * * @return */ private List<SortModel> filledData(ArrayList<String> nickNames) { List<SortModel> mSortList = new ArrayList<SortModel>(); for (int i = 0; i < nickNames.size(); i++) { SortModel sortModel = new SortModel(); sortModel.setSmallPhoto(bitmaps.get(i)); sortModel.setName(nickNames.get(i)); sortModel.setId(UserIdList.get(i)); // 汉字转换成拼音 String pinyin = characterParser.getSelling(nickNames.get(i)); String sortString = pinyin.substring(0, 1).toUpperCase(); // 正则表达式,判断首字母是否是英文字母 if (sortString.matches("[A-Z]")) { sortModel.setSortLetters(sortString.toUpperCase()); } else { sortModel.setSortLetters("#"); } mSortList.add(sortModel); } return mSortList; } /** * 根据输入框中的值来过滤数据并更新ListView * * @param filterStr */ private void filterData(String filterStr) { List<SortModel> filterDateList = new ArrayList<SortModel>(); if (TextUtils.isEmpty(filterStr)) { filterDateList = SourceDateList; } else { filterDateList.clear(); for (SortModel sortModel : SourceDateList) { String name = sortModel.getName(); if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) { filterDateList.add(sortModel); } } } // 根据a-z进行排序 Collections.sort(filterDateList, pinyinComparator); adapter.updateListView(filterDateList); } @Override public void onRefresh() { if(SourceDateList.size()!=0){ SourceDateList.clear(); initView(); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 swipeRefresh.setRefreshing(false); } }, 1000); }else {} } }<file_sep>/app/src/main/java/com/gymnast/MyReceiver.java package com.gymnast; import android.app.Activity; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AlertDialog; import android.util.Log; import android.widget.Toast; import com.gymnast.data.net.API; import com.gymnast.view.home.HomeActivity; import com.gymnast.view.live.activity.CloseLiveActivity; import com.gymnast.view.live.activity.LiveActivity; public class MyReceiver extends BroadcastReceiver { private NetworkInfo wifiNetInfo; private NetworkInfo mobileNetInfo; public static Dialog dialog; public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { final Activity activity=App.nowActivity; String action=intent.getAction(); dialog = new AlertDialog.Builder(activity) .setTitle("网络设置") .setIcon(R.mipmap.timg) .setMessage("请您选择是否设置您的网络?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent=new Intent("android.settings.WIFI_SETTINGS"); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } }).setNeutralButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).create(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)){ Log.i("tag", "网络状态发生改变"); ConnectivityManager manager= (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); mobileNetInfo=manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); wifiNetInfo=manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!mobileNetInfo.isConnected() && !wifiNetInfo.isConnected()) { Toast.makeText(activity, "亲,网络有点不给力呢!", Toast.LENGTH_SHORT).show(); App.isNetStateOK=false; dialog.show(); }else { if(manager.getActiveNetworkInfo().equals(mobileNetInfo)){ Toast.makeText(activity,"当前网络为数据连接,请注意您的流量使用情况!!!",Toast.LENGTH_SHORT).show(); App.isNetStateOK=true; }else if (manager.getActiveNetworkInfo().equals(wifiNetInfo)){ Toast.makeText(activity,"当前网络为WiFi连接!",Toast.LENGTH_SHORT).show(); App.isNetStateOK=true; } dialog.dismiss(); } } } } <file_sep>/app/src/main/java/com/gymnast/view/live/adapter/MessageAdapter.java package com.gymnast.view.live.adapter; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.gymnast.R; import com.gymnast.data.hotinfo.LiveMessage; import com.gymnast.data.net.API; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.personal.activity.ImageActivity; import com.squareup.picasso.Picasso; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by Administrator on 2016/7/29. */ public class MessageAdapter extends RecyclerView.Adapter { Context context; ArrayList<LiveMessage> messageList; public MessageAdapter(Context context,ArrayList<LiveMessage> messageList){ this.context=context; if (messageList.size()==0){ this.messageList=new ArrayList<>(); }else { this.messageList=messageList; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View viewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyleview_recent_activity_message, null); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); viewItem.setLayoutParams(lp); return new MessageViewHolder(viewItem); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { MessageViewHolder viewHolder= (MessageViewHolder) holder; final LiveMessage message=messageList.get(position); Picasso.with(context).load(message.getIconUrl()).into(viewHolder.civPhoto); String imageUrl=message.getPictureUrl().trim(); String imageUrlFinal=""; if (!imageUrl.contains("null")&&!imageUrl.equals(API.IMAGE_URL)&&!imageUrl.equals("")){ viewHolder.ivPic.setVisibility(View.VISIBLE); viewHolder.tvContent.setVisibility(View.GONE); if (imageUrl.contains("easemob")){ imageUrlFinal=imageUrl; }else { imageUrlFinal= PicUtil.getImageUrlDetail(context,message.getPictureUrl(), 328, 122); } PicassoUtil.handlePic(context, imageUrlFinal, viewHolder.ivPic, 328, 122); final String finalImageUrlFinal = imageUrlFinal; viewHolder.ivPic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(context, ImageActivity.class); i.putExtra("IMAGE", finalImageUrlFinal); context.startActivity(i); } }); }else { viewHolder.ivPic.setVisibility(View.GONE); viewHolder.tvContent.setVisibility(View.VISIBLE); viewHolder.tvContent.setText(message.getContent()); if (position==0){ viewHolder.tvContent.setTextColor(Color.RED); }else { viewHolder.tvContent.setTextColor(Color.parseColor("#666666")); } } viewHolder.tvTimeUtilNow.setText(message.getTimeUntilNow()); viewHolder.tvTimeUtilNow.setBackgroundColor(context.getResources().getColor(R.color.common_bg)); viewHolder.tvTimeUtilNow.setTextColor(context.getResources().getColor(R.color.day_edit_hit_color)); } @Override public int getItemCount() { return messageList.size(); } class MessageViewHolder extends RecyclerView.ViewHolder{ CircleImageView civPhoto; ImageView ivPic; TextView tvTimeUtilNow,tvContent; public MessageViewHolder(View itemView) { super(itemView); civPhoto= (CircleImageView) itemView.findViewById(R.id.civPhoto); ivPic= (ImageView) itemView.findViewById(R.id.ivPic); tvTimeUtilNow= (TextView) itemView.findViewById(R.id.tvTimeUtilNow); tvContent= (TextView) itemView.findViewById(R.id.tvContent); } } } <file_sep>/app/src/main/java/com/gymnast/view/picker/SlideDateTimePicker.java package com.gymnast.view.picker; import java.util.Date; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; public class SlideDateTimePicker{ public static final int HOLO_DARK = 1; public static final int HOLO_LIGHT = 2; private FragmentManager mFragmentManager; private SlideDateTimeListener mListener; private Date mInitialDate; private Date mMinDate; private Date mMaxDate; private boolean mIsClientSpecified24HourTime; private boolean mIs24HourTime; private int mTheme; private int mIndicatorColor; public SlideDateTimePicker(FragmentManager fm){ // See if there are any DialogFragments from the FragmentManager FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag(SlideDateTimeDialogFragment.TAG_SLIDE_DATE_TIME_DIALOG_FRAGMENT); // Remove if found if (prev != null){ ft.remove(prev); ft.commit(); } mFragmentManager = fm; } public void setListener(SlideDateTimeListener listener) { mListener = listener; } public void setInitialDate(Date initialDate) { mInitialDate = initialDate; } public void setMinDate(Date minDate) { mMinDate = minDate; } public void setMaxDate(Date maxDate) { mMaxDate = maxDate; } private void setIsClientSpecified24HourTime(boolean isClientSpecified24HourTime){ mIsClientSpecified24HourTime = isClientSpecified24HourTime; } public void setIs24HourTime(boolean is24HourTime){ setIsClientSpecified24HourTime(true); mIs24HourTime = is24HourTime; } public void setTheme(int theme) { mTheme = theme; } public void setIndicatorColor(int indicatorColor) { mIndicatorColor = indicatorColor; } public void show(){ if (mListener == null){ throw new NullPointerException( "Attempting to bind null listener to SlideDateTimePicker"); } if (mInitialDate == null){ setInitialDate(new Date()); } SlideDateTimeDialogFragment dialogFragment = SlideDateTimeDialogFragment.newInstance( mListener, mInitialDate, mMinDate, mMaxDate, mIsClientSpecified24HourTime, mIs24HourTime, mTheme, mIndicatorColor); dialogFragment.show(mFragmentManager, SlideDateTimeDialogFragment.TAG_SLIDE_DATE_TIME_DIALOG_FRAGMENT); } /* * The following implements the builder API to simplify * creation and display of the dialog. */ public static class Builder{ // Required private FragmentManager fm; private SlideDateTimeListener listener; // Optional private Date initialDate; private Date minDate; private Date maxDate; private boolean isClientSpecified24HourTime; private boolean is24HourTime; private int theme; private int indicatorColor; public Builder(FragmentManager fm) { this.fm = fm; } /** * @see SlideDateTimePicker#setListener(SlideDateTimeListener) */ public Builder setListener(SlideDateTimeListener listener){ this.listener = listener; return this; } /** * @see SlideDateTimePicker#setInitialDate(Date) */ public Builder setInitialDate(Date initialDate){ this.initialDate = initialDate; return this; } /** * @see SlideDateTimePicker#setMinDate(Date) */ public Builder setMinDate(Date minDate){ this.minDate = minDate; return this; } /** * @see SlideDateTimePicker#setMaxDate(Date) */ public Builder setMaxDate(Date maxDate){ this.maxDate = maxDate; return this; } /** * @see SlideDateTimePicker#setIs24HourTime(boolean) */ public Builder setIs24HourTime(boolean is24HourTime){ this.isClientSpecified24HourTime = true; this.is24HourTime = is24HourTime; return this; } /** * @see SlideDateTimePicker#setTheme(int) */ public Builder setTheme(int theme) { this.theme = theme; return this; } /** * @see SlideDateTimePicker#setIndicatorColor(int) */ public Builder setIndicatorColor(int indicatorColor) { this.indicatorColor = indicatorColor; return this; } /** * <p>Build and return a {@code SlideDateTimePicker} object based on the previously * supplied parameters.</p> * <p>You should call {@link #show()} immediately after this.</p> * @return */ public SlideDateTimePicker build(){ SlideDateTimePicker picker = new SlideDateTimePicker(fm); picker.setListener(listener); picker.setInitialDate(initialDate); picker.setMinDate(minDate); picker.setMaxDate(maxDate); picker.setIsClientSpecified24HourTime(isClientSpecified24HourTime); picker.setIs24HourTime(is24HourTime); picker.setTheme(theme); picker.setIndicatorColor(indicatorColor); return picker; } } } <file_sep>/app/src/main/java/com/gymnast/data/personal/DynamicData.java package com.gymnast.data.personal; import java.io.Serializable; import java.util.ArrayList; /** * Created by Cymbi on 2016/8/27. */ public class DynamicData implements Serializable { //动态id private int id; //用户id private int userId; //创建时间 private Long createTime; //1为个人动态,2为活动动态,3为明星动态,4为圈子动态 private int type; //动态图片 private String topicTitle; //内容 private String topicContent; //图片地址 private ArrayList<String> imgUrl; //视频直播 private String videoUrl; //可见范围0所有可见,1好友可见 private int topicVisible; // private int pageviews;//多少人浏览 //这个人发布的动态的id private String fromId; //动态发起人的id private int fromType; //动态状态,-2未屏蔽,-1为删除,0为正常 private int state; //用户姓名 private String nickName; //用户头像 private String avatar; //认证 private int authenticate; //赞 private int zanCounts; //回复 private int commentCounts; //用户类型 private String authInfo; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPageviews() { return pageviews; } public void setPageviews(int pageviews) { this.pageviews = pageviews; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getAuthInfo() { return authInfo; } public void setAuthInfo(String authInfo) { this.authInfo = authInfo; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getTopicTitle() { return topicTitle; } public void setTopicTitle(String topicTitle) { this.topicTitle = topicTitle; } public String getTopicContent() { return topicContent; } public void setTopicContent(String topicContent) { this.topicContent = topicContent; } public ArrayList<String> getImgUrl() { return imgUrl; } public void setImgUrl(ArrayList<String> imgUrl) { this.imgUrl = imgUrl; } public String getVideoUrl() { return videoUrl; } public void setVideoUrl(String videoUrl) { this.videoUrl = videoUrl; } public int getTopicVisible() { return topicVisible; } public void setTopicVisible(int topicVisible) { this.topicVisible = topicVisible; } public String getFromId() { return fromId; } public void setFromId(String fromId) { this.fromId = fromId; } public int getFromType() { return fromType; } public void setFromType(int fromType) { this.fromType = fromType; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public int getAuthenticate() { return authenticate; } public void setAuthenticate(int authenticate) { this.authenticate = authenticate; } public int getZanCounts() { return zanCounts; } public void setZanCounts(int zanCounts) { this.zanCounts = zanCounts; } public int getCommentCounts() { return commentCounts; } public void setCommentCounts(int commentCounts) { this.commentCounts = commentCounts; } } <file_sep>/app/src/main/java/com/gymnast/utils/VerifyPhoneUtil.java package com.gymnast.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Cymbi on 2016/9/7. */ public class VerifyPhoneUtil { /** * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通) * @param mobiles * @return */ public static boolean isMobileNO(String mobiles){ Pattern p = Pattern.compile("^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}$"); Matcher m = p.matcher(mobiles); return m.matches(); } /** * 判断邮箱是否合法 * @param email * @return */ public static boolean isEmail(String email){ if (null==email || "".equals(email)) return false; //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配 Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配 Matcher m = p.matcher(email); return m.matches(); } public static boolean isZipNO(String zipString){ String str = "^[1-9][0-9]{5}$"; return Pattern.compile(str).matcher(zipString).matches(); } } <file_sep>/app/src/main/java/com/gymnast/view/live/entity/BarrageViewEntity.java package com.gymnast.view.live.entity; import java.io.Serializable; /** * Created by zzqybyb19860112 on 2016/10/9. */ public class BarrageViewEntity implements Serializable { private String picUrl; private String content; public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } <file_sep>/app/src/main/java/com/gymnast/data/user/UserService.java package com.gymnast.data.user; import com.gymnast.data.Service; import com.gymnast.data.net.Result; import com.gymnast.data.net.UserData; import rx.Observable; /** * Created by fldyown on 16/6/14. */ public interface UserService extends Service{ public Observable<Result> getVerifyCode(String phone); public Observable<Result<VerifyCode>> verifyPhone(String phone, String code); public Observable<Result> register(String phone, String pwd, String nickname, String avatar); public Observable<Result> retrievePassword(String phone, String pwd, String re_pwd); public Observable<Result<UserData>> login(String phone, String pwd); } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/activity/AddConditionActivity.java package com.gymnast.view.hotinfoactivity.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; /** * Created by Cymbi on 2016/9/8. */ public class AddConditionActivity extends ImmersiveActivity { private EditText etAddConditionName; private String text; private TextView tvAddConditionSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting_add); setview(); } private void setview() { etAddConditionName=(EditText)findViewById(R.id.etAddConditionName); tvAddConditionSave=(TextView)findViewById(R.id.tvAddConditionSave); findViewById(R.id.ivAddConditionBack).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AddConditionActivity.this.finish(); } }); tvAddConditionSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { text=etAddConditionName.getText().toString(); Intent i=new Intent(AddConditionActivity.this,PromulgateActivityActivity.class); i.putExtra("add",text); setResult(16,i); finish(); } }); } } <file_sep>/app/src/main/java/com/gymnast/view/home/view/SearchUserFragment.java package com.gymnast.view.home.view; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.google.gson.JsonObject; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.CacheUtils; import com.gymnast.utils.JSONParseUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.view.home.adapter.SearchUserAdapter; import com.gymnast.data.user.SearchUserEntity; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by zzqybyb19860112 on 2016/9/4. */ public class SearchUserFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{ RecyclerView recyclerView; List<SearchUserEntity> dataList=new ArrayList<>(); SearchUserAdapter adapter; boolean isRefresh=false; private String fromId,token; private SwipeRefreshLayout srlSearch; public static final int HANDLE_DATA=1; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==HANDLE_DATA){ adapter=new SearchUserAdapter(getActivity(),dataList); adapter.setFriends(dataList); recyclerView.setAdapter(adapter); adapter.getFilter().filter(isRefresh == true ? HomeSearchResultAcitivity.etSearch.getText().toString().trim() : HomeSearchResultAcitivity.getSearchText()); srlSearch.setRefreshing(false); } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater,container,savedInstanceState); View view=inflater.inflate(R.layout.search_common_fragment,null); recyclerView= (RecyclerView) view.findViewById(R.id.recycleView); srlSearch= (SwipeRefreshLayout) view.findViewById(R.id.srlSearch); RefreshUtil.refresh(srlSearch, getActivity()); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); getInfo(); setData(); srlSearch.setOnRefreshListener(this); return view; } private void getInfo() { SharedPreferences share= getActivity().getSharedPreferences("UserInfo", Context.MODE_PRIVATE); fromId = share.getString("UserId",""); token = share.getString("Token",""); } private void setData() { ArrayList<String> cacheData= (ArrayList<String>) CacheUtils.readJson(getActivity(), SearchUserFragment.this.getClass().getName() + ".json"); if (cacheData==null||cacheData.size()==0) { new Thread() { @Override public void run() { String uri = API.BASE_URL + "/v1/search/model"; HashMap<String, String> params = new HashMap<String, String>(); params.put("userId", fromId); params.put("model", "1"); params.put("pageNumber", "100"); params.put("pages", "1"); String result = PostUtil.sendPostMessage(uri, params); try { JSONObject jsonObject=new JSONObject(result); boolean atten=jsonObject.getBoolean("atten"); } catch (JSONException e) { e.printStackTrace(); } JSONParseUtil.parseNetDataSearchUser(getActivity(), result,SearchUserFragment.this.getClass().getName() + ".json", dataList,handler,HANDLE_DATA); } }.start(); }else { JSONParseUtil.parseLocalDataSearchUser(getActivity(),SearchUserFragment.this.getClass().getName() + ".json", dataList,handler,HANDLE_DATA); } } @Override public void onRefresh() { isRefresh=true; setData(); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 srlSearch.setRefreshing(false); } }, 1000); } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonalCircleCreateActivity.java package com.gymnast.view.personal.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.data.personal.SelectType; import com.gymnast.utils.PostUtil; import com.gymnast.view.ImmersiveActivity; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMGroup; import com.hyphenate.chat.EMGroupManager; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * Created by yf928 on 2016/8/10. */ public class PersonalCircleCreateActivity extends ImmersiveActivity { private ImageView back; private TextView type; private EditText et_title,content; private TextView submit; private SharedPreferences share; private String token,id; private int typeid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_circle); share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",""); id = share.getString("UserId",""); setview(); initview(); } private void setview() { back= (ImageView) findViewById(R.id.personal_back); type = (TextView)findViewById(R.id.type); submit = (TextView)findViewById(R.id.submit); content=(EditText) findViewById(R.id.circle_content); et_title= (EditText)findViewById(R.id.circle_title); } private void initview() { back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); type.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(PersonalCircleCreateActivity.this,PersonalSelectTypeActivity.class); startActivityForResult(i,100); } }); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getdata(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==100){ if(resultCode==10){ String name = data.getStringExtra("typename"); typeid=data.getIntExtra("typeid",0); type.setText(name); } } } public void getdata() { new Thread(new Runnable() { @Override public void run() { try { SelectType type =new SelectType(); String title= et_title.getText().toString(); String details=content.getText().toString(); EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions(); option.maxUsers = 1000; option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin; String []allMembers=new String[]{}; EMGroup group = EMClient.getInstance().groupManager().createGroup(id,title,allMembers, null, option); String groupId=group.getGroupId(); String uri= API.BASE_URL+"/v1/circle/add"; Map<String,String> parmas=new HashMap<String, String>(); parmas.put("token",token); parmas.put("createId",id); parmas.put("title",title); parmas.put("details",details); parmas.put("group_id",groupId+""); parmas.put("circleType",typeid+""); String result= PostUtil.sendPostMessage(uri,parmas); JSONObject obj=new JSONObject(result); if(obj.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PersonalCircleCreateActivity.this,"圈子创建成功",Toast.LENGTH_SHORT).show(); finish(); } }); }else { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PersonalCircleCreateActivity.this,"圈子创建失败",Toast.LENGTH_SHORT).show(); } }); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/activity/SignUpActivity.java package com.gymnast.view.hotinfoactivity.activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.hotinfoactivity.adapter.SingnUpAdapter; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Cymbi on 2016/9/10. */ public class SignUpActivity extends ImmersiveActivity implements View.OnClickListener{ private ImageView ivSignUpBack,ivSignUpHead; private TextView tvSignUpTitle,tvSignUpMoney,tvSignUpReport,tvSignUpAllMoney,tvSignUpSubmit; private RecyclerView rvSignUp; private SharedPreferences share; private int id,createId,activityId,price; private String userId,template,nickName,phoneNew,token,imageUrl,title; ArrayList<String> answer=new ArrayList<>(); private List<String>list=new ArrayList<>(); SingnUpAdapter adapter; public static final int HANDLE_DATA=1; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANDLE_DATA: rvSignUp.setVisibility(View.VISIBLE); tvSignUpReport.setVisibility(View.VISIBLE); adapter=new SingnUpAdapter(SignUpActivity.this,list); rvSignUp.setAdapter(adapter); adapter.notifyDataSetChanged(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); setView(); getInfo(); getTitleData(); queryMemberTemplate(); } private void getTitleData() { PicassoUtil.handlePic(SignUpActivity.this, PicUtil.getImageUrlDetail(SignUpActivity.this, StringUtil.isNullAvatar(imageUrl),320,320),ivSignUpHead,320,320); tvSignUpTitle.setText(title); if (price==0){ tvSignUpMoney.setText("免费"); tvSignUpAllMoney.setTextSize(15); tvSignUpAllMoney.setText("免费"); }else { tvSignUpMoney.setText(price+""); tvSignUpAllMoney.setText(price+""); } } private void queryMemberTemplate() { new Thread(new Runnable() { @Override public void run() { try { String uri=API.BASE_URL+"/v1/activity/memberTemplate"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("id",id+""); String result= PostUtil.sendPostMessage(uri,params); JSONObject object=new JSONObject(result); if(object.getInt("state")==200) { JSONObject data = object.getJSONObject("data"); activityId = data.getInt("id"); createId = data.getInt("userId"); template = data.getString("template"); if(template!=null&template!="null"&!template.equals("")){ String[] s = template.split(","); for (int i = 0; i < s.length; i++) { list.add(s[i]); } handler.sendEmptyMessage(HANDLE_DATA); }else {} } } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void setView() { rvSignUp=(RecyclerView) findViewById(R.id.rvSignUp); ivSignUpBack=(ImageView) findViewById(R.id.ivSignUpBack); ivSignUpHead=(ImageView) findViewById(R.id.ivSignUpHead); tvSignUpTitle=(TextView) findViewById(R.id.tvSignUpTitle); tvSignUpMoney=(TextView) findViewById(R.id.tvSignUpMoney); tvSignUpAllMoney=(TextView) findViewById(R.id.tvSignUpAllMoney); tvSignUpReport=(TextView) findViewById(R.id.tvSignUpReport); tvSignUpSubmit=(TextView) findViewById(R.id.tvSignUpSubmit); ivSignUpBack.setOnClickListener(this); tvSignUpSubmit.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.ivSignUpBack: finish(); break; case R.id.tvSignUpSubmit: Sign(); break; } } public void Sign() { String answerEnd = null; if(list.size()!=0){ boolean isAllAnswered=allAnswered(); if (isAllAnswered==false){ return; } answerEnd=getAllAnswer(); } final String finalAnswerEnd = answerEnd; new Thread(new Runnable() { @Override public void run() { String uri= API.BASE_URL+"/v1/activity/signup"; HashMap<String,String> params=new HashMap<String, String>(); HashMap<String,String> map=new HashMap<String, String>(); params.put("token",token); params.put("activityId",activityId+""); params.put("userId",userId); params.put("userNick",nickName); params.put("phone",phoneNew); if(list.size()!=0){ params.put("memberInfo", finalAnswerEnd); }else {} String result=PostUtil.sendPostMessage(uri,params); try{ JSONObject object=new JSONObject(result); int state=object.getInt("state"); if (state==200){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(SignUpActivity.this,"报名成功",Toast.LENGTH_SHORT).show(); Intent i=new Intent(); setResult(10,i); finish(); } }); }else if(state==10005){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(SignUpActivity.this,"不能重复报名!",Toast.LENGTH_SHORT).show(); SignUpActivity.this.finish(); } }); } }catch (Exception e){ e.printStackTrace(); } } }).start(); } private String getAllAnswer(){ String myData; StringBuffer sb=new StringBuffer("{"); for (int i=0;i<answer.size();i++){ sb.append("\""); sb.append(list.get(i)); sb.append("\":\""); sb.append(answer.get(i)); sb.append("\","); } sb.substring(0,sb.length()); String src=sb.toString(); String s= src.substring(0,src.length()-1)+"}"; myData = s.replaceAll("\\\\",""); return myData; } private boolean allAnswered() { boolean isAll=false; if (answer.size()!=0){ answer.clear(); } for (int i=0;i<list.size();i++){ ArrayList<View> viewList = rvSignUp.getChildAt(i).getTouchables(); EditText etOne= (EditText) viewList.get(0); String myAnswer=etOne.getText().toString(); if (myAnswer!=null&&!myAnswer.equals("")){ answer.add(myAnswer); }else { continue; } } if (answer.size()==list.size()){ isAll=true ; }else { Toast.makeText(SignUpActivity.this,"信息填写不完整,请检查!",Toast.LENGTH_SHORT).show(); } return isAll; } public void getInfo() { share = getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token", ""); userId = share.getString("UserId",""); nickName = share.getString("NickName",""); phoneNew = share.getString("Phone",""); Intent i=getIntent(); id= i.getIntExtra("activityId",0); price= i.getIntExtra("price",0); imageUrl= i.getStringExtra("imageUrl"); title= i.getStringExtra("title"); } } <file_sep>/app/src/main/java/com/gymnast/event/EventBus.java package com.gymnast.event; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; //有必要时再说 http://www.loongwind.com/archives/264.html public class EventBus { public static volatile EventBus bus; private final Subject<Object, Object> _bus; private EventBus() { _bus = new SerializedSubject<>(PublishSubject.create()); } public static EventBus getInstance() { if (bus == null) { synchronized (EventBus.class) { if (bus == null) { bus = new EventBus(); } } } return bus; } public void send(Event event) { _bus.onNext(event); } public <T> Observable<T> toObservable(Class<T> event) { return _bus.ofType(event); } public boolean hasObservers() { return _bus.hasObservers(); } }<file_sep>/app/src/main/java/com/gymnast/view/home/HomeActivity.java package com.gymnast.view.home; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.ConnectivityManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import android.view.KeyEvent; import com.gymnast.App; import com.gymnast.MyReceiver; import com.gymnast.R; import com.gymnast.data.user.User; import com.gymnast.event.Event; import com.gymnast.event.EventBus; import com.gymnast.view.BaseToolbarActivity; import com.gymnast.view.dialog.QuickOptionDialog; import com.gymnast.view.home.view.HomeSearchActivity; import com.gymnast.view.home.fragment.HotInfoFragment; import com.gymnast.view.home.fragment.MinePackFragment; import com.gymnast.view.home.fragment.StandFragment; import com.gymnast.view.personal.activity.PersonalActivity; import com.gymnast.view.user.LoginActivity; import com.gymnast.view.widget.BadgeView; import com.gymnast.view.widget.CustomViewPager; import java.util.ArrayList; import java.util.List; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; public class HomeActivity extends BaseToolbarActivity implements View.OnClickListener { private final static int INFO = 0; private final static int STAND = 1; private final static int PACK = 2; @BindView(R.id.home_viewpager) CustomViewPager pager; @BindView(R.id.tab_info_btn) Button tabInfoBtn; @BindView(R.id.tab_stand_btn) Button tabStandBtn; @BindView(R.id.tab_play_btn) Button tabPlayBtn; @BindView(R.id.tab_pack_btn) Button tabPackBtn; @BindView(R.id.ivSearch) ImageView ivSearch; @BindView(R.id.toolbar_save)TextView save; @BindView(R.id.tab_quick_option_btn) ImageButton tabQuickOptionBtn; private int currentTabIndex = 0; // 当前tab下标 List<Fragment> fragmentList; HotInfoFragment infoFragment = null; StandFragment standFragment = null; //PlayGroundFragment playFragment = null; MinePackFragment packFragment = null; private String token,id; private com.makeramen.roundedimageview.RoundedImageView toolbar_head; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { fragmentList = getSupportFragmentManager().getFragments(); if (fragmentList != null && fragmentList.size() > 0) { boolean showFlag = false; FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); for (int i = fragmentList.size() - 1; i >= 0; i--) { Fragment fragment = fragmentList.get(i); if (fragment != null) { if (!showFlag) { ft.show(fragmentList.get(i)); showFlag = true; } else { ft.hide(fragmentList.get(i)); } } } ft.commit(); } } toolbar_head=(com.makeramen.roundedimageview.RoundedImageView)findViewById(R.id.toolbar_head); SharedPreferences share = getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",null); id = share.getString("UserId",""); save.setVisibility(View.GONE); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); } /** * 连按两次返回 * @param keyCode * @param event * @return */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode== KeyEvent.KEYCODE_BACK){ Dialog dialog = new AlertDialog.Builder(this) .setTitle("确认退出") .setIcon(R.mipmap.timg) .setMessage("请您选择是否退出系统?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { HomeActivity.this.finish(); } }).setNeutralButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).create(); dialog.show(); } return super.onKeyDown(keyCode, event); } @Override public void onConfigurationChanged(Configuration newConfig){ super.onConfigurationChanged(newConfig); if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){ //land } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){ //port } } @Override protected int getLayout() { return R.layout.activity_home; } @Override protected void initViews(Bundle savedInstanceState) { //toolbarHead.setVisibility(View.GONE); fragmentList = new ArrayList<Fragment>(); infoFragment = new HotInfoFragment(); standFragment = new StandFragment(); //playFragment = new PlayGroundFragment(); packFragment = new MinePackFragment(); fragmentList.add(infoFragment); fragmentList.add(standFragment); fragmentList.add(packFragment); FragmentPagerAdapter fragmentPagerAdapter = new HomeFragmentPagerAdapter(this.getSupportFragmentManager(), fragmentList); pager.setAdapter(fragmentPagerAdapter); pager.setOffscreenPageLimit(fragmentList.size()); pager.setSlide(false); this.mActionBarHelper.setDisplayHomeAsUpEnabled(false); setTitle("居中"); } @Override protected void initListeners() { tabInfoBtn.setOnClickListener(this); tabStandBtn.setOnClickListener(this); tabPlayBtn.setOnClickListener(this); tabPackBtn.setOnClickListener(this); tabQuickOptionBtn.setOnClickListener(this); // toolbarHead.setOnClickListener(this); pager.addOnPageChangeListener(new HomeViewPagerListener()); // 登录监听 mSubscription = EventBus.getInstance() .toObservable(Event.class) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Event>() { @Override public void call(Event objectsEvent) { if (objectsEvent.t != null) { if (objectsEvent.t.getClass().isAssignableFrom(User.class)) { Toast.makeText(HomeActivity.this, "登录刷新:" + ((User) objectsEvent.t).nickname, Toast.LENGTH_SHORT).show(); } } } }); ivSearch.setOnClickListener(this); } public void initData() { setTabSelection(INFO);// 设置默认选中的tab页 } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tab_info_btn: setTabSelection(INFO); break; case R.id.tab_stand_btn: setTabSelection(STAND); break; case R.id.tab_play_btn: //setTabSelection(PLAY); Intent i = new Intent(this, PersonalActivity.class); startActivity(i); break; case R.id.tab_pack_btn: setTabSelection(PACK); break; case R.id.tab_quick_option_btn: showQuickOption(); break; case R.id.toolbar_head: if (TextUtils.isEmpty(token)) { Intent intent = new Intent(HomeActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } else { Intent inten = new Intent(HomeActivity.this, PersonalActivity.class); inten.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(inten); } break; case R.id.ivSearch: if (TextUtils.isEmpty(token)||!App.isStateOK) { Toast.makeText(this, "亲你还没有登录哟~", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(HomeActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }else { Intent intent = new Intent(HomeActivity.this, HomeSearchActivity.class); HomeActivity.this.startActivity(intent); } break; default: setTabSelection(INFO); break; } } // 显示快速操作界面 private void showQuickOption() { final QuickOptionDialog dialog = new QuickOptionDialog(HomeActivity.this); if (TextUtils.isEmpty(token)||!App.isStateOK) { Toast.makeText(this, "亲你还没有登录哟~", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(HomeActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } else { dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); dialog.show(); } } /** * 根据传入的index参数来设置选中的tab页 */ private void setTabSelection(int index) { // 重置状态 resetState(); switch (index) { case INFO: { // 信息 tabInfoBtn.setTextColor(this.getResources().getColor(R.color.home_tab_pressed_color)); tabInfoBtn.setSelected(true); break; } case STAND: { // 看台 tabStandBtn.setTextColor(this.getResources().getColor(R.color.home_tab_pressed_color)); tabStandBtn.setSelected(true); break; } case PACK: { //操场 tabPackBtn.setTextColor(this.getResources().getColor(R.color.home_tab_pressed_color)); tabPackBtn.setSelected(true); break; } /*case PLAY: { // 背包 tabPlayBtn.setTextColor(this.getResources().getColor(R.color.home_tab_pressed_color)); tabPlayBtn.setSelected(true); break; }*/ } pager.setCurrentItem(index, false); currentTabIndex = index; } /** * 重置状态 */ private void resetState() { tabInfoBtn.setTextColor(this.getResources().getColor(R.color.home_tab_nor_color)); tabInfoBtn.setSelected(false); tabStandBtn.setTextColor(this.getResources().getColor(R.color.home_tab_nor_color)); tabStandBtn.setSelected(false); tabPackBtn.setTextColor(this.getResources().getColor(R.color.home_tab_nor_color)); tabPackBtn.setSelected(false); tabPlayBtn.setTextColor(this.getResources().getColor(R.color.home_tab_nor_color)); tabPlayBtn.setSelected(false); } /** * 设置tab标记 */ private void setBadgeView(BadgeView badgeView, int num) { if (num > 0) { badgeView.setText(String.valueOf(num)); badgeView.show(); } else { badgeView.hide(); } } @Override public void onBackPressed() {//back to home Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_HOME); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); startActivity(intent); } private class HomeFragmentPagerAdapter extends FragmentPagerAdapter { private List<Fragment> fragmentList; public HomeFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) { super(fm); this.fragmentList = fragmentList; } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList == null ? 0 : fragmentList.size(); } } private class HomeViewPagerListener implements ViewPager.OnPageChangeListener { @Override public void onPageScrollStateChanged(int position) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { setTabSelection(position); } } //设置主界面头像,现在先不要 /*private void setdata() { new Thread(new Runnable() { public String return_avatar; @Override public void run() { String uri = API.BASE_URL + "/v1/account/center_info"; HashMap<String, String> params = new HashMap<>(); params.put("token", token); params.put("account_id", id); String result = GetUtil.sendGetMessage(uri, params); if (TextUtils.isEmpty(token)) { } else { try { JSONObject obj = new JSONObject(result); JSONObject data = obj.getJSONObject("data"); return_avatar = data.getString("avatar"); final Bitmap bitmap= PicUtil.getImageBitmap(API.IMAGE_URL + return_avatar); if (obj.getInt("state") == 200) { runOnUiThread(new Runnable() { @Override public void run() { toolbar_head.setImageBitmap(bitmap); } }); } } catch (Exception e) { e.printStackTrace(); } } } }).start(); }*/ }<file_sep>/app/src/main/java/com/gymnast/utils/StringUtil.java package com.gymnast.utils; import android.util.Log; import java.util.List; /** * Created by zzqybyb19860112 on 2016/8/25. */ public class StringUtil { public static String isNullAvatar(String tempString){ boolean isNull=tempString == null || tempString.equals("") ||tempString.equals("null"); boolean isFalse=false; if (!isNull){ isFalse=(!tempString.contains(".png"))&&(!tempString.contains(".jpg"))&&(!tempString.contains(".jpeg"))&&(!tempString.contains(".gif")); } return isNull||isFalse?"http://image.tiyujia.com/group1/M00/00/00/052YyFfXxLKARvQWAAAbNiA-OGw444.png":"http://image.tiyujia.com/"+tempString; } public static String isNullImage(String tempString){ boolean isNull=tempString == null || tempString.equals("") ||tempString.equals("null"); boolean isFalse=false; if (!isNull){ isFalse=(!tempString.contains(".png"))&&(!tempString.contains(".jpg"))&&(!tempString.contains(".jpeg"))&&(!tempString.contains(".gif")); } return isNull||isFalse?"http://image.tiyujia.com/group1/M00/00/05/052YyFfozOqAOoAPAAN3M9vaMhU687.png":"http://image.tiyujia.com/"+tempString; } public static String isNullImageUrl(String tempString){ boolean isNull=tempString == null || tempString.equals("") ||tempString.equals("null"); boolean isFalse=false; if (!isNull){ isFalse=(!tempString.contains(".png"))&&(!tempString.contains(".jpg"))&&(!tempString.contains(".jpeg"))&&(!tempString.contains(".gif")); } return isNull||isFalse?"http://image.tiyujia.com/group1/M00/00/0A/052YyFf4Z9CANLLFAALMR1kNvzI190.png":"http://image.tiyujia.com/"+tempString; } public static String isNullGroupId(String tempString){ return tempString == null || tempString.equals("") || tempString.equals("null")?"000":tempString; } public static String isNullAuth(String tempString){ return tempString == null ||tempString.equals("")||tempString.equals("null")?"":tempString; } public static String isNullDATA(String tempString){ return tempString == null ||tempString.equals("")||tempString.equals("null")?"0":tempString; } public static String isNullNickName(String tempString){ return tempString == null ||tempString.equals("")||tempString.equals("null")?"":tempString; } public static String listToString(List<String> stringList){ if (stringList==null) { return null; } StringBuilder result=new StringBuilder(); boolean flag=false; for (String string : stringList) { if (flag) { result.append(","); }else { flag=true; } result.append(string); } return result.toString(); } } <file_sep>/app/src/main/java/com/gymnast/data/user/Data.java package com.gymnast.data.user; /** * Created by Cymbi on 2016/8/15. */ public class Data { public String id; public String phone; } <file_sep>/app/src/main/java/com/gymnast/view/live/entity/EndLiveEntity.java package com.gymnast.view.live.entity; import android.graphics.Bitmap; import java.io.Serializable; /** * Created by zzqybyb19860112 on 2016/10/8. */ public class EndLiveEntity implements Serializable { String totalTime; int peopleNumber; int shareNumber; int priseNumber; String bitmapSmallPhotoUrl; String groupId; String nickName; public String getBitmapSmallPhotoUrl() { return bitmapSmallPhotoUrl; } public void setBitmapSmallPhotoUrl(String bitmapSmallPhotoUrl) { this.bitmapSmallPhotoUrl = bitmapSmallPhotoUrl; } public String getTotalTime() { return totalTime; } public void setTotalTime(String totalTime) { this.totalTime = totalTime; } public int getPeopleNumber() { return peopleNumber; } public void setPeopleNumber(int peopleNumber) { this.peopleNumber = peopleNumber; } public int getShareNumber() { return shareNumber; } public void setShareNumber(int shareNumber) { this.shareNumber = shareNumber; } public int getPriseNumber() { return priseNumber; } public void setPriseNumber(int priseNumber) { this.priseNumber = priseNumber; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } } <file_sep>/app/src/main/java/com/gymnast/view/home/adapter/HotInfoDynamicRecyclerViewAdapter.java package com.gymnast.view.home.adapter; import android.app.Activity; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import butterknife.BindView; import butterknife.ButterKnife; import com.gymnast.R; import com.gymnast.data.hotinfo.ConcerDevas; import com.gymnast.data.net.API; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.view.personal.activity.PersonalDynamicDetailActivity; import java.util.List; public class HotInfoDynamicRecyclerViewAdapter extends RecyclerView.Adapter<HotInfoDynamicRecyclerViewAdapter.ViewHolder> { private final List<ConcerDevas> mValues; private Activity activity; public HotInfoDynamicRecyclerViewAdapter(Activity activity, List<ConcerDevas> items) { mValues = items; this.activity = activity; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_hot_info_dynamic, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { final ConcerDevas dynamic = mValues.get(position); if (dynamic != null) { String imageUrl=""; if (dynamic.bgmUrl==null||dynamic.bgmUrl.equals("")){ imageUrl=dynamic.imageUrl; }else { imageUrl=dynamic.bgmUrl; } if (imageUrl.contains(",")){ String urls[]=imageUrl.split(","); String imageUrl2= API.IMAGE_URL+urls[0]; PicassoUtil.handlePic(activity, PicUtil.getImageUrl(activity,API.IMAGE_URL+imageUrl2), holder.dynamicPicture, 670, 372); }else { PicassoUtil.handlePic(activity, PicUtil.getImageUrl(activity, API.IMAGE_URL+imageUrl), holder.dynamicPicture, 670, 372); } holder.dynamicPicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(activity,PersonalDynamicDetailActivity.class); intent.putExtra("CirleID",dynamic.id); activity.startActivity(intent); } }); } } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.hot_info_dynamic_picture) ImageView dynamicPicture; public ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } } <file_sep>/app/src/main/java/com/gymnast/data/user/User.java package com.gymnast.data.user; /** * Created by fldyown on 16/6/12. */ public class User { public String nickname; public String phone; public String pwd; } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/activity/ActivityDetailsActivity.java package com.gymnast.view.hotinfoactivity.activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.App; import com.gymnast.R; import com.gymnast.data.hotinfo.RecentActivityDetail; import com.gymnast.data.hotinfo.UserDevas; import com.gymnast.data.net.API; import com.gymnast.utils.CallBackUtil; import com.gymnast.utils.CollectUtil; import com.gymnast.utils.DataCleanManagerUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.utils.StringUtil; import com.gymnast.utils.TimeUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.home.adapter.HotInfoActivityUserRecyclerViewAdapter; import com.gymnast.view.hotinfoactivity.adapter.CallBackAdapter; import com.gymnast.view.hotinfoactivity.entity.CallBackDetailEntity; import com.gymnast.view.hotinfoactivity.entity.CallBackEntity; import com.gymnast.view.personal.listener.WrapContentLinearLayoutManager; import com.gymnast.view.user.LoginActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; /** * Created by Cymbi on 2016/8/22. */ public class ActivityDetailsActivity extends ImmersiveActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener{ private TextView tvDetailTitle,tvDetailMoney,tvDetailPeopleNumber,tvDetailSignUp,tvDetailAddress,tvDetailTime,tvDetailPhone,tvDetailCountDown,tvCollect,tvReport,tvDelete, tvSpacial,tvTop; private ImageView ivDetailImage,ivClose,ivBack,ivMoreChoice; private View view; SwipeRefreshLayout reflesh; private RecyclerView rvCallBack; private RecyclerView rvActiveUserList; private EditText etCallBack; private TextView tvCallBackSend; RelativeLayout rlAll; LinearLayout llShareToFriends,llShareToWeiChat,llShareToQQ,llShareToQQZone,llShareToMicroBlog; private WebView tvDescContent; public static int shareNumber=0;//分享次数 private long startTime,endTime,lastTime; private String phone,descContent,title,imageUrl,address,token,userId,nickName,phoneNew,maxPeople="0"; private int price,surplusPeople,x,memberCount; private int Userid; private int UserId; int activeID; int notifyPos=0; String avatar; private SharedPreferences share; RecentActivityDetail recentActiveData; List<CallBackEntity> commentList=new ArrayList<>(); List<UserDevas> userWantToGo=new ArrayList<>(); CallBackAdapter commentAdapter; boolean isCollected; HotInfoActivityUserRecyclerViewAdapter userLikeAdapter; public static boolean isComment=true; public static final int HANDLE_BANNER_ACTIVE_DATA=1; public static final int HANDLE_NEW_ACTIVE_DATA=2; public static final int HANDLE_SEARCH_ACTIVE_DATA=3; public static final int HANDLE_HISTORY_DATA=4; public static final int HANDLE_COMMENT_DATA=5; public static final int HANDLE_MAIN_USER_BACK=6; public static final int HANDLE_USER_WANT_TO_GO=7; static ArrayList<CallBackDetailEntity> detailMSGs; ArrayList<String> userABC=new ArrayList<>(); Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case CollectUtil.TO_COLLECT: Toast.makeText(ActivityDetailsActivity.this,"已收藏!",Toast.LENGTH_SHORT).show(); tvCollect.setText("取消收藏"); isCollected=true; break; case CollectUtil.CANCEL_COLLECT: Toast.makeText(ActivityDetailsActivity.this,"已取消收藏!",Toast.LENGTH_SHORT).show(); tvCollect.setText("收藏"); isCollected=false; break; case CollectUtil.ERROR: Toast.makeText(ActivityDetailsActivity.this,"服务器异常!",Toast.LENGTH_SHORT).show(); break; case HANDLE_USER_WANT_TO_GO: userLikeAdapter=new HotInfoActivityUserRecyclerViewAdapter(ActivityDetailsActivity.this,userWantToGo); WrapContentLinearLayoutManager manager1=new WrapContentLinearLayoutManager(ActivityDetailsActivity.this,LinearLayoutManager.HORIZONTAL,false); rvActiveUserList.setLayoutManager(manager1); rvActiveUserList.setAdapter(userLikeAdapter); break; case HANDLE_MAIN_USER_BACK: commentAdapter.notifyItemChanged(notifyPos); break; case HANDLE_COMMENT_DATA: userABC= (ArrayList<String>) msg.obj; commentAdapter=new CallBackAdapter(ActivityDetailsActivity.this,commentList); WrapContentLinearLayoutManager manager=new WrapContentLinearLayoutManager(ActivityDetailsActivity.this,LinearLayoutManager.VERTICAL,false); rvCallBack.setLayoutManager(manager); rvCallBack.setAdapter(commentAdapter); commentAdapter.setOnItemClickListener(new CallBackAdapter.OnItemClickListener() { @Override public void OnCallBackClick(View view,int position, ArrayList<CallBackDetailEntity> detailMSGs) { isComment=false; notifyPos=position; ActivityDetailsActivity.detailMSGs=detailMSGs; ActivityDetailsActivity.type=ActivityDetailsActivity.CALL_BACK_TYPE_ONE; String backWho=commentList.get(position).getCallBackNickName(); firstCommenter=backWho; etCallBack.requestFocus(); etCallBack.setText(""); etCallBack.setHint("回复" + backWho); InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager.isActive()) { inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS); ActivityDetailsActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } } }); break; case HANDLE_BANNER_ACTIVE_DATA: handleData(); break; case HANDLE_NEW_ACTIVE_DATA: handleData(); break; case HANDLE_SEARCH_ACTIVE_DATA: handleData(); break; case HANDLE_HISTORY_DATA: handleHistoryData(); break; } } }; private void autoRefresh(){ InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(etCallBack.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); RefreshUtil.refresh(reflesh, this); setBaseState(); setCallBackView(); commentAdapter.notifyDataSetChanged(); rvCallBack.scrollToPosition(3); etCallBack.setFocusable(true); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 reflesh.setRefreshing(false); } }, 1000); } private void handleHistoryData() { ivMoreChoice.setVisibility(View.GONE); tvDetailTime.setText(TimeUtil.getDetailTime(startTime) + "~" + TimeUtil.getDetailTime(endTime)); tvDetailTitle.setText(title + ""); PicassoUtil.handlePic(ActivityDetailsActivity.this, PicUtil.getImageUrlDetail(ActivityDetailsActivity.this, StringUtil.isNullAvatar(imageUrl), x, 1920), ivDetailImage, x, 720); if(price==0){ tvDetailMoney.setText("免费"); }else { tvDetailMoney.setText("¥"+price); } tvDetailAddress.setText(address+""); tvDetailPhone.setText(phone + ""); tvDetailPeopleNumber.setVisibility(View.INVISIBLE); tvDetailCountDown.setText("活动已结束"); WindowManager wm = (WindowManager) ActivityDetailsActivity.this.getSystemService(Context.WINDOW_SERVICE); int width = wm.getDefaultDisplay().getWidth(); if(width > 520){ this.tvDescContent.setInitialScale(160); }else if(width > 450){ this.tvDescContent.setInitialScale(140); }else if(width > 300){ this.tvDescContent.setInitialScale(120); }else{ this.tvDescContent.setInitialScale(100); } tvDescContent.loadDataWithBaseURL(null, descContent, "text/html", "utf-8", null); tvDescContent.getSettings().setJavaScriptEnabled(true); // 设置启动缓存 ; tvDescContent.getSettings().setAppCacheEnabled(true); tvDescContent.setWebChromeClient(new WebChromeClient()); tvDescContent.getSettings().setJavaScriptEnabled(true); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); setContentView(R.layout.activity_activity_details); Rect rect = new Rect(); ActivityDetailsActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); x = rect.width(); getInfo(); setView(); setCallBackView(); initData(); try{ Userid=Integer.parseInt(userId);}catch (Exception e){e.printStackTrace();} getSignUpInfo(); getCollectionMenber(); getPageView(); } private void getPageView() { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/pageViwes"; HashMap<String,String>params=new HashMap<>(); params.put("types",2+""); params.put("typeId",activeID+""); String result= PostUtil.sendPostMessage(uri,params); } }).start(); } private void getCollectionMenber() { new Thread(){ @Override public void run() { try{ String uri=API.BASE_URL+"/v1/collect/users "; HashMap<String,String> params=new HashMap<String, String>(); params.put("model","1"); params.put("modelId",activeID+""); String result=PostUtil.sendPostMessage(uri,params); JSONObject object=new JSONObject(result); if (object.getInt("state")!=200){ userWantToGo=new ArrayList<UserDevas>(); return; } JSONArray array=object.getJSONArray("data"); for (int i=0;i<array.length();i++){ JSONObject data=array.getJSONObject(i); UserDevas userDevas=new UserDevas(); userDevas.id=data.getInt("id"); userDevas.nickname=data.getString("nickname"); userDevas.imageUrl=data.getString("avatar"); userDevas.bgmUrl=data.getString("avatar"); userWantToGo.add(userDevas); } handler.sendEmptyMessage(HANDLE_USER_WANT_TO_GO); }catch (Exception e){ e.printStackTrace(); } } }.start(); } String firstCommenter=""; private void setCallBackView() { CallBackUtil.getCallBackData(2, activeID, commentList, handler, HANDLE_COMMENT_DATA); reflesh.setRefreshing(false); } private void getSignUpInfo() { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/activity/memberPeople"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("activityId",activeID+""); params.put("userId",userId); String result=PostUtil.sendPostMessage(uri,params); try { JSONObject object=new JSONObject(result); if(object.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { tvDetailSignUp.setText("已报名"); tvDetailSignUp.setBackgroundColor(getResources().getColor(R.color.background)); tvDetailSignUp.setClickable(false); } }); }else if(object.getInt("state")==10002){ runOnUiThread(new Runnable() { @Override public void run() { tvDetailSignUp.setText("报名"); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } private void getInfo() { share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token", ""); userId = share.getString("UserId","");//当前用户id nickName = share.getString("NickName", ""); avatar = share.getString("Avatar", ""); phoneNew = share.getString("Phone",""); Intent data=getIntent(); activeID=data.getIntExtra("ActiveID", 0); UserId=data.getIntExtra("UserId", 0); recentActiveData= (RecentActivityDetail) data.getSerializableExtra("RecentActivityDetail"); } private void setView() { reflesh = (SwipeRefreshLayout) findViewById(R.id.srlReflesh); RefreshUtil.refresh(reflesh,this); etCallBack= (EditText) findViewById(R.id.etCallBack); etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); tvCallBackSend= (TextView) findViewById(R.id.tvCallBackSend); rvCallBack= (RecyclerView) findViewById(R.id.rvCallBack); rvActiveUserList= (RecyclerView) findViewById(R.id.rvActiveUserList); rlAll= (RelativeLayout) findViewById(R.id.rlAll); ivDetailImage=(ImageView) findViewById(R.id.ivDetailImage); ivBack=(ImageView) findViewById(R.id.ivDetailBack); tvDetailTitle=(TextView) findViewById(R.id.tvDetailTitle); tvDetailCountDown=(TextView) findViewById(R.id.tvDetailCountDown); tvDetailMoney=(TextView) findViewById(R.id.tvDetailMoney); tvDetailPeopleNumber=(TextView) findViewById(R.id.tvDetailPeopleNumber); tvDetailSignUp=(TextView) findViewById(R.id.tvDetailSignUp); tvDetailAddress=(TextView) findViewById(R.id.tvDetailAddress); tvDetailTime=(TextView) findViewById(R.id.tvDetailTime); tvDetailPhone=(TextView) findViewById(R.id.tvDetailPhone); tvDescContent=(WebView) findViewById(R.id.tvDescContent); ivMoreChoice= (ImageView) findViewById(R.id.ivMoreChoice); view = getLayoutInflater().inflate(R.layout.share_dialog, null); llShareToFriends= (LinearLayout) view.findViewById(R.id.llShareToFriends); llShareToWeiChat= (LinearLayout) view.findViewById(R.id.llShareToWeiChat); llShareToQQ= (LinearLayout) view.findViewById(R.id.llShareToQQ); llShareToQQZone= (LinearLayout) view.findViewById(R.id.llShareToQQZone); llShareToMicroBlog= (LinearLayout) view.findViewById(R.id.llShareToMicroBlog); tvCollect= (TextView) view.findViewById(R.id.tvCollect); tvReport= (TextView) view.findViewById(R.id.tvReport); tvDelete= (TextView) view.findViewById(R.id.tvDelete); tvTop= (TextView) view.findViewById(R.id.tvTop); tvSpacial= (TextView) view.findViewById(R.id.tvSpacial); ivClose= (ImageView) view.findViewById(R.id.ivClose); tvTop.setVisibility(View.GONE); tvSpacial.setVisibility(View.GONE); tvDelete.setVisibility(View.GONE); ivMoreChoice.setOnClickListener(this); llShareToFriends.setOnClickListener(this); llShareToWeiChat.setOnClickListener(this); llShareToQQ.setOnClickListener(this); llShareToQQZone.setOnClickListener(this); llShareToMicroBlog.setOnClickListener(this); tvCollect.setOnClickListener(this); tvReport.setOnClickListener(this); tvDelete.setOnClickListener(this); tvTop.setOnClickListener(this); tvSpacial.setOnClickListener(this); tvDetailSignUp.setOnClickListener(this); tvDetailPeopleNumber.setOnClickListener(this); tvCallBackSend.setOnClickListener(this); reflesh.setOnRefreshListener(this); tvDetailPhone.setOnClickListener(this); final Dialog dialog= new Dialog(this,R.style.Dialog_Fullscreen); getWindow().setBackgroundDrawableResource(android.R.color.transparent); dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.main_menu_animstyle); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 wl.width = ViewGroup.LayoutParams.MATCH_PARENT; wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 dialog.onWindowAttributesChanged(wl); // 设置点击外围解散 dialog.setCanceledOnTouchOutside(true); ivMoreChoice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { view.setVisibility(View.VISIBLE); dialog.show(); } }); ivClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } private void initData() { if (recentActiveData==null&&activeID!=0){ getMSGFromNetwork(activeID); }else { memberCount=recentActiveData.getLoverNum(); maxPeople=recentActiveData.getMaxpeople(); startTime=recentActiveData.getStartTime(); endTime=recentActiveData.getEndTime(); phone=recentActiveData.getPhone(); descContent=recentActiveData.getDetail(); title=recentActiveData.getTitle(); activeID=recentActiveData.getId(); price=recentActiveData.getPrice(); imageUrl=recentActiveData.getPictureURL(); address=recentActiveData.getAddress(); handler.sendEmptyMessage(HANDLE_HISTORY_DATA); } reflesh.setRefreshing(false); } public void getMSGFromNetwork(final int ID){ new Thread(){ @Override public void run() { try { String url= API.BASE_URL+"/v1/activity/query"; HashMap<String,String> params=new HashMap<>(); params.put("id",ID+""); params.put("pageNumber",1+""); params.put("createId",userId); params.put("page", 1 + ""); String result= PostUtil.sendPostMessage(url,params); JSONObject object=new JSONObject(result); JSONArray array=object.getJSONArray("data"); JSONObject data=array.getJSONObject(0); memberCount=data.getInt("memberCount"); isCollected=((data.getInt("isCollection"))==1)?true:false; activeID=data.getInt("id"); maxPeople=data.getString("maxPeople"); startTime=data.getLong("startTime"); endTime=data.getLong("endTime"); lastTime=data.getLong("lastTime"); phone=data.getString("phone"); descContent=data.getString("descContent"); title=data.getString("title"); price=data.getInt("price"); imageUrl=data.getString("imgUrls"); address=data.getString("address"); handler.sendEmptyMessage(HANDLE_NEW_ACTIVE_DATA); }catch (Exception e){ e.printStackTrace(); } } }.start(); } private void handleData(){ Long systemTime = new Date(System.currentTimeMillis()).getTime();//获取当前时间 surplusPeople = Integer.valueOf(maxPeople)-memberCount; //剩余报名人数 tvDetailTime.setText(TimeUtil.getDetailTime(startTime)+"~"+TimeUtil.getDetailTime(endTime)); tvDetailTitle.setText(title+""); PicassoUtil.handlePic(ActivityDetailsActivity.this, PicUtil.getImageUrlDetail(ActivityDetailsActivity.this, StringUtil.isNullAvatar(imageUrl), x, 1920),ivDetailImage,x,720); if(price==0){ tvDetailMoney.setText("免费"); }else { tvDetailMoney.setText("¥"+price); } tvDetailAddress.setText(address+""); tvDetailPhone.setText(phone+""); if(maxPeople==null){ tvDetailPeopleNumber.setText("已报名"+memberCount); }else { if(surplusPeople>100000){ tvDetailPeopleNumber.setText("已报名"+memberCount+", "+"无限制"); }else { tvDetailPeopleNumber.setText("已报名" + memberCount + ", " + "剩余" + surplusPeople + "个名额"); } } if(systemTime>=startTime&&systemTime<=endTime){ tvDetailCountDown.setText("活动已开始"); } if(systemTime>=startTime&&systemTime>=endTime){ tvDetailCountDown.setText("活动已结束"); tvDetailSignUp.setBackgroundColor(getResources().getColor(R.color.background)); tvDetailSignUp.setClickable(false); } if(systemTime<startTime){ String disTime=TimeUtil.getDisTime(systemTime, startTime); tvDetailCountDown.setText("活动倒计时:"+disTime); tvDetailSignUp.setText("报名"); } WindowManager wm = (WindowManager) ActivityDetailsActivity.this.getSystemService(Context.WINDOW_SERVICE); int width = wm.getDefaultDisplay().getWidth(); if(width > 520){ this.tvDescContent.setInitialScale(160); }else if(width > 450){ this.tvDescContent.setInitialScale(140); }else if(width > 300){ this.tvDescContent.setInitialScale(120); }else{ this.tvDescContent.setInitialScale(100); } tvDescContent.loadDataWithBaseURL(null, descContent, "text/html", "utf-8", null); tvDescContent.getSettings().setJavaScriptEnabled(true); // 设置启动缓存 ; tvDescContent.getSettings().setAppCacheEnabled(true); tvDescContent.setWebChromeClient(new WebChromeClient()); tvDescContent.getSettings().setJavaScriptEnabled(true); if (isCollected){ tvCollect.setText("取消收藏"); }else { tvCollect.setText("收藏"); } } private void shareToFriends() { if (!checkLogIn()){return;}; Toast.makeText(this, "分享到朋友圈!", Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToWeiChat() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到微信!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToQQ() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到QQ!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToQQZone() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到QQ空间!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToMicroBlog() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到微博!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void collect() { if (!checkLogIn()){return;}; if (isCollected){ CollectUtil.goToCancelCollect(handler, token, 1, activeID); }else { CollectUtil.goToCollect(handler,token,1,activeID); } } private void report() { if (!checkLogIn()){return;}; Toast.makeText(this,"已举报!",Toast.LENGTH_SHORT).show(); } private void delete() { if (!checkLogIn()){return;}; Toast.makeText(this,"已删除!",Toast.LENGTH_SHORT).show(); } private void spacial() { if (!checkLogIn()){return;}; Toast.makeText(this,"已加精!",Toast.LENGTH_SHORT).show(); } private void toTop() { if (!checkLogIn()){return;}; Toast.makeText(this,"已置顶!",Toast.LENGTH_SHORT).show(); } private boolean checkLogIn(){ boolean isStateOk=true; if (!App.isNetStateOK){ Toast.makeText(this,"亲,没网了呢!",Toast.LENGTH_SHORT).show(); isStateOk=false; }else { if (token.equals("") || !App.isStateOK) { Toast.makeText(this, "您还没登陆呢,亲!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(ActivityDetailsActivity.this, LoginActivity.class); ActivityDetailsActivity.this.startActivity(intent); isStateOk = false; } } return isStateOk; } @Override public void onClick(View view) { switch (view.getId()){ case R.id.tvCallBackSend: handleSendMSG(); break; case R.id.llShareToFriends: shareToFriends(); break; case R.id.llShareToWeiChat: shareToWeiChat(); break; case R.id.llShareToQQ: shareToQQ(); break; case R.id.llShareToQQZone: shareToQQZone(); break; case R.id.llShareToMicroBlog: shareToMicroBlog(); break; case R.id.tvCollect: collect(); break; case R.id.tvReport: report(); break; case R.id.tvDelete: delete(); break; case R.id.tvSpacial: spacial(); break; case R.id.tvTop: toTop(); break; case R.id.tvDetailPhone: final AlertDialog builder = new AlertDialog.Builder(ActivityDetailsActivity.this).create(); builder.setView(getLayoutInflater().inflate(R.layout.activity_personal_dialog, null)); builder.show(); //去掉dialog四边的黑角 builder.getWindow().setBackgroundDrawable(new BitmapDrawable()); TextView text=(TextView) builder.getWindow().findViewById(R.id.text); text.setText("直接拨打"+tvDetailPhone.getText()+"?"); builder.getWindow().findViewById(R.id.dialog_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { builder.dismiss(); } }); TextView dialog_confirm=(TextView)builder.getWindow().findViewById(R.id.dialog_confirm); dialog_confirm.setText("拨打"); dialog_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+tvDetailPhone.getText().toString().trim())); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); builder.dismiss(); } }); break; case R.id.tvDetailPeopleNumber: if (!checkLogIn()){return;}; //首页banner还没有传参数过来 if(UserId==Userid){ Intent i=new Intent(ActivityDetailsActivity.this,AuditActivity.class); i.putExtra("activityId",activeID); startActivity(i); }else {} break; case R.id.tvDetailSignUp: if (!checkLogIn()){return;}; Intent i=new Intent(ActivityDetailsActivity.this,SignUpActivity.class); i.putExtra("activityId",activeID); i.putExtra("imageUrl",imageUrl); i.putExtra("title",title); i.putExtra("price",price); startActivityForResult(i,100); break; } } String toNickName; public static final int CALL_BACK_TYPE_ONE=1111; public static final int CALL_BACK_TYPE_TWO=2222; public static int type; private void handleSendMSG() { toNickName=etCallBack.getHint().toString().trim().substring(2); if(!App.isStateOK|token.equals("")){ Toast.makeText(ActivityDetailsActivity.this,"您还没有登录,请登陆!",Toast.LENGTH_SHORT).show(); ActivityDetailsActivity.this.startActivity(new Intent(ActivityDetailsActivity.this,LoginActivity.class)); return; }else { String comment = etCallBack.getText().toString().trim(); if (isComment) { if (comment.equals("")) { Toast.makeText(ActivityDetailsActivity.this, "回复内容为空!", Toast.LENGTH_SHORT).show();//非空判断 setBaseState(); return; } else {//评论活动 etCallBack.setText(""); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(etCallBack.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); CallBackUtil.handleCallBackMSG(2, activeID, Integer.valueOf(userId), comment); CallBackEntity entity = new CallBackEntity(); entity.setCallBackImgUrl(StringUtil.isNullAvatar(avatar)); entity.setCallBackNickName(nickName); entity.setCallBackTime(System.currentTimeMillis()); entity.setCallBackText(comment); entity.setEntities(new ArrayList<CallBackDetailEntity>()); commentList.add(entity); commentAdapter.notifyItemChanged(commentList.size() - 1); rvCallBack.scrollToPosition(0); autoRefresh(); } } else { if (comment.equals("")) { Toast.makeText(ActivityDetailsActivity.this, "回复内容为空!", Toast.LENGTH_SHORT).show();//非空判断 isComment = true; setBaseState(); return; }else { if (toNickName.equals(nickName)) { Toast.makeText(ActivityDetailsActivity.this, "不能回复自己!", Toast.LENGTH_SHORT).show(); isComment = true; setBaseState(); return; } else { if (type==CALL_BACK_TYPE_TWO){//2号类型回复 int callBackPOS=CallBackAdapter.callBackToPOS; int commentID = commentList.get(callBackPOS).getCommentID(); int toID = CallBackAdapter.callBackToID; ArrayList<CallBackDetailEntity> detailMSGList = CallBackAdapter.MSGS; CallBackUtil.handleBack(token, commentID, Integer.valueOf(userId), toID, comment, detailMSGList, handler, HANDLE_MAIN_USER_BACK, nickName, toNickName); isComment = true; autoRefresh(); }else{//1号类型回复 int commentID = commentList.get(notifyPos).getCommentID(); etCallBack.setText(""); CallBackUtil.handleBack(token, commentID, Integer.valueOf(userId), -1, comment, detailMSGs, handler, HANDLE_MAIN_USER_BACK, nickName, ""); isComment = true; autoRefresh(); } } } } } } private void setBaseState(){ etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==100){ if(resultCode==10){ View view=getLayoutInflater().inflate(R.layout.apply_dialog, null); final Dialog dialog = new Dialog(ActivityDetailsActivity.this, R.style.transparentFrameWindowStyle); ImageView im_cancel=(ImageView) view.findViewById(R.id.im_cancel); im_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); } } } @Override protected void onResume() { super.onResume(); handleData(); etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); if (commentList.size()!=0){ commentList.clear(); setCallBackView(); } getSignUpInfo(); } @Override public void onRefresh() { setCallBackView(); handleData(); etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 reflesh.setRefreshing(false); } }, 1000); } } <file_sep>/app/src/main/java/com/gymnast/data/hotinfo/RecentBigActivity.java package com.gymnast.data.hotinfo; import java.io.Serializable; /** * Created by Administrator on 2016/7/27. */ public class RecentBigActivity implements Serializable { int bigPic,pictureA,pictureB,pictureC,pictureD; String bigTitle;// int bigNum; String bigTitleA; String bigTitleB; String bigTitleC; String bigTitleD; String bigTypeA; String bigTypeB; String bigTypeC; String bigTypeD; String bigLoveA; String bigLoveB; String bigLoveC; String bigLoveD; public RecentBigActivity() { } public int getBigNum() { return bigNum; } public void setBigNum(int bigNum) { this.bigNum = bigNum; } public String getBigTitle() { return bigTitle; } public void setBigTitle(String bigTitle) { this.bigTitle = bigTitle; } public int getPictureD() { return pictureD; } public void setPictureD(int pictureD) { this.pictureD = pictureD; } public String getBigTitleA() { return bigTitleA; } public void setBigTitleA(String bigTitleA) { this.bigTitleA = bigTitleA; } public String getBigTitleB() { return bigTitleB; } public void setBigTitleB(String bigTitleB) { this.bigTitleB = bigTitleB; } public String getBigTitleC() { return bigTitleC; } public void setBigTitleC(String bigTitleC) { this.bigTitleC = bigTitleC; } public String getBigTitleD() { return bigTitleD; } public void setBigTitleD(String bigTitleD) { this.bigTitleD = bigTitleD; } public String getBigTypeA() { return bigTypeA; } public void setBigTypeA(String bigTypeA) { this.bigTypeA = bigTypeA; } public String getBigTypeB() { return bigTypeB; } public void setBigTypeB(String bigTypeB) { this.bigTypeB = bigTypeB; } public String getBigTypeC() { return bigTypeC; } public void setBigTypeC(String bigTypeC) { this.bigTypeC = bigTypeC; } public String getBigTypeD() { return bigTypeD; } public void setBigTypeD(String bigTypeD) { this.bigTypeD = bigTypeD; } public String getBigLoveA() { return bigLoveA; } public void setBigLoveA(String bigLoveA) { this.bigLoveA = bigLoveA; } public String getBigLoveB() { return bigLoveB; } public void setBigLoveB(String bigLoveB) { this.bigLoveB = bigLoveB; } public String getBigLoveC() { return bigLoveC; } public void setBigLoveC(String bigLoveC) { this.bigLoveC = bigLoveC; } public String getBigLoveD() { return bigLoveD; } public void setBigLoveD(String bigLoveD) { this.bigLoveD = bigLoveD; } public int getBigPic() { return bigPic; } public void setBigPic(int bigPic) { this.bigPic = bigPic; } public int getPictureA() { return pictureA; } public void setPictureA(int pictureA) { this.pictureA = pictureA; } public int getPictureB() { return pictureB; } public void setPictureB(int pictureB) { this.pictureB = pictureB; } public int getPictureC() { return pictureC; } public void setPictureC(int pictureC) { this.pictureC = pictureC; } } <file_sep>/app/src/main/java/com/gymnast/view/dialog/QuickOptionDialog.java package com.gymnast.view.dialog; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Display; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import com.gymnast.R; import com.gymnast.view.hotinfoactivity.activity.PromulgateActivityActivity; import com.gymnast.view.live.activity.CreateLiveActivity; import com.gymnast.view.live.activity.SearchActivity; import com.gymnast.view.pack.view.PlayActivityIssueActivity; import com.gymnast.view.personal.activity.PersonalActivity; import com.gymnast.view.personal.activity.PersonalCircleCreateActivity; public class QuickOptionDialog extends Dialog implements View.OnClickListener { Context context; private ImageView mClose; public interface OnQuickOptionformClick { void onQuickOptionClick(int id); } private OnQuickOptionformClick mListener; private QuickOptionDialog(Context context, boolean flag, OnCancelListener listener) { super(context, flag, listener); } @SuppressLint("InflateParams") private QuickOptionDialog(Context context, int defStyle) { super(context, defStyle); this.context=context; View contentView = getLayoutInflater().inflate(R.layout.activity_home_tab_quick_option_dialog, null); contentView.findViewById(R.id.ll_quick_option_activity).setOnClickListener(this); contentView.findViewById(R.id.ll_quick_option_live).setOnClickListener(this); contentView.findViewById(R.id.ll_quick_option_dynamic).setOnClickListener(this); contentView.findViewById(R.id.ll_quick_option_concern).setOnClickListener(this); contentView.findViewById(R.id.ll_quick_option_circle).setOnClickListener(this); contentView.findViewById(R.id.ll_quick_option_task).setOnClickListener(this); mClose = (ImageView) contentView.findViewById(R.id.iv_close); Animation operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.quick_option_dialog_close); LinearInterpolator lin = new LinearInterpolator(); operatingAnim.setInterpolator(lin); mClose.startAnimation(operatingAnim); mClose.setOnClickListener(this); requestWindowFeature(Window.FEATURE_NO_TITLE); contentView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { QuickOptionDialog.this.dismiss(); return true; } }); super.setContentView(contentView); } public QuickOptionDialog(Context context) { this(context, R.style.quick_option_dialog); } @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); getWindow().setGravity(Gravity.BOTTOM); WindowManager m = getWindow().getWindowManager(); Display d = m.getDefaultDisplay(); WindowManager.LayoutParams p = getWindow().getAttributes(); p.width = d.getWidth(); getWindow().setAttributes(p); } public void setOnQuickOptionformClickListener(OnQuickOptionformClick lis) { mListener = lis; } @Override public void onClick(View v) { final int id = v.getId(); switch (id) { case R.id.iv_close: dismiss(); break; case R.id.ll_quick_option_activity: context.startActivity(new Intent(context, PromulgateActivityActivity.class)); dismiss(); break; case R.id.ll_quick_option_live: context.startActivity(new Intent(context, CreateLiveActivity.class)); break; case R.id.ll_quick_option_dynamic: context.startActivity(new Intent(context, PlayActivityIssueActivity.class)); break; case R.id.ll_quick_option_concern: context.startActivity(new Intent(context, SearchActivity.class)); break; case R.id.ll_quick_option_circle: context.startActivity(new Intent(context, PersonalCircleCreateActivity.class)); break; case R.id.ll_quick_option_task: Intent i= new Intent(context, PersonalActivity.class); i.putExtra("page",2); context.startActivity(i); break; default: break; } if (mListener != null) { mListener.onQuickOptionClick(id); } dismiss(); } }<file_sep>/app/src/main/java/com/gymnast/utils/CollectUtil.java package com.gymnast.utils; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.widget.TextView; import android.widget.Toast; import com.gymnast.App; import com.gymnast.data.net.API; import org.json.JSONObject; import java.util.HashMap; /** * Created by zzqybyb19860112 on 2016/9/22. */ public class CollectUtil { public static final int TO_COLLECT=111111; public static final int CANCEL_COLLECT=222222; public static final int ERROR=333333; public static void toCollect(Context context, final Handler handler, final int modelID,final TextView tvLove){ SharedPreferences share=context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE); final String token=share.getString("Token", ""); if (token==null|| !App.isStateOK||token.equals("")){ Toast.makeText(context, "您还没有登陆呢!", Toast.LENGTH_SHORT).show(); return; } new Thread(){ @Override public void run() { try{ String uri= API.BASE_URL+"/v1/collect/create"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("model","1"); params.put("modelId",modelID+""); String result= PostUtil.sendPostMessage(uri,params); JSONObject object=new JSONObject(result); Message message=new Message(); message.obj=tvLove; if (object.getInt("state")==200){ message.what=TO_COLLECT; handler.sendMessage(message); }else { message.what=ERROR; handler.sendMessage(message); } }catch (Exception e){ e.printStackTrace(); } } }.start(); } public static void goToCollect(final Handler handler, final String token, final int model, final int modelID){ new Thread(){ @Override public void run() { try{ String uri= API.BASE_URL+"/v1/collect/create"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("model",model+""); params.put("modelId",modelID+""); String result= PostUtil.sendPostMessage(uri,params); JSONObject object=new JSONObject(result); if (object.getInt("state")==200){ handler.sendEmptyMessage(TO_COLLECT); }else { handler.sendEmptyMessage(ERROR); } }catch (Exception e){ e.printStackTrace(); } } }.start(); } public static void goToCancelCollect(final Handler handler, final String token,final int model, final int modelID){ new Thread(){ @Override public void run() { try{ String uri= API.BASE_URL+"/v1/collect/concel"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("model",model+""); params.put("modelId",modelID+""); String result= PostUtil.sendPostMessage(uri,params); JSONObject object=new JSONObject(result); if (object.getInt("state")==200){ handler.sendEmptyMessage(CANCEL_COLLECT); }else { handler.sendEmptyMessage(ERROR); } }catch (Exception e){ e.printStackTrace(); } } }.start(); } } <file_sep>/app/src/main/java/com/gymnast/view/live/adapter/BarrageItemAdapter.java package com.gymnast.view.live.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.gymnast.R; import com.gymnast.utils.PicassoUtil; import com.gymnast.view.live.entity.BarrageItem; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by 永不言败 on 2016/8/8. */ public class BarrageItemAdapter extends RecyclerView.Adapter { Context context; ArrayList<BarrageItem> lists; public BarrageItemAdapter(Context context,ArrayList<BarrageItem> lists){ this.context=context; if (lists.size()==0){ this.lists=new ArrayList<>(); }else { this.lists=lists; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View viewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycleview_barrage, null); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); viewItem.setLayoutParams(lp); return new BarrageViewHolder(viewItem); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final BarrageViewHolder viewHolder= (BarrageViewHolder) holder; BarrageItem item=lists.get(position); PicassoUtil.handlePic(context, item.getPhotoUrl(), viewHolder.civPhoto, 72, 72); viewHolder.tvTime.setText(item.getTime()); viewHolder.tvBody.setText(item.getBody()); final int[] priseNo = {item.getPriseNumber()}; viewHolder.tvPriseNumber.setText(priseNo[0] +"");//其他人点了赞也要能显示 viewHolder.tvPriseNumber.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { priseNo[0]++; viewHolder.tvPriseNumber.setText(priseNo[0] +""); viewHolder.tvPriseNumber.invalidate(); } }); viewHolder.tvName.setText(item.getName()); } @Override public int getItemCount() { return lists.size(); } class BarrageViewHolder extends RecyclerView.ViewHolder{ CircleImageView civPhoto; TextView tvTime,tvBody,tvPriseNumber,tvName; public BarrageViewHolder(View itemView) { super(itemView); civPhoto= (CircleImageView) itemView.findViewById(R.id.civPhoto); tvTime= (TextView) itemView.findViewById(R.id.tvTime); tvBody= (TextView) itemView.findViewById(R.id.tvBody); tvPriseNumber= (TextView) itemView.findViewById(R.id.tvPriseNumber); tvName= (TextView) itemView.findViewById(R.id.tvName); } } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonalEditNickNameActivity.java package com.gymnast.view.personal.activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.PostUtil; import com.gymnast.view.ImmersiveActivity; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * Created by Cymbi on 2016/8/16. */ public class PersonalEditNickNameActivity extends ImmersiveActivity { private EditText etEditName; private TextView tvEditNicknameSave; private String token,id,nickname; private ImageView ivEditNickNameBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_nickname); SharedPreferences share = getSharedPreferences("UserInfo",MODE_PRIVATE); token= share.getString("Token",""); id= share.getString("UserId",""); setView(); setListeners(); } private void setView() { etEditName=(EditText)findViewById(R.id.etEditName); tvEditNicknameSave=(TextView) findViewById(R.id.tvEditNicknameSave); ivEditNickNameBack=(ImageView) findViewById(R.id.ivEditNickNameBack); } private void setListeners() { ivEditNickNameBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); tvEditNicknameSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setdata(); } }); } private void setdata (){ new Thread(new Runnable() { @Override public void run() { try { String uri= API.BASE_URL+"/v1/account/info/edit"; Map<String, String> params=new HashMap<>(); params.put("token",token); params.put("account_id",id); nickname = etEditName.getText().toString(); params.put("nickname",nickname); String result= PostUtil.sendPostMessage(uri,params); JSONObject json = new JSONObject(result); if(json.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { finish(); Toast.makeText(PersonalEditNickNameActivity.this,"昵称修改成功",Toast.LENGTH_SHORT).show(); } }); } if(json.getInt("state")==301){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PersonalEditNickNameActivity.this,"请填写昵称",Toast.LENGTH_SHORT).show(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } } <file_sep>/app/src/main/java/com/gymnast/utils/StorePhotosUtil.java package com.gymnast.utils; import java.io.FileOutputStream; import java.io.IOException; import android.graphics.Bitmap; public class StorePhotosUtil { FileOutputStream fos; private Bitmap bitmap; private String fileName; public StorePhotosUtil(Bitmap bitmap, String fileName) { this.bitmap=bitmap; this.fileName=fileName; //调用存储方法 store(); } private void store() { try { if (bitmap!=null) { fos = new FileOutputStream(fileName); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (bitmap!=null) { fos.flush(); fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>/app/src/main/java/com/gymnast/view/home/adapter/SearchUserAdapter.java package com.gymnast.view.home.adapter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.GetUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.home.view.HomeSearchResultAcitivity; import com.gymnast.data.user.SearchUserEntity; import com.gymnast.view.personal.activity.PersonalOtherHomeActivity; import com.makeramen.roundedimageview.RoundedImageView; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by 永不言败 on 2016/8/9. */ public class SearchUserAdapter extends RecyclerView.Adapter implements Filterable { Context context; List<SearchUserEntity> entities; List<SearchUserEntity> mCopyInviteMessages; List<SearchUserEntity> inviteMessages; private static final int VIEW_TYPE = -1; public SearchUserAdapter(Context context, List<SearchUserEntity> entities) { this.context = context; if (entities.size()!=0){ this.entities = entities; }else { this.entities =new ArrayList<>(); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemview = LayoutInflater.from(context).inflate(R.layout.item_found_rv, null); LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); itemview.setLayoutParams(lp1); if(VIEW_TYPE==viewType){ LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); View view=LayoutInflater.from(context).inflate(R.layout.empty_view, parent, false); view.setLayoutParams(lp2); return new empty(view); } return new FoundViewHolder(itemview); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if(holder instanceof FoundViewHolder) { final SharedPreferences share= context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE); final String UserId = share.getString("UserId",""); final String token = share.getString("Token",""); final FoundViewHolder viewHolder = (FoundViewHolder) holder; final SearchUserEntity entity = entities.get(position); PicassoUtil.handlePic(context, PicUtil.getImageUrlDetail(context, StringUtil.isNullAvatar(entity.getPhotoUrl()), 72, 72),viewHolder.rivPhoto,72,72); viewHolder.tvLiveName.setText(entity.getName()); String Authinfo=entity.getAuthinfo(); if(Authinfo!=null&&!Authinfo.equals("null")){ viewHolder.tvType.setText(entity.getAuthinfo()); }else {viewHolder.tvType.setText("");} viewHolder.rivPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (entities.size() != 0) { Intent intent = new Intent(context, PersonalOtherHomeActivity.class); intent.putExtra("UserID", entity.getId()); context.startActivity(intent); } } }); final int toId=entity.getId(); viewHolder.tvConcern.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(new Runnable() { @Override public void run() { String uri= API.BASE_URL+"/v1/attention/user"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("fromId",UserId); params.put("toId",toId+""); String result= GetUtil.sendGetMessage(uri,params); try { JSONObject object=new JSONObject(result); if (object.getInt("state")==200){ final Activity activity=(Activity)context; activity.runOnUiThread(new Runnable() { @Override public void run() { viewHolder.tvConcern.setText("已关注"); viewHolder.tvConcern.setBackgroundResource(R.drawable.border_radius_concern); viewHolder.tvConcern.setTextColor(context.getResources().getColor(R.color.hot_info_circle_content_color)); Toast.makeText(context,"点击成功",Toast.LENGTH_SHORT).show(); } }); }else{Activity activity=(Activity)context; activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context,"已关注过了,请勿重复关注",Toast.LENGTH_SHORT).show(); } });} } catch (JSONException e) { e.printStackTrace(); Activity activity=(Activity)context; activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context,"已关注过了,请勿重复关注",Toast.LENGTH_SHORT).show(); } }); } } }).start(); } }); } } @Override public int getItemCount() { return entities.size() > 0 ? entities.size() : 1; } public void setFriends(List<SearchUserEntity> data) { //复制数据 mCopyInviteMessages = new ArrayList<>(); this.mCopyInviteMessages.addAll(data); this.inviteMessages = data; this.notifyDataSetChanged(); } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { //初始化过滤结果对象 FilterResults results = new FilterResults(); //假如搜索为空的时候,将复制的数据添加到原始数据,用于继续过滤操作 if (results.values == null) { entities.clear(); entities.addAll(mCopyInviteMessages); } //关键字为空的时候,搜索结果为复制的结果 if (constraint == null || constraint.length() == 0) { results.values = mCopyInviteMessages; results.count = mCopyInviteMessages.size(); } else { String searchText= HomeSearchResultAcitivity.getSearchText(); String prefixString; if (searchText.equals("")){ prefixString=searchText.toString(); }else { prefixString= constraint.toString(); } final int count = inviteMessages.size(); //用于存放暂时的过滤结果 final ArrayList<SearchUserEntity> newValues = new ArrayList<SearchUserEntity>(); for (int i = 0; i < count; i++) { final SearchUserEntity value = inviteMessages.get(i); String username = value.getName(); // First match against the whole ,non-splitted value,假如含有关键字的时候,添加 if (username.contains(prefixString)) { newValues.add(value); } else { //过来空字符开头 final String[] words = username.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].contains(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results;//过滤结果 } @Override protected void publishResults(CharSequence constraint, FilterResults results) { SearchUserAdapter.this.inviteMessages.clear();//清除原始数据 SearchUserAdapter.this.inviteMessages.addAll((List<SearchUserEntity>) results.values);//将过滤结果添加到这个对象 if (results.count > 0) { SearchUserAdapter.this.notifyDataSetChanged();//有关键字的时候刷新数据 } else { //关键字不为零但是过滤结果为空刷新数据 if (constraint.length() != 0) { SearchUserAdapter.this.notifyDataSetChanged(); return; } //加载复制的数据,即为最初的数据 SearchUserAdapter.this.setFriends(mCopyInviteMessages); } } }; } @Override public int getItemViewType(int position) { if (entities.size() <= 0) { return VIEW_TYPE; } return super.getItemViewType(position); } class empty extends RecyclerView.ViewHolder{ public empty(View itemView) { super(itemView); } } class FoundViewHolder extends RecyclerView.ViewHolder{ RoundedImageView rivPhoto; TextView tvLiveName,tvType,tvConcern; public FoundViewHolder(View itemView) { super(itemView); rivPhoto= (RoundedImageView) itemView.findViewById(R.id.rivPhoto); tvLiveName= (TextView) itemView.findViewById(R.id.tvLiveName); tvType= (TextView) itemView.findViewById(R.id.tvType); tvConcern= (TextView) itemView.findViewById(R.id.tvConcern); } } } <file_sep>/app/src/main/java/com/gymnast/utils/CacheUtils.java package com.gymnast.utils; import android.content.Context; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; /** * Created by zzqybyb19860112 on 2016/9/24. */ public class CacheUtils { public static File CacheRoot; /**       * 存储Json文件       * @param context       * @param json     json字符串       * @param fileName   存储的文件名       * @param append    true 增加到文件末,false则覆盖掉原来的文件       */ public static boolean writeJson(Context c, String json, String fileName, boolean append) { CacheRoot = Environment.getExternalStorageState() .equals(Environment.MEDIA_MOUNTED ) ? c .getExternalCacheDir():c.getCacheDir(); FileOutputStream fos=null; ObjectOutputStream os =null; try { File ff = new File(CacheRoot, fileName); Log.i("tag","write------>"+ff.getPath()); boolean boo=ff.exists(); fos=new FileOutputStream(ff, append); os=new ObjectOutputStream(fos); if (append && boo) { FileChannel fc=fos.getChannel(); fc.truncate(fc.position() - 4); } os.writeObject(json); } catch ( Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch ( Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch ( Exception e) { e.printStackTrace(); } } } return true; } /**       * 读取json数据       * @param c       * @param fileName       * @return 返回值为list       */ @SuppressWarnings("resource") public static List<String> readJson(Context c, String fileName) { CacheRoot = Environment.getExternalStorageState() .equals(Environment.MEDIA_MOUNTED ) ? c .getExternalCacheDir():c.getCacheDir(); FileInputStream fis=null; ObjectInputStream ois=null; List<String> result=new ArrayList<String>(); File des=new File(CacheRoot, fileName); try { fis=new FileInputStream(des); ois=new ObjectInputStream(fis); while (fis.available()>0) result.add((String) ois.readObject()); } catch ( Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch ( Exception e) { e.printStackTrace(); } } if (ois != null) { try { ois.close(); } catch (Exception e) { e.printStackTrace(); } } } return result; } } <file_sep>/app/src/main/java/com/gymnast/view/pack/view/ChoicenessCircleFragment.java package com.gymnast.view.pack.view; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.data.pack.ChoicenessData; import com.gymnast.data.personal.PostsData; import com.gymnast.utils.GetUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.pack.adapter.ChoicenessAdapter; import com.gymnast.view.pack.adapter.ImageAdapter; import com.gymnast.view.personal.activity.PersonalPostsDetailActivity; import com.gymnast.view.personal.adapter.CircleItemAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ChoicenessCircleFragment extends Fragment implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener{ private View view; private String token; private String id; private ImageView ivCircleMore; private RecyclerView rvCircle,rvPosts; private List<String> imageUrlList=new ArrayList<>(); private String imgUrls; private List<ChoicenessData> list=new ArrayList<>(); private List<PostsData> listdata=new ArrayList<>(); public static final int HANFLE_DATA_UPDATE=1; public static final int HANFLE_DATA_VP_START=2; public static final int HANFLE_DATA_VP_P=3; private ChoicenessAdapter choicenessAdapter; private CircleItemAdapter Circleadapter; private SwipeRefreshLayout swipeRefresh; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANFLE_DATA_UPDATE: choicenessAdapter = new ChoicenessAdapter(getActivity(),list); Circleadapter = new CircleItemAdapter(getActivity(),listdata); rvCircle.setAdapter(choicenessAdapter); rvPosts.setAdapter(Circleadapter); Circleadapter.setOnItemClickListener(new CircleItemAdapter.OnItemClickListener() { @Override public void OnItemClickListener(View view, int position) { PostsData postsData =listdata.get(position); Intent i=new Intent(getActivity(), PersonalPostsDetailActivity.class); int TieZiID= postsData.getId(); i.putExtra("TieZiID",TieZiID); getActivity().startActivity(i); } }); choicenessAdapter.notifyDataSetChanged(); Circleadapter.notifyDataSetChanged(); swipeRefresh.setRefreshing(false); break; } } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view=inflater.inflate(R.layout.fragment_pack_auslese,container,false); getInfo(); setview(); getcircle(); getposts(); getBanner(); return view; } private void getBanner() { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/deva/get"; HashMap<String,String> parmas=new HashMap<String, String>(); parmas.put("area",1+""); parmas.put("model",1+""); String result=GetUtil.sendGetMessage(uri,parmas); try { JSONObject object=new JSONObject(result); JSONArray activityDevas= object.getJSONArray("activityDevas"); for (int i=0;i<activityDevas.length();i++){ JSONObject json=activityDevas.getJSONObject(i); String title= json.getString("title"); imgUrls= json.getString("imgUrls"); int ActiveID=json.getInt("id"); int UserId=json.getInt("userId"); imageUrlList.add(API.IMAGE_URL+imgUrls); } handler.sendEmptyMessage(HANFLE_DATA_VP_START); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } public void getInfo() { SharedPreferences share= getActivity().getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token", ""); id = share.getString("UserId", ""); } private void getcircle() { new Thread(new Runnable() { public int id; public int circleItemCount; public String headImgUrl; public String title; @Override public void run() { String uri= API.BASE_URL+"/v1/deva/get"; HashMap<String,String> parmas=new HashMap<String, String>(); parmas.put("area",3+""); parmas.put("model",3+""); try { String result= GetUtil.sendGetMessage(uri,parmas); JSONObject obj=new JSONObject(result); JSONArray cirleDevas= obj.getJSONArray("cirleDevas"); for(int i=0;i<cirleDevas.length();i++) { JSONObject data = cirleDevas.getJSONObject(i); title = data.getString("title"); id = data.getInt("id"); headImgUrl = data.getString("bgmUrl"); circleItemCount = data.getInt("circleItemCount"); ChoicenessData choicenessData = new ChoicenessData(); choicenessData.setCircleItemCount(circleItemCount); choicenessData.setHeadImgUrl(headImgUrl); choicenessData.setTitle(title); choicenessData.setId(id); list.add(choicenessData); } handler.sendEmptyMessage(HANFLE_DATA_UPDATE); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } private void setview() { rvCircle=(RecyclerView)view.findViewById(R.id.auslese_lv_circle); rvPosts=(RecyclerView)view.findViewById(R.id.auslese_lv_posts); ivCircleMore=(ImageView)view.findViewById(R.id.ivCircleMore); ivCircleMore.setOnClickListener(this); swipeRefresh=(SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh); RefreshUtil.refresh(swipeRefresh,getActivity()); swipeRefresh.setOnRefreshListener(this); } public void getposts() { new Thread(new Runnable() { @Override public void run() { String uri2= API.BASE_URL+"/v1/circleItem/list"; Map<String,String> parmas2=new HashMap<String, String>(); parmas2.put("start",0+""); parmas2.put("pageSize",100+""); String result2= PostUtil.sendPostMessage(uri2,parmas2); try { JSONObject object=new JSONObject(result2); JSONArray data=object.getJSONArray("data"); for(int j=0;j<data.length();j++) { JSONObject datas = data.getJSONObject(j); String title = datas.getString("title"); long createTime = datas.getLong("createTime"); String content = datas.getString("baseContent"); String imgUrl = StringUtil.isNullAvatar(datas.getString("imgUrl")); imgUrl = PicUtil.getImageUrlDetail(getActivity(), imgUrl, 320, 320); String nickname = datas.getString("nickname"); String avatar = StringUtil.isNullAvatar(datas.getString("avatar")); String circleTitle = datas.getString("circleTitle"); int state = datas.getInt("state"); int zanCount = datas.getInt("zanCount"); int meetCount = datas.getInt("meetCount"); int circleId = datas.getInt("circleId"); int createId = datas.getInt("createId"); int id = datas.getInt("id"); JSONObject pageViews= datas.getJSONObject("pageViews"); int pageviews=pageViews.getInt("pageviews"); PostsData postsData = new PostsData(); postsData.setCreateTime(createTime); postsData.setTitle(title); postsData.setContent(content); postsData.setImgUrl(imgUrl); postsData.setNickname(nickname); postsData.setAvatar(avatar); postsData.setCircleTitle(circleTitle); postsData.setState(state); postsData.setZanCount(zanCount); postsData.setMeetCount(meetCount); postsData.setCircleId(circleId); postsData.setCreateId(createId); postsData.setId(id); postsData.setPageviews(pageviews); listdata.add(postsData); } handler.sendEmptyMessage(HANFLE_DATA_UPDATE); } catch (Exception e) { e.printStackTrace(); } } }).start(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.ivCircleMore: Intent i=new Intent(getActivity(), MoreCircleActivity.class); getActivity().startActivity(i); break; } } @Override public void onRefresh() { if(list.size()!=0||listdata.size()!=0){ list.clear(); listdata.clear(); getcircle(); getposts(); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 swipeRefresh.setRefreshing(false); } }, 1000); }else { } } @Override public void onResume() { super.onResume(); onRefresh(); } }<file_sep>/app/src/main/java/com/gymnast/view/pack/view/StarFragment.java package com.gymnast.view.pack.view; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.data.pack.ConcernData; import com.gymnast.data.personal.DynamicData; import com.gymnast.utils.GetUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.hotinfoactivity.activity.ActivityDetailsActivity; import com.gymnast.view.live.activity.LiveActivity; import com.gymnast.view.pack.adapter.ConcernAdapter; import com.gymnast.view.personal.activity.PersonalDynamicDetailActivity; import com.gymnast.view.personal.activity.PersonalPostsDetailActivity; import com.gymnast.view.personal.adapter.DynamicAdapter; import com.gymnast.view.user.LoginActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class StarFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{ RecyclerView rvMyConcern; List<ConcernData> activityList=new ArrayList<>(); private View view; private String token; private int start=0; private int pageSize=50; private LinearLayout llMyConcernLogin; private TextView tvMyConcernLogin; private String userId; private String authInfo; private SwipeRefreshLayout swipeRefresh; public static final int HANFLE_DATA_UPDATE=1; private ConcernAdapter adapter; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANFLE_DATA_UPDATE: adapter = new ConcernAdapter(getActivity(),activityList); rvMyConcern.setAdapter(adapter); adapter.setOnItemClickListener(new ConcernAdapter.OnItemClickListener() { @Override public void OnItemClickListener(View view, int position) { ConcernData item= activityList.get(position); String fromtype=item.getFromType(); if (activityList.size() != 0) { if (fromtype.equals("1")) { Intent i = new Intent(getActivity(), LiveActivity.class); i.putExtra("item", item); startActivity(i); } else if (fromtype .equals("2")) { int ActiveID = Integer.parseInt(item.getFromId()); Intent i = new Intent(getActivity(), ActivityDetailsActivity.class); i.putExtra("ActiveID", ActiveID); startActivity(i); } else if (fromtype.equals("3")) { int tieZiID = Integer.parseInt(item.getFromId()); Intent i = new Intent(getActivity(), PersonalPostsDetailActivity.class); i.putExtra("TieZiID", tieZiID); startActivity(i); }else if(fromtype.equals("null")){ Intent i=new Intent(getActivity(),PersonalDynamicDetailActivity.class); i.putExtra("CirleID",item.getId()); startActivity(i); } } } }); adapter.notifyDataSetChanged(); swipeRefresh.setRefreshing(false); break; } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_recyclerview, container, false); SharedPreferences share = getActivity().getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",null); userId = share.getString("UserId",null); setview(); initView(); getdata(); return view; } private void initView() { if(TextUtils.isEmpty(token)){ llMyConcernLogin.setVisibility(View.VISIBLE); rvMyConcern.setVisibility(View.GONE); swipeRefresh.setVisibility(View.GONE); }else { llMyConcernLogin.setVisibility(View.GONE); rvMyConcern.setVisibility(View.VISIBLE); } tvMyConcernLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); } private void setview() { rvMyConcern = (RecyclerView) view.findViewById(R.id.rvMyConcern); llMyConcernLogin= (LinearLayout) view.findViewById(R.id.llMyConcernLogin); tvMyConcernLogin= (TextView) view.findViewById(R.id.tvMyConcernLogin); swipeRefresh=(SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh); RefreshUtil.refresh(swipeRefresh,getActivity()); swipeRefresh.setOnRefreshListener(this); } public void getdata() { new Thread(new Runnable() { public String returnType; private String returnfromId; @Override public void run() { try { String uri= API.BASE_URL+"/v1/concern/starConcern/"+start+"/"+pageSize; HashMap<String,String> params=new HashMap<String, String>(); String result= GetUtil.sendGetMessage(uri,params); JSONObject json=new JSONObject(result); JSONArray data = json.getJSONArray("data"); for (int i=0;i<data.length();i++){ ArrayList<String> imageURL=new ArrayList<String>(); JSONObject object= data.getJSONObject(i); JSONObject userVo= object.getJSONObject("userVo"); JSONObject pageViews= object.getJSONObject("pageViews"); int pageviews=pageViews.getInt("pageviews"); String tempAuth= StringUtil.isNullAuth(object.getString("userAuthVo")); if(!tempAuth.equals("")){ JSONObject accountAuth=new JSONObject(tempAuth); authInfo=accountAuth.getString("authInfo"); } String returnNickName=userVo.getString("nickName"); String returnAvatar=userVo.getString("avatar"); int returnAuthenticate=userVo.getInt("authenticate"); int returnId=object.getInt("id"); int returnUserId=object.getInt("userId"); long returnCreateTime= object.getLong("createTime"); if(object.getString("fromType")!=null){ returnType=object.getString("fromType"); }else {} if(object.getString("fromId")!=null){ returnfromId=object.getString("fromId"); }else {} String returnTopicTitle= object.getString("topicTitle"); String returnTopicContent=object.getString("topicContent"); int returnZanCounts=object.getInt("zanCounts"); int returnCommentCounts=object.getInt("commentCounts"); String returnVideoUrl=object.getString("videoUrl"); int returnState=object.getInt("state"); String urls= object.getString("imgUrl"); if (urls==null|urls.equals("null")|urls.equals("")){ }else { String [] imageUrls=urls.split(","); for (int j=0;j<imageUrls.length;j++){ imageURL.add(API.IMAGE_URL+imageUrls[j]); } } ConcernData data1=new ConcernData(); data1.setId(returnId); data1.setUserId(returnUserId); data1.setFromType(returnType); data1.setFromId(returnfromId); data1.setImgUrl(imageURL); data1.setPageviews(pageviews); data1.setNickName(returnNickName); data1.setTopicContent(returnTopicContent); data1.setTopicTitle(returnTopicTitle); data1.setAuthenticate(returnAuthenticate); data1.setAvatar(returnAvatar); data1.setCommentCounts(returnCommentCounts); data1.setZanCounts(returnZanCounts); data1.setCreateTime(returnCreateTime); if(!tempAuth.equals("")){ data1.setAuthInfo(authInfo); } data1.setState(returnState); data1.setAuthInfo(""); //data1.setTopicVisible(return_topicVisible); activityList.add(data1); } handler.sendEmptyMessage(HANFLE_DATA_UPDATE); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } @Override public void onRefresh() { if(activityList.size()!=0){ activityList.clear(); getdata(); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 swipeRefresh.setRefreshing(false); } }, 1000); }else { } } }<file_sep>/app/src/main/java/com/gymnast/view/home/adapter/HotInfoCircleRecyclerViewAdapter.java package com.gymnast.view.home.adapter; import android.app.Activity; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import com.gymnast.R; import com.gymnast.data.hotinfo.CirleDevas; import com.gymnast.utils.GlobalInfoUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.personal.activity.PersonalCircleActivity; import com.gymnast.view.personal.activity.PersonalOtherHomeActivity; import com.gymnast.view.personal.activity.PersonalPostsDetailActivity; import com.makeramen.roundedimageview.RoundedImageView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class HotInfoCircleRecyclerViewAdapter extends RecyclerView.Adapter<HotInfoCircleRecyclerViewAdapter.ViewHolder> { private final List<CirleDevas> mValues; private Activity activity; public HotInfoCircleRecyclerViewAdapter(Activity activity, List<CirleDevas> items) { mValues = items; this.activity = activity; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_hot_info_circle, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { final CirleDevas circle = mValues.get(position); if (circle != null) { String imageUrl= StringUtil.isNullAvatar(circle.userIconVo.avatar); PicassoUtil.handlePic(activity, imageUrl, holder.circleUserHead, 320, 320); SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日 HH:mm"); String time=sdf.format(new Date(circle.createTime))+""; if (time.startsWith("0")){ time=time.substring(1); } holder.circleArticleTime.setText(time); holder.circleArticleTitle.setText(circle.title+""); holder.circleArticleContent.setText(circle.baseContent + ""); holder.circleFrom.setText(circle.circleTitle+""); holder.circleUserName.setText(circle.userIconVo.nickname+""); holder.circleViewer.setText(circle.viewCount+"次浏览"); holder.circleLike.setText(circle.zanCount+""); holder.circleDiscuss.setText(circle.comCount+""); if(circle.userIconVo.authInfo!=null&&!circle.userIconVo.authInfo.equals("")){ holder.tvAuthInfo.setVisibility(View.VISIBLE); holder.tvAuthInfo.setText(circle.userIconVo.authInfo+""); }else { holder.tvAuthInfo.setVisibility(View.GONE); } holder.circleFrom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(activity, PersonalCircleActivity.class); i.putExtra("CircleId",circle.circleId); activity.startActivity(i); } }); holder.circleUserHead.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(activity, PersonalOtherHomeActivity.class); i.putExtra("UserID",circle.userIconVo.id); activity.startActivity(i); } }); } holder.linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(activity,PersonalPostsDetailActivity.class); i.putExtra("TieZiID",circle.id); activity.startActivity(i); } }); } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.hot_info_circle_user_head1) RoundedImageView circleUserHead; @BindView(R.id.hot_info_circle_user_name1) TextView circleUserName; @BindView(R.id.hot_info_circle_article_time1) TextView circleArticleTime; @BindView(R.id.hot_info_circle_article_title1) TextView circleArticleTitle; @BindView(R.id.hot_info_circle_article_content1) TextView circleArticleContent; @BindView(R.id.hot_info_circle_viewer1) TextView circleViewer;//浏览人次数 @BindView(R.id.hot_info_circle_discuss1) TextView circleDiscuss;//消息条数 @BindView(R.id.hot_info_circle_like1) TextView circleLike;//点赞人次数 @BindView(R.id.linearLayout)LinearLayout linearLayout; @BindView(R.id.hot_info_circle_from1) TextView circleFrom; @BindView(R.id.tvAuthInfo) TextView tvAuthInfo; public ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonalConsigneeActivity.java package com.gymnast.view.personal.activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.PostUtil; import com.gymnast.view.ImmersiveActivity; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * Created by Cymbi on 2016/8/18. */ public class PersonalConsigneeActivity extends ImmersiveActivity { private EditText et_activity_name; private TextView save; private String nickname; private String token,id; private ImageView back; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_consignee); SharedPreferences share = getSharedPreferences("UserInfo",MODE_PRIVATE); token= share.getString("Token",""); id= share.getString("UserId",""); setView(); setListeners(); } private void setView() { et_activity_name=(EditText)findViewById(R.id.et_activity_name); save=(TextView) findViewById(R.id.save); back=(ImageView) findViewById(R.id.personal_back); } private void setListeners() { back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setData(); } }); } private void setData (){ new Thread(new Runnable() { @Override public void run() { try { String uri= API.BASE_URL+"/v1/account/info/edit"; Map<String, String> params=new HashMap<>(); params.put("token",token); params.put("account_id",id); nickname = et_activity_name.getText().toString(); params.put("nickname",nickname); String result= PostUtil.sendPostMessage(uri,params); JSONObject json = new JSONObject(result); if(json.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { finish(); Toast.makeText(PersonalConsigneeActivity.this,"昵称修改成功",Toast.LENGTH_SHORT).show(); } }); } if(json.getInt("state")==301){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PersonalConsigneeActivity.this,"请填写昵称",Toast.LENGTH_SHORT).show(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } } <file_sep>/app/src/main/java/com/gymnast/view/home/adapter/SearchCircleAdapter.java package com.gymnast.view.home.adapter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.data.personal.CircleData; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.PostUtil; import com.gymnast.view.home.view.HomeSearchResultAcitivity; import com.gymnast.view.personal.activity.PersonalCircleActivity; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by zzqybyb19860112 on 2016/9/5. */ public class SearchCircleAdapter extends RecyclerView.Adapter implements Filterable { private final List<CircleData> mValues ; List<CircleData> mCopyInviteMessages; List<CircleData> inviteMessages; private Context context; private static final int VIEW_TYPE = -1; public SearchCircleAdapter( Context context,List<CircleData> mValues) { this.context=context; if(mValues.size()==0){ this.mValues = new ArrayList<>(); }else { this.mValues = mValues; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemview = LayoutInflater.from(context).inflate(R.layout.item_circle_rv, null); LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); itemview.setLayoutParams(lp1); if(VIEW_TYPE==viewType){ LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); View view=LayoutInflater.from(context).inflate(R.layout.empty_view, parent, false); view.setLayoutParams(lp2); return new empty(view); } return new CircleItemViewHolder(itemview); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { SharedPreferences share= context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE); final String UserId = share.getString("UserId", ""); final String token = share.getString("Token",""); if (viewHolder instanceof CircleItemViewHolder) { final CircleItemViewHolder holder= (CircleItemViewHolder) viewHolder; final CircleData data = mValues.get(position); PicassoUtil.handlePic(context, PicUtil.getImageUrlDetail(context, data.getHeadImgUrl(), 320, 320), holder.ivCirclePhoto, 320, 320); holder.tvCircleName.setText(data.getTitle()); holder.tvCircleName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mValues.size()!=0) { Intent i = new Intent(context, PersonalCircleActivity.class); i.putExtra("CircleId", data.getId()); context.startActivity(i); } } }); holder.tvCircleType.setText(data.getDetails()); holder.tvCircleConcern.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/cern/add"; Map<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("concernId",data.getId()+""); params.put("accountId",UserId); params.put("concernType",4+""); String result= PostUtil.sendPostMessage(uri,params); try { JSONObject object=new JSONObject(result); if(object.getInt("state")==200){ Activity activity=(Activity)context; activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context,"关注成功",Toast.LENGTH_SHORT).show(); holder.tvCircleConcern.setText("已关注"); holder.tvCircleConcern.setBackgroundColor(context.getResources().getColor(R.color.background)); } }); }else { Activity activity=(Activity)context; activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context,"已关注过了,请勿重复关注",Toast.LENGTH_SHORT).show(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } }); } } @Override public int getItemCount() { return mValues.size() > 0 ? mValues.size() : 1; } public int getItemViewType(int position) { if (mValues.size() <= 0) { return VIEW_TYPE; } return super.getItemViewType(position); } public void setFriends(List<CircleData> data) { //复制数据 mCopyInviteMessages = new ArrayList<>(); this.mCopyInviteMessages.addAll(data); this.inviteMessages = data; this.notifyDataSetChanged(); } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { //初始化过滤结果对象 FilterResults results = new FilterResults(); //假如搜索为空的时候,将复制的数据添加到原始数据,用于继续过滤操作 if (results.values == null) { mValues.clear(); mValues.addAll(mCopyInviteMessages); } //关键字为空的时候,搜索结果为复制的结果 if (constraint == null || constraint.length() == 0) { results.values = mCopyInviteMessages; results.count = mCopyInviteMessages.size(); } else { String searchText= HomeSearchResultAcitivity.getSearchText(); String prefixString; if (searchText.equals("")){ prefixString=searchText.toString(); }else { prefixString= constraint.toString(); } final int count = inviteMessages.size(); //用于存放暂时的过滤结果 final ArrayList<CircleData> newValues = new ArrayList<CircleData>(); for (int i = 0; i < count; i++) { final CircleData value = inviteMessages.get(i); String username = value.getTitle(); // First match against the whole ,non-splitted value,假如含有关键字的时候,添加 if (username.contains(prefixString)) { newValues.add(value); } else { //过来空字符开头 final String[] words = username.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].contains(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results;//过滤结果 } @Override protected void publishResults(CharSequence constraint, FilterResults results) { SearchCircleAdapter.this.inviteMessages.clear();//清除原始数据 SearchCircleAdapter.this.inviteMessages.addAll((List<CircleData>) results.values);//将过滤结果添加到这个对象 if (results.count > 0) { SearchCircleAdapter.this.notifyDataSetChanged();//有关键字的时候刷新数据 } else { //关键字不为零但是过滤结果为空刷新数据 if (constraint.length() != 0) { SearchCircleAdapter.this.notifyDataSetChanged(); return; } //加载复制的数据,即为最初的数据 SearchCircleAdapter.this.setFriends(mCopyInviteMessages); } } }; } class empty extends RecyclerView.ViewHolder{ public empty(View itemView) { super(itemView); } } public class CircleItemViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.ivCirclePhoto) ImageView ivCirclePhoto; @BindView(R.id.tvCircleName) TextView tvCircleName; @BindView(R.id.tvCircleType) TextView tvCircleType; @BindView(R.id.tvCircleConcern) TextView tvCircleConcern; public CircleItemViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/fragment/AuditedFragment.java package com.gymnast.view.hotinfoactivity.fragment; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.gymnast.R; import com.gymnast.data.hotinfo.AuditData; import com.gymnast.data.net.API; import com.gymnast.utils.PostUtil; import com.gymnast.view.hotinfoactivity.adapter.AuditMainAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by Cymbi on 2016/9/12. */ public class AuditedFragment extends Fragment { private View view; private ImageView ivAvatar; private TextView tvUserName,tvPass,tvUser,tvPhone; private RecyclerView rvAudit; private RecyclerView mainRecyclerview; private int activityId; private SharedPreferences share; private String token,key,value,realname="",sex="",age="",phone="",address="",id=""; private List<AuditData> MainList=new ArrayList<>(); public static final int HANDLER_UPDATA=1; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case HANDLER_UPDATA: AuditMainAdapter adapter = new AuditMainAdapter(getActivity(),MainList); mainRecyclerview.setAdapter(adapter); adapter.notifyDataSetChanged(); break; } } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.audit_recycleview,container,false); getinfo(); setview(); getdata(); return view; } private void getdata() { new Thread(new Runnable() { @Override public void run() { String uri= API.BASE_URL+"/v1/activity/memberPeople"; Map<String,String> params=new HashMap<>(); params.put("token",token); params.put("activityId",activityId+""); Log.i("tag","token====="+token); Log.i("tag","activityId====="+activityId); String result= PostUtil.sendPostMessage(uri,params); try { Log.i("tag","result-----"+result); JSONObject object = new JSONObject(result); JSONArray data = object.getJSONArray("data"); for(int i=0;i<data.length();i++){ AuditData audit= new AuditData(); JSONObject obj = data.getJSONObject(i); String userNick= obj.getString("userNick"); String avatar= obj.getString("avatar"); int examineType = obj.getInt("examineType"); String memberInfo = obj.getString("memberInfo"); JSONObject json=new JSONObject(memberInfo); Iterator<String> iter = json.keys(); while (iter.hasNext()) { key = iter.next(); value = json.getString(key); if (key.equals("手机号码")||key.equals("手机号")) { phone = value; continue; }else if (key.equals("姓名")) { realname = value; continue; }else if (key.equals("性别")) { sex = value; continue; } else if (key.equals("年龄")) { age = value; continue; } else if (key.equals("地址")) { address = value; continue; } else if (key.equals("身份证")) { id = value; continue; }else { } } audit.setPhone(phone); audit.setRealname(realname); audit.setSex(sex); audit.setAge(age); audit.setAddress(address); audit.setId(id); audit.setAvatar(avatar); audit.setUsername(userNick); if(examineType==1){ MainList.add(audit); }else {} } handler.sendEmptyMessage(HANDLER_UPDATA); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } private void setview() { mainRecyclerview=(RecyclerView)view.findViewById(R.id.recyclerview); } private void getinfo() { activityId=getActivity().getIntent().getIntExtra("activityId",0); share= getActivity().getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",""); } } <file_sep>/app/src/main/java/com/gymnast/utils/LiveUtil.java package com.gymnast.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import android.util.Log; import android.widget.Toast; import com.gymnast.App; import com.gymnast.MyReceiver; import com.gymnast.data.net.API; import com.gymnast.view.live.activity.LiveActivity; import com.gymnast.view.live.entity.LiveItem; import com.gymnast.view.user.LoginActivity; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMGroup; import com.hyphenate.chat.EMGroupManager; import org.json.JSONObject; import java.util.HashMap; /** * Created by zzqybyb19860112 on 2016/8/19. */ public class LiveUtil { public static final int UPDATE_STATE_OK = 1; public static final int MAINUSER_IN_OK = 2; public static final int MAINUSER_IN_ERROR = 3; public static final int OTHERUSER_IN_OK = 4; public static final int OTHERUSER_IN_ERROR = 5; /** * url 请求地址 * token 系统token * liveId 请求用的直播Id * imgUrl发送图片消息时上传到服务器返回的地址,可以只发图片 * content 图文直播的文字内容 */ public static String sendLiveMessage(final String url, final String token, final int liveId, final String imgUrl, final String content) { String result = null; HashMap<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("liveId", liveId + ""); params.put("imgUrl", imgUrl); params.put("content", content); result = PostUtil.sendPostMessage(url, params); return result; } public static void doNext(Activity activity, LiveItem live) { Intent intent = new Intent(activity, LiveActivity.class); intent.putExtra("type", live.getUserType()); intent.putExtra("bigPictureUrl", PicUtil.getImageUrl(activity, live.getBigPictureUrl())); intent.putExtra("liveId", live.getLiveId()); intent.putExtra("title", live.getTitle()); intent.putExtra("groupId", live.getGroupId()); intent.putExtra("mainPhotoUrl", PicUtil.getImageUrl(activity, live.getMainPhotoUrl())); intent.putExtra("liveOwnerId", live.getLiveOwnerId()); intent.putExtra("liveState",live.getLiveState()); activity.startActivity(intent); } public static void doIntoLive(Activity activity, final Handler handler, final LiveItem liveItem) { final SharedPreferences share = activity.getSharedPreferences("UserInfo", Context.MODE_PRIVATE); final String userId = share.getString("UserId", ""); final String token = share.getString("Token", ""); if (App.isNetStateOK){ if (token.equals("")||! App.isStateOK) { Toast.makeText(activity, "亲,您还没有登陆呢!", Toast.LENGTH_SHORT).show(); activity.startActivity(new Intent(activity, LoginActivity.class)); } else { if (liveItem.getUserType() == LiveActivity.USER_MAIN) {//播主进入界面 long nowTime = System.currentTimeMillis(); if (nowTime < liveItem.getStartTime()) { Toast.makeText(activity, "直播时间未到,您不能提前开始直播!", Toast.LENGTH_SHORT).show(); return; } else { if (liveItem.getLiveState() == 0) { if (liveItem.getGroupId() == null || liveItem.getGroupId().equals("")) { new Thread() { @Override public void run() { EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions(); option.maxUsers = 1000; option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin; String[] allMembers = new String[]{}; EMGroup group = null; try { group = EMClient.getInstance().groupManager().createGroup(liveItem.liveOwnerId + "", liveItem.getTitle(), allMembers, null, option); if (group != null) { Log.i("tag", "创建环信群组成功"); String groupId = group.getGroupId(); String url2 = API.BASE_URL + "/v1/live/update_live"; HashMap<String, String> params2 = new HashMap<>(); params2.put("token", token); params2.put("id", liveItem.liveOwnerId + ""); params2.put("groupId", groupId); liveItem.setGroupId(groupId); Log.i("tag", "groupId========" + groupId); String result2 = PostUtil.sendPostMessage(url2, params2); Log.i("tag", "result2------------->" + result2); String url3 = API.BASE_URL + "/v1/live/update_status"; HashMap<String, String> params3 = new HashMap<>(); params3.put("token", token); params3.put("id", userId + ""); params3.put("status", 1 + ""); String result3 = PostUtil.sendPostMessage(url3, params3); Log.i("tag", "result3------------->" + result3); JSONObject obj = new JSONObject(result3); if (obj.getInt("state") == 200) {//用户状态正常 handler.sendEmptyMessage(UPDATE_STATE_OK); } } else { Log.i("tag", "创建环信群组失败"); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } else { new Thread() { @Override public void run() { try { String url = API.BASE_URL + "/v1/live/update_status"; HashMap<String, String> param = new HashMap<>(); param.put("token", token); param.put("id", liveItem.getLiveId() + ""); param.put("status", 1 + ""); String result1 = PostUtil.sendPostMessage(url, param); Log.i("tag", "更新直播状态结果:" + result1); JSONObject obj = new JSONObject(result1); if (obj.getInt("state") == 200) {//用户状态正常 handler.sendEmptyMessage(UPDATE_STATE_OK); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } } else { new Thread() { @Override public void run() { try { String url = API.BASE_URL + "/v1/live/in"; HashMap<String, String> param = new HashMap<>(); param.put("token", token); param.put("id", userId); String result = PostUtil.sendPostMessage(url, param); JSONObject object = new JSONObject(result); if (object.getInt("state") == 200) { handler.sendEmptyMessage(MAINUSER_IN_OK); } else { handler.sendEmptyMessage(MAINUSER_IN_ERROR); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } } } else {//普通观众进入界面 if (liveItem.getGroupId() == null || liveItem.getGroupId().equals("")) { Toast.makeText(activity, "播主还未开启直播!", Toast.LENGTH_SHORT).show(); return; } else { new Thread() { @Override public void run() { try { String url = API.BASE_URL + "/v1/live/in"; HashMap<String, String> param = new HashMap<>(); param.put("token", token); param.put("id", userId); String result = PostUtil.sendPostMessage(url, param); JSONObject object = new JSONObject(result); if (object.getInt("state") == 200) { handler.sendEmptyMessage(OTHERUSER_IN_OK); } else { handler.sendEmptyMessage(OTHERUSER_IN_ERROR); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } } } }else { Toast.makeText(activity, "亲,没有网络啦!", Toast.LENGTH_SHORT).show(); handler.postDelayed(new Runnable() { @Override public void run() { MyReceiver.dialog.show(); } }, 3000); } } } <file_sep>/app/src/main/java/com/gymnast/view/pack/view/PlayActivityIssueActivity.java package com.gymnast.view.pack.view; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PostUtil; import com.gymnast.view.BaseToolbarActivity; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.dialog.PicSelectDialogUtils; import com.gymnast.view.pack.adapter.PhotoPickerAdapter; import com.gymnast.view.recyclerview.RecyclerAdapter; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import butterknife.BindView; /** * Created by yf928 on 2016/8/10. */ public class PlayActivityIssueActivity extends ImmersiveActivity implements RecyclerAdapter.OnItemClickListener ,View.OnClickListener{ private ArrayList<Bitmap> mPics = new ArrayList<>(); private PhotoPickerAdapter mPhotoPickerAdapter; private Bitmap mDefaultBitmap; private int visible,type=3; private SharedPreferences share; private String token,id,cernTitle="null"; private RecyclerView rvIssue; private TextView tvIssueSelectRange; private TextView tvIssueEdit; private EditText etIssueContent; private RelativeLayout rlIssueRange; private TextView save; private ImageView back; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dynamic_issue); initData(); initViews(); } private void initViews() { initPhotePicker(); initEditText(); } /** * 检测输入框字数 */ private void initEditText() { etIssueContent.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String number = etIssueContent.getText().toString(); tvIssueEdit.setText(number.length()+"/"+2500); } @Override public void afterTextChanged(Editable s) { } }); } private void initData() { share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",""); id = share.getString("UserId",""); rvIssue=(RecyclerView)findViewById(R.id.rvIssue); tvIssueSelectRange=(TextView)findViewById(R.id.tvIssueSelectRange); tvIssueEdit=(TextView)findViewById(R.id.tvIssueEdit); etIssueContent=(EditText)findViewById(R.id.etIssueContent); rlIssueRange=(RelativeLayout)findViewById(R.id.rlIssueRange); save=(TextView)findViewById(R.id.tvSetPhoneSave); back=(ImageView)findViewById(R.id.personal_back); rlIssueRange.setOnClickListener(this); save.setOnClickListener(this); back.setOnClickListener(this); } /** * 初始化照片选择器 */ private void initPhotePicker() { //默认显示图片 mDefaultBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_add_to); mPics.add(mDefaultBitmap); mPhotoPickerAdapter = new PhotoPickerAdapter(this, mPics, R.layout.item_photo_picker); rvIssue.setLayoutManager(new GridLayoutManager(this, 7)); rvIssue.setItemAnimator(new DefaultItemAnimator()); rvIssue.setAdapter(mPhotoPickerAdapter); mPhotoPickerAdapter.setOnItemClickListener(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case PicSelectDialogUtils.IMAGE_OPEN: //相册返回 addPic(); break; case PicSelectDialogUtils.PIC_FROM_CAMERA: addPic(); break; } } if(requestCode==100){ if(resultCode==10){ String s = data.getStringExtra("RadioButton"); tvIssueSelectRange.setText(s); visible =data.getIntExtra("RadiobuttonNumber",0); } } } /** * 添加图片 */ private void addPic() { Bitmap bitmap = PicUtil.getSmallBitmap(PicSelectDialogUtils.CURRENT_FILENAME); if (bitmap != null && mPics.size() > 0) { mPics.remove(mPics.size() - 1); mPics.add(bitmap); mPics.add(mDefaultBitmap); mPhotoPickerAdapter.notifyItemRangeChanged(mPics.size() - 2, mPics.size()); } } @Override public void OnItemClickListener(View view, int position) { } @Override public void onClick(View v) { switch (v.getId()){ case R.id.rlIssueRange: Intent i=new Intent(this,PackRangeActivity.class); startActivityForResult(i,100); break; case R.id.tvSetPhoneSave: update(); break; case R.id.personal_back: finish(); break; } } private void update() { new Thread(new Runnable() { @Override public void run() { try { String content = etIssueContent.getText().toString(); String uri= API.BASE_URL+"/v1/cern/insert"; HashMap<String ,String> params=new HashMap<String, String>(); params.put("userId",id); params.put("type",type+""); params.put("cernTitle",cernTitle); params.put("content",content); params.put("visible",visible+""); String reasult= PostUtil.sendPostMessage(uri,params); JSONObject obj=new JSONObject(reasult); if(obj.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PlayActivityIssueActivity.this,"发布成功",Toast.LENGTH_SHORT).show(); finish(); } }); } } catch (JSONException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PlayActivityIssueActivity.this,"发布失败 ",Toast.LENGTH_SHORT).show(); } }); } } }).start(); } } <file_sep>/app/src/main/java/com/gymnast/view/customview/MyLinearLayout.java package com.gymnast.view.customview; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.gymnast.R; /** * Created by zzqybyb19860112 on 2016/9/26. */ public class MyLinearLayout extends ViewGroup { public MyLinearLayout(Context context) { super(context); } public MyLinearLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MyLinearLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); int lowestBottom = 0; int lineHeight = 0; int myWidth = resolveSize(100, widthMeasureSpec); int wantedHeight = 0; for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == View.GONE) { continue; } child.measure(getChildMeasureSpec(widthMeasureSpec, 0, child.getLayoutParams().width), getChildMeasureSpec(heightMeasureSpec, 0, child.getLayoutParams().height)); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); lineHeight = Math.max(childHeight, lineHeight); if (childWidth + childLeft + getPaddingRight() > myWidth) { // Wrap this line childLeft = getPaddingLeft(); childTop = lowestBottom; // Spaced below the previous lowest point lineHeight = childHeight; } childLeft += childWidth ; if (childHeight + childTop > lowestBottom) { // New lowest point lowestBottom = childHeight + childTop; } } wantedHeight += childTop + lineHeight + getPaddingBottom(); setMeasuredDimension(myWidth, resolveSize(wantedHeight, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); int lowestBottom = 0; int myWidth = right - left; for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == View.GONE) { continue; } int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); if (childWidth + childLeft + getPaddingRight() > myWidth) { // Wrap this line childLeft = getPaddingLeft(); childTop = lowestBottom; // Spaced below the previous lowest point } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); childLeft += childWidth ; if (childHeight + childTop > lowestBottom) { // New lowest point lowestBottom = childHeight + childTop; } } } }<file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'android-apt' android { compileSdkVersion 24 buildToolsVersion "24.0.0" defaultConfig { applicationId "com.homesport" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "V0.2 beta" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' //社交对接 compile project(':social_sdk_library_project') //首页横幅 compile 'com.bigkoo:convenientbanner:2.0.5' //控件绑定 compile 'com.jakewharton:butterknife:8.0.1' apt 'com.jakewharton:butterknife-compiler:8.0.1' //网络访问 compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' compile 'com.squareup.okhttp3:logging-interceptor:3.3.1' compile 'com.squareup.okhttp3:okhttp:3.3.1' //图片加载 compile 'com.github.bumptech.glide:glide:3.7.0' //权限请求 compile 'com.tbruyelle.rxpermissions:rxpermissions:0.7.0@aar' //响应框架 compile 'io.reactivex:rxandroid:1.2.0' compile 'io.reactivex:rxjava:1.1.6' //圆形图片 compile 'de.hdodenhof:circleimageview:2.0.0' //圆角图片 compile 'com.makeramen:roundedimageview:2.2.1' compile files('libs/rt.jar') compile files('libs/org.apache.http.legacy.jar') compile 'org.jetbrains:annotations-java5:15.0' compile files('libs/hyphenatechat_3.1.4.jar') compile files('libs/hyphenatechat_3.1.5.jar') compile 'com.android.support:support-v4:24.2.0' compile 'com.android.support:design:24.2.0' compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.android.support:recyclerview-v7:24.2.0' } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonalOtherHomeActivity.java package com.gymnast.view.personal.activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.hotinfo.CirleDevas; import com.gymnast.data.hotinfo.UserDevas; import com.gymnast.data.net.API; import com.gymnast.data.pack.ConcernData; import com.gymnast.data.personal.DynamicData; import com.gymnast.data.personal.PostsData; import com.gymnast.utils.GetUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.hotinfoactivity.activity.ActivityDetailsActivity; import com.gymnast.view.live.activity.LiveActivity; import com.gymnast.view.pack.adapter.ConcernAdapter; import com.gymnast.view.personal.adapter.DynamicAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Cymbi on 2016/9/4. */ public class PersonalOtherHomeActivity extends ImmersiveActivity { List<ConcernData> activityList=new ArrayList<>(); private RecyclerView recyclerview; private ImageView back,mHead; private TextView mContent,title,mFans,tvConcern,mNickname,tvauthInfo; private Button mSign; private State state; private SharedPreferences share; private String Godtoken="<PASSWORD>"; public static final int HANFLE_DATA_UPDATE=1; private ConcernAdapter adapter; private int userID; private CollapsingToolbarLayout mCollapsingToolbarLayout; private AppBarLayout appbar; private String token,UserId,returnAccountAuth,name,avatar; private Toolbar tb; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANFLE_DATA_UPDATE: adapter = new ConcernAdapter(PersonalOtherHomeActivity.this,activityList); recyclerview.setAdapter(adapter); adapter.setOnItemClickListener(new ConcernAdapter.OnItemClickListener() { @Override public void OnItemClickListener(View view, int position) { ConcernData item= activityList.get(position); String fromtype=item.getFromType(); if (activityList.size() != 0) { if (fromtype.equals("1")) { Intent i = new Intent(PersonalOtherHomeActivity.this, LiveActivity.class); i.putExtra("item", item); startActivity(i); } else if (fromtype.equals("2")) { int ActiveID = Integer.parseInt(item.getFromId()); Intent i = new Intent(PersonalOtherHomeActivity.this, ActivityDetailsActivity.class); i.putExtra("ActiveID",ActiveID); startActivity(i); } else if (fromtype.equals("3")) { int tieZiID = Integer.parseInt(item.getFromId()); Intent i = new Intent(PersonalOtherHomeActivity.this, PersonalPostsDetailActivity.class); i.putExtra("TieZiID", tieZiID); startActivity(i); } else if (fromtype.equals("null")) { Intent i = new Intent(PersonalOtherHomeActivity.this, PersonalDynamicDetailActivity.class); i.putExtra("CirleID", item.getId()); startActivity(i); } } } }); adapter.notifyDataSetChanged(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other_home); getInfo(); setView(); getUser(); getSign(); getData(); setListeners(); setSupportActionBar(tb); } private void getSign() { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/attention/user_check"; HashMap<String,String> params=new HashMap<>(); params.put("token",token); params.put("fromId",UserId); params.put("toId",userID+""); String result=GetUtil.sendGetMessage(uri,params); try { JSONObject object=new JSONObject(result); final int data=object.getInt("data"); runOnUiThread(new Runnable() { @Override public void run() { if (data==0){ mSign.setText("关注"); }else { mSign.setText("已关注"); } } }); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } public void getInfo() { share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); UserId = share.getString("UserId",""); token = share.getString("Token",""); try { userID = getIntent().getIntExtra("UserID", 0); }catch (Exception e){ e.printStackTrace(); } } private void setListeners() { back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); /** * 通过枚举修改AppBarLyout状态 */ appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (verticalOffset == 0) { if (state != State.EXPANDED) { state = State.EXPANDED;//修改状态标记为展开 title.setVisibility(View.GONE); } } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) { if (state != State.COLLAPSED) { title.setVisibility(View.VISIBLE);//显示title控件 state = State.COLLAPSED;//修改状态标记为折叠 title.setText(name);//设置title为用户名 } } else { if (state != State.INTERNEDIATE) { if (state == State.COLLAPSED) { title.setVisibility(View.GONE);//由折叠变为中间状态时隐藏播放按钮 } state = State.INTERNEDIATE;//修改状态标记为中间 } } } }); mSign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/attention/user"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("fromId",UserId); params.put("toId",userID+""); String result=GetUtil.sendGetMessage(uri,params); try { JSONObject object=new JSONObject(result); int data=object.getInt("data"); if (object.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { mSign.setText("已关注"); Toast.makeText(PersonalOtherHomeActivity.this,"关注成功",Toast.LENGTH_SHORT).show(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } }); mHead.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(PersonalOtherHomeActivity.this,ImageActivity.class); i.putExtra("IMAGE",API.IMAGE_URL+avatar); startActivity(i); } }); } private void setView() { recyclerview=(RecyclerView)findViewById(R.id.recyclerview); back= (ImageView)findViewById(R.id.me_back); mHead= (ImageView)findViewById(R.id.me_head); mNickname= (TextView)findViewById(R.id.nickname); mContent= (TextView)findViewById(R.id.content); tvConcern= (TextView)findViewById(R.id.tvConcern); mFans= (TextView)findViewById(R.id.me_fans); mSign= (Button)findViewById(R.id.sign); title=(TextView)findViewById(R.id.personal_name_title); tvauthInfo=(TextView)findViewById(R.id.authInfo); tb=(Toolbar)findViewById(R.id.toolbar); appbar=(AppBarLayout)findViewById(R.id.personal_appbar); mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collp_toolbar_layout); } public void getUser() { new Thread(new Runnable() { @Override public void run() { String uri= API.BASE_URL+"/v1/account/center_info"; HashMap<String, String> params = new HashMap<>(); params.put("token", Godtoken); params.put("account_id", userID+""); String result = GetUtil.sendGetMessage(uri, params); try { JSONObject obj = new JSONObject(result); JSONObject data = obj.getJSONObject("data"); //判断用户类型是否为空,不为空再获取他的JsonObject final String tempAuth=StringUtil.isNullAuth(data.getString("accountAuth")); if(!tempAuth.equals("")){ JSONObject accountAuth=new JSONObject(tempAuth); returnAccountAuth=accountAuth.getString("authinfo"); } name = data.getString("nickname"); avatar = data.getString("avatar"); final String signature=data.getString("signature"); final int Concern = data.getInt("gz"); final int fans= data.getInt("fs"); if (obj.getInt("state") == 200){ runOnUiThread(new Runnable() { @Override public void run() { PicassoUtil.handlePic(PersonalOtherHomeActivity.this, PicUtil.getImageUrlDetail(PersonalOtherHomeActivity.this, StringUtil.isNullAvatar(avatar), 320, 320),mHead,320,320); mNickname.setText(name); if(signature=="null"){ mContent.setText("这个人很懒,什么也没有留下"); }else { mContent.setText(signature); } tvConcern.setText(Concern+"关注"); mFans.setText(fans+"粉丝"); if(!tempAuth.equals("")){ tvauthInfo.setText("("+returnAccountAuth+")"); } } }); } } catch (Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PersonalOtherHomeActivity.this,"服务器故障,数据解析出错",Toast.LENGTH_SHORT).show(); } }); } } }).start(); } public void getData() { new Thread(new Runnable() { public String returnfromId; public String returnType; public String authInfo; @Override public void run() { try { String uri= API.BASE_URL+"/v1/my/concern/list"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",Godtoken); params.put("accountId", userID+""); String result= GetUtil.sendGetMessage(uri,params); JSONObject json=new JSONObject(result); JSONArray data = json.getJSONArray("data"); for (int i=0;i<data.length();i++){ ArrayList<String> imageURL=new ArrayList<String>(); JSONObject object= data.getJSONObject(i); JSONObject userVo= object.getJSONObject("userVo"); JSONObject pageViews= object.getJSONObject("pageViews"); int pageviews=pageViews.getInt("pageviews"); String tempAuth= StringUtil.isNullAuth(object.getString("userAuthVo")); if(!tempAuth.equals("")){ JSONObject accountAuth=new JSONObject(tempAuth); authInfo=accountAuth.getString("authInfo"); } String returnNickName=userVo.getString("nickName"); String returnAvatar=userVo.getString("avatar"); int returnAuthenticate=userVo.getInt("authenticate"); int returnId=object.getInt("id"); int returnUserId=object.getInt("userId"); long returnCreateTime= object.getLong("createTime"); if(object.getString("fromType")!=null){ returnType=object.getString("fromType"); }else {} if(object.getString("fromId")!=null){ returnfromId=object.getString("fromId"); }else {} String returnTopicTitle= object.getString("topicTitle"); String returnTopicContent=object.getString("topicContent"); int returnZanCounts=object.getInt("zanCounts"); int returnCommentCounts=object.getInt("commentCounts"); String returnVideoUrl=object.getString("videoUrl"); int returnState=object.getInt("state"); String urls= object.getString("imgUrl"); if (urls==null|urls.equals("null")|urls.equals("")){ }else { String [] imageUrls=urls.split(","); for (int j=0;j<imageUrls.length;j++){ imageURL.add(API.IMAGE_URL+imageUrls[j]); } } ConcernData data1=new ConcernData(); data1.setId(returnId); data1.setUserId(returnUserId); data1.setFromType(returnType); data1.setFromId(returnfromId); data1.setImgUrl(imageURL); data1.setPageviews(pageviews); data1.setNickName(returnNickName); data1.setTopicContent(returnTopicContent); data1.setTopicTitle(returnTopicTitle); data1.setAuthenticate(returnAuthenticate); data1.setAvatar(returnAvatar); data1.setCommentCounts(returnCommentCounts); data1.setZanCounts(returnZanCounts); data1.setCreateTime(returnCreateTime); if(!tempAuth.equals("")){ data1.setAuthInfo(authInfo); } data1.setState(returnState); data1.setAuthInfo(""); activityList.add(data1); } handler.sendEmptyMessage(HANFLE_DATA_UPDATE); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //枚举出Toolbar的三种状态 private enum State{ EXPANDED, COLLAPSED, INTERNEDIATE } @Override protected void onResume() { super.onResume(); getUser(); getSign(); } }<file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/activity/SettingSiteActivity.java package com.gymnast.view.hotinfoactivity.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; /** * Created by yf928 on 2016/8/9. */ public class SettingSiteActivity extends ImmersiveActivity implements View.OnClickListener{ private ImageView ivSetSiteBack; private EditText etSetSiteAddress; private TextView tvSetSiteSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting_site); setview(); } private void setview() { ivSetSiteBack=(ImageView)findViewById(R.id.ivSetSiteBack); tvSetSiteSave=(TextView)findViewById(R.id.tvSetSiteSave); etSetSiteAddress=(EditText) findViewById(R.id.etSetSiteAddress); ivSetSiteBack.setOnClickListener(this); tvSetSiteSave.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.ivSetSiteBack: finish(); break; case R.id.tvSetSiteSave: String maddress= etSetSiteAddress.getText().toString(); Intent i=new Intent(); i.putExtra("address",maddress); setResult(14,i); finish(); } } } <file_sep>/app/src/main/java/com/gymnast/view/home/view/SearchLiveFragment.java package com.gymnast.view.home.view; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.CacheUtils; import com.gymnast.utils.DialogUtil; import com.gymnast.utils.JSONParseUtil; import com.gymnast.utils.LiveUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.view.home.adapter.SearchLiveAdapter; import com.gymnast.view.live.entity.LiveItem; import com.gymnast.view.personal.activity.PersonalOtherHomeActivity; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by zzqybyb19860112 on 2016/9/4. */ public class SearchLiveFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{ private RecyclerView recyclerView; List<LiveItem> dataList=new ArrayList<>(); SearchLiveAdapter adapter; LiveItem liveItem; private SwipeRefreshLayout srlSearch; boolean isRefresh=false; public static final int HANDLE_DATA=6; public static final int UPDATE_STATE_OK=1; public static final int MAINUSER_IN_OK=2; public static final int MAINUSER_IN_ERROR=3; public static final int OTHERUSER_IN_OK=4; public static final int OTHERUSER_IN_ERROR=5; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANDLE_DATA: adapter=new SearchLiveAdapter(getActivity(),dataList); adapter.setFriends(dataList); recyclerView.setAdapter(adapter); adapter.getFilter().filter(isRefresh == true ? HomeSearchResultAcitivity.etSearch.getText().toString().trim() : HomeSearchResultAcitivity.getSearchText()); srlSearch.setRefreshing(false); adapter.setOnItemClickListener(new SearchLiveAdapter.OnItemClickListener() { @Override public void OnItemPhotoClick(View view, LiveItem live) { if (view.getId() == R.id.rivSearchPhoto){ liveItem = live; Intent intent1 = new Intent(getActivity(), PersonalOtherHomeActivity.class); int userDevasID=Integer.valueOf(liveItem.getLiveOwnerId()); intent1.putExtra("UserID", userDevasID); getActivity().startActivity(intent1); }else if (view.getId() == R.id.ivSearchBig){ liveItem = live; LiveUtil.doIntoLive(getActivity(),handler,liveItem); } } }); break; case UPDATE_STATE_OK: Toast.makeText(getActivity(),"您开启了直播",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case MAINUSER_IN_OK: Toast.makeText(getActivity(),"您开启了直播",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case MAINUSER_IN_ERROR: DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; case OTHERUSER_IN_OK: Toast.makeText(getActivity(),"您已进入直播室",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case OTHERUSER_IN_ERROR: DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; } } }; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.search_common_fragment, container, false); recyclerView = (RecyclerView) view.findViewById(R.id.recycleView); srlSearch= (SwipeRefreshLayout) view.findViewById(R.id.srlSearch); RefreshUtil.refresh(srlSearch, getActivity()); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); setData(); srlSearch.setOnRefreshListener(this); return view; } private void setData() { ArrayList<String> cacheData= (ArrayList<String>) CacheUtils.readJson(getActivity(), SearchLiveFragment.this.getClass().getName() + ".json"); if (cacheData==null||cacheData.size()==0) { new Thread() { @Override public void run() { try { String uri = API.BASE_URL + "/v1/search/model"; HashMap<String, String> params = new HashMap<String, String>(); params.put("model", "4"); params.put("pageNumber", "100"); params.put("pages", "1"); String result = PostUtil.sendPostMessage(uri, params); JSONParseUtil.parseNetDataSearchLive(getActivity(), result, SearchLiveFragment.this.getClass().getName() + ".json", dataList, handler, HANDLE_DATA); } catch (Exception e) { e.printStackTrace(); } } }.start(); }else { JSONParseUtil.parseLocalDataSearchLive(getActivity(), SearchLiveFragment.this.getClass().getName() + ".json", dataList, handler, HANDLE_DATA); } } @Override public void onRefresh() { isRefresh=true; setData(); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 srlSearch.setRefreshing(false); } }, 1000); } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/activity/SettingPriceActivity.java package com.gymnast.view.hotinfoactivity.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; /** * Created by yf928 on 2016/8/9. */ public class SettingPriceActivity extends ImmersiveActivity implements View.OnClickListener{ private ImageView ivSetPriceBack; private EditText etPriceNumber; private TextView tvSetPriceSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting_price); setview(); } private void setview() { ivSetPriceBack=(ImageView)findViewById(R.id.ivSetPriceBack); etPriceNumber=(EditText)findViewById(R.id.etSetPriceNumber); tvSetPriceSave=(TextView)findViewById(R.id.tvSetPriceSave); tvSetPriceSave.setOnClickListener(this); ivSetPriceBack.setOnClickListener(this); } @Override public void onClick(View v) { Intent i=new Intent(); switch (v.getId()){ case R.id.ivSetPriceBack: i.putExtra("price",0.0); setResult(15,i); finish(); break; case R.id.tvSetPriceSave: String met_activity_price= etPriceNumber.getText().toString(); if(met_activity_price.equals("")|met_activity_price==null|met_activity_price.equals("0")|met_activity_price.equals("0.0")|met_activity_price.equals("0.00")){ i.putExtra("price",0.0); }else { double price= Double.parseDouble(met_activity_price); i.putExtra("price",price); } setResult(15,i); finish(); break; } } } <file_sep>/app/src/main/java/com/gymnast/view/personal/fragment/WalletFragmengt.java package com.gymnast.view.personal.fragment; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.gymnast.R; import com.gymnast.view.personal.adapter.WalletAdapter; import com.gymnast.view.user.LoginActivity; import java.util.ArrayList; import java.util.List; /** * Created by yf928 on 2016/8/3. */ public class WalletFragmengt extends Fragment{ private RecyclerView listitem; private WalletAdapter packAdapter; private List<LiveItems> packitem=new ArrayList<>(); private View view; private String token; private LinearLayout linear; private TextView tv_login; private LinearLayout login_ll; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_wallet,container,false); SharedPreferences share = getActivity().getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",null); setView(); initView(); return view; } private void setView() { listitem = (RecyclerView)view.findViewById(R.id.recyclerview); listitem.setHasFixedSize(true); linear= (LinearLayout) view.findViewById(R.id.linear); login_ll= (LinearLayout) view.findViewById(R.id.login_ll); tv_login= (TextView) view.findViewById(R.id.tv_login); } private void initView() { if(TextUtils.isEmpty(token)){ login_ll.setVisibility(View.VISIBLE); linear.setVisibility(View.GONE); }else { linear.setVisibility(View.VISIBLE); login_ll.setVisibility(View.GONE); } tv_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); } public WalletFragmengt() { for(int i=0;i<20;i++){ LiveItems liveItem = new LiveItems("",null,""+i,""+i) ; packitem.add(liveItem); } } public static WalletFragmengt newInstance(String param1, String param2) { WalletFragmengt fragment = new WalletFragmengt(); return fragment; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //创建线性布局 LinearLayoutManager circleLayout = new LinearLayoutManager(getActivity()); circleLayout.setOrientation(LinearLayoutManager.HORIZONTAL); packAdapter = new WalletAdapter(getActivity(), packitem); //设置布局管理器 listitem.setLayoutManager(circleLayout); listitem.setHasFixedSize(true); listitem.setAdapter(packAdapter); } public static class LiveItems { public final String liveUrl; public final String liveViewer; public final String livePicture; public final String liveTitle; public LiveItems(String liveUrl,String livePicture, String liveViewer, String liveTitle) { this.liveUrl = liveUrl; this.liveViewer = liveViewer; this.liveTitle = liveTitle; this.livePicture=livePicture; } } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonalDynamicActivity.java package com.gymnast.view.personal.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.data.pack.ConcernData; import com.gymnast.data.personal.DynamicData; import com.gymnast.utils.GetUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.hotinfoactivity.activity.ActivityDetailsActivity; import com.gymnast.view.live.activity.LiveActivity; import com.gymnast.view.pack.adapter.ConcernAdapter; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Cymbi on 2016/8/27. */ public class PersonalDynamicActivity extends ImmersiveActivity { private RecyclerView mRecyclerview; List<ConcernData> activityList=new ArrayList<>(); public static final int HANFLE_DATA_UPDATE=1; private ConcernAdapter adapter; private SharedPreferences share; private String token,id; private ImageView back; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANFLE_DATA_UPDATE: adapter = new ConcernAdapter(PersonalDynamicActivity.this,activityList); mRecyclerview.setAdapter(adapter); adapter.setOnItemClickListener(new ConcernAdapter.OnItemClickListener() { @Override public void OnItemClickListener(View view, int position) { ConcernData item= activityList.get(position); String fromtype=item.getFromType(); if (activityList.size() != 0) { if (fromtype.equals("1")) { Intent i = new Intent(PersonalDynamicActivity.this, LiveActivity.class); i.putExtra("item", item); startActivity(i); } else if (fromtype.equals("2")) { int ActiveID = Integer.parseInt(item.getFromId()); Intent i = new Intent(PersonalDynamicActivity.this, ActivityDetailsActivity.class); i.putExtra("ActiveID",ActiveID); startActivity(i); } else if (fromtype.equals("3")) { int tieZiID = Integer.parseInt(item.getFromId()); Intent i = new Intent(PersonalDynamicActivity.this, PersonalPostsDetailActivity.class); i.putExtra("TieZiID", tieZiID); startActivity(i); } else if (fromtype.equals("null")) { Intent i = new Intent(PersonalDynamicActivity.this, PersonalDynamicDetailActivity.class); i.putExtra("CirleID", item.getId()); startActivity(i); } } } }); adapter.notifyDataSetChanged(); break; } } }; private String authInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_dynamic); share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",""); id = share.getString("UserId",""); setView(); setListeners(); getData(); } private void setListeners() { back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void setView() { mRecyclerview = (RecyclerView)findViewById(R.id.recyclerview); back= (ImageView)findViewById(R.id.personal_back); } public void getData() { new Thread(new Runnable() { public String returnfromId; public String returnType; public String authInfo; @Override public void run() { try { String uri= API.BASE_URL+"/v1/my/concern/list"; HashMap<String,String> parmas=new HashMap<String, String>(); parmas.put("token",token); parmas.put("accountId",id); String result= GetUtil.sendGetMessage(uri,parmas); JSONObject json=new JSONObject(result); JSONArray data = json.getJSONArray("data"); for (int i=0;i<data.length();i++){ ArrayList<String> imageURL=new ArrayList<String>(); JSONObject object= data.getJSONObject(i); JSONObject userVo= object.getJSONObject("userVo"); JSONObject pageViews= object.getJSONObject("pageViews"); int pageviews=pageViews.getInt("pageviews"); String tempAuth= StringUtil.isNullAuth(object.getString("userAuthVo")); if(!tempAuth.equals("")){ JSONObject accountAuth=new JSONObject(tempAuth); authInfo=accountAuth.getString("authInfo"); } String returnNickName=userVo.getString("nickName"); String returnAvatar=userVo.getString("avatar"); int returnAuthenticate=userVo.getInt("authenticate"); int returnId=object.getInt("id"); int returnUserId=object.getInt("userId"); long returnCreateTime= object.getLong("createTime"); if(object.getString("fromType")!=null){ returnType=object.getString("fromType"); }else {} if(object.getString("fromId")!=null){ returnfromId=object.getString("fromId"); }else {} String returnTopicTitle= object.getString("topicTitle"); String returnTopicContent=object.getString("topicContent"); int returnZanCounts=object.getInt("zanCounts"); int returnCommentCounts=object.getInt("commentCounts"); String returnVideoUrl=object.getString("videoUrl"); int returnState=object.getInt("state"); String urls= object.getString("imgUrl"); if (urls==null|urls.equals("null")|urls.equals("")){ }else { String [] imageUrls=urls.split(","); for (int j=0;j<imageUrls.length;j++){ imageURL.add(API.IMAGE_URL+imageUrls[j]); } } ConcernData data1=new ConcernData(); data1.setId(returnId); data1.setUserId(returnUserId); data1.setFromType(returnType); data1.setFromId(returnfromId); data1.setImgUrl(imageURL); data1.setPageviews(pageviews); data1.setNickName(returnNickName); data1.setTopicContent(returnTopicContent); data1.setTopicTitle(returnTopicTitle); data1.setAuthenticate(returnAuthenticate); data1.setAvatar(returnAvatar); data1.setCommentCounts(returnCommentCounts); data1.setZanCounts(returnZanCounts); data1.setCreateTime(returnCreateTime); if(!tempAuth.equals("")){ data1.setAuthInfo(authInfo); } data1.setState(returnState); data1.setAuthInfo(""); activityList.add(data1); } handler.sendEmptyMessage(HANFLE_DATA_UPDATE); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } <file_sep>/app/src/main/java/com/gymnast/view/home/fragment/HotInfoFragment.java package com.gymnast.view.home.fragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import com.bigkoo.convenientbanner.ConvenientBanner; import com.bigkoo.convenientbanner.holder.CBViewHolderCreator; import com.bigkoo.convenientbanner.holder.Holder; import com.gymnast.App; import com.gymnast.R; import com.gymnast.data.DataManager; import com.gymnast.data.hotinfo.ActivtyDevas; import com.gymnast.data.hotinfo.CirleDevas; import com.gymnast.data.hotinfo.ConcerDevas; import com.gymnast.data.hotinfo.HotInfoData; import com.gymnast.data.hotinfo.HotInfoService; import com.gymnast.data.hotinfo.LiveDevas; import com.gymnast.data.hotinfo.UserDevas; import com.gymnast.data.net.Result; import com.gymnast.utils.DialogUtil; import com.gymnast.utils.LiveUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.BaseFragment; import com.gymnast.view.home.adapter.HotInfoActivityUserRecyclerViewAdapter; import com.gymnast.view.home.adapter.HotInfoCircleRecyclerViewAdapter; import com.gymnast.view.home.adapter.HotInfoDynamicRecyclerViewAdapter; import com.gymnast.view.home.adapter.HotInfoLiveRecyclerViewAdapter; import com.gymnast.view.home.view.MorePostsActivity; import com.gymnast.view.pack.view.MoreCircleActivity; import com.gymnast.view.home.view.MoreDynamicActivity; import com.gymnast.view.home.view.MoreUserActivity; import com.gymnast.view.hotinfoactivity.activity.ActivityDetailsActivity; import com.gymnast.view.hotinfoactivity.activity.CalendarActivityActivity; import com.gymnast.view.hotinfoactivity.activity.HistoryActivityActivity; import com.gymnast.view.hotinfoactivity.activity.NewActiveActivity; import com.gymnast.view.live.activity.LiveActivity; import com.gymnast.view.live.activity.MoreLiveActivity; import com.gymnast.view.live.entity.LiveItem; import com.gymnast.view.user.LoginActivity; import java.util.ArrayList; import java.util.List; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class HotInfoFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener { HotInfoService hotInfoService; @BindView(R.id.hot_info_swipe_container) SwipeRefreshLayout swipeContainer; @BindView(R.id.home_hot_info_banner) ConvenientBanner banner; @BindView(R.id.home_hot_info_banner_title) TextView banner_title; @BindView(R.id.ivLiveMore) ImageView ivLiveMore; @BindView(R.id.ivDynamicMore) ImageView ivDynamicMore; @BindView(R.id.ivCircleMore) ImageView ivCircleMore; @BindView(R.id.ivUserMore) ImageView ivUserMore; @BindView(R.id.hot_info_live_list) RecyclerView liveList; @BindView(R.id.hot_info_dynamic_list) RecyclerView dynamicList; @BindView(R.id.hot_info_circle_list) RecyclerView circleList; @BindView(R.id.hot_info_activity_user_list) RecyclerView activityUserList; @BindView(R.id.hot_info_recent) Button btnHotActivity; @BindView(R.id.hot_info_history) Button btnHisActivity; @BindView(R.id.hot_info_activity) Button btnActivityCalendar; private List<ActivtyDevas> items = new ArrayList<>(); private List<ActivtyDevas> itemsTemp = new ArrayList<>(); private List<LiveDevas> liveItems = new ArrayList<>(); private HotInfoLiveRecyclerViewAdapter liveAdapter; private List<ConcerDevas> dynamicItems = new ArrayList<>(); private HotInfoDynamicRecyclerViewAdapter dynamicAdapter; private List<UserDevas> activityUserItems = new ArrayList<>(); private HotInfoActivityUserRecyclerViewAdapter activityUserAdapter; private List<CirleDevas> circleItems = new ArrayList<>(); private HotInfoCircleRecyclerViewAdapter circleAdapter; LiveItem liveItem; public static final int UPDATE_STATE_OK=1; public static final int MAINUSER_IN_OK=2; public static final int MAINUSER_IN_ERROR=3; public static final int OTHERUSER_IN_OK=4; public static final int OTHERUSER_IN_ERROR=5; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case UPDATE_STATE_OK: Toast.makeText(getActivity(),"您开启了直播",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case MAINUSER_IN_OK: Toast.makeText(getActivity(),"您开启了直播",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case MAINUSER_IN_ERROR: DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; case OTHERUSER_IN_OK: Toast.makeText(getActivity(),"您已进入直播室",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case OTHERUSER_IN_ERROR: DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; } } }; public HotInfoFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); hotInfoService = DataManager.getService(HotInfoService.class); } @Override public void onActivityCreated( Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); banner.startTurning(2500); } @Override public void onPause() { super.onPause(); banner.stopTurning(); } @Override protected int getLayout() { return R.layout.fragment_hot_info; } @Override protected void initViews(Bundle savedInstanceState) { //banner banner.setPages(new CBViewHolderCreator<ImageHolderView>() { @Override public ImageHolderView createHolder() { return new ImageHolderView(); } }, items) .setPageIndicator( new int[] { R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused }) .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT); //最新活动 btnHotActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), NewActiveActivity.class)); } }); btnHisActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), HistoryActivityActivity.class)); } }); btnActivityCalendar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), CalendarActivityActivity.class)); } }); //直播 LinearLayoutManager liveLayout =new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); liveAdapter = new HotInfoLiveRecyclerViewAdapter(getActivity(), liveItems); liveList.setLayoutManager(liveLayout); liveList.setAdapter(liveAdapter); liveAdapter.setOnItemClickListener(new HotInfoLiveRecyclerViewAdapter.OnItemClickListener() { @Override public void OnBigPhotoClick(View view, LiveDevas liveDevas) { if (view.getId()==R.id.hot_info_live_picture) { liveItem = new LiveItem(); SharedPreferences share = getActivity().getSharedPreferences("UserInfo", Context.MODE_PRIVATE); String userId = share.getString("UserId", ""); String token = share.getString("Token", ""); if (!token.equals("") && App.isStateOK) { int userType = 0; if (liveDevas.userId == Integer.parseInt(userId)) { userType = LiveActivity.USER_MAIN; } else { userType = LiveActivity.USER_OTHER; } liveItem.setUserType(userType); liveItem.setStartTime(liveDevas.startTime); liveItem.setLiveState(liveDevas.state); liveItem.setLiveId(liveDevas.id); String bigUrl = liveDevas.bgmUrl == null ? StringUtil.isNullAvatar(liveDevas.imageUrl) : StringUtil.isNullAvatar(liveDevas.bgmUrl); liveItem.setBigPictureUrl(bigUrl); liveItem.setTitle(liveDevas.title); liveItem.setGroupId(liveDevas.groupId); liveItem.setMainPhotoUrl(StringUtil.isNullAvatar(liveDevas.avatar));// liveItem.setCurrentNum(liveDevas.watchNumber); liveItem.setLiveOwnerId(liveDevas.userId + ""); LiveUtil.doIntoLive(getActivity(), handler, liveItem); }else { Toast.makeText(getActivity(), "亲,您还没有登陆呢!", Toast.LENGTH_SHORT).show(); getActivity().startActivity(new Intent(getActivity(), LoginActivity.class)); } } } }); liveList.setNestedScrollingEnabled(false); //动态 GridLayoutManager dynamicLayout = new GridLayoutManager(getActivity(),3); dynamicAdapter = new HotInfoDynamicRecyclerViewAdapter(getActivity(), dynamicItems); dynamicList.setLayoutManager(dynamicLayout); dynamicList.setAdapter(dynamicAdapter); dynamicList.setNestedScrollingEnabled(false); ////圈子 LinearLayoutManager circleLayout = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); circleAdapter = new HotInfoCircleRecyclerViewAdapter(getActivity(), circleItems); circleList.setLayoutManager(circleLayout); circleList.setAdapter(circleAdapter); circleList.setNestedScrollingEnabled(false); //用户 LinearLayoutManager activityUserLayout = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); activityUserAdapter =new HotInfoActivityUserRecyclerViewAdapter(getActivity(), activityUserItems); activityUserList.setLayoutManager(activityUserLayout); activityUserList.setAdapter(activityUserAdapter); activityUserList.setNestedScrollingEnabled(false); } @Override protected void initListeners() { swipeContainer.setOnRefreshListener(this); ivLiveMore.setOnClickListener(this); ivDynamicMore.setOnClickListener(this); ivCircleMore.setOnClickListener(this); ivUserMore.setOnClickListener(this); } @Override protected void initData() { Subscription hotInfo = hotInfoService.getAllHotInfo().subscribeOn(Schedulers.io())// .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Result<HotInfoData>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Toast.makeText(getActivity(), "刷新失败", Toast.LENGTH_SHORT).show(); Log.i("tag","error----------"+e.toString()); } @Override public void onNext(Result<HotInfoData> result) { if (result.state == 200) { refresh(result.data); } else { Toast.makeText(getActivity(), "诶~网络好像有问题啊", Toast.LENGTH_SHORT).show(); } } }); mCompositeSubscription.add(hotInfo); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.ivLiveMore: Intent intent1=new Intent(getActivity(), MoreLiveActivity.class); getActivity().startActivity(intent1); break; case R.id.ivDynamicMore: Intent intent2=new Intent(getActivity(), MoreDynamicActivity.class); getActivity().startActivity(intent2); break; case R.id.ivCircleMore: Intent intent3=new Intent(getActivity(), MorePostsActivity.class); getActivity().startActivity(intent3); break; case R.id.ivUserMore: Intent intent4=new Intent(getActivity(), MoreUserActivity.class); getActivity().startActivity(intent4); break; } } @Override public void onRefresh() { updateData(); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 swipeContainer.setRefreshing(false); } }, 500); // 5秒后发送消息,停止刷新 } public void updateData() { Subscription hotInfo = hotInfoService.getAllHotInfo().subscribeOn(Schedulers.io())// .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Result<HotInfoData>>() { @Override public void onCompleted() { swipeContainer.setRefreshing(false); } @Override public void onError(Throwable e) { swipeContainer.setRefreshing(false); Toast.makeText(getActivity(), "刷新内容失败", Toast.LENGTH_SHORT).show(); } @Override public void onNext(Result<HotInfoData> result) { swipeContainer.setRefreshing(false); if (result.state == 200) { refresh(result.data); } else { Toast.makeText(getActivity(), "当前网络状态不佳,请检查您的网络设置!", Toast.LENGTH_SHORT).show(); } } }); mCompositeSubscription.add(hotInfo); } //banner set public class ImageHolderView implements Holder<ActivtyDevas> { private ImageView iv; int pos=0; @Override public View createView(Context context) { iv = new ImageView(context); iv.setScaleType(ImageView.ScaleType.FIT_XY); iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ActivtyDevas devas = itemsTemp.get(pos); int id = devas.id; int userId = devas.userId; Intent intent = new Intent(getActivity(), ActivityDetailsActivity.class); intent.putExtra("ActiveID", id); intent.putExtra("UserId", userId); getActivity().startActivity(intent); } }); return iv; } @Override public void UpdateUI(Context context, final int position, ActivtyDevas data) { pos=position; Rect rect = new Rect(); ((Activity)context).getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); int x = rect.width(); if (itemsTemp.get(position).getImageUrl()!=null && !itemsTemp.get(position).getImageUrl().equals("")){ PicassoUtil.handlePic(context, PicUtil.getImageUrlDetail(context, itemsTemp.get(position).getImageUrl(), x, 1920), iv, x, 720); }else { PicassoUtil.handlePic(context, PicUtil.getImageUrlDetail(context, itemsTemp.get(position).getBgmUrl(), x, 1920), iv, x, 720); } int newPos=position-1==-1?itemsTemp.size()-1:position-1; banner_title.setText(itemsTemp.get(newPos).title); } } /** * 刷新方法 * @param data */ private void refresh(HotInfoData data) { //banner if (data.activityDevas != null && data.activityDevas.size() > 0) { items.clear(); itemsTemp.clear(); items.addAll(data.activityDevas); itemsTemp.addAll(items); banner.notifyDataSetChanged(); } //live if (data.liveDevas != null && data.liveDevas.size() > 0) { liveItems.clear(); liveItems.addAll(data.liveDevas); liveAdapter.notifyDataSetChanged(); } //dynamic if (data.concerDevas != null && data.concerDevas.size() > 0) { dynamicItems.clear(); dynamicItems.addAll(data.concerDevas); dynamicAdapter.notifyDataSetChanged(); } //circle if (data.cirleItemDevas != null && data.cirleItemDevas.size() > 0) { circleItems.clear(); circleItems.addAll(data.cirleItemDevas); circleAdapter.notifyDataSetChanged(); } //user if (data.userDevas != null && data.userDevas.size() > 0) { activityUserItems.clear(); activityUserItems.addAll(data.userDevas); activityUserAdapter.notifyDataSetChanged(); } } } <file_sep>/app/src/main/java/com/gymnast/view/personal/adapter/CircleAdminAdapter.java package com.gymnast.view.personal.adapter; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.data.personal.CircleMainData; import com.gymnast.utils.GetUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.StringUtil; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * Created by Cymbi on 2016/9/22. */ public class CircleAdminAdapter extends RecyclerView.Adapter { Context context; List<CircleMainData> mValue; private String id,token; int tag=-1; public CircleAdminAdapter(Context context, List<CircleMainData> mValue) { this.context = context; if(mValue.size()==0){ this.mValue=new ArrayList<>(); }else { this.mValue = mValue; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater= LayoutInflater.from(context); View view=inflater.inflate(R.layout.item_circle_main,parent,false); SharedPreferences share = context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE); id = share.getString("UserId", ""); token = share.getString("Token", ""); return new AdminHolder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if(holder instanceof AdminHolder){ AdminHolder viewholder=(AdminHolder) holder; final CircleMainData circleMainData = mValue.get(position); PicassoUtil.handlePic(context, PicUtil.getImageUrlDetail(context, StringUtil.isNullAvatar(circleMainData.getAvatar()), 320, 320),viewholder.me_head,320,320); viewholder.tvNickname.setText(circleMainData.getNickname()); List<String> AdminIds=circleMainData.getAdminIds(); viewholder.circle_admin.setVisibility(View.GONE); for(int i=0;i<AdminIds.size();i++){ String str = AdminIds.get(i); try{ int admin=Integer.parseInt(str); int userId=circleMainData.getUserId(); if(admin == userId){ tag=position; viewholder.circle_admin.setVisibility(View.VISIBLE); } }catch (Exception e){e.printStackTrace();} } viewholder.llSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LayoutInflater inflater= LayoutInflater.from(context); View v=inflater.inflate(R.layout.setmaster_dialog, null); final Dialog dialog = new Dialog(context,R.style.Dialog_Fullscreen); LinearLayout llSetMaster = (LinearLayout) v.findViewById(R.id.llSetMaster); TextView tvText = (TextView) v.findViewById(R.id.tvText); tvText.setText("设置为管理员"); TextView cancel = (TextView) v.findViewById(R.id.cancel); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); llSetMaster.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(new Runnable() { String adminIds; @Override public void run() { try { int circle_id= circleMainData.getCircleId(); String admin=String.valueOf(circleMainData.getUserId()); String uri= API.BASE_URL+"/v1/circle/setAdminIds"; HashMap<String,String> params=new HashMap<>(); params.put("token",token); params.put("accountId",id); List<String> AdminIds=circleMainData.getAdminIds(); Log.e("AdminIds",AdminIds+""); if(AdminIds!=null&&AdminIds.size()!=0){ String str= StringUtil.listToString(AdminIds); adminIds=str+","+admin; params.put("adminIds",adminIds); }else { params.put("adminIds",admin); } params.put("circleId",circle_id+""); String result=PostUtil.sendPostMessage(uri,params); JSONObject obj=new JSONObject(result); if(obj.getInt("state")==200){ String url=API.BASE_URL+"/v1/circle/getOne/"; HashMap<String,String> par=new HashMap<String, String>(); par.put("circleId",circle_id+""); par.put("accountId",id+""); String res= GetUtil.sendGetMessage(url,par); JSONObject object=new JSONObject(res); JSONObject data = object.getJSONObject("data"); JSONObject circle=data.getJSONObject("circle"); String circleAdminIds=circle.getString("adminIds"); List<String> adminlist = Arrays.asList(circleAdminIds.split(",")); circleMainData.setAdminIds(adminlist); Activity activity=(Activity)context; activity.runOnUiThread(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }){}.start(); dialog.dismiss(); } }); notifyDataSetChanged(); dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.main_menu_animstyle); Activity activity=(Activity)context; WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = activity.getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 dialog.onWindowAttributesChanged(wl); // 设置点击外围解散 dialog.setCanceledOnTouchOutside(true); dialog.show(); } }); } } @Override public int getItemCount() { return mValue.size(); } class AdminHolder extends RecyclerView.ViewHolder{ private final ImageView me_head; private final TextView tvNickname; private final TextView circle_admin; private final LinearLayout llSelect; public AdminHolder(View itemView) { super(itemView); me_head=(ImageView)itemView.findViewById(R.id.me_head); tvNickname=(TextView)itemView.findViewById(R.id.tvNickname); circle_admin=(TextView)itemView.findViewById(R.id.circle_admin); // circle_main=(TextView)itemView.findViewById(R.id.circle_main); llSelect=(LinearLayout)itemView.findViewById(R.id.llSelect); } } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/ImageActivity.java package com.gymnast.view.personal.activity; import android.os.Bundle; import android.util.Log; import android.view.View; import com.gymnast.R; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.personal.customview.TouchImageView; /** * Created by Cymbi on 2016/9/21. */ public class ImageActivity extends ImmersiveActivity { private TouchImageView iv_dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_dialog); iv_dialog=(TouchImageView) findViewById(R.id.iv_dialog); String image=getIntent().getStringExtra("IMAGE"); Log.i("tag","imageUrl------------"+ image); if (image.contains("easemob")||image.contains("__")){ PicassoUtil.handlePic(this, image, iv_dialog, 720, 720); }else { PicassoUtil.handlePic(this, PicUtil.getImageUrlDetail(this, image, 720, 720), iv_dialog, 720, 720); } iv_dialog.setMaxZoom(33); iv_dialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonalDynamicDetailActivity.java package com.gymnast.view.personal.activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.App; import com.gymnast.R; import com.gymnast.data.hotinfo.ConcerDevas; import com.gymnast.data.net.API; import com.gymnast.data.pack.ConcernData; import com.gymnast.data.personal.DynamicData; import com.gymnast.utils.CallBackUtil; import com.gymnast.utils.GetUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.hotinfoactivity.adapter.CallBackAdapter; import com.gymnast.view.hotinfoactivity.entity.CallBackDetailEntity; import com.gymnast.view.hotinfoactivity.entity.CallBackEntity; import com.gymnast.view.personal.adapter.GridAdapter; import com.gymnast.view.personal.listener.MyTextWatcher; import com.gymnast.view.personal.listener.WrapContentLinearLayoutManager; import com.gymnast.view.user.LoginActivity; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; /** * Created by Cymbi on 2016/9/2. */ public class PersonalDynamicDetailActivity extends ImmersiveActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener,View.OnLayoutChangeListener { private ImageView mPersonal_menu,personal_back,mDynamic_head,ivClose; private TextView mDynamic_name,mDynamic_time,mDynamic_Title,mDynamic_context,star_type,tvCollect,tvReport,tvDelete, tvSpacial,tvTop; private GridView mGridview; private Dialog cameradialog; LinearLayout llShareToFriends,llShareToWeiChat,llShareToQQ,llShareToQQZone,llShareToMicroBlog; public static int shareNumber=0;//分享次数 private SimpleDateFormat sdf =new SimpleDateFormat("MM月-dd日 HH:mm"); View view; int circleUserID; TextView tvSendDynamic; EditText etCallBackDynamic; ImageView ivSendDynamic; RecyclerView rvCallBack; int notifyPos=0; SwipeRefreshLayout reflesh; String firstCommenter=""; boolean isPraised=false; String token,nowUserId,nickName,avatar; int dynamicID; List<CallBackEntity> commentList=new ArrayList<>(); CallBackAdapter commentAdapter; public static boolean isComment=true; public static final int HANDLE_COMMENT_DATA=1; public static final int HANDLE_MAIN_USER_BACK=2; public static final int HANDLE_PRAISE=3; public static final int HANDLE_CANCEL_PRAISE=4; public static final int HANDLE_UNKNOWN_ERROR=5; public static final int HANDLE_START_PRAISE=6; static ArrayList<CallBackDetailEntity> detailMSGs; ArrayList<String> userABC=new ArrayList<>(); Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case HANDLE_START_PRAISE: boolean isStartPraised= (boolean) msg.obj; ivSendDynamic.setVisibility(View.VISIBLE); if (isStartPraised){ ivSendDynamic.setImageResource(R.mipmap.like_pressed); }else { ivSendDynamic.setImageResource(R.mipmap.like_normal); } ivSendDynamic.invalidate(); break; case HANDLE_UNKNOWN_ERROR: Toast.makeText( PersonalDynamicDetailActivity.this,"未知错误,请重试!",Toast.LENGTH_SHORT).show(); break; case HANDLE_CANCEL_PRAISE: Toast.makeText( PersonalDynamicDetailActivity.this,"已取消点赞!",Toast.LENGTH_SHORT).show(); ivSendDynamic.setImageResource(R.mipmap.like_normal); break; case HANDLE_PRAISE: Toast.makeText( PersonalDynamicDetailActivity.this,"已点赞!",Toast.LENGTH_SHORT).show(); ivSendDynamic.setImageResource(R.mipmap.like_pressed); break; case HANDLE_MAIN_USER_BACK: commentAdapter.notifyItemChanged(notifyPos); break; case HANDLE_COMMENT_DATA: userABC = (ArrayList<String>) msg.obj; commentAdapter = new CallBackAdapter(PersonalDynamicDetailActivity.this, commentList); WrapContentLinearLayoutManager manager = new WrapContentLinearLayoutManager(PersonalDynamicDetailActivity.this, LinearLayoutManager.VERTICAL, false); rvCallBack.setLayoutManager(manager); rvCallBack.setAdapter(commentAdapter); commentAdapter.setOnItemClickListener(new CallBackAdapter.OnItemClickListener() { @Override public void OnCallBackClick(View view, int position, ArrayList<CallBackDetailEntity> detailMSGs) { isComment = false; notifyPos = position; PersonalDynamicDetailActivity.detailMSGs = detailMSGs; PersonalDynamicDetailActivity.type=PersonalDynamicDetailActivity.CALL_BACK_TYPE_ONE; String backWho = commentList.get(position).getCallBackNickName(); firstCommenter = backWho; etCallBackDynamic.requestFocus(); etCallBackDynamic.setText(""); etCallBackDynamic.setHint("回复" + backWho); InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager.isActive()) { inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS); PersonalDynamicDetailActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); tvSendDynamic.setVisibility(View.VISIBLE); ivSendDynamic.setVisibility(View.GONE); } } }); break; }}}; //屏幕高度 private int screenHeight=0; //软件盘弹起后所占高度阀值 private int keyHeight=0; private View activityRootView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); setContentView(R.layout.dynamic_details); getBaseInfo(); setView(); //获取屏幕高度 screenHeight = this.getWindowManager().getDefaultDisplay().getHeight(); //阀值设置为屏幕高度的1/3 keyHeight = screenHeight/3; activityRootView.addOnLayoutChangeListener(this); setData(); setCallBackView(); getPageView(); } private void getPageView() { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/pageViwes"; HashMap<String,String>params=new HashMap<>(); params.put("types",1+""); params.put("typeId",dynamicID+""); PostUtil.sendPostMessage(uri,params); } }).start(); } private void getBaseInfo() { SharedPreferences share = getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token", ""); nowUserId = share.getString("UserId","");//当前用户id nickName = share.getString("NickName", ""); avatar = share.getString("Avatar", ""); dynamicID= getIntent().getIntExtra("CirleID",0); } private void autoRefresh(){ InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(etCallBackDynamic.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); RefreshUtil.refresh(reflesh, this); setBaseState(); setCallBackView(); rvCallBack.scrollToPosition(0); ivSendDynamic.setVisibility(View.VISIBLE); tvSendDynamic .setVisibility(View.GONE); etCallBackDynamic.setFocusable(true); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 reflesh.setRefreshing(false); } }, 500); } private void setView() { reflesh = (SwipeRefreshLayout) findViewById(R.id.srlReflesh); RefreshUtil.refresh(reflesh, this); etCallBackDynamic= (EditText) findViewById(R.id.etCallBackDynamic); etCallBackDynamic.setHint("说点什么吧。。。"); etCallBackDynamic.setHintTextColor(Color.parseColor("#999999")); ivSendDynamic= (ImageView) findViewById(R.id.ivSendDynamic); rvCallBack= (RecyclerView) findViewById(R.id.rvCallBack); tvSendDynamic=(TextView) findViewById(R.id.tvSendDynamic); mPersonal_menu=(ImageView)findViewById(R.id.personal_menu); personal_back=(ImageView)findViewById(R.id.personal_back); mDynamic_head=(ImageView)findViewById(R.id.dynamic_head); mDynamic_name=(TextView)findViewById(R.id.dynamic_name); mDynamic_time=(TextView)findViewById(R.id.dynamic_time); mDynamic_Title=(TextView)findViewById(R.id.dynamic_Title); mDynamic_context=(TextView)findViewById(R.id.dynamic_context); activityRootView=findViewById(R.id.activityRootView); star_type=(TextView)findViewById(R.id.star_type); mGridview=(GridView)findViewById(R.id.gridview); view = getLayoutInflater().inflate(R.layout.share_dialog, null); llShareToFriends= (LinearLayout) view.findViewById(R.id.llShareToFriends); llShareToWeiChat= (LinearLayout) view.findViewById(R.id.llShareToWeiChat); llShareToQQ= (LinearLayout) view.findViewById(R.id.llShareToQQ); llShareToQQZone= (LinearLayout) view.findViewById(R.id.llShareToQQZone); llShareToMicroBlog= (LinearLayout) view.findViewById(R.id.llShareToMicroBlog); tvCollect= (TextView) view.findViewById(R.id.tvCollect); tvReport= (TextView) view.findViewById(R.id.tvReport); tvDelete= (TextView) view.findViewById(R.id.tvDelete); tvTop= (TextView) view.findViewById(R.id.tvTop); tvSpacial= (TextView) view.findViewById(R.id.tvSpacial); cameradialog = new Dialog(this,R.style.Dialog_Fullscreen); ivClose=(ImageView) view.findViewById(R.id.ivClose); mPersonal_menu.setOnClickListener(this); personal_back.setOnClickListener(this); mDynamic_head.setOnClickListener(this); mDynamic_name.setOnClickListener(this); mDynamic_time.setOnClickListener(this); mDynamic_Title.setOnClickListener(this); llShareToFriends.setOnClickListener(this); llShareToWeiChat.setOnClickListener(this); llShareToQQ.setOnClickListener(this); llShareToQQZone.setOnClickListener(this); llShareToMicroBlog.setOnClickListener(this); tvCollect.setOnClickListener(this); tvReport.setOnClickListener(this); tvDelete.setOnClickListener(this); tvSpacial.setOnClickListener(this); tvTop.setOnClickListener(this); ivClose.setOnClickListener(this); reflesh.setOnRefreshListener(this); tvSendDynamic.setOnClickListener(this); ivSendDynamic.setOnClickListener(this); etCallBackDynamic.addTextChangedListener(new MyTextWatcher(tvSendDynamic, ivSendDynamic, etCallBackDynamic)); } private void setData() { new Thread(new Runnable() { @Override public void run() { String uri = API.BASE_URL + "/v1/concern/getOne"; HashMap<String, String> params = new HashMap<String, String>(); params.put("concernId", dynamicID + ""); if (nowUserId!=null){ params.put("accountId",nowUserId); } Log.i("tag","dynamicID="+dynamicID); String result = GetUtil.sendGetMessage(uri, params); try { JSONObject object = new JSONObject(result); if (object.getInt("state") == 200) { final ArrayList<String> imageURL = new ArrayList<String>(); JSONObject data = object.getJSONObject("data"); JSONObject concern = data.getJSONObject("concern"); circleUserID=concern.getInt("userId"); JSONObject userVo = concern.getJSONObject("userVo"); boolean isCollection = data.getBoolean("isCollection"); isPraised = data.getBoolean("isZan"); final long createTime = concern.getLong("createTime"); final String topicTitle = concern.getString("topicTitle"); final String topicContent = concern.getString("topicContent"); final String nickName = userVo.getString("nickName"); String zanCounts = concern.getString("zanCounts"); String commentCounts = concern.getString("commentCounts"); String urls = concern.getString("imgUrl"); final String avatar = userVo.getString("avatar"); if (urls == null | urls.equals("null") | urls.equals("")) { } else { String[] imageUrls = urls.split(","); for (int j = 0; j < imageUrls.length; j++) { imageURL.add(API.IMAGE_URL + imageUrls[j]); } } Message message=new Message(); message.obj=isPraised; message.what=HANDLE_START_PRAISE; handler.sendMessage(message); runOnUiThread(new Runnable() { @Override public void run() { PicassoUtil.handlePic(PersonalDynamicDetailActivity.this, PicUtil.getImageUrlDetail(PersonalDynamicDetailActivity.this, StringUtil.isNullAvatar(avatar), 320, 320), mDynamic_head, 320, 320); mDynamic_name.setText(nickName); if(!topicTitle.equals("null")&&topicTitle!=null){ mDynamic_Title.setText(topicTitle); } mDynamic_time.setText(sdf.format(new Date(createTime)) + ""); mDynamic_context.setText(" "+topicContent); GridAdapter adapter = new GridAdapter(PersonalDynamicDetailActivity.this, imageURL); mGridview.setAdapter(adapter); adapter.notifyDataSetChanged(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.tvSendDynamic: handleSendMSG(); break; case R.id.ivSendDynamic: priseActive(); break; case R.id.personal_back: finish(); break; case R.id.personal_menu: showdialog(); break; case R.id.dynamic_head: Intent intent=new Intent(PersonalDynamicDetailActivity.this,PersonalOtherHomeActivity.class); intent.putExtra("UserID",circleUserID); PersonalDynamicDetailActivity.this.startActivity(intent); break; case R.id.llShareToFriends: shareToFriends(); break; case R.id.llShareToWeiChat: shareToWeiChat(); break; case R.id.llShareToQQ: shareToQQ(); break; case R.id.llShareToQQZone: shareToQQZone(); break; case R.id.llShareToMicroBlog: shareToMicroBlog(); break; case R.id.tvCollect: collect(); break; case R.id.tvReport: report(); break; case R.id.tvDelete: delete(); break; case R.id.tvSpacial: spacial(); break; case R.id.tvTop: toTop(); break; case R.id.ivClose: cameradialog.dismiss(); break; } } private void showdialog() { cameradialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = cameradialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.main_menu_animstyle); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 wl.width = ViewGroup.LayoutParams.MATCH_PARENT; wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 cameradialog.onWindowAttributesChanged(wl); // 设置点击外围解散 cameradialog.setCanceledOnTouchOutside(true); cameradialog.show(); } private void shareToFriends() { Toast.makeText(this, "分享到朋友圈!", Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToWeiChat() { Toast.makeText(this,"分享到微信!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToQQ() { Toast.makeText(this,"分享到QQ!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToQQZone() { Toast.makeText(this,"分享到QQ空间!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToMicroBlog() { Toast.makeText(this,"分享到微博!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void collect() { Toast.makeText(this,"已收藏!",Toast.LENGTH_SHORT).show(); } private void report() { Toast.makeText(this,"已举报!",Toast.LENGTH_SHORT).show(); } private void delete() { Toast.makeText(this,"已删除!",Toast.LENGTH_SHORT).show(); } private void spacial() { Toast.makeText(this,"已加精!",Toast.LENGTH_SHORT).show(); } private void toTop() { Toast.makeText(this,"已置顶!",Toast.LENGTH_SHORT).show(); } private void priseActive() { new Thread(){ @Override public void run() { try{ String uri= API.BASE_URL+"/v1/zan/add"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("bodyId",dynamicID+""); params.put("bodyType",2+""); params.put("accountId",nowUserId); String result= PostUtil.sendPostMessage(uri, params); JSONObject obj=new JSONObject(result); int state=obj.getInt("state"); if (state==200){ if (isPraised){ handler.sendEmptyMessage(HANDLE_CANCEL_PRAISE); }else { handler.sendEmptyMessage(HANDLE_PRAISE); } isPraised=!isPraised; }else { handler.sendEmptyMessage(HANDLE_UNKNOWN_ERROR); } }catch (Exception e){ e.printStackTrace(); } } }.start(); } private void setCallBackView() { CallBackUtil.getCallBackData(3, dynamicID, commentList, handler, HANDLE_COMMENT_DATA); reflesh.setRefreshing(false); } String toNickName; public static final int CALL_BACK_TYPE_ONE=1111; public static final int CALL_BACK_TYPE_TWO=2222; public static int type; private void handleSendMSG() { toNickName=etCallBackDynamic.getHint().toString().trim().substring(2); if(!App.isStateOK|token.equals("")){//未登录 Toast.makeText(PersonalDynamicDetailActivity.this,"您还没有登录,请登陆!",Toast.LENGTH_SHORT).show(); PersonalDynamicDetailActivity.this.startActivity(new Intent(PersonalDynamicDetailActivity.this,LoginActivity.class)); return; }else { String comment = etCallBackDynamic.getText().toString().trim(); if (isComment) { if (comment.equals("")) { Toast.makeText(PersonalDynamicDetailActivity.this, "回复内容为空!", Toast.LENGTH_SHORT).show();//非空判断 setBaseState(); return; } else {//评论帖子 etCallBackDynamic.setText(""); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(etCallBackDynamic.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); CallBackUtil.handleCallBackMSG(3, dynamicID, Integer.valueOf(nowUserId), comment); CallBackEntity entity = new CallBackEntity(); entity.setCallBackImgUrl(StringUtil.isNullAvatar(avatar)); entity.setCallBackNickName(nickName); entity.setCallBackTime(System.currentTimeMillis()); entity.setCallBackText(comment); entity.setEntities(new ArrayList<CallBackDetailEntity>()); commentList.add(entity); commentAdapter.notifyItemChanged(commentList.size() - 1); rvCallBack.scrollToPosition(0); autoRefresh(); } } else { if (comment.equals("")) {//非空判断 Toast.makeText(PersonalDynamicDetailActivity.this, "回复内容为空!", Toast.LENGTH_SHORT).show();//非空判断 isComment = true; setBaseState(); return; } else { if (toNickName.equals(nickName)) {//回复自己 Toast.makeText(PersonalDynamicDetailActivity.this, "不能回复自己!", Toast.LENGTH_SHORT).show(); isComment = true; setBaseState(); return; } else {//回复他人 if (type == CALL_BACK_TYPE_TWO) {//2号类型回复 int callBackPOS=CallBackAdapter.callBackToPOS; int commentID = commentList.get(callBackPOS).getCommentID(); int toID = CallBackAdapter.callBackToID; ArrayList<CallBackDetailEntity> detailMSGList = CallBackAdapter.MSGS; CallBackUtil.handleBack(token, commentID, Integer.valueOf(nowUserId), toID, comment, detailMSGList, handler, HANDLE_MAIN_USER_BACK, nickName, toNickName); isComment = true; autoRefresh(); } else {//1号类型回复 int commentID = commentList.get(notifyPos).getCommentID(); CallBackUtil.handleBack(token, commentID, Integer.valueOf(nowUserId), -1, comment, detailMSGs, handler, HANDLE_MAIN_USER_BACK, nickName, ""); isComment = true; autoRefresh(); } } } } } } private void setBaseState(){ etCallBackDynamic.setHint("说点什么吧。。。"); etCallBackDynamic.setHintTextColor(Color.parseColor("#999999")); etCallBackDynamic.setText(""); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0); } @Override protected void onResume() { super.onResume(); activityRootView.addOnLayoutChangeListener(this); etCallBackDynamic.setHint("说点什么吧。。。"); etCallBackDynamic.setHintTextColor(Color.parseColor("#999999")); etCallBackDynamic.setText(""); setData(); if (commentList.size()!=0){ commentList.clear(); setCallBackView(); } } @Override public void onRefresh() { setCallBackView(); setData(); etCallBackDynamic.setHint("说点什么吧。。。"); etCallBackDynamic.setHintTextColor(Color.parseColor("#999999")); etCallBackDynamic.setText(""); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 reflesh.setRefreshing(false); } }, 1000); } @Override public void onBackPressed() { super.onBackPressed(); isComment=true; } @Override public void onLayoutChange(View v, int left, int top, int right,int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高,就认为软键盘弹起 if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){ /* View view=getLayoutInflater().inflate(R.layout.log_out_dialog, null); Dialog dialog = new Dialog(this, R.style.transparentFrameWindowStyle); dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.log_out_dialog); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y=oldBottom - bottom; dialog.onWindowAttributesChanged(wl); dialog.show();*/ Toast.makeText(PersonalDynamicDetailActivity.this,"软键盘弹起",Toast.LENGTH_SHORT).show(); }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){ Toast.makeText(PersonalDynamicDetailActivity.this,"软键盘收起",Toast.LENGTH_SHORT).show(); } } } <file_sep>/app/src/main/java/com/gymnast/data/hotinfo/NewActivityItemDevas.java package com.gymnast.data.hotinfo; import java.io.Serializable; /** * Created by Cymbi on 2016/8/19. */ public class NewActivityItemDevas implements Serializable { public int getActiveId() { return activeId; } public void setActiveId(int activeId) { this.activeId = activeId; } private int activeId; boolean isCollected; public boolean isCollected() { return isCollected; } public void setIsCollected(boolean isCollected) { this.isCollected = isCollected; } //收藏人数 public int collection; //Title public String title; //详细信息 public String descContent; //封面地址 public String imgUrls; //活动开始时间 public Long startTime; //活动结束时间 public Long endTime; //报名结束时间 public Long lastTime; //线下活动地址 public String address; //活动发布人名字 public String nickname; //活动价格 public int price; //最大人数限制 public String maxPeople; //联系电话 public String phone; //线上活动跳转地址 public String targetUrl; //活动是否需要审核:0不需要审核,1需要审核 public int examine; //活动启用状态:0启用,1禁用 public String activityType; //活动类型:0是线上,1是线下 public int type; //报名活动计数 public int memberCount; //报名活动模块 public String memberTemplate; String authInfo; int zanCount,msgCount; int mask; int userID; public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } int pageViews;//多少人浏览 public int getPageViews() { return pageViews; } public void setPageViews(int pageViews) { this.pageViews = pageViews; } public int getZanCount() { return zanCount; } public void setZanCount(int zanCount) { this.zanCount = zanCount; } public int getMsgCount() { return msgCount; } public void setMsgCount(int msgCount) { this.msgCount = msgCount; } public int getMask() { return mask; } public void setMask(int mask) { this.mask = mask; } public String getAuthInfo() { return authInfo; } public void setAuthInfo(String authInfo) { this.authInfo = authInfo; } //哪些人可以看 0表示所有人,1表示我的关注,2表示我的粉丝 public int visible; public String getDescContent() { return descContent; } public void setDescContent(String descContent) { this.descContent = descContent; } public Long getEndTime() { return endTime; } public void setEndTime(Long endTime) { this.endTime = endTime; } public Long getLastTime() { return lastTime; } public void setLastTime(Long lastTime) { this.lastTime = lastTime; } public String getMaxPeople() { return maxPeople; } public void setMaxPeople(String maxPeople) { this.maxPeople = maxPeople; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getTargetUrl() { return targetUrl; } public void setTargetUrl(String targetUrl) { this.targetUrl = targetUrl; } public int getExamine() { return examine; } public void setExamine(int examine) { this.examine = examine; } public String getActivityType() { return activityType; } public void setActivityType(String activityType) { this.activityType = activityType; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getMemberCount() { return memberCount; } public void setMemberCount(int memberCount) { this.memberCount = memberCount; } public String getMemberTemplate() { return memberTemplate; } public void setMemberTemplate(String memberTemplate) { this.memberTemplate = memberTemplate; } public int getVisible() { return visible; } public void setVisible(int visible) { this.visible = visible; } public int getCollection() { return collection; } public void setCollection(int collection) { this.collection = collection; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImgUrls() { return imgUrls; } public void setImgUrls(String imgUrls) { this.imgUrls=imgUrls; } public Long getStartTime() { return startTime; } public void setStartTime(Long startTime) { this.startTime = startTime; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } <file_sep>/app/src/main/java/com/gymnast/data/net/Result.java package com.gymnast.data.net; /** * Created by fldyown on 16/6/27. */ public class Result<T> { public int state; public String successmsg; public String phone; public int code; public T data; @Override public String toString() { return "{" + "state=" + state + ", successmsg='" + successmsg + '\'' + ", data='" + data + '\'' + '}'; } }<file_sep>/app/src/main/java/com/gymnast/view/live/customview/MyTextView.java package com.gymnast.view.live.customview; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.widget.TextView; import com.gymnast.R; /** * Created by Administrator on 2016/8/3. */ public class MyTextView extends TextView { public boolean isOut=false; public boolean isSelect=false; public boolean isToday=false; public int posInCalendar=0; Context context; public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); this.context=context; TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.MyTextView); isOut=array.getBoolean(R.styleable.MyTextView_isOut,false); isSelect=array.getBoolean(R.styleable.MyTextView_isSelect,false); isToday=array.getBoolean(R.styleable.MyTextView_isToday,false); posInCalendar=array.getInt(R.styleable.MyTextView_myPosition,0); this.setIsOut(isOut); this.setIsToday(isToday); this.setIsSelect(isSelect); this.setPosInCalendar(posInCalendar); array.recycle(); } public int getPosInCalendar() { return posInCalendar; } public void setPosInCalendar(int posInCalendar) { this.posInCalendar = posInCalendar; } public boolean isToday() { return isToday; } public void setIsToday(boolean isToday) { this.isToday = isToday; } public boolean isSelect() { return isSelect; } public void setIsSelect(boolean isSelect) { this.isSelect = isSelect; } public boolean isOut() { return isOut; } public void setIsOut(boolean isOut) { this.isOut = isOut; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isOut){ this.setTextColor(getResources().getColor(R.color.half_black)); }else { this.setTextColor(getResources().getColor(R.color.hot_info_circle_content_color)); } if (isSelect) { this.setTextColor(getResources().getColor(R.color.white)); this.setBackgroundResource(R.mipmap.bg_circle_red); }else { this.setBackgroundResource(0); } if (isToday){ Drawable smallRedPoint=context.getResources().getDrawable(R.drawable.border_radius_circle_red_point); smallRedPoint.setBounds(0, 0, 8, 8); this.setCompoundDrawables(null, null,null,smallRedPoint); this.setCompoundDrawablePadding(-12); }else { this.setCompoundDrawables(null, null,null,null); } this.setGravity(Gravity.CENTER); Rect rect = new Rect(); ((Activity)context).getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); int x = rect.width(); this.setTextSize(TypedValue.COMPLEX_UNIT_PX,27*x/750); } } <file_sep>/app/src/main/java/com/gymnast/view/personal/listener/MyTextWatcher.java package com.gymnast.view.personal.listener; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.gymnast.R; /** * Created by zzqybyb19860112 on 2016/9/21. */ public class MyTextWatcher implements TextWatcher { TextView tvSendTieZi; ImageView ivSendTiezi; EditText etCallBackTieZi; public MyTextWatcher(TextView tvSendTieZi, ImageView ivSendTiezi,EditText etCallBackTieZi) { this.tvSendTieZi = tvSendTieZi; this.ivSendTiezi = ivSendTiezi; this.etCallBackTieZi = etCallBackTieZi; } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if (!editable.toString().equals("")){ tvSendTieZi.setVisibility(View.VISIBLE); ivSendTiezi.setVisibility(View.GONE); }else { tvSendTieZi.setVisibility(View.GONE); ivSendTiezi.setVisibility(View.VISIBLE); } } } <file_sep>/app/src/main/java/com/gymnast/data/user/UserServiceImpl.java package com.gymnast.data.user; import com.gymnast.App; import com.gymnast.data.net.Result; import com.gymnast.data.net.UserApi; import com.gymnast.data.net.UserData; import com.gymnast.utils.RetrofitUtil; import java.io.File; import java.util.HashMap; import okhttp3.MediaType; import okhttp3.RequestBody; import rx.Observable; /** * Created by fldyown on 16/6/14. */ public class UserServiceImpl implements UserService { UserApi api; public UserServiceImpl() { api = RetrofitUtil.createApi(App.getContext(), UserApi.class); } @Override public Observable<Result> getVerifyCode(String phone) { HashMap<String, String> params = new HashMap<>(); params.put("phone", phone); return api.getVerifyCode(params); } @Override public Observable<Result<VerifyCode>> verifyPhone(String phone, String code) { HashMap<String, String> params = new HashMap<>(); params.put("phone", phone); params.put("code", code); return api.verifyPhone(params); } @Override public Observable<Result> register(String phone, String pwd, String nickname, String avatar) { HashMap<String, RequestBody> params = new HashMap<>(); params.put("phone", RequestBody.create(MediaType.parse("text/plain"), phone)); params.put("pwd", RequestBody.create(MediaType.parse("text/plain"), pwd)); params.put("nickname", RequestBody.create(MediaType.parse("text/plain"), nickname)); if (avatar != null) { params.put("avatar", RequestBody.create(MediaType.parse("image/*"), new File(avatar))); } return api.register(params); } @Override public Observable<Result> retrievePassword(String phone, String pwd, String re_pwd) { HashMap<String, String> params = new HashMap<>(); params.put("phone", phone); params.put("pwd", pwd); params.put("re_pwd", re_pwd); return api.retrievePassword(params); } @Override public Observable<Result<UserData>> login(String phone, String pwd) { HashMap<String, String> params = new HashMap<String, String>(); params.put("phone", phone); params.put("pwd", pwd); return api.login(params); } } <file_sep>/app/src/main/java/com/gymnast/data/hotinfo/LiveMessage.java package com.gymnast.data.hotinfo; import java.io.Serializable; /** * Created by 永不放弃 on 2016/7/30. */ public class LiveMessage implements Serializable { String iconUrl; String pictureUrl; String timeUntilNow; long createTime; String content; public LiveMessage() { } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public String getPictureUrl() { return pictureUrl; } public void setPictureUrl(String pictureUrl) { this.pictureUrl = pictureUrl; } public String getTimeUntilNow() { return timeUntilNow; } public void setTimeUntilNow(String timeUntilNow) { this.timeUntilNow = timeUntilNow; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } <file_sep>/app/src/main/java/com/gymnast/data/personal/CircleMainData.java package com.gymnast.data.personal; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by Cymbi on 2016/9/21. */ public class CircleMainData implements Serializable { private String avatar; private String nickname; private int userId; private int circleId; private Integer circleMasterId; private List<String> adminIds; public Integer getCircleMasterId() { return circleMasterId; } public void setCircleMasterId(Integer circleMasterId) { this.circleMasterId = circleMasterId; } public List<String> getAdminIds() { return adminIds; } public void setAdminIds(List<String> adminIds) { this.adminIds = adminIds; } public int getCircleId() { return circleId; } public void setCircleId(int circleId) { this.circleId = circleId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } } <file_sep>/app/src/main/java/com/gymnast/utils/CallBackUtil.java package com.gymnast.utils; import android.os.Handler; import android.os.Message; import android.util.Log; import com.gymnast.data.net.API; import com.gymnast.view.hotinfoactivity.entity.CallBackDetailEntity; import com.gymnast.view.hotinfoactivity.entity.CallBackEntity; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by zzqybyb19860112 on 2016/9/18. */ public class CallBackUtil { public static void getCallBackData(final int comment_type, final int comment_id,final List<CallBackEntity> list,final Handler handler, final int status){ new Thread(){ @Override public void run() { try{ ArrayList<String> userABC=new ArrayList<String>(); if (list.size()!=0){ list.clear(); userABC.clear(); } String uri = API.BASE_URL + "/v1/comment/query/" + comment_type + "/" + comment_id; HashMap<String, String> params = new HashMap<String, String>(); String result= GetUtil.sendGetMessage(uri, params); Log.i("tag","result------->"+result); JSONObject object=new JSONObject(result); JSONArray array=object.getJSONArray("data"); for (int i=0;i<array.length();i++){ JSONObject data=array.getJSONObject(i); CallBackEntity entity=new CallBackEntity(); JSONObject userVo=data.getJSONObject("userVo"); entity.setCallBackImgUrl(StringUtil.isNullAvatar(userVo.getString("avatar"))); userABC.add(userVo.getString("nickName")); entity.setCommentID(data.getInt("id")); entity.setCallBackNickName(userVo.getString("nickName")); entity.setCallBackText(data.getString("commentContent")); entity.setCallBackTime(data.getLong("createTime")); entity.setCommenterId(data.getInt("commentAccount")); JSONArray comment=data.getJSONArray("replyVos"); ArrayList<CallBackDetailEntity> detailList=new ArrayList<>(); if (comment==null){ continue; } for (int j=0;j<comment.length();j++){ JSONObject commentDetail=comment.getJSONObject(j); CallBackDetailEntity detail=new CallBackDetailEntity(); detail.setContent(commentDetail.getString("replyContent")); detail.setFromID(commentDetail.getInt("replyFromUser")); detail.setToID(commentDetail.getInt("replyToUser")); String from; String to; String jsonFrom=StringUtil.isNullNickName(commentDetail.getString("fromUserVo")); if (jsonFrom==null||jsonFrom.equals("")){ from=""; }else { JSONObject jsonObject=new JSONObject(jsonFrom); from=jsonObject.getString("nickName"); } String jsonTo=StringUtil.isNullNickName(commentDetail.getString("toUserVo")); if (jsonTo==null||jsonTo.equals("")){ to=""; }else { JSONObject jsonObject=new JSONObject(jsonTo); to=jsonObject.getString("nickName"); } detail.setFrom(from); detail.setTo(to); detailList.add(detail); userABC.add(from); userABC.add(to); } entity.setEntities(detailList); list.add(entity); } Message message=new Message(); message.what=status; message.obj=userABC; handler.sendMessage(message); }catch (Exception e){ e.printStackTrace(); } } }.start(); } public static void handleCallBackMSG(final int comment_type, final int comment_id, final int comment_account, final String comment_content){ new Thread(){ @Override public void run() { try{ String uri=API.BASE_URL+"/v1/comment/insert"; HashMap<String,String> params=new HashMap<String, String>(); params.put("comment_type",comment_type+""); params.put("comment_id",comment_id+""); params.put("comment_account",comment_account+""); params.put("comment_content", comment_content + ""); PostUtil.sendPostMessage(uri, params); }catch (Exception e){ e.printStackTrace(); } } }.start(); } public static void handleBack(final String token, final int reply_parent_id, final int reply_from_user, final int reply_to_user, final String reply_content, final ArrayList<CallBackDetailEntity> detailMSGs, final Handler handler, final int status, final String from, final String to){ new Thread(){ @Override public void run() { try{ String uri=API.BASE_URL+"/v1/reply/addReply"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token+""); params.put("reply_parent_id",reply_parent_id+""); params.put("reply_from_user",reply_from_user+""); params.put("reply_to_user",reply_to_user+""); params.put("reply_content", reply_content + ""); String result=PostUtil.sendPostMessage(uri,params); JSONObject object=new JSONObject(result); if (object.getInt("state")==200){ CallBackDetailEntity entity=new CallBackDetailEntity(); entity.setFrom(from); entity.setTo(to); entity.setContent(reply_content); detailMSGs.add(entity); } handler.sendEmptyMessage(status); }catch (Exception e){ e.printStackTrace(); } } }.start(); } } <file_sep>/app/src/main/java/com/gymnast/view/live/activity/MoreLiveActivity.java package com.gymnast.view.live.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.DialogUtil; import com.gymnast.utils.LiveUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.home.adapter.SearchLiveAdapter; import com.gymnast.view.live.entity.LiveItem; import com.gymnast.view.personal.activity.PersonalOtherHomeActivity; import com.gymnast.view.user.LoginActivity; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MoreLiveActivity extends ImmersiveActivity implements View.OnClickListener{ ImageView ivBack; private EditText etSearch; RecyclerView rvMoreLive; ArrayList<LiveItem> list=new ArrayList<>(); SearchLiveAdapter adapter; LiveItem liveItem; public static final int HANDLE_DATA=6; public static final int UPDATE_STATE_OK=1; public static final int MAINUSER_IN_OK=2; public static final int MAINUSER_IN_ERROR=3; public static final int OTHERUSER_IN_OK=4; public static final int OTHERUSER_IN_ERROR=5; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case HANDLE_DATA: adapter = new SearchLiveAdapter(MoreLiveActivity.this, list); adapter.setFriends(list); rvMoreLive.setAdapter(adapter); adapter.getFilter().filter(etSearch.getText().toString()); adapter.notifyDataSetChanged(); adapter.setOnItemClickListener(new SearchLiveAdapter.OnItemClickListener() { @Override public void OnItemPhotoClick(View view, LiveItem live) { if (view.getId() == R.id.rivSearchPhoto) { liveItem = live; Intent intent1 = new Intent(MoreLiveActivity.this, PersonalOtherHomeActivity.class); int userID = Integer.valueOf(liveItem.getLiveOwnerId()); intent1.putExtra("UserID", userID); MoreLiveActivity.this.startActivity(intent1); } else if (view.getId() == R.id.ivSearchBig) { liveItem = live; LiveUtil.doIntoLive(MoreLiveActivity.this, handler, liveItem); } } }); break; case UPDATE_STATE_OK: Toast.makeText(MoreLiveActivity.this, "您开启了直播", Toast.LENGTH_SHORT).show(); LiveUtil.doNext(MoreLiveActivity.this, liveItem); break; case MAINUSER_IN_OK: Toast.makeText(MoreLiveActivity.this,"您开启了直播",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(MoreLiveActivity.this, liveItem); break; case MAINUSER_IN_ERROR: DialogUtil.goBackToLogin(MoreLiveActivity.this, "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; case OTHERUSER_IN_OK: Toast.makeText(MoreLiveActivity.this,"您已进入直播室",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(MoreLiveActivity.this, liveItem); break; case OTHERUSER_IN_ERROR: DialogUtil.goBackToLogin(MoreLiveActivity.this, "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_more_live); etSearch= (EditText) findViewById(R.id.etSearch); ivBack= (ImageView) findViewById(R.id.ivBack); rvMoreLive= (RecyclerView) findViewById(R.id.rvMoreLive); rvMoreLive.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); rvMoreLive.setLayoutManager(layoutManager); setData(); setListener(); } private void setData() { new Thread(){ @Override public void run() { try{ String uri= API.BASE_URL+"/v1/search/model"; HashMap<String,String> params=new HashMap<String, String>(); params.put("model","4"); params.put("pageNumber","100"); params.put("pages", "1"); String result = PostUtil.sendPostMessage(uri, params); JSONObject json = new JSONObject(result); final SharedPreferences share =getSharedPreferences("UserInfo", Context.MODE_PRIVATE); final String userId = share.getString("UserId", ""); if (json.getInt("state")==200){ JSONArray data = json.getJSONArray("data"); for (int i=0;i<data.length();i++){ JSONObject object=data.getJSONObject(i); LiveItem live=new LiveItem(); String imageUrl=StringUtil.isNullImageUrl(object.getString("bgmUrl")); String title=object.getString("title"); String groupId=(StringUtil.isNullGroupId(object.getString("groupId"))); int liveId=object.getInt("id"); long startTime=object.getLong("createTime"); int state=object.getInt("state"); JSONObject account=object.getJSONObject("account"); String authTemp=StringUtil.isNullAuth(account.getString("auth")); String authInfoTemp=""; if (authTemp!=null&&!authTemp.equals("")){ JSONObject auth=new JSONObject(authTemp); authInfoTemp=auth.getString("authinfo"); } String nickName=account.getString("nickName"); String avatar=StringUtil.isNullAvatar(account.getString("avatar")); String liveOwnerId=account.getString("id"); int number=object.getString("number")==null?0:object.getInt("number"); live.setUserType(liveOwnerId.equals(userId) ? LiveActivity.USER_MAIN : LiveActivity.USER_OTHER); live.setBigPictureUrl(imageUrl); live.setLiveId(liveId); live.setTitle(title); live.setGroupId(groupId); live.setMainPhotoUrl(avatar); live.setCurrentNum(number); live.setLiveOwnerId(liveOwnerId); live.setStartTime(startTime); live.setAuthInfo(authInfoTemp); live.setNickName(nickName); live.setLiveState(state); list.add(live); } }else{ list=new ArrayList<LiveItem>(); } handler.sendEmptyMessage(HANDLE_DATA); }catch (Exception e){ e.printStackTrace(); } } }.start(); } private void setListener() { ivBack.setOnClickListener(this); etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { adapter.getFilter().filter(charSequence); } @Override public void afterTextChanged(Editable editable) { } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.ivBack: finish(); break; } } } <file_sep>/app/src/main/java/com/gymnast/data/personal/CircleData.java package com.gymnast.data.personal; import java.io.Serializable; /** * 我创建的圈子列表 * Created by Cymbi on 2016/8/25. */ public class CircleData implements Serializable { //标题,名称 private String title; //类型 private String details; //圈子头像 private String headImgUrl; //圈子数量 private int circleItemCount; //圈子id private int id; private boolean concerned; private int ismeet; //创建者id private int createId; public int getCreateId() { return createId; } public void setCreateId(int createId) { this.createId = createId; } public int getIsmeet() { return ismeet; } public void setIsmeet(int ismeet) { this.ismeet = ismeet; } public boolean isConcerned() { return concerned; } public void setConcerned(boolean concerned) { this.concerned = concerned; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getHeadImgUrl() { return headImgUrl; } public void setHeadImgUrl(String headImgUrl) { this.headImgUrl = headImgUrl; } public int getCircleItemCount() { return circleItemCount; } public void setCircleItemCount(int circleItemCount) { this.circleItemCount = circleItemCount; } } <file_sep>/app/src/main/java/com/gymnast/view/personal/contact/SortModel.java package com.gymnast.view.personal.contact; import android.graphics.Bitmap; public class SortModel { private String name; // 显示的数据 private String sortLetters; // 显示数据拼音的首字母 private Bitmap smallPhoto; private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSortLetters() { return sortLetters; } public void setSortLetters(String sortLetters) { this.sortLetters = sortLetters; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Bitmap getSmallPhoto() { return smallPhoto; } public void setSmallPhoto(Bitmap smallPhoto) { this.smallPhoto = smallPhoto; } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/customView/MyCMDTextView.java package com.gymnast.view.hotinfoactivity.customView; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.TextView; /** * Created by Cymbi on 2016/9/17. */ public class MyCMDTextView extends TextView { boolean isCancel; public MyCMDTextView(Context context, AttributeSet attrs) { super(context, attrs); } public MyCMDTextView(Context context, AttributeSet attrs,boolean isCancel) { super(context, attrs); this.isCancel=isCancel; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } public boolean isCancel() { return isCancel; } public void setCancel(boolean cancel) { isCancel = cancel; } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/entity/CallBackEntity.java package com.gymnast.view.hotinfoactivity.entity; import java.util.ArrayList; /** * Created by zzqybyb19860112 on 2016/9/17. */ public class CallBackEntity { String callBackImgUrl;//评论者的头像地址 String callBackNickName;//评论者的昵称 long callBackTime;//评论时间 String callBackText;//评论内容 int commenterId;//评论者的系统id int commentID; ArrayList<CallBackDetailEntity> entities; public int getCommentID() { return commentID; } public void setCommentID(int commentID) { this.commentID = commentID; } public int getCommenterId() { return commenterId; } public void setCommenterId(int commenterId) { this.commenterId = commenterId; } public String getCallBackImgUrl() { return callBackImgUrl; } public void setCallBackImgUrl(String callBackImgUrl) { this.callBackImgUrl = callBackImgUrl; } public String getCallBackNickName() { return callBackNickName; } public void setCallBackNickName(String callBackNickName) { this.callBackNickName = callBackNickName; } public long getCallBackTime() { return callBackTime; } public void setCallBackTime(long callBackTime) { this.callBackTime = callBackTime; } public String getCallBackText() { return callBackText; } public void setCallBackText(String callBackText) { this.callBackText = callBackText; } public ArrayList<CallBackDetailEntity> getEntities() { return entities; } public void setEntities(ArrayList<CallBackDetailEntity> entities) { this.entities = entities; } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonalEditAddressActivity.java package com.gymnast.view.personal.activity; import android.os.Bundle; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; /** * Created by yf928 on 2016/7/27. */ public class PersonalEditAddressActivity extends ImmersiveActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_address_edit); } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/adapter/AuditMainAdapter.java package com.gymnast.view.hotinfoactivity.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.gymnast.R; import com.gymnast.data.hotinfo.AuditData; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.hotinfoactivity.activity.AuditActivity; import com.gymnast.view.hotinfoactivity.customView.MyCMDTextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; /** * Created by Cymbi on 2016/9/16. */ public class AuditMainAdapter extends RecyclerView.Adapter { Context context; List<AuditData> list; public AuditMainAdapter(Context context, List<AuditData> list) { this.context = context; if(list.size()==0){ this.list =new ArrayList<>(); }else { this.list = list; } } List<CheckBox> listCheckBox=new ArrayList<>(); @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater=LayoutInflater.from(context); View view= inflater.inflate(R.layout.item_audit,parent,false); return new MainHolder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if(holder instanceof MainHolder){ final MainHolder viewholder=(MainHolder)holder; AuditData auditData=list.get(position); ((AuditActivity)context).setOnItemClickListener(new AuditActivity.CheckBoxShowCMD() { @Override public void showOrHide(boolean isShow) { for (CheckBox checkBox:listCheckBox){ if (isShow){ checkBox.setVisibility(View.GONE); }else { checkBox.setVisibility(View.VISIBLE); } } } }); PicassoUtil.handlePic(context, PicUtil.getImageUrlDetail(context, StringUtil.isNullAvatar(auditData.getAvatar()), 72, 72),viewholder.ivAvatar,72,72); viewholder.tvUserName.setText(auditData.getUsername()); viewholder.tvRealName.setText(auditData.getRealname()); viewholder.tvSex.setText(auditData.getSex()); String age=auditData.getAge().toString(); if(!age.equals("")&&age!=null&&!age.equals("null")){ viewholder.tvAge.setVisibility(View.VISIBLE); viewholder.tvAge.setText(age); }else { viewholder.tvAge.setVisibility(View.GONE); } if(!auditData.getAddress().equals("")&&auditData.getAddress()!=null&&!auditData.getAddress().equals("null")){ viewholder.tvAddress.setVisibility(View.VISIBLE); viewholder.tvAddress.setText(auditData.getAddress()); }else { viewholder.tvAddress.setVisibility(View.GONE); } if(!auditData.getId().equals("")&&auditData.getId()!=null&&!auditData.getId().equals("null")){ viewholder.tvID.setVisibility(View.VISIBLE); viewholder.tvID.setText(auditData.getId()); }else { viewholder.tvID.setVisibility(View.GONE); } viewholder.tvPhone.setText(auditData.getPhone()); if(auditData.getExamineType()==0){ viewholder.tvPass.setText("未通过"); }else { viewholder.tvPass.setText("通过"); } } } @Override public int getItemCount() { return list.size(); } class MainHolder extends RecyclerView.ViewHolder{ private final ImageView ivAvatar; private final TextView tvUserName,tvRealName,tvAddress,tvPhone,tvSex,tvAge,tvID,tvPass; private CheckBox cbSelect; public MainHolder(View itemView) { super(itemView); ivAvatar= (ImageView)itemView.findViewById(R.id.ivAvatar); tvUserName=(TextView)itemView.findViewById(R.id.tvUserName); tvRealName=(TextView)itemView.findViewById(R.id.tvRealName); tvAddress=(TextView)itemView.findViewById(R.id.tvAddress); tvPhone=(TextView)itemView.findViewById(R.id.tvPhone); tvSex=(TextView)itemView.findViewById(R.id.tvSex); tvAge=(TextView)itemView.findViewById(R.id.tvAge); tvID=(TextView)itemView.findViewById(R.id.tvID); tvPass=(TextView)itemView.findViewById(R.id.tvPass); cbSelect= (CheckBox) itemView.findViewById(R.id.cbSelect); listCheckBox.add(cbSelect); } } }<file_sep>/app/src/main/java/com/gymnast/utils/TimeUtil.java package com.gymnast.utils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * Created by zzqybyb19860112 on 2016/9/7. */ public class TimeUtil { public static String getDetailTime(long timeMillions){ SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日HH时mm分"); String temptime=sdf.format(new Date(timeMillions)); String month=temptime.substring(0, 2); String day=temptime.substring(3, 5); String hour=temptime.substring(6, 8); String minute=temptime.substring(9,11); month=NumberUtil.handleNumber(month); day=NumberUtil.handleNumber(day); hour=NumberUtil.handleNumber(hour); minute=NumberUtil.handleNumber(minute); return month+"月"+day+"日"+hour+"时"+minute+"分"; } public static String getDetailTimeNumber(long timeMillions){ SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日HH时mm分"); String temptime=sdf.format(new Date(timeMillions)); String month=temptime.substring(0, 2); String day=temptime.substring(3, 5); String hour=temptime.substring(6, 8); String minute=temptime.substring(9,11); month=NumberUtil.handleNumber(month); day=NumberUtil.handleNumber(day); return month+"月"+day+"日 "+hour+":"+minute; } public static String getMonthDayTime(long timeMillions){ SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日"); String temptime=sdf.format(new Date(timeMillions)); String month=temptime.substring(0, 2); String day=temptime.substring(3, 5); month=NumberUtil.handleNumber(month); day=NumberUtil.handleNumber(day); return month+"月"+day+"日"; } public static String getNumberTime(long timeMillions){ SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日HH时mm分"); String temptime=sdf.format(new Date(timeMillions)); String month=temptime.substring(0, 2); String day=temptime.substring(3, 5); String hour=temptime.substring(6, 8); String minute=temptime.substring(9,11); month=NumberUtil.handleNumber(month); day=NumberUtil.handleNumber(day); return month+"月"+day+"日 "+hour+":"+minute; } public static String getDisTime(long nowTime,long beginTime){ long disTime=beginTime-nowTime; String result=""; if (disTime<86400L*1000L){ long hour= disTime/3600000L; long minute=(disTime-hour*3600000L)/60000L; result=hour+"小时"+minute+"分"; }else { long day= (disTime/86400000L); long hour= (disTime-day*86400000L)/3600000L; long minute=(disTime-day*86400000L-hour*3600000L)/60000L; result=day+"天"+hour+"小时"+minute+"分"; } return result; } public static String checkTime(long timeInMillions){ String time=""; Calendar calendarBegin=Calendar.getInstance(Locale.CHINESE); calendarBegin.setTimeInMillis(timeInMillions); Calendar calendarNow=Calendar.getInstance(Locale.CHINESE); long nowTimeInMillions=System.currentTimeMillis(); calendarNow.setTimeInMillis(nowTimeInMillions); long disTime=timeInMillions-nowTimeInMillions; int beginDay= calendarBegin.get(Calendar.DAY_OF_WEEK); int realDay= calendarNow.get(Calendar.DAY_OF_WEEK); int realWeek= calendarNow.get(Calendar.WEEK_OF_YEAR); int beginWeek= calendarBegin.get(Calendar.WEEK_OF_YEAR); if (beginDay==realDay&&disTime<=1000L*60L*60L*24L*7L){ time="今天"+setStartTime(timeInMillions); }else if (beginWeek==realWeek){ time="本周"+setNumberToChinese(beginDay)+setStartTime(timeInMillions); }else { SimpleDateFormat sdf=new SimpleDateFormat("MM-dd HH:ss"); time=sdf.format(new Date(timeInMillions)); } return time; } private static String setStartTime(long timeInMillions){ Date date=new Date(); date.setTime(timeInMillions); SimpleDateFormat sdf=new SimpleDateFormat("HH:mm"); String time=sdf.format(date); String hour=time.substring(0,2); if (Integer.valueOf(hour)<10){ time=time.substring(1); return time; } return time; } private static String setNumberToChinese(int beginDay) { String dayInCN=""; switch (beginDay){ case 1:dayInCN="日";break; case 2:dayInCN="一";break; case 3:dayInCN="二";break; case 4:dayInCN="三";break; case 5:dayInCN="四";break; case 6:dayInCN="五";break; case 7:dayInCN="六";break; } return dayInCN; } public static String setLoveNum(int number){ String favNumber=""; if (number<1000){ favNumber=number+""; }else if (number<10000){ favNumber=number/1000+"K"; }else{ favNumber=number/10000+"万"; } return favNumber; } } <file_sep>/app/src/main/java/com/gymnast/view/widget/photoview/gestures/GestureDetector.java package com.gymnast.view.widget.photoview.gestures; import android.view.MotionEvent; public interface GestureDetector { boolean onTouchEvent(MotionEvent ev); boolean isScaling(); void setOnGestureListener(OnGestureListener listener); } <file_sep>/app/src/main/java/com/gymnast/view/home/adapter/SearchActiveAdapter.java package com.gymnast.view.home.adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.gymnast.R; import com.gymnast.data.hotinfo.NewActivityItemDevas; import com.gymnast.utils.NumberUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.StringUtil; import com.gymnast.view.home.view.HomeSearchResultAcitivity; import com.gymnast.view.hotinfoactivity.activity.ActivityDetailsActivity; import com.gymnast.view.personal.activity.PersonalOtherHomeActivity; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by zzqybyb19860112 on 2016/9/6. */ public class SearchActiveAdapter extends RecyclerView.Adapter implements Filterable { private final List<NewActivityItemDevas> mValues ; List<NewActivityItemDevas> mCopyInviteMessages; List<NewActivityItemDevas> inviteMessages; Context context; private static final int VIEW_TYPE = -1; public SearchActiveAdapter( Context context, List<NewActivityItemDevas> mValues) { this.context=context; if(mValues.size()==0){ this.mValues=new ArrayList<>(); }else { this.mValues=mValues; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_active, null); LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); itemview.setLayoutParams(lp1); if(VIEW_TYPE==viewType){ LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); View view=LayoutInflater.from(context).inflate(R.layout.empty_view, parent, false); view.setLayoutParams(lp2); return new empty(view); } return new SearchActiveHolder(itemview); } public static String setTime(long time){ SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日"); String timeTmp=sdf.format(new Date(time)); String month=timeTmp.substring(0, 2); String day=timeTmp.substring(3,5); month= NumberUtil.handleNumber(month); day= NumberUtil.handleNumber(day); return month+"月"+day+"日"; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof SearchActiveHolder) { SearchActiveHolder viewHolder = (SearchActiveHolder) holder; final NewActivityItemDevas data=mValues.get(position); viewHolder.ivActiveItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mValues.size()!=0) { Intent intent = new Intent(context, ActivityDetailsActivity.class); intent.putExtra("ActiveID", data.getActiveId()); intent.putExtra("UserId", data.getUserID()); context.startActivity(intent); } } }); PicassoUtil.handlePic(context, PicUtil.getImageUrlDetail(context, StringUtil.isNullAvatar(data.getImgUrls()), 320, 320), viewHolder.ivActiveItem, 320, 320); viewHolder.tvActiveTitle.setText(data.getTitle()); viewHolder.tvActiveStart.setText(setTime(data.getStartTime())+"开始"); viewHolder.tvActiveFrom.setText("来自:"+data.getNickname()); viewHolder.tvActiveFrom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mValues.size()!=0) { Intent intent = new Intent(context, PersonalOtherHomeActivity.class); intent.putExtra("UserID", data.getUserID()); context.startActivity(intent); } } }); viewHolder.tvActiveSee.setText(data.getPageViews()+"次浏览"); viewHolder.tvActiveZan.setText(data.getZanCount()+""); viewHolder.tvActiveMSG.setText(data.getMsgCount() + ""); } } @Override public int getItemCount() { return mValues.size() > 0 ? mValues.size() : 1; } @Override public int getItemViewType(int position) { if (mValues.size() <= 0) { return VIEW_TYPE; } return 0; } public void setFriends(List<NewActivityItemDevas> data) { //复制数据 mCopyInviteMessages = new ArrayList<>(); this.mCopyInviteMessages.addAll(data); this.inviteMessages = data; this.notifyDataSetChanged(); } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { //初始化过滤结果对象 FilterResults results = new FilterResults(); //假如搜索为空的时候,将复制的数据添加到原始数据,用于继续过滤操作 if (results.values == null) { mValues.clear(); mValues.addAll(mCopyInviteMessages); } //关键字为空的时候,搜索结果为复制的结果 if (constraint == null || constraint.length() == 0) { results.values = mCopyInviteMessages; results.count = mCopyInviteMessages.size(); } else { String searchText= HomeSearchResultAcitivity.getSearchText(); String prefixString; if (searchText.equals("")){ prefixString=searchText.toString(); }else { prefixString= constraint.toString(); } final int count = inviteMessages.size(); //用于存放暂时的过滤结果 final ArrayList<NewActivityItemDevas> newValues = new ArrayList<NewActivityItemDevas>(); for (int i = 0; i < count; i++) { final NewActivityItemDevas value = inviteMessages.get(i); String username = value.getTitle(); // First match against the whole ,non-splitted value,假如含有关键字的时候,添加 if (username.contains(prefixString)) { newValues.add(value); } else { //过来空字符开头 final String[] words = username.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].contains(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results;//过滤结果 } @Override protected void publishResults(CharSequence constraint, FilterResults results) { SearchActiveAdapter.this.inviteMessages.clear();//清除原始数据 SearchActiveAdapter.this.inviteMessages.addAll((List<NewActivityItemDevas>) results.values);//将过滤结果添加到这个对象 if (results.count > 0) { SearchActiveAdapter.this.notifyDataSetChanged();//有关键字的时候刷新数据 } else { //关键字不为零但是过滤结果为空刷新数据 if (constraint.length() != 0) { SearchActiveAdapter.this.notifyDataSetChanged(); return; } //加载复制的数据,即为最初的数据 SearchActiveAdapter.this.setFriends(mCopyInviteMessages); } } }; } class empty extends RecyclerView.ViewHolder{ public empty(View itemView) { super(itemView); } } class SearchActiveHolder extends RecyclerView.ViewHolder{ @BindView(R.id.llActiveItem) LinearLayout llActiveItem; @BindView(R.id.ivActiveItem) ImageView ivActiveItem; @BindView(R.id.tvActiveTitle) TextView tvActiveTitle; @BindView(R.id.tvActiveStart) TextView tvActiveStart; @BindView(R.id.tvActiveFrom) TextView tvActiveFrom; @BindView(R.id.tvActiveSee) TextView tvActiveSee; @BindView(R.id.tvActiveZan) TextView tvActiveZan; @BindView(R.id.tvActiveMSG) TextView tvActiveMSG; public SearchActiveHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } <file_sep>/app/src/main/java/com/gymnast/view/home/fragment/MinePackFragment.java package com.gymnast.view.home.fragment; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.gymnast.R; import com.gymnast.view.pack.adapter.MyFragmentPagerAdapter; import com.gymnast.view.pack.view.MyConcernFragment; import com.gymnast.view.pack.view.ChoicenessCircleFragment; import com.gymnast.view.pack.view.StarFragment; import java.util.ArrayList; import java.util.List; public class MinePackFragment extends Fragment { private List<String> mTitle=new ArrayList<String>(); private List<Fragment> mFragment = new ArrayList<Fragment>(); private TabLayout tab; private ViewPager vp; private View view; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ view = inflater.inflate(R.layout.fragment_mine_pack, null); setview(); initView(); MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getChildFragmentManager(), mTitle, mFragment); vp.setAdapter(adapter); //tablayout和viewpager关联 tab.setupWithViewPager(vp); //为tablayout设置适配器 tab.setTabGravity(TabLayout.GRAVITY_FILL); tab.setTabMode(TabLayout.MODE_FIXED); vp.setOffscreenPageLimit(2); return view; } private void setview() { tab =(TabLayout) view.findViewById(R.id.pack_tab); vp =(ViewPager) view.findViewById(R.id.pack_vp); } private void initView() { mTitle.add("好友动态"); mTitle.add("大咖动态"); mTitle.add("精选圈子"); mFragment.add(new MyConcernFragment()); mFragment.add(new StarFragment()); mFragment.add(new ChoicenessCircleFragment()); } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/OrdersActivity.java package com.gymnast.view.personal.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.pack.view.MyConcernFragment; import com.gymnast.view.pack.view.ChoicenessCircleFragment; import com.gymnast.view.pack.view.StarFragment; import com.gymnast.view.personal.adapter.PersonalAdapter; import com.gymnast.view.personal.fragment.AllFragment; import java.util.ArrayList; import java.util.List; /** * Created by yf928 on 2016/7/20. */ public class OrdersActivity extends ImmersiveActivity { private List<Fragment> mFragment=new ArrayList<Fragment>(); private List<String> mTitle = new ArrayList<String>(); private TabLayout tab; private ViewPager vp; private ImageView back; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_orders); initview(); PersonalAdapter adapterd = new PersonalAdapter(getSupportFragmentManager(),mFragment,mTitle); vp.setAdapter(adapterd); //tablayout和viewpager关联 tab.setupWithViewPager(vp); //为tablayout设置适配器 tab.setTabsFromPagerAdapter(adapterd); tab.setTabGravity(TabLayout.GRAVITY_FILL); tab.setTabMode(TabLayout.MODE_FIXED); } private void initview() { tab=(TabLayout) findViewById(R.id.personal_orders_tab); vp=(ViewPager)findViewById(R.id.personal_orders_vp); back=(ImageView)findViewById(R.id.back); mTitle.add("全部"); mTitle.add("待付款"); mTitle.add("待发货"); mTitle.add("待收货"); mTitle.add("待评价"); mFragment.add(new AllFragment()); mFragment.add(new MyConcernFragment()); mFragment.add(new StarFragment()); mFragment.add(new ChoicenessCircleFragment()); mFragment.add(new ChoicenessCircleFragment()); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } <file_sep>/app/src/main/java/com/gymnast/view/personal/activity/PersonSettingActivity.java package com.gymnast.view.personal.activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.App; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.CustomUtil; import com.gymnast.utils.DataCleanManagerUtil; import com.gymnast.utils.GetUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.home.HomeActivity; import com.hyphenate.EMCallBack; import com.hyphenate.chat.EMClient; import org.json.JSONObject; import java.util.HashMap; /** * Created by yf928 on 2016/7/25. */ public class PersonSettingActivity extends ImmersiveActivity { private RelativeLayout data,address,feedback,about,clean,authentication; private TextView cache,code; private AlertDialog builder; private ImageView back; private TextView personal_exit; private SharedPreferences share; private String token; private Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState ) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_setting); setView(); setListeners(); } private void setView() { data=(RelativeLayout)findViewById(R.id.data); address=(RelativeLayout)findViewById(R.id.address); feedback=(RelativeLayout)findViewById(R.id.feedback); about=(RelativeLayout)findViewById(R.id.about); clean=(RelativeLayout)findViewById(R.id.clean); authentication=(RelativeLayout)findViewById(R.id.authentication); cache=(TextView)findViewById(R.id.cache); code=(TextView)findViewById(R.id.code); personal_exit=(TextView)findViewById(R.id.personal_exit); back= (ImageView)findViewById(R.id.personal_back); share= getSharedPreferences("UserInfo",Context.MODE_PRIVATE); token = share.getString("Token",""); } private void setListeners() { data.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (App.isStateOK){ Intent i = new Intent(PersonSettingActivity.this, PersonalEditDataActivity.class); startActivity(i); }else { Toast.makeText(PersonSettingActivity.this,"您还没有登陆呢,亲!",Toast.LENGTH_SHORT).show(); } } }); address.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(PersonSettingActivity.this, PersonalAddressActivity.class); startActivity(i); } }); feedback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(PersonSettingActivity.this, PersonalFeedbackActivity.class); startActivity(i); } }); about.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(PersonSettingActivity.this, PersonalAboutActivity.class); startActivity(i); } }); authentication.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(PersonSettingActivity.this, PersonalAuthenticationActivity.class); startActivity(i); } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); code.setText(CustomUtil.getVersionName(this)); clean.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { builder = new AlertDialog.Builder(PersonSettingActivity.this).create(); builder.setView(getLayoutInflater().inflate(R.layout.activity_personal_dialog, null)); builder.show(); //去掉dialog四边的黑角 builder.getWindow().setBackgroundDrawable(new BitmapDrawable()); builder.getWindow().findViewById(R.id.dialog_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { builder.dismiss(); } }); builder.getWindow().findViewById(R.id.dialog_confirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DataCleanManagerUtil.cleanInternalCache(getApplicationContext()); Toast.makeText(getApplicationContext(), "清理完成", Toast.LENGTH_LONG).show(); builder.dismiss(); } }); } }); personal_exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (App.isStateOK){ showDialogs(); }else { Toast.makeText(PersonSettingActivity.this,"您还没有登陆,不能注销账号!",Toast.LENGTH_SHORT).show(); } } }); } private void showDialogs() { View view=getLayoutInflater().inflate(R.layout.log_out_dialog, null); dialog = new Dialog(this, R.style.transparentFrameWindowStyle); Button cancel=(Button)view.findViewById(R.id.btnCancle); Button sure=(Button)view.findViewById(R.id.btnSure); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); sure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { EMClient.getInstance().logout(true, new EMCallBack() { @Override public void onSuccess() { Log.i("tag","环信注销成功"); } @Override public void onProgress(int progress, String status) { Log.i("tag","环信注销中。。。"); } @Override public void onError(int code, String message) { Log.i("tag","环信注销失败"); } }); String uri= API.BASE_URL+"/v1/account/signout"; HashMap<String, String> params=new HashMap<>(); params.put("token",token); String result= GetUtil.sendGetMessage(uri,params); JSONObject obj; try{ obj=new JSONObject(result); if(obj.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PersonSettingActivity.this,"注销成功",Toast.LENGTH_SHORT).show(); Log.e("注销token=",token); share.edit().clear().commit(); Intent i=new Intent(PersonSettingActivity.this, HomeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); App.isStateOK=false; finish(); } }); } }catch (Exception e){ } } }).start(); } }); dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.log_out_dialog); // WindowManager.LayoutParams wl = window.getAttributes(); //设置dialog显示在屏幕的位置 //wl.x = 0; //wl.y = getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 //wl.width = ViewGroup.LayoutParams.MATCH_PARENT; //wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 //dialog.onWindowAttributesChanged(wl); // 设置点击外围解散 dialog.setCanceledOnTouchOutside(true); dialog.show(); } } <file_sep>/app/src/main/java/com/gymnast/data/personal/PostsData.java package com.gymnast.data.personal; import java.io.Serializable; /** * Created by Cymbi on 2016/9/1. */ public class PostsData implements Serializable { private String avatar; private String nickname; private String title; private String content; private String imgUrl; private int userid; private int id; //来自哪个圈子 private String circleTitle; //圈子id private int circleId; //创建者id private int createId; //帖子状态,0为正常可以访问,-1为删除,-2为屏蔽如有业务需求,可以再加入 private int state; private int zanCount; //浏览量 private int meetCount; private int msgCount; //浏览量 private int pageviews; public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public int getPageviews() { return pageviews; } public void setPageviews(int pageviews) { this.pageviews = pageviews; } public int getMsgCount() { return msgCount; } public void setMsgCount(int msgCount) { this.msgCount = msgCount; } public long createTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getCircleTitle() { return circleTitle; } public void setCircleTitle(String circleTitle) { this.circleTitle = circleTitle; } public int getCircleId() { return circleId; } public void setCircleId(int circleId) { this.circleId = circleId; } public int getCreateId() { return createId; } public void setCreateId(int createId) { this.createId = createId; } public int getState() { return state; } public void setState(int state) { this.state = state; } public int getZanCount() { return zanCount; } public void setZanCount(int zanCount) { this.zanCount = zanCount; } public int getMeetCount() { return meetCount; } public void setMeetCount(int meetCount) { this.meetCount = meetCount; } } <file_sep>/app/src/main/java/com/gymnast/view/home/fragment/WTAFragment.java package com.gymnast.view.home.fragment; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.CacheUtils; import com.gymnast.utils.DialogUtil; import com.gymnast.utils.JSONParseUtil; import com.gymnast.utils.LiveUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.view.home.adapter.StandSquareLiveRecyclerViewAdapter; import com.gymnast.view.live.entity.LiveItem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class WTAFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{ SwipeRefreshLayout reflesh; RecyclerView liveList; static List<LiveItem> liveItems = new ArrayList<>(); static Bitmap mainPhoto; private WTAFragment instance=null; public StandSquareLiveRecyclerViewAdapter standLiveAdapter; static LiveItem liveItem; public static final int UPDATE_STATE_OK=1; public static final int MAINUSER_IN_OK=2; public static final int MAINUSER_IN_ERROR=3; public static final int OTHERUSER_IN_OK=4; public static final int OTHERUSER_IN_ERROR=5; public static final int HANDLE_DATA_OK=6; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case HANDLE_DATA_OK: if (liveItems.size()>0){ GridLayoutManager dynamicLayout = new GridLayoutManager(getActivity(), 2); liveList.setLayoutManager(dynamicLayout); }else { GridLayoutManager dynamicLayout = new GridLayoutManager(getActivity(), 1); liveList.setLayoutManager(dynamicLayout); } standLiveAdapter = new StandSquareLiveRecyclerViewAdapter(getActivity(), liveItems); liveList.setAdapter(standLiveAdapter); reflesh.setRefreshing(false); standLiveAdapter.setOnItemClickListener(new StandSquareLiveRecyclerViewAdapter.OnItemClickListener() { @Override public void OnBigPhotoClick(View view, LiveItem liveItem) { WTAFragment.liveItem = liveItem; LiveUtil.doIntoLive(getActivity(), handler, liveItem); } }); break; case UPDATE_STATE_OK: Toast.makeText(getActivity(), "您开启了直播", Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case MAINUSER_IN_OK: Toast.makeText(getActivity(),"您开启了直播",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case MAINUSER_IN_ERROR: DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; case OTHERUSER_IN_OK: Toast.makeText(getActivity(),"您已进入直播室",Toast.LENGTH_SHORT).show(); LiveUtil.doNext(getActivity(), liveItem); break; case OTHERUSER_IN_ERROR: DialogUtil.goBackToLogin(getActivity(), "是否重新登陆?", "账号在其他地方登陆,您被迫下线!!!"); break; } } }; public WTAFragment() { } public WTAFragment newInstance(String param1, String param2,Context context) { mainPhoto= BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_test_3); mainPhoto= PicUtil.compress(mainPhoto, 100, 100); if(instance==null){ instance=new WTAFragment(); } return instance; } private void initData(final Context context) { ArrayList<String> cacheData= (ArrayList<String>) CacheUtils.readJson(context, WTAFragment.this.getClass().getName() + ".json"); if (cacheData==null||cacheData.size()==0){ new Thread(){ @Override public void run() { HashMap<String, String> params = new HashMap<>(); params.put("pageNo", 1 + ""); params.put("pageSize", 6 + ""); params.put("lab", "5"); String uri = API.BASE_URL + "/v1/live/list/lab"; String result = PostUtil.sendPostMessage(uri, params); JSONParseUtil.parseNetDataStand(context, result, WTAFragment.this.getClass().getName() + ".json", liveItems, handler, HANDLE_DATA_OK); } }.start(); }else { JSONParseUtil.parseLocalDataStand(context,WTAFragment.this.getClass().getName()+".json", liveItems, handler, HANDLE_DATA_OK); } } View rootView=null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { if (rootView==null){ rootView = inflater.inflate(R.layout.fragment_stand_square, container, false); liveList = (RecyclerView) rootView.findViewById(R.id.stand_square_live_list); reflesh = (SwipeRefreshLayout) rootView.findViewById(R.id.srlReflesh); RefreshUtil.refresh(reflesh, getActivity()); } return rootView; } @Override public void onDestroyView() { super.onDestroyView(); if(rootView!=null&&rootView.getParent()!=null){ ((ViewGroup)rootView.getParent()).removeView(rootView); } } @Override public void onActivityCreated( Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState==null) { initData(getActivity()); } reflesh.setOnRefreshListener(this); } @Override public void onRefresh() { initData(getActivity()); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 reflesh.setRefreshing(false); } }, 1000); } } <file_sep>/app/src/main/java/com/gymnast/data/Service.java package com.gymnast.data; /** * Created by fldyown on 16/7/1. */ public interface Service { } <file_sep>/app/src/main/java/com/gymnast/data/user/UserIconVo.java package com.gymnast.data.user; import java.io.Serializable; /** * Created by zzqybyb19860112 on 2016/9/26. */ public class UserIconVo implements Serializable{ public String nickname; public int id; public int auth; public String avatar; public String authInfo; } <file_sep>/app/src/main/java/com/gymnast/utils/LogUtil.java package com.gymnast.utils; import android.util.Log; import com.gymnast.App; /** * Created by zzqybyb19860112 on 2016/8/25. */ public class LogUtil { public static void i(String tag,String content){ if (App.debug){ Log.i(tag,content); }else { } } } <file_sep>/app/src/main/java/com/gymnast/data/hotinfo/MoreLiveEntity.java package com.gymnast.data.hotinfo; import android.graphics.Bitmap; import java.io.Serializable; /** * Created by 永不言败 on 2016/8/9. */ public class MoreLiveEntity implements Serializable { Bitmap mainPhoto,bigPicture; String liveName,mainName; int totalNumber; public MoreLiveEntity() { } public Bitmap getMainPhoto() { return mainPhoto; } public void setMainPhoto(Bitmap mainPhoto) { this.mainPhoto = mainPhoto; } public Bitmap getBigPicture() { return bigPicture; } public void setBigPicture(Bitmap bigPicture) { this.bigPicture = bigPicture; } public String getLiveName() { return liveName; } public void setLiveName(String liveName) { this.liveName = liveName; } public String getMainName() { return mainName; } public void setMainName(String mainName) { this.mainName = mainName; } public int getTotalNumber() { return totalNumber; } public void setTotalNumber(int totalNumber) { this.totalNumber = totalNumber; } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/activity/PromulgateActivityActivity.java package com.gymnast.view.hotinfoactivity.activity; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.Html; import android.text.TextWatcher; import android.text.format.DateFormat; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.DialogUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.StorePhotosUtil; import com.gymnast.utils.UploadUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.hotinfoactivity.adapter.AddSelectAdapter; import com.gymnast.view.picker.SlideDateTimeListener; import com.gymnast.view.picker.SlideDateTimePicker; import com.gymnast.view.recyclerview.RecyclerAdapter; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; /** * Created by yf928 on 2016/8/8. */ public class PromulgateActivityActivity extends ImmersiveActivity implements View.OnClickListener, RecyclerAdapter.OnItemClickListener { private ArrayList<String> list=new ArrayList<String>(); private RelativeLayout rlAddvancedSetting,rlRange,rlSite,rlApply,rlMoney,rlNumber,rlPhone; private LinearLayout llAdvancedDown,llDown,llTogglebuttonOpen; private ScrollView scrollView; private boolean isOpen;// 为false显示,为true不显示 private EditText etActivityDescribe,etActivityName; private TextView tvActivityAddress,tvTest,tvPromulgateStartTime,tvPromulgateOverTime,camera,gallery,cancel,tvAddImage,tvPublish,tvSecletEndTime,tvSelectNumber,tvSelectPhone,tvSelectRange,tvPriceNumber; private ImageView ivArrows,ivHead,ivHeadBackground,ivAdd,ivPromulgateBack,add; private ToggleButton togglebutton,togglebutton1; private RadioButton buttonUp,buttonDown; private Dialog dialog; private SimpleDateFormat mFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private TimerTask task; private Date dateStartTime,dateOverTime,dateApplyTime; private SharedPreferences share; private RadioGroup myRadioGroup; private Integer type; private double prices,price; private AddSelectAdapter mAddSelectAdapter; private RecyclerView rvPhotos; private int examine,visible,mSelectNumber; private CheckBox cbPhone,cbId,cbName,cbSex,cbAge,cbAddress; private String address,phone,title,num,imageUrl,nowTime,token,id,fileName = "",picAddress=null; private long startTime,lastTime,endTime; private static final int KEY = 1; private final int PIC_FROM_CAMERA = 2; public static final int HANDLE_TIME_CHANGE=3; private Bitmap bitmap; private Handler handler = new Handler() { @Override public void handleMessage (Message msg) { super.handleMessage(msg); switch (msg.what) { case KEY : long sysTime = System.currentTimeMillis(); CharSequence sysTimeStr = DateFormat.format("yyyy-MM-dd hh:mm", sysTime); tvPromulgateStartTime.setText(sysTimeStr); break; case HANDLE_TIME_CHANGE: String time= (String) msg.obj; tvPromulgateStartTime.setText(time); tvPromulgateStartTime.invalidate(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_promulgate); getWindow().setSoftInputMode(WindowManager.LayoutParams. SOFT_INPUT_ADJUST_PAN); share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",""); id = share.getString("UserId",""); setview(); initview(); /** * 刚进activity的时候更新start_time时间 */ Timer timer=new Timer(); task=new TimerTask() { @Override public void run() { nowTime=mFormatter.format(new Date()); Message msg=new Message(); msg.what=HANDLE_TIME_CHANGE; msg.obj=nowTime; handler.sendMessage(msg); } }; timer.schedule(task,1,1000); } private void setview() { ivPromulgateBack=(ImageView)findViewById(R.id.ivPromulgateBack); rlAddvancedSetting=(RelativeLayout) findViewById(R.id.rlAddvancedSetting); llAdvancedDown=(LinearLayout) findViewById(R.id.llAdvancedDown); llTogglebuttonOpen=(LinearLayout) findViewById(R.id.llTogglebuttonOpen); llDown=(LinearLayout) findViewById(R.id.llDown); scrollView=(ScrollView) findViewById(R.id.scrollView); etActivityDescribe =(EditText)findViewById(R.id.etActivityDescribe); etActivityName =(EditText)findViewById(R.id.etActivityName); tvTest =(TextView)findViewById(R.id.tvTest); rlNumber =(RelativeLayout)findViewById(R.id.rlNumber); rlPhone =(RelativeLayout)findViewById(R.id.rlPhone); rlRange =(RelativeLayout)findViewById(R.id.rlRange); rlApply =(RelativeLayout)findViewById(R.id.rlApply); rlMoney =(RelativeLayout)findViewById(R.id.rlMoney); tvActivityAddress = (TextView) findViewById(R.id.tvActivityAddress); tvPromulgateStartTime =(TextView)findViewById(R.id.tvPromulgateStartTime); tvSelectNumber =(TextView)findViewById(R.id.tvSelectNumber); tvSelectPhone =(TextView)findViewById(R.id.tvSelectPhone); tvPromulgateOverTime =(TextView)findViewById(R.id.tvPromulgateOverTime); tvPublish =(TextView)findViewById(R.id.tvPublish); rlSite =(RelativeLayout)findViewById(R.id.rlSite); tvAddImage =(TextView)findViewById(R.id.tvAddImage); tvSelectRange =(TextView)findViewById(R.id.tvSelectRange); tvSecletEndTime =(TextView)findViewById(R.id.tvSecletEndTime); tvPriceNumber =(TextView)findViewById(R.id.tvPriceNumber); ivArrows=(ImageView)findViewById(R.id.ivArrows); ivHead=(ImageView)findViewById(R.id.ivHead); ivHeadBackground=(ImageView)findViewById(R.id.ivHeadBackground); ivAdd=(ImageView)findViewById(R.id.ivAdd); add=(ImageView)findViewById(R.id.add); etActivityDescribe.setSelection(etActivityDescribe.getText().length()); ivArrows.setBackgroundResource(R.mipmap.icon_more_lower); togglebutton = (ToggleButton) findViewById(R.id.togglebutton); togglebutton1 = (ToggleButton) findViewById(R.id.togglebutton1); buttonUp = (RadioButton) findViewById(R.id.buttonUp); buttonDown = (RadioButton) findViewById(R.id.buttonDown); myRadioGroup = (RadioGroup) findViewById(R.id.myRadioGroup); rvPhotos = (RecyclerView) findViewById(R.id.rvPhotos); String over = mFormatter.format(System.currentTimeMillis()+1000L*60L*60L*24L); tvPromulgateOverTime.setText(over); buttonUp.setChecked(true); togglebutton.setOnClickListener(this); togglebutton1.setOnClickListener(this); rlAddvancedSetting.setOnClickListener(this); rlNumber.setOnClickListener(this); rlPhone.setOnClickListener(this); rlRange.setOnClickListener(this); rlSite.setOnClickListener(this); ivPromulgateBack.setOnClickListener(this); ivHead.setOnClickListener(this); ivHeadBackground.setOnClickListener(this); tvPromulgateOverTime.setOnClickListener(this); tvPromulgateStartTime.setOnClickListener(this); rlApply.setOnClickListener(this); tvPublish.setOnClickListener(this); rlMoney.setOnClickListener(this); ivAdd.setOnClickListener(this); } private void setdata() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String start = tvPromulgateStartTime.getText().toString(); String over = tvPromulgateOverTime.getText().toString(); String apply = tvSecletEndTime.getText().toString().equals("请点击选择结束时间") ? over : tvSecletEndTime.getText().toString(); String p = tvPriceNumber.getText().toString().equals("免费") ? "0元" : tvPriceNumber.getText().toString(); String p1 = p.substring(0, p.length() - 1); price = Double.parseDouble(p1); address = tvActivityAddress.getText().toString(); title = etActivityName.getText().toString(); // final String desc= et_activity_describe.getText().toString(); phone = tvSelectPhone.getText().toString(); try { dateStartTime = format.parse(start); dateOverTime = format.parse(over); dateApplyTime = format.parse(apply); } catch (ParseException e) { e.printStackTrace(); } //时间戳 startTime = dateStartTime.getTime(); endTime = dateOverTime.getTime(); lastTime = dateApplyTime.getTime(); if (startTime > endTime) { Toast.makeText(PromulgateActivityActivity.this, "开始时间不能大于结束时间!", Toast.LENGTH_SHORT).show(); } else if (lastTime > endTime) { Toast.makeText(PromulgateActivityActivity.this, "报名时间不能大于结束时间!", Toast.LENGTH_SHORT).show(); } else if (lastTime < startTime) { Toast.makeText(PromulgateActivityActivity.this, "报名时间不能小于开始时间!", Toast.LENGTH_SHORT).show(); } else { if (!isAll()) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PromulgateActivityActivity.this, "信息填写不完全,请检查", Toast.LENGTH_SHORT).show(); } }); } else { new Thread(new Runnable() { @Override public void run() { try { String uri2 = API.BASE_URL + "/v1/activity/release"; HashMap<String, String> params = new HashMap<>(); params.put("token", token); params.put("createId", id); params.put("title", title); // params.put("desc", Html.toHtml(etActivityDescribe.getText()));// params.put("desc", etActivityDescribe.getText().toString()); params.put("examine", examine + ""); params.put("image", imageUrl);// params.put("startTime", startTime + "");// params.put("endTime", endTime + "");// // params.put("groupId", ""); if (lastTime != 0) { params.put("lastTime", lastTime + ""); } else { } if (togglebutton.isChecked()) { String request = getRequestParams(); params.put("memberTemplate", request); } else { } params.put("price", prices + ""); params.put("address", address); if (tvSelectNumber.getText() == "无限制") { params.put("maxPeople", ""); } else { params.put("maxPeople", num); } params.put("maxPeople", mSelectNumber + ""); params.put("visible", visible + ""); params.put("phone", phone); if(type==0){ params.put("type", 0+""); }else { params.put("type", 1+""); } String result1 = PostUtil.sendPostMessage(uri2, params); JSONObject json = new JSONObject(result1); if (json.getInt("state") == 200) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PromulgateActivityActivity.this, "活动发布成功", Toast.LENGTH_SHORT).show(); finish(); } }); } else if (json.getInt("state") == 500) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PromulgateActivityActivity.this, "state==500", Toast.LENGTH_SHORT).show(); finish(); } }); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } } } private String getRequestParams() { StringBuffer sb=new StringBuffer(); sb.append(cbPhone.getText()+","); sb.append(cbName.getText()+","); if (cbId.isChecked()){ sb.append(cbId.getText()+","); }else { sb.append(""); } if (cbSex.isChecked()){ sb.append(cbSex.getText()+","); }else { sb.append(""); } if (cbAge.isChecked()){ sb.append(cbAge.getText()+","); }else { sb.append(""); } if (cbAddress.isChecked()){ sb.append(cbAddress.getText()); }else { sb.append(""); } return sb.toString(); } private boolean isAll() { if(imageUrl==null|title==null|etActivityDescribe.getText()==null|phone==null|startTime==0|endTime==0){ return false; } return true; } private void initview() { /** * 显示高级选项 */ etActivityDescribe.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String number = etActivityDescribe.getText().toString(); tvTest.setText(number.length()+"/"+2500); } @Override public void afterTextChanged(Editable s) { } }); if(!myRadioGroup.isClickable()){ type=0; }else { } myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(buttonUp.getId()==checkedId){ type= 0; }else if(buttonDown.getId()==checkedId){ type= 1; } type=0; } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.ivPromulgateBack: finish(); break; case R.id.rlAddvancedSetting: llAdvancedDown.setVisibility(View.VISIBLE); Handler handler = new Handler(); if(isOpen){ llAdvancedDown.setVisibility(View.GONE); handler.post(new Runnable() { @Override public void run() { scrollView.fullScroll(ScrollView.FOCUS_DOWN); } }); ivArrows.setBackgroundResource(R.mipmap.icon_more_lower); }else{ ivArrows.setBackgroundResource(R.mipmap.icon_more_upper); handler.post(new Runnable() { @Override public void run() { scrollView.fullScroll(ScrollView.FOCUS_DOWN); } }); } isOpen=!isOpen; break; case R.id.togglebutton: if(togglebutton.isChecked()){ llTogglebuttonOpen.setVisibility(View.VISIBLE); cbName= (CheckBox) findViewById(R.id.cbName); cbPhone= (CheckBox) findViewById(R.id.cbPhone); cbId= (CheckBox) findViewById(R.id.cbId); cbSex= (CheckBox) findViewById(R.id.cbSex); cbAddress= (CheckBox) findViewById(R.id.cbAddress); cbAge= (CheckBox) findViewById(R.id.cbAge); }else { llTogglebuttonOpen.setVisibility(View.GONE); } break; case R.id.togglebutton1: if(togglebutton.isChecked()){ examine=1; }else { examine=0; } break; case R.id.rlNumber: Intent a =new Intent(this,SettingNumberActivity.class); startActivityForResult(a,101); break; case R.id.rlPhone: Intent b =new Intent(this,SettingPhoneActivity.class); startActivityForResult(b,102); break; case R.id.rlRange: Intent c =new Intent(this,SettingRangeActivity.class); startActivityForResult(c,103); break; case R.id.rlSite: Intent d =new Intent(this,SettingSiteActivity.class); startActivityForResult(d,104); break; case R.id.rlMoney: Intent e =new Intent(this,SettingPriceActivity.class); startActivityForResult(e,105); break; case R.id.ivAdd: Intent f =new Intent(this,AddConditionActivity.class); startActivityForResult(f,106); break; case R.id.ivHead: showDialogs(); break; case R.id.ivHeadBackground: showDialogs(); break; case R.id.tvPromulgateStartTime: //当开始选择时间的时候,就要结束掉更新时间的线程 task.cancel(); new SlideDateTimePicker.Builder(getSupportFragmentManager()) .setListener(listener) .setInitialDate(new Date()) .setIs24HourTime(true) .build() .show(); break; case R.id.tvPromulgateOverTime: new SlideDateTimePicker.Builder(getSupportFragmentManager()) .setListener(listener1) .setInitialDate(new Date()) .setIs24HourTime(true) .build() .show(); break; case R.id.rlApply: new SlideDateTimePicker.Builder(getSupportFragmentManager()) .setListener(listener2) .setInitialDate(new Date()) .setIs24HourTime(true) .build() .show(); break; case R.id.tvPublish: setdata(); break; } } private void showDialogs() { View view = getLayoutInflater().inflate(R.layout.dialog_phone, null); dialog = new Dialog(this,R.style.Dialog_Fullscreen); camera=(TextView)view.findViewById(R.id.camera); gallery=(TextView)view.findViewById(R.id.gallery); cancel=(TextView)view.findViewById(R.id.cancel); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); //从相册获取 gallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, 1000); ivHeadBackground.setVisibility(View.GONE); add.setVisibility(View.GONE); tvAddImage.setVisibility(View.GONE); dialog.dismiss(); } }); //拍照 camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fileName = getPhotopath(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); File out = new File(fileName); Uri uri = Uri.fromFile(out); // 获取拍照后未压缩的原图片,并保存在uri路径中 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent,PIC_FROM_CAMERA); ivHeadBackground.setVisibility(View.GONE); add.setVisibility(View.GONE); tvAddImage.setVisibility(View.GONE); dialog.dismiss(); } }); dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.main_menu_animstyle); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 wl.width = ViewGroup.LayoutParams.MATCH_PARENT; wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 dialog.onWindowAttributesChanged(wl); // 设置点击外围解散 dialog.setCanceledOnTouchOutside(true); dialog.show(); } //开始时间选择器的确定和取消按钮的返回操作 SlideDateTimeListener listener = new SlideDateTimeListener() { @Override public void onDateTimeSet(Date date){ tvPromulgateStartTime.setText(mFormatter.format(date) ); } // Optional cancel listener @Override public void onDateTimeCancel() { Toast.makeText(PromulgateActivityActivity.this, "还未选择时间哟", Toast.LENGTH_SHORT).show(); } }; //结束时间选择器的确定和取消按钮的返回操作 SlideDateTimeListener listener1 = new SlideDateTimeListener() { @Override public void onDateTimeSet(Date date) { tvPromulgateOverTime.setText(mFormatter.format(date) ); } // Optional cancel listener @Override public void onDateTimeCancel(){ Toast.makeText(PromulgateActivityActivity.this, "还未选择时间哟", Toast.LENGTH_SHORT).show(); } }; //报名结束时间选择器的确定和取消按钮的返回操作 SlideDateTimeListener listener2 = new SlideDateTimeListener() { @Override public void onDateTimeSet(Date date) { tvSecletEndTime.setText(mFormatter.format(date) ); } // Optional cancel listener @Override public void onDateTimeCancel(){ Toast.makeText(PromulgateActivityActivity.this, "还未选择时间哟", Toast.LENGTH_SHORT).show(); } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==PIC_FROM_CAMERA&&resultCode == Activity.RESULT_OK) { final Bitmap bitmap = PicUtil.getSmallBitmap(fileName); // 这里是先压缩质量,再调用存储方法 new StorePhotosUtil(bitmap, fileName); if (bitmap!=null) { new Thread(new Runnable() { @Override public void run() { try { String uri= API.BASE_URL+"/v1/upload"; String result=UploadUtil.uploadFile2(uri, fileName); JSONObject object = new JSONObject(result); JSONObject data=object.getJSONObject("data"); String newUrl = URI.create(data.getString("url")).getPath(); imageUrl=newUrl; runOnUiThread(new Runnable() { @Override public void run() { ivHead.setImageBitmap(bitmap); } }); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } } if (requestCode == 1000 && data != null){ // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口 final ContentResolver resolver = getContentResolver(); final Uri originalUri = data.getData(); // 获得图片的uri try { Bitmap bitmap1 = MediaStore.Images.Media.getBitmap(resolver, originalUri); bitmap= PicUtil.compress(bitmap1, 720 , 720); ivHead.setImageBitmap(bitmap); }catch (Exception e){ e.printStackTrace(); } Thread thread1=new Thread(){ @Override public void run() { String path=UploadUtil.getRealFilePath(PromulgateActivityActivity.this,originalUri); imageUrl=UploadUtil.getNetWorkImageAddress(path, PromulgateActivityActivity.this); runOnUiThread(new Runnable() { @Override public void run() { if (imageUrl!=null){ dialog.dismiss(); } } }); } }; thread1.setPriority(8); thread1.start(); } if(requestCode==101){ if(resultCode==11){ num=data.getStringExtra("Number"); if(num.length()!=0){ try{ mSelectNumber = Integer.parseInt(num); tvSelectNumber.setText(mSelectNumber + " 人"); }catch (Exception e){ e.printStackTrace(); } }else { tvSelectNumber.setText("无限制"); } } } if(requestCode==102){ if(resultCode==12){ String s = data.getStringExtra("Phone"); tvSelectPhone.setText(s); } } if(requestCode==103){ if(resultCode==13){ String s = data.getStringExtra("RadioButton"); tvSelectRange.setText(s); visible =data.getIntExtra("RadiobuttonNumber",0); } } if(requestCode==104){ if(resultCode==14){ String s = data.getStringExtra("address"); tvActivityAddress.setText(s); } } if(requestCode==105){ if(resultCode==15) { double s = data.getDoubleExtra("price", 0.0); if(s==0.0){ tvPriceNumber.setText("免费"); prices=0.0; }else { tvPriceNumber.setText(s+"元"); prices=s; }} } if(requestCode==106){ if(resultCode==16){ String s=data.getStringExtra("add"); if (s != null ) { list.add(s); mAddSelectAdapter = new AddSelectAdapter(this, list, R.layout.gridview_select); rvPhotos.setLayoutManager(new GridLayoutManager(this, 7)); rvPhotos.setItemAnimator(new DefaultItemAnimator()); rvPhotos.setAdapter(mAddSelectAdapter); mAddSelectAdapter.setOnItemClickListener(this); mAddSelectAdapter.notifyItemRangeChanged(list.size(), list.size()); mAddSelectAdapter.setOnItemClickListener(this); } } } } /** * 路径 * @return */ private String getPhotopath() { // 照片全路径 String fileName = ""; // 文件夹路径 String pathUrl = Environment.getExternalStorageDirectory()+"/Zyx/"; //照片名 String name = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".png"; File file = new File(pathUrl); if (!file.exists()) { Log.e("TAG", "第一次创建文件夹"); file.mkdirs();// 如果文件夹不存在,则创建文件夹 } fileName=pathUrl+name; return fileName; } @Override public void OnItemClickListener(View view, int position) { } } <file_sep>/app/src/main/java/com/gymnast/view/hotinfoactivity/adapter/CallBackAdapter.java package com.gymnast.view.hotinfoactivity.adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.gymnast.R; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.TimeUtil; import com.gymnast.view.hotinfoactivity.activity.ActivityDetailsActivity; import com.gymnast.view.hotinfoactivity.entity.CallBackDetailEntity; import com.gymnast.view.hotinfoactivity.entity.CallBackEntity; import com.gymnast.view.personal.activity.PersonalDynamicDetailActivity; import com.gymnast.view.personal.activity.PersonalOtherHomeActivity; import com.gymnast.view.personal.activity.PersonalPostsDetailActivity; import com.gymnast.view.personal.listener.WrapContentLinearLayoutManager; import java.util.ArrayList; import java.util.List; /** * Created by zzqybyb19860112 on 2016/9/17. */ public class CallBackAdapter extends RecyclerView.Adapter { Context context; List<CallBackEntity> list; public CallBackAdapter( Context context,List<CallBackEntity> list) { this.context = context; if (list.size()==0){ this.list=new ArrayList<>(); }else { this.list = list; } } public static int callBackToID=0; public static int callBackToPOS=0; public static ArrayList<CallBackDetailEntity> MSGS=new ArrayList<>(); @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); View viewItem =inflater.inflate(R.layout.item_recylerview_callback, null); viewItem.setLayoutParams(lp); return new CallBackViewHolder(viewItem); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int pos) { if (viewHolder instanceof CallBackViewHolder){ final CallBackViewHolder holder=(CallBackViewHolder)viewHolder; final CallBackEntity entity=list.get(pos); if (list.size()!=0){ if (pos==list.size()-1){ holder.tvBottomLine.setVisibility(View.INVISIBLE); } } PicassoUtil.handlePic(context, entity.getCallBackImgUrl(), holder.rivCallBackPic, 720, 1080); holder.tvCallBackNickName.setText(entity.getCallBackNickName()); holder.tvCallBackTime.setText(TimeUtil.getDetailTimeNumber(entity.getCallBackTime())); holder.tvCallBackContent.setText(entity.getCallBackText()); final ArrayList<CallBackDetailEntity> detailMSGs=entity.getEntities(); if (detailMSGs!=null&&detailMSGs.size()>0){ CallBackDetailAdapter adapter=new CallBackDetailAdapter(context,detailMSGs); WrapContentLinearLayoutManager manager=new WrapContentLinearLayoutManager(context,LinearLayoutManager.VERTICAL,false); holder.rvCallBackDetail.setLayoutManager(manager); holder.rvCallBackDetail.setAdapter(adapter); adapter.setOnNameClickListener(new CallBackDetailAdapter.OnNameClickListener() { @Override public void OnNameClick(View view, int position, ArrayList<CallBackDetailEntity> detailMSGs, int toID,String toName) { callBackToID = toID; callBackToPOS = pos; MSGS = detailMSGs; if (context instanceof ActivityDetailsActivity) { ActivityDetailsActivity.type=ActivityDetailsActivity.CALL_BACK_TYPE_TWO; EditText editTextActive = ((EditText) ((ActivityDetailsActivity) context).findViewById(R.id.etCallBack)); if (editTextActive != null) { editTextActive.requestFocus(); editTextActive.setHint("回复" + toName); ActivityDetailsActivity.isComment = false; InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager.isActive()) { ((ActivityDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS); } } } else if (context instanceof PersonalPostsDetailActivity) { PersonalPostsDetailActivity.type=PersonalPostsDetailActivity.CALL_BACK_TYPE_TWO; EditText editTextTieZi = ((EditText) ((PersonalPostsDetailActivity) context).findViewById(R.id.etCallBackTieZi)); TextView tvSendTieZi = ((TextView) ((PersonalPostsDetailActivity) context).findViewById(R.id.tvSendTieZi)); ImageView ivSendTiezi = ((ImageView) ((PersonalPostsDetailActivity) context).findViewById(R.id.ivSendTiezi)); if (editTextTieZi != null) { editTextTieZi.requestFocus(); editTextTieZi.setHint("回复" + toName); PersonalPostsDetailActivity.isComment = false; InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager.isActive()) { ((PersonalPostsDetailActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS); tvSendTieZi.setVisibility(View.VISIBLE); ivSendTiezi.setVisibility(View.GONE); } } }else if (context instanceof PersonalDynamicDetailActivity){ PersonalDynamicDetailActivity.type=PersonalDynamicDetailActivity.CALL_BACK_TYPE_TWO; EditText editTextTieZi = ((EditText) ((PersonalDynamicDetailActivity) context).findViewById(R.id.etCallBackDynamic)); TextView tvSendTieZi = ((TextView) ((PersonalDynamicDetailActivity) context).findViewById(R.id.tvSendDynamic)); ImageView ivSendTiezi = ((ImageView) ((PersonalDynamicDetailActivity) context).findViewById(R.id.ivSendDynamic)); if (editTextTieZi != null) { editTextTieZi.requestFocus(); editTextTieZi.setHint("回复" + toName); PersonalDynamicDetailActivity.isComment = false; InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager.isActive()) { ((PersonalDynamicDetailActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS); tvSendTieZi.setVisibility(View.VISIBLE); ivSendTiezi.setVisibility(View.GONE); } } } } }); holder.rvCallBackDetail.setVisibility(View.VISIBLE); }else { holder.rvCallBackDetail.setVisibility(View.GONE); } holder.rivCallBackPic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(context, PersonalOtherHomeActivity.class); int userID=entity.getCommenterId(); i.putExtra("UserID", userID); context.startActivity(i); } }); if(onItemClickListener!=null){ holder.tvBackCommenter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //注意,这里的position不要用上面参数中的position,会出现位置错乱\ onItemClickListener.OnCallBackClick(holder.tvBackCommenter,pos,detailMSGs); } }); } } } private OnItemClickListener onItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } public interface OnItemClickListener { void OnCallBackClick(View view,int position,ArrayList<CallBackDetailEntity> detailMSGs); } @Override public int getItemCount() { return list.size(); } class CallBackViewHolder extends RecyclerView.ViewHolder{ ImageView rivCallBackPic; TextView tvCallBackNickName; TextView tvCallBackTime; TextView tvCallBackContent; TextView tvBackCommenter; TextView tvBottomLine; RecyclerView rvCallBackDetail; public CallBackViewHolder(View itemView) { super(itemView); rivCallBackPic= (ImageView) itemView.findViewById(R.id.rivCallBackPic); tvCallBackNickName= (TextView) itemView.findViewById(R.id.tvCallBackNickName); tvCallBackTime= (TextView) itemView.findViewById(R.id.tvCallBackTime); tvCallBackContent= (TextView) itemView.findViewById(R.id.tvCallBackContent); rvCallBackDetail= (RecyclerView) itemView.findViewById(R.id.rvCallBackDetail); tvBackCommenter= (TextView) itemView.findViewById(R.id.tvBackCommenter); tvBottomLine= (TextView) itemView.findViewById(R.id.tvBottomLine); } } } <file_sep>/app/src/main/java/com/gymnast/view/picker/BigImageActivity.java package com.gymnast.view.picker; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.gymnast.R; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.dialog.PicSelectDialogUtils; import com.gymnast.view.widget.photoview.HackyViewPager; import com.gymnast.view.widget.photoview.PhotoView; import com.gymnast.view.widget.photoview.PhotoViewAttacher; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.List; /** * 大图片预览 * 用法:传递参数images字符串数组和position * @author summer * @description * @date 2014年5月7日 下午3:38:11 */ public class BigImageActivity extends ImmersiveActivity { private static final String STATE_POSITION = "STATE_POSITION"; HackyViewPager mPager; TextView mTextView; Context mContext; private int pagerPosition; //当前选择位置 private String[] imageUrls; //图片地址数组 ProgressBar mProgressBar;//图片加载进度 private Bitmap defBitmap, failBitmap;//默认图片,失败图片 private List<Bitmap> imageBitmaps; private boolean mIsUrl; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout frameLayout = new FrameLayout(this); mPager = new HackyViewPager(this); mTextView = new TextView(this); mTextView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); mTextView.setPadding(5, 5, 5, 5); mTextView.setTextColor(0xffffffff); frameLayout.addView(mPager); frameLayout.addView(mTextView); setContentView(frameLayout); mContext = this; Bundle bundle = getIntent().getBundleExtra("data"); assert bundle != null; imageUrls = bundle.getStringArray("images"); imageBitmaps = PicSelectDialogUtils.BITMAPS; pagerPosition = bundle.getInt("position", 0); mIsUrl = bundle.getBoolean("isUrl"); //图片加载工具类配置存放位置 defBitmap = failBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); if (savedInstanceState != null) { pagerPosition = savedInstanceState.getInt(STATE_POSITION); } if (mIsUrl) { mPager.setAdapter(new ImagePagerAdapter(imageUrls)); } else if (!mIsUrl && imageBitmaps != null) { mPager.setAdapter(new ImagePagerAdapter(imageBitmaps)); } mPager.setCurrentItem(pagerPosition); mPager.setOnPageChangeListener(mPageChangeListener); updateShowNum(); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(STATE_POSITION, mPager.getCurrentItem()); } //显示页码 private void updateShowNum() { if (mIsUrl) { if (imageUrls.length > 0) { mTextView.setText(String.format("%d/%d", pagerPosition + 1, imageUrls.length)); } } else if (!mIsUrl && imageBitmaps != null) { if (imageBitmaps.size() > 0) { mTextView.setText(String.format("%d/%d", pagerPosition + 1, imageBitmaps.size())); } } } ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageScrollStateChanged(int state) { } @Override public void onPageSelected(int position) { pagerPosition = position; updateShowNum(); } }; //图片适配器 private class ImagePagerAdapter extends PagerAdapter { private String[] images; private List<Bitmap> imageBitmaps; private LayoutInflater inflater; ImagePagerAdapter(String[] images) { this.images = images; inflater = getLayoutInflater(); } public ImagePagerAdapter(List<Bitmap> imageBitmaps) { this.imageBitmaps = imageBitmaps; inflater = getLayoutInflater(); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { if (images != null) return images.length; else if (imageBitmaps != null) return imageBitmaps.size(); else return 0; } @Override public Object instantiateItem(ViewGroup view, int position) { View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false); assert imageLayout != null; PhotoView imageView = (PhotoView) imageLayout.findViewById(R.id.image); /* mProgressBar = (ProgressBar) imageLayout.findViewById(R.id.loading); mProgressBar.setVisibility(View.GONE);*/ if (mIsUrl) { ImageLoader.getInstance().displayImage(images[position], imageView); } else if (!mIsUrl && imageBitmaps != null) { imageView.setImageBitmap(imageBitmaps.get(position)); } //单击退出 imageView.setOnPhotoTapListener(onPhotoTapListener); view.addView(imageLayout, 0); return imageLayout; } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public void restoreState(Parcelable state, ClassLoader loader) { } @Override public Parcelable saveState() { return null; } } //单击事件处理 private PhotoViewAttacher.OnPhotoTapListener onPhotoTapListener = new PhotoViewAttacher.OnPhotoTapListener() { @Override public void onPhotoTap(View view, float x, float y) { finish(); } }; @Override protected void onDestroy() { super.onDestroy(); PicSelectDialogUtils.BITMAPS = null; } }
ce04225203faaeeae507eafec1f8216fa38ac40c
[ "Java", "Gradle" ]
82
Java
928902646/Gymnast
aefab7bdb47a7a81e8ecaa6e3f3650fdb795c7d1
4a7062ee5bc910652f92d6789e0fb431701237c4
refs/heads/master
<file_sep>function getPortrait() { $.ajax({ url: "/photos", type: "GET", datatype: "script" }); } function displayPortrait(url) { $("#portrait").attr("src", url); }<file_sep>source 'http://rubygems.org' gem 'rails', '3.2.4' gem 'jquery-rails' gem 'sqlite3-ruby', :require => 'sqlite3' gem 'paperclip', '~> 2.3' gem 'pry' gem 'json'<file_sep>var allQuestions; var allAnimals; var currentQuestionnaire; var currentIndex; function navigate_to(view) { $("#webcam").css("visibility", "hidden"); $("#container").css("visibility", "hidden"); $("#container").css("z-index", "-9999"); $("#container>div").css("visibility", "hidden"); $("#container>div").css("z-index", "-9999"); if (view == "survey") { showQuestion(); } else if (view == "photobooth") { $("#webcam").css("visibility", "visible"); //$('#photobooth').html(webcam.get_html(600, 600)); } $("#" + view).css("visibility", "visible"); $("#" + view + ">div").css("visibility", "visible"); $("#" + view).css("z-index", "9999"); $("#" + view + ">div").css("z-index", "9999"); } function loadQuestionnaire() { currentQuestionnaire = []; while (currentQuestionnaire.length < 4) { var question = allQuestions[Math.floor(Math.random() * allQuestions.length)]; // This is wildly inefficient but I don't have time to think about it var unique = true; for (var i = 0; i < currentQuestionnaire.length; i++) { if (currentQuestionnaire[i].question == question.question) unique = false; } if (unique) currentQuestionnaire.push(question); } currentIndex = 0; } function nextQuestion() { currentIndex++; if (currentIndex < currentQuestionnaire.length) showQuestion(); else navigate_to('photobooth'); } function showQuestion() { var question = currentQuestionnaire[currentIndex]; $("#question").html(question.question); var answerList = ""; for (var i = 0; i < question.answers.length && i < 8; i++) { answerList += "<li><a class='cmd survey_answer' onclick='nextQuestion();'>" + question.answers[i] + "</a></li>"; } $("#answers").html(answerList); } function setResult(name, url) { var animal; for (var i = 0; animal == null && i < allAnimals.length; i++) if (name == allAnimals[i].filename) animal = allAnimals[i]; var aOrAn; if (animal["name"] == "Eagle") aOrAn = "an"; else aOrAn = "a"; $("#result_title").html("You are " + aOrAn + " " + animal["name"] + "!"); $("#result_description").html(animal["description"]); $("#result_invitation").html("" + "We thought we’d try an experiment...There’s a meeting of the " + animal["plural"] + " tonight on the elevator at " + "<span class='highlight'>" + animal['meeting_time'] + "</span>. You should be there." + animal["reminder"]); $("#snapshot").attr("src", url); $("#result_image").attr("src", "/assets/" + animal["filename"] + ".png"); } function upload() { webcam.snap(webcam.api_url, function() { $.ajax({ url: "/photos", type: "POST", datatype: "script" }); navigate_to("loader"); }); } function reset() { loadQuestionnaire(); webcam.reset(); navigate_to("welcome"); }<file_sep>class PhotosController < ApplicationController def create @photo = Photo.new(params[:photo]) @photo.description = ALL_ANIMALS.sample["filename"] @photo.image = File.new(upload_path) @photo.save respond_to do |format| format.js { render :layout => false } end end def new @questions = ALL_QUESTIONS @animals = ALL_ANIMALS end def index @photo = Photo.all.sample end def random @photo = Photo.all.sample respond_to do |format| format.js { render :layout => false } end end def upload File.open(upload_path, 'w') do |f| f.write request.raw_post.force_encoding("UTF-8") end respond_to do |format| format.json { head :ok } end end private def upload_path # is used in upload and create file_name = session[:session_id].to_s + '.jpg' File.join(Rails.root, 'public', 'uploads', file_name) end end
6ab040074a4e75561a057f3d8913ad2f64af4a96
[ "JavaScript", "Ruby" ]
4
JavaScript
abgoldstein/webcam_app
164e70700af04283b46c055b1a65dc46180d5547
19657e6a8a863647ffa9ae8da14164fdeee57fa9
refs/heads/master
<repo_name>NicolasTicona/faas-cesar-encryption<file_sep>/cesar-function/handler.js "use strict" // EXAMPLE // const cesarEncryption = require('./handler') // cesarEncryption({ // encryptN: 3, // encryptThis: 'Hello World' // }, (err, response) => { // if(err) return console.log('Have a error', err) // console.log(response.status) // console.log(response.encryption); // }) module.exports = (context, callback) => { let alphabetLower = 'abcdefghijklmñnopqrstuvxyz '; let alphabetUpper = 'ABCDEFGHIJQLMÑNOPQRSTUVXYZ.' let nonalphabet = '123456789' let n = context.encryptN || 3; let string = context.encryptThis; let encryptionString = ''; try { for(let index = 0; index < string.length; index++) { let operation; let letter = string.charAt(index) for(let number_i = 0; number_i < nonalphabet.length; number_i++){ if(letter === nonalphabet.charAt(number_i)){ encryptionString += letter; break } } for(let lower_i = 0; lower_i < alphabetLower.length; lower_i++){ if(letter === alphabetLower.charAt(lower_i)){ operation = lower_i + n; if(operation > 27){ encryptionString += alphabetLower[operation - 27]; } else{ encryptionString += alphabetLower[operation]; } break; } } for(let upper_i = 0; upper_i < alphabetUpper.length; upper_i++) { if(letter === alphabetUpper.charAt(upper_i)){ operation = upper_i + n; if(operation > 27){ encryptionString += alphabetUpper[operation - 27]; } else{ encryptionString += alphabetUpper[operation]; } break; } } } // no err callback(null, {status: "done", encryption: encryptionString}); } catch (error) { callback('Verifique si la cadena existe ' + error) } }
087f3fe0d417a4bdfea66f768c75bb3565bf1426
[ "JavaScript" ]
1
JavaScript
NicolasTicona/faas-cesar-encryption
8707ceb4780c6b1d197cc7703d42574c8d25b250
409ebd9160de4af577aea8ef82bf72ec866f35cb
refs/heads/master
<repo_name>iandreyev/WebSocketServer<file_sep>/README.md # WebSocketServer [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) **WebSocketServer** - A WebSocket server class. ## Install Via Composer ``` bash $ composer require dimrakitin/websocketserver ``` ## Usage *server.php* ``` php define('ADDRESS', '127.0.0.1'); define('PORT', 5555); $server = new WebSocketServer\WebSocketServer(ADDRESS, PORT); echo 'Server started '.ADDRESS.':'.PORT."\n"; ``` ** Add callback function** ``` php $server->onConnect = function ($server, $client) { socket_getpeername($client['socket'], $ip); echo 'New connect '.$ip."\n"; }; $server->onDisconnect = function ($server, $client) { socket_getpeername($client['socket'], $ip); echo 'Disconnect '.$ip."\n"; }; $server->onMessage = function ($server, $client, $data) { socket_getpeername($client['socket'], $ip); echo 'onMessage '.$ip.' - '.$data."\n"; $server->sendAll($data); }; ``` **Run loop** ``` php $server->run(); ``` **Client code** ``` javascript var wsUri = "ws://localhost:5555"; websocket = new WebSocket(wsUri); websocket.onopen = function(ev) {}; websocket.onmessage = function(ev) { var data = ev.data; console.log(data); }; websocket.onclose = function(ev) { console.log("onclose"); }; websocket.onerror = function(ev) {}; window.onbeforeunload = function() { websocket.close(); websocket = null; }; ``` Full example you can see at [github](https://github.com/Rakitin/WebSocketChat) ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. <file_sep>/src/WebSocketServer.php <?php namespace WebSocketServer; class WebSocketServer { private $address; private $port; private $socket_master; private $clients; private $callback_connect; private $callback_disconnect; private $callback_message; private $callback_loop; public function __construct($address, $port) { $this->address = $address; $this->port = $port; $this->clients = array(); } public function __destruct() { socket_close($this->socket_master); } public function run() { $this->socket_master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket_master === false) { throw new Exception(socket_strerror(socket_last_error())); } socket_set_option($this->socket_master, SOL_SOCKET, SO_REUSEADDR, 1); if (socket_bind($this->socket_master, $this->address, $this->port) === false) { throw new Exception(socket_strerror(socket_last_error())); } if (socket_listen($this->socket_master, 5) === false) { throw new Exception(socket_strerror(socket_last_error())); } $NULL = null; //$this->clients = array($this->socket_master); while (true) { $sockets_read = array(); $sockets_read[] = $this->socket_master; foreach ($this->clients as $client) { $sockets_read[] = $client['socket']; } socket_select($sockets_read, $NULL, $NULL, 0, 1000000); if (in_array($this->socket_master, $sockets_read)) { // new connect $socket_new = socket_accept($this->socket_master); $this->addClient($socket_new); $found_socket = array_search($this->socket_master, $sockets_read); unset($sockets_read[$found_socket]); } foreach ($sockets_read as $socket) { $buf = socket_read($socket, 1024 * 10/* , PHP_NORMAL_READ */); if (!strlen($buf)) { $this->removeClient($socket); } else { $data = $this->decode($buf); $this->messageHandler($socket, $data); } } if (isset($this->callback_loop)) { if (!is_callable($this->callback_loop)) { throw new Exception('onLoop is not call back'); } call_user_func($this->callback_loop, $this, $socket); } } } private function addClient($socket) { $header = socket_read($socket, 1024); $info = $this->handshaking($header, $socket, $this->address, $this->port); $client['socket'] = $socket; $client['uri'] = parse_url($info['uri']); $client['uri']['queryes'] = array(); if (isset($client['uri']['query'])) { parse_str($client['uri']['query'], $client['uri']['queryes']); } $this->clients[] = $client; if (isset($this->callback_connect)) { if (!is_callable($this->callback_connect)) { throw new Exception('onConnect is not call back'); } call_user_func($this->callback_connect, $this, $client); } } private function removeClient($socket) { foreach ($this->clients as $kay => $client) { if ($client['socket'] === $socket) { if (isset($this->callback_disconnect)) { if (!is_callable($this->callback_disconnect)) { throw new Exception('onDisconnect is not call back'); } call_user_func($this->callback_disconnect, $this, $client); } socket_close($client['socket']); unset($this->clients[$kay]); } } } private function messageHandler($socket, $data) { switch ($data['type']) { case 'text': if (isset($this->callback_message)) { if (!is_callable($this->callback_message)) { throw new Exception('onMessage is not call back'); } foreach ($this->clients as $kay => $client) { if ($client['socket'] === $socket) { call_user_func($this->callback_message, $this, $client, $data['payload']); } } } break; case 'close': $this->removeClient($socket); break; case 'ping': break; case 'pong': break; default: break; } } private function handshaking($header, $client_socket, $host, $port) { $info = array(); $headers = array(); $lines = preg_split("/\r\n/", $header); $head = explode(' ', $lines[0]); $info['method'] = $head[0]; $info['uri'] = $head[1]; foreach ($lines as $line) { $line = chop($line); if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } $secKey = $headers['Sec-WebSocket-Key']; $secAccept = base64_encode(pack('H*', sha1($secKey.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n". "Upgrade: websocket\r\n". "Connection: Upgrade\r\n". "WebSocket-Origin: {$host}\r\n". "WebSocket-Location: ws://{$host}:{$port}\r\n". "Sec-WebSocket-Accept:$secAccept\r\n\r\n"; socket_write($client_socket, $upgrade, strlen($upgrade)); return $info; } private function encode($payload, $type = 'text', $masked = true) { $frameHead = array(); $frame = ''; $payloadLength = strlen($payload); switch ($type) { case 'text': // first byte indicates FIN, Text-Frame (10000001): $frameHead[0] = 129; break; case 'close': // first byte indicates FIN, Close Frame(10001000): $frameHead[0] = 136; break; case 'ping': // first byte indicates FIN, Ping frame (10001001): $frameHead[0] = 137; break; case 'pong': // first byte indicates FIN, Pong frame (10001010): $frameHead[0] = 138; break; } // set mask and payload length (using 1, 3 or 9 bytes) if ($payloadLength > 65535) { $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8); $frameHead[1] = ($masked === true) ? 255 : 127; for ($i = 0; $i < 8; ++$i) { $frameHead[$i + 2] = bindec($payloadLengthBin[$i]); } // most significant bit MUST be 0 (close connection if frame too big) if ($frameHead[2] > 127) { $this->close(1004); return false; } } elseif ($payloadLength > 125) { $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8); $frameHead[1] = ($masked === true) ? 254 : 126; $frameHead[2] = bindec($payloadLengthBin[0]); $frameHead[3] = bindec($payloadLengthBin[1]); } else { $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength; } // convert frame-head to string: foreach (array_keys($frameHead) as $i) { $frameHead[$i] = chr($frameHead[$i]); } if ($masked === true) { // generate a random mask: $mask = array(); for ($i = 0; $i < 4; ++$i) { $mask[$i] = chr(rand(0, 255)); } $frameHead = array_merge($frameHead, $mask); } $frame = implode('', $frameHead); // append payload to frame: $framePayload = array(); for ($i = 0; $i < $payloadLength; ++$i) { $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i]; } return $frame; } private function decode($data) { $mask = ''; $unmaskedPayload = ''; $decodedData = array(); // estimate frame type: $firstByteBinary = sprintf('%08b', ord($data[0])); $secondByteBinary = sprintf('%08b', ord($data[1])); $opcode = bindec(substr($firstByteBinary, 4, 4)); $isMasked = ($secondByteBinary[0] == '1') ? true : false; $payloadLength = ord($data[1]) & 127; if ($isMasked === false) { // close connection if unmasked frame is received return array('type' => '', 'payload' => '', 'error' => 'protocol error (1002)'); } switch ($opcode) { case 1: $decodedData['type'] = 'text'; break; // text frame case 8: $decodedData['type'] = 'close'; break; // connection close frame case 9: $decodedData['type'] = 'ping'; break; // ping frame case 10: $decodedData['type'] = 'pong'; break; // pong frame default: // Close connection on unknown opcode return array('type' => '', 'payload' => '', 'error' => 'unknown opcode (1003)'); } if ($payloadLength === 126) { $mask = substr($data, 4, 4); $payloadOffset = 8; $dataLength = sprintf('%016b', ord($data[2]).ord($data[3])); $dataLength = base_convert($dataLength, 2, 10); } elseif ($payloadLength === 127) { $mask = substr($data, 10, 4); $payloadOffset = 14; $dataLength = ''; for ($i = 2; $i < 8; ++$i) { $dataLength .= sprintf('%08b', ord($data[$i])); } $dataLength = base_convert($dataLength, 2, 10); } else { $mask = substr($data, 2, 4); $payloadOffset = 6; $dataLength = base_convert(sprintf('%08b', ord($data[1]) & 63), 2, 10); } if ($isMasked === true) { for ($i = $payloadOffset; $i < $dataLength + $payloadOffset; ++$i) { $j = $i - $payloadOffset; $unmaskedPayload .= $data[$i] ^ $mask[$j % 4]; } $decodedData['payload'] = $unmaskedPayload; } else { $payloadOffset = $payloadOffset - 4; $decodedData['payload'] = substr($data, $payloadOffset); } $decodedData['offset'] = $payloadOffset; return $decodedData; } public function sendAll($msg) { $data = $this->encode($msg, 'text', false); foreach ($this->clients as $client) { if ($client['socket'] === $this->socket_master) { continue; } @socket_write($client['socket'], $data, strlen($data)); } } public function send($client, $msg) { $data = $this->encode($msg, 'text', false); @socket_write($client['socket'], $data, strlen($data)); } public function setOnConnect($callback) { $this->callback_connect = $callback; } public function setOnDisconnect($callback) { $this->callback_disconnect = $callback; } public function setOnMessage($callback) { $this->callback_message = $callback; } public function setOnLoop($callback) { $this->callback_loop = $callback; } public function __set($attr, $value) { if ($attr == 'onConnect') { $this->setOnConnect($value); } elseif ($attr == 'onDisconnect') { $this->setOnDisconnect($value); } elseif ($attr == 'onMessage') { $this->setOnMessage($value); } elseif ($attr == 'onLoop') { $this->setOnLoop($value); } else { throw new Exception("Attrebut: '".$attr."' does not exist \n"); } } public function getClients() { return $this->clients; } }
22c98dda97dcb20d787b18a25132e13005255bf2
[ "Markdown", "PHP" ]
2
Markdown
iandreyev/WebSocketServer
53ed1f52939303cfe38e6d4f9e66e588b7e6a53f
480ceb1e4496ebaf28fbb8524b80b5e8f356cfb7
refs/heads/master
<repo_name>rickdemonn/Hillel-Front-End<file_sep>/src/hw12/js/time-app.js "use strict"; showClock(); function createImage(digit) { const img = document.createElement('img'); img.setAttribute('src','clock-images/' + digit + '.png'); img.className = 'clock-img'; return img; } function showClock(){ const date = new Date(); let hours = date.getHours(); let minutes = date.getMinutes(); let seconds = date.getSeconds(); hours = (hours < 10) ? '0' + hours : hours; minutes = (minutes < 10) ? '0' + minutes : minutes; seconds = (seconds < 10) ? '0' + seconds : seconds; const firstDigitOfHours = parseInt(hours / 10); const secondDigitOfHours = parseInt(hours % 10); const firstDigitOfMinutes = parseInt(minutes / 10); const secondDigitOfMinutes = parseInt(minutes % 10); const firstDigitOfSeconds = parseInt(seconds / 10); const secondDigitOfSeconds = parseInt(seconds % 10); const doubleDotsImgName = 'dots'; const clock = document.getElementById("clock"); clock.innerHTML = ''; clock.appendChild(createImage(firstDigitOfHours)); clock.appendChild(createImage(secondDigitOfHours)); clock.appendChild(createImage(doubleDotsImgName)); clock.appendChild(createImage(firstDigitOfMinutes)); clock.appendChild(createImage(secondDigitOfMinutes)); clock.appendChild(createImage(doubleDotsImgName)); clock.appendChild(createImage(firstDigitOfSeconds)); clock.appendChild(createImage(secondDigitOfSeconds)); setTimeout(showClock, 1000); }<file_sep>/src/hw11/js/data.js const users = [{ id: '1', name: '<NAME>', age: 20, mail: '<EMAIL>', phone: '+380 97 123 4567', card: '4029-6100-4092-8291', balance: 10000, cars: {} }, { id: '2', name: '<NAME>', age: 35, mail: '<EMAIL>', phone: '+38 097-38-91-123', card: '4029-6100-4729-9827', balance: 10000, cars: {} }, { id: '3', name: '<NAME>', age: 46, mail: '<EMAIL>', phone: '+380979876543', card: '4029-6100-4822-8387', balance: 10000, cars: {} }] const cars = [{ id: '1', model: 'Tesla model x', isInGarage: true, price: 100000, owner: {} }, { id: '2', model: 'Ford Mustang', isInGarage: true, price: 50000, owner: {} }, { id: '3', model: 'Jeguli', isInGarage: true, price: 1000, owner: {} }] const companies = [{ id: '1', name: 'Google', cars: {}, balance: 1000000 }, { id: '2', name: 'NovaPoshta', cars: {}, balance: 40000 }]<file_sep>/src/hw10/js/data.js 'use strict'; const categories = [ { id: "1", name: 'Laptops', items: [ { id: '10', name: 'Apple Macbook 15', price: 2000, }, { id: '11', name: 'Apple Macbook 13', price: 1500, }, { id: '12', name: 'Dell XPS', price: 2000, }, { id: '13', name: 'Chromebook', price: 500, }, ], }, { id: "2", name: 'Phones', items: [ { id: '21', name: 'iPhone', price: 1500, }, { id: '22', name: 'Samsung S20 Ultra', price: 5000, }, ], }, ]; <file_sep>/README.md # Hillel-Front-End Home Works <file_sep>/src/hw16/js/data.js const tasks = [ new TodoTask(1, "Learn JS", 2, 3), new TodoTask(2, "Be Happy", 3, 2), new TodoTask(3, "Build House", 4, 1)//wrong status ];<file_sep>/src/hw14/js/functions.js "use strict"; function appStart() { const selector = '#wrapper'; $(selector).html(''); showButtons(selector); if (checkStorage()) { localStorage.setItem('cars', JSON.stringify(cars)); localStorage.setItem('users', JSON.stringify(users)); localStorage.setItem('companies', JSON.stringify(companies)); } } function checkStorage() { return !localStorage.getItem('cars') || !localStorage.getItem('users') || !localStorage.getItem('companies'); } function showButtons(selector) { for (let i = 0; i < buttons.length; i++) { $(selector).append($('<button/>', { id: buttons[i].btnId, value: buttons[i].value, name: buttons[i].name, type: 'button', text: buttons[i].value, 'data-id': buttons[i].dataId, }).click(showElementBlock)); } } function showElementBlock(event, nameFromOtherResource) { let name = event.currentTarget.name; if (name === 'undefined' || name === '') { name = nameFromOtherResource; } const idSelector = '#' + name; const wrapSelector = '#wrapper'; $(wrapSelector).html(''); showButtons(wrapSelector); $('<div/>', { id: name, }).appendTo(wrapSelector); $('<h2/>', { id: 'title', text: name }).appendTo(idSelector); const elementsFromLocalStorage = JSON.parse(localStorage.getItem(name)); setObjsToShowFromLocalStorage(elementsFromLocalStorage, idSelector, name); } function setObjsToShowFromLocalStorage(elements, idSelector, name) { for (let i = 0; i < elements.length; i++) { const element = elements[i]; $(createObjWithButtons(element)).appendTo(idSelector); } $('<button/>', { name: name, type: 'button', text: 'Create ' + name, }).click(createObj).appendTo(idSelector); } function createObjWithButtons(element) { const nameOrModel = element.name || element.model; const userWithButtonsBlockSelector = $('<div/>', {'class': 'element'}); $('<div>', {text: nameOrModel}).appendTo(userWithButtonsBlockSelector); createBtnForObjBlock('btn-view', 'View', element.id, handleViewClick, userWithButtonsBlockSelector); createBtnForObjBlock('btn-edit', 'Edit', element.id, handleEditClick, userWithButtonsBlockSelector); createBtnForObjBlock('btn-remove', 'Remove', element.id, handleRemoveClick, userWithButtonsBlockSelector); return userWithButtonsBlockSelector; } function createBtnForObjBlock(id, text, elementId, handler, elementToAppend) { $('<button/>', { id: id, type: 'button', text: text, 'data-id': elementId, }).click(handler).appendTo(elementToAppend); } function handleViewClick(event) { $('#form').remove(); const selectedElement = getSelectedObjForHandler(event); showViewForm(selectedElement); } function handleEditClick(event) { $('#form').remove(); const selectedElement = getSelectedObjForHandler(event); showObjEditForm(selectedElement); } function showViewForm(objElement) { const nameOrModel = objElement.name || objElement.model; const viewUserTitleSelector = $('<h2/>', {id: 'view-' + objElement + '-title', text: nameOrModel + '`s Info'}) const form = createFormForObj(viewUserTitleSelector, objElement); setFormFields(form, objElement); $(form).find('[id=btn-save]').addClass('hidden'); $(form).children().attr("readonly", true); $('#wrapper').append(form); } function createFormForObj(titleSelector, objElement, clickHandler, objName, objId) { const form = $('<form/>', {id: 'form'}); if (titleSelector) { $(titleSelector).appendTo(form); } for (let index in objElement) { $('<div/>', {html: [index + '']}).appendTo(form); $(createInput(index + '')).appendTo(form); } $('<input/>', {id: 'btn-save', type: 'button', value: 'Save', 'data-id': objId, 'name': objName}) .click(clickHandler).appendTo(form); return form; } function createInput(name) { return $('<input/>', {type: 'text', name: name}); } function setFormFields(form, objElement) { for (let index in objElement) { if (!isEmpty(objElement[index + ''])) { $(form).find('[name=' + index + ']').val(objElement[index + '']); } } } function getSelectedObjForHandler(event) { const elemId = event.target.getAttribute('data-id'); const elementName = event.target.parentNode.parentElement.id; const objElements = JSON.parse(localStorage.getItem(elementName)); return objElements.find(function (objElement) { return objElement.id === elemId; }); } function handleRemoveClick(event) { const wrapSelector = '#wrapper'; $(wrapSelector).html(''); showButtons(wrapSelector); const elementName = event.target.parentNode.parentElement.id; const objId = event.target.getAttribute('data-id'); const objs = JSON.parse(localStorage.getItem(elementName)); const obj = objs.find(function (obj) { if (obj.id === objId) { return obj; } }) const nameOrModel = obj.name || obj.model; $('<div/>', {id: 'confirm-remove-block'}) .append($('<h2/>', {text: 'Remove object : ' + nameOrModel + ' ?'})) .append($('<button/>', {name: elementName, 'data-id': objId, text: 'yes', type: 'button'}).click(handleConfirmRemoveClick)) .append($('<button/>', {name: elementName,'data-id': objId, text: 'no', type: 'button'}).click(handleDoNotConfirmRemoveClick)) .appendTo(wrapSelector); } function createObj(event) { $('#form').remove(); const objName = event.target.parentNode.id; const objs = JSON.parse(localStorage.getItem(objName)); let maxId = 1; objs.find(function (obj) { const idInNum = parseInt(obj.id); if (idInNum > maxId) { maxId = idInNum; } }); let objElem = objs[0]; if (objs.length === 0) { if (objName === 'users') { objElem = users[0]; } else if (objName === 'cars') { objElem = cars[0]; } else { objElem = companies[0]; } } const autoGeneratedId = maxId + 1 + ''; const createObjTitleSelector = $('<h2/>', {text: 'Create New element in ' + objName}); const form = createFormForObj(createObjTitleSelector, objElem, handleSaveNewUser, objName); $(form).find('[name=id]').val(autoGeneratedId).attr("readonly", true); $(form).appendTo('#wrapper'); } function handleSaveNewUser(event) { const form = event.target.parentNode; const objName = $(form).find('[id=btn-save]').attr('name'); const objs = JSON.parse(localStorage.getItem(objName)); const isMistake = validate(form, objName); if (!isMistake) { let newObj; if (objName === 'users') { newObj = new User(form.elements[0].value, form.elements[1].value, form.elements[2].value, form.elements[3].value, form.elements[4].value, form.elements[5].value, form.elements[6].value, form.elements[7].value ); } if (objName === 'cars') { newObj = new Car(form.elements[0].value, form.elements[1].value, form.elements[2].value, form.elements[3].value, form.elements[4].value ); } if (objName === 'companies') { newObj = new Company(form.elements[0].value, form.elements[1].value, form.elements[2].value, form.elements[3].value ); } objs.push(newObj); localStorage.setItem(objName, JSON.stringify(objs)); showElementBlock(event, objName); } } function validate(form, objName) { const idPattern = /^\d{1,}$/; const namePattern = /[A-Z][a-z]{1,} [A-Z][a-z]{1,}/; const nameCompany = /[A-Za-z]{1,}/; const agePattern = /^\d{1,2}$/; const mailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; const phonePattern = /^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$/; const cardPattern = /^\d{4}-\d{4}-\d{4}-\d{4}$/; const balancePattern = /^\d{1,}$/; const pricePattern = /^\d{1,}$/; const modelPattern = /w{1,}/; const isInGaragePattern = /w{4,5}/; const ownerPattern = /w{1,}/; // const patterns = { // id: /^\d{1,}$/, // name: /[A-Z][a-z]{1,} [A-Z][a-z]{1,}/, // compName: /[A-Za-z]{1,}/, // age: /^\d{1,2}$/, // mail: /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/, // phone: /^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$/, // card: /^\d{4}-\d{4}-\d{4}-\d{4}$/, // balance: /^\d{1,}$/, // price: /^\d{1,}$/, // model: /w{1,}/, // isInGarage: /w{4,5}/, // owner: /w{1,}/, // } //TODO const validationsUser = { id: function (field) { return idPattern.test(field.value); }, name: function (field) { return namePattern.test(field.value); }, age: function (field) { return agePattern.test(field.value); }, mail: function (field) { return mailPattern.test(field.value); }, phone: function (field) { return phonePattern.test(field.value); }, card: function (field) { return cardPattern.test(field.value); }, balance: function (field) { return balancePattern.test(field.value); }, cars: function (field) { return true; } } const validationsCar = { id: function (field) { return idPattern.test(field.value); }, name: function (field) { return modelPattern.test(field.value); }, age: function (field) { return isInGaragePattern.test(field.value); }, mail: function (field) { return pricePattern.test(field.value); }, phone: function (field) { return ownerPattern.test(field.value); } } const validationsCompany = { id: function (field) { return idPattern.test(field.value); }, name: function (field) { return nameCompany.test(field.value); }, cars: function (field) { return true; }, balance: function (field) { return balancePattern.test(field.value); } } let isMistake = false; let validations; let validationDelta; if (objName === 'users') { validations = validationsUser; validationDelta = 2; } else if (objName === 'cars') { validations = validationsCar; validationDelta = 1; } else { validations = validationsCompany; validationDelta = 2; } for (let i = 0; i < form.elements.length - validationDelta; i++) { const field = form.elements[i]; const validator = validations[field.name]; if (validator && !validator(field)) { field.classList.add('error'); isMistake = true; } else { field.classList.remove('error'); } } return isMistake; } function handlerSaveClick(event) { const id = event.target.getAttribute('data-id'); const form = event.target.parentNode; const objName = event.target.parentNode.previousSibling.id; const objs = JSON.parse(localStorage.getItem(objName)); const isMistake = validate(form); const isUniqId = checkUniqIdForUpdate(form, objs, id); if (!isMistake && isUniqId) { let fields = {}; // objs.find(function (obj) { // if (obj.id === id) { // console.log(obj); // $(form).find('[type=text]').each(item => { // fields[item.name] = $(item).val(); // }); // obj = {fields: fields}; // } // }); // } // localStorage.setItem(objName, JSON.stringify(objs)); // showElementBlock(event, objName);//TODO if (objName === 'users') { objs.find(function (user) { if (user.id === id) { user.id = form.elements.id.value; user.name = form.elements.name.value; user.age = form.elements.age.value; user.mail = form.elements.mail.value; user.phone = form.elements.phone.value; user.card = form.elements.card.value; user.balance = form.elements.balance.value; user.cars = form.elements.cars.value; } }); localStorage.setItem('users', JSON.stringify(objs)); showElementBlock(event, 'users'); } if (objName === 'cars') { objs.find(function (car) { if (car.id === id) { car.id = form.elements.id.value; car.model = form.elements.model.value; car.isInGarage = form.elements.isInGarage.value; car.price = form.elements.price.value; car.owner = form.elements.owner.value; } }); localStorage.setItem('cars', JSON.stringify(objs)); showElementBlock(event, 'cars'); } if (objName === 'companies') { objs.find(function (company) { if (company.id === id) { company.id = form.elements.id.value; company.name = form.elements.name.value; company.cars = form.elements.cars.value; company.balance = form.elements.balance.value; } }); localStorage.setItem('companies', JSON.stringify(objs)); showElementBlock(event, 'companies'); } } } function checkUniqIdForUpdate(form, objs, id) { let isUniqId = true; const formIdValue = form.elements.id.value; objs.find(function (obj) { if (formIdValue === obj.id && formIdValue !== id) { isUniqId = false; form.elements.id.classList.add('error'); } }); return isUniqId; } function handleDoNotConfirmRemoveClick(event) { const name = event.currentTarget.id; showElementBlock(event, name); } function handleConfirmRemoveClick(event) { const objId = event.target.getAttribute('data-id'); const name = event.target.name; const objs = JSON.parse(localStorage.getItem(name)); const newObjs = []; objs.find(function (obj) { if (obj.id !== objId) { newObjs.push(obj); } }); localStorage.setItem(name, JSON.stringify(newObjs)); showElementBlock(event, name); } function showObjEditForm(obj) { const objName = event.target.parentNode.parentNode.id; const nameOrModel = obj.name || obj.model; const EditUserTitleSelect = $('<h2/>', {id: 'view-user-title', text: nameOrModel + '`s Edit Form'}); const form = createFormForObj(EditUserTitleSelect, obj, handlerSaveClick, objName, obj.id); setFormFields(form, obj); if (objName !== 'cars') { $('<button/>', {type: 'button', 'data-id': obj.id, 'data-name': objName, text: 'Buy Car'}) .click(handleBuyCar).appendTo(form); } $('#wrapper').append(form); } function handleBuyCar(event) { const objsName = event.target.dataset.name; const objId = event.target.dataset.id; const cars = JSON.parse(localStorage.getItem('cars')); const carsBlock = $('<div/>', {id: 'cars-block'}); cars.forEach(car => { if (car.isInGarage) { $(carsBlock).append( $('<div/>', {text: car.model + ' ' + car.price}).addClass('car-block').append( $('<button/>', { type: 'button', 'data-id': car.id, 'data-objid': objId, 'data-objsname': objsName, text: 'select' }).click(handleSelectCarForBuy) ) ).appendTo('#wrapper'); } }); } function handleSelectCarForBuy(event) { const objsName = event.target.dataset.objsname; const objId = event.target.dataset.objid; const carId = event.target.dataset.id; const objs = JSON.parse(localStorage.getItem(objsName)); const cars = JSON.parse(localStorage.getItem('cars')); const currentTargetObj = objs.find(obj => { if (obj.id === objId) { return obj; } }); const currentTargetCar = cars.find(car => { if (car.id === carId) { return car; } }); if (currentTargetObj.balance > currentTargetCar.price) { currentTargetObj.cars = currentTargetCar.model; currentTargetCar.isInGarage = false; currentTargetCar.owner = currentTargetObj.name; currentTargetObj.balance -= currentTargetCar.price; localStorage.setItem(objsName, JSON.stringify(objs)); localStorage.setItem('cars', JSON.stringify(cars)); showElementBlock(event, objsName); } else { $('<div/>', {text: 'No Money No Honey'}).appendTo('#wrapper'); } } function isEmpty(obj) { for (let prop in obj) { if (obj.hasOwnProperty(prop)) { return false; } } return JSON.stringify(obj) === JSON.stringify({}); } <file_sep>/src/hw14/js/User.js function User(id, name, age, mail, phone, card, balance, cars) { this.id = id; this.name = name; this.age = age; this.mail = mail; this.phone = phone; this.card = card; this.balance = balance; this.cars = cars; } <file_sep>/src/hw10/js/functions.js 'use strict'; function checkFormToDelete() { const form = document.getElementById('form'); if (form) { form.remove(); } } function handleCategoryClick(event) { checkFormToDelete(); event.preventDefault(); const categoryId = event.target.getAttribute('data-id'); const selectedCategory = categories.find(function (category) { return category.id === categoryId; }); const products = selectedCategory.items; showProducts(products, categoryId); } function handleProductClick(event) { checkFormToDelete(); event.preventDefault(); const productId = event.target.getAttribute('data-id'); const categoryId = event.target.getAttribute('data-category-id'); const selectedCategory = categories.find(function (category) { return category.id === categoryId; }); const selectedProduct = selectedCategory.items.find(function (product) { return product.id === productId; }); showProduct(selectedProduct); } function showItems(items, parentId, clickHandler, additionalAttributes) { const parent = document.getElementById(parentId); parent.innerHTML = ''; const title = document.createElement('h2'); title.innerHTML = 'Choose Item'; parent.appendChild(title); for (let i = 0; i < items.length; i++) { const element = document.createElement('a'); element.setAttribute('href', items[i].id); element.innerText = items[i].name; element.setAttribute('data-id', items[i].id); if (additionalAttributes && additionalAttributes.length) { for (let j = 0; j < additionalAttributes.length; j++) { element.setAttribute(additionalAttributes[j].key, additionalAttributes[j].value); } } element.addEventListener('click', clickHandler); parent.appendChild(element); } } function showCategories() { showItems(categories, 'categories', handleCategoryClick); } function showProducts(items, categoryId) { const attributes = [ { key: 'data-category-id', value: categoryId, } ]; showItems(items, 'products', handleProductClick, attributes); document.getElementById('info').innerHTML = ''; } function showProduct(product) { const parent = document.getElementById('info'); parent.innerHTML = ''; const title = document.createElement('h2'); title.textContent = product.name; parent.appendChild(title); const price = document.createElement('div'); price.textContent = '$' + product.price; parent.appendChild(price); const buyButton = document.createElement('input'); buyButton.setAttribute('type', 'button'); buyButton.setAttribute('id', 'buy-btn'); buyButton.setAttribute('value', 'Buy'); buyButton.addEventListener('click', function () { wrapper.appendChild(createFormBySelectedProductForBuy(product)); }); parent.appendChild(buyButton); } function createFormBySelectedProductForBuy(selectedProduct) { const form = createElementWithAttribute('form', 'name', 'form'); form.setAttribute('id', 'form'); const formTitle = createElementWithAttribute('h2', 'id', 'form-title'); formTitle.innerHTML = 'Form to buy ' + selectedProduct.name; form.appendChild(formTitle); form.appendChild(createInputTextField('Enter your Fio * ', 'fio', 'Name & Last Name')); const cities = ['Odessa', 'Kiev', 'Chernigov']; form.appendChild(createCitySelectInput(cities)); form.appendChild(createInputTextField('Enter post number * ', 'post', 'Number of Post unit')); form.appendChild(createRadios()); const cost = document.createElement('div'); form.appendChild(createCountField(selectedProduct, cost)); form.appendChild(createComment()); const formButton = createElementWithAttribute('button', 'type', 'button'); formButton.setAttribute('id', 'form-button'); formButton.innerHTML = 'Buy'; formButton.addEventListener('click', function () { let isMistake = false; if (form.elements.fio.value === '') { form.elements.fio.className = 'error'; isMistake = true; } else { form.elements.fio.className = ''; } if (form.elements.city.value === '0') { form.elements.city.className = 'error'; isMistake = true; } else { form.elements.city.className = ''; } if (form.elements.post.value === '') { form.elements.post.className = 'error'; isMistake = true; } else { form.elements.post.className = ''; } const valueOfCountProduct = form.elements['count-of-product'].value; if (valueOfCountProduct === '' || isNaN(valueOfCountProduct) || parseInt(valueOfCountProduct) < 1) { form.elements['count-of-product'].className = 'error'; isMistake = true; } else { form.elements['count-of-product'].className = ''; } const radios = document.getElementById('radios'); if (form.elements['pay-method'].value === '') { radios.className = 'error'; isMistake = true; } else { radios.className = ''; } if (!isMistake) { wrapper.innerHTML = ''; const result = createElementWithAttribute('div', 'id', 'result'); result.style.backgroundColor = 'chartreuse'; result.style.margin = '0 auto'; result.innerHTML = 'You buy ' + selectedProduct.name + ' in quantity: ' + form.elements['count-of-product'].value + ' successfully!'; //send to server request wrapper.appendChild(result); } }); form.appendChild(cost); form.appendChild(formButton); return form; } function createElementWithAttribute(element, attribute, value) { const newElement = document.createElement(element); newElement.setAttribute(attribute, value); return newElement; } function createRadios() { const radios = createElementWithAttribute('div', 'id', 'radios'); radios.appendChild(createRadio('N', 'Nal Pay')); radios.appendChild(createRadio('O', 'Online pay')); return radios; } function createInputTextField(innerText, name, placeholder) { const fioWrap = document.createElement('div'); fioWrap.innerText = innerText; const fio = createElementWithAttribute('input', 'type', 'text'); fio.setAttribute('name', name); fio.setAttribute('placeholder', placeholder); fioWrap.appendChild(fio); return fioWrap; } function createCitySelectInput(cities) { const cityWrap = document.createElement('div'); cityWrap.innerText = 'Choose your city * '; const city = createElementWithAttribute('select', 'name', 'city'); const defaultCity = createElementWithAttribute('option', 'value', '0'); defaultCity.innerHTML = '---select city---'; city.appendChild(defaultCity); for (let i = 0; i < cities.length; i++) { const currentCity = createElementWithAttribute('option', 'value', cities[i]); currentCity.innerHTML = cities[i]; city.appendChild(currentCity); } cityWrap.appendChild(city); return cityWrap; } function createRadio(value, text) { const radio = document.createElement('div'); const radioOption = createElementWithAttribute('input', 'type', 'radio'); radioOption.setAttribute('name', 'pay-method'); radioOption.setAttribute('value', value); radio.innerText = text; radio.appendChild(radioOption); return radio; } function createCountField(selectedProduct, cost) { const countWrap = document.createElement('div'); countWrap.innerText = 'Enter count of products '; const countOfProduct = createElementWithAttribute('input', 'type', 'number'); countOfProduct.setAttribute('name', 'count-of-product'); countOfProduct.setAttribute('placeholder', 'count of product'); countOfProduct.setAttribute('value', '1'); countOfProduct.addEventListener('input', function () { cost.innerText = 'Price is ' + selectedProduct.price * countOfProduct.value; }); countWrap.appendChild(countOfProduct); return countWrap; } function createComment() { const commentWrap = document.createElement('div'); commentWrap.innerText = 'Your Comment '; const comment = createElementWithAttribute('textarea', 'name', 'comment'); commentWrap.appendChild(comment); return commentWrap; }<file_sep>/src/hw11/js/functions.js "use strict"; function appStart() { const wrap = document.getElementById('wrapper'); wrap.appendChild(createButton('btn-users', 'Show Users', '1', showElementBlock, users, 'users')); wrap.appendChild(createButton('btn-companies', 'Show Companies', '2', showElementBlock, companies, 'companies')); wrap.appendChild(createButton('btn-cars', 'Show Cars', '3', showElementBlock, cars, 'cars')); } function showElementBlock(event) { const name = event.currentTarget.name; const obj = event.currentTarget.obj; checkElementToRemove('users'); checkElementToRemove('cars'); checkElementToRemove('companies'); checkElementToRemove('form'); checkElementToRemove('confirm-remove-block'); const wrap = document.getElementById('wrapper'); const block = createElement('div', [{name: 'id', value: name}]); const title = createElement('h2', [{name: 'id', value: 'title'}], name.toUpperCase()); block.appendChild(title); if (!localStorage.getItem(name)) { localStorage.setItem(name, JSON.stringify(obj)); } const elementsFromLocalStorage = JSON.parse(localStorage.getItem(name)); for (let i = 0; i < elementsFromLocalStorage.length; i++) { const element = elementsFromLocalStorage[i]; block.appendChild(createObjWithButtons(element)); } block.appendChild(createButton('create-' + name, 'Create ' + name, '', createUser)); wrap.appendChild(block); } function createObjWithButtons(element) { const userWithButtonsBlock = createElement('div', [{name: 'class', value: 'element'}]); const nameOrModel = element.name || element.model; const userElem = createElement('div', null, nameOrModel); userWithButtonsBlock.appendChild(userElem); userWithButtonsBlock.appendChild(createButton('btn-view', 'View', element.id, handleViewClick)); userWithButtonsBlock.appendChild(createButton('btn-edit', 'Edit', element.id, handleEditClick)); userWithButtonsBlock.appendChild(createButton('btn-remove', 'Remove', element.id, handleRemoveClick)); return userWithButtonsBlock; } function handleViewClick(event) { checkElementToRemove('form'); const selectedElement = getSelectedObjForHandler(event); showViewForm(selectedElement); } function handleEditClick(event) { checkElementToRemove('form'); const selectedElement = getSelectedObjForHandler(event); showObjEditForm(selectedElement); } function showViewForm(objElement) { const wrap = document.getElementById('wrapper'); const nameOrModel = objElement.name || objElement.model; const viewUserTitle = createElement('h2', [{name: 'id', value: 'view-' + objElement + '-title'}], nameOrModel + '`s Info'); const form = createFormForObj(viewUserTitle, objElement); setFormFields(form, objElement); form.elements['btn-save'].style.display = 'none'; for (let i = 0; i < form.elements.length; i++) { form.elements[i].readOnly = true; } wrap.appendChild(form); } function createFormForObj(title, objElement, clickHandler) { const form = createElement('form', [{name: 'id', value: 'form'}], null); if (title) { form.appendChild(title); } for (let index in objElement) { form.appendChild(createElement('div', null, [index + ''])); form.appendChild(createInput(index)); } const nameOrModel = objElement.name || objElement.model; form.appendChild(createButton('btn-save', 'Save', nameOrModel, clickHandler)); return form; } function setFormFields(form, objElement) { for (let index in objElement) { form.elements[index].value = objElement[index]; } } function getSelectedObjForHandler(event) { const elemId = event.target.getAttribute('data-id'); const elementName = event.target.parentNode.parentElement.id; const objElements = JSON.parse(localStorage.getItem(elementName)); return objElements.find(function (objElement) { return objElement.id === elemId; }); } function handleRemoveClick(event) { checkElementToRemove('users'); checkElementToRemove('cars'); checkElementToRemove('companies'); checkElementToRemove('form'); const elementName = event.target.parentNode.parentElement.id; const objId = event.target.getAttribute('data-id'); const wrap = document.getElementById('wrapper'); const objs = JSON.parse(localStorage.getItem(elementName)); const obj = objs.find(function (obj) { if (obj.id === objId) { return obj; } }) const nameOrModel = obj.name || obj.model; const removeObjTitle = createElement('h2', null, 'Remove object : ' + nameOrModel + ' ?'); const confirmRemove = createElement('div', [{name: 'id', value: 'confirm-remove-block'}]); confirmRemove.appendChild(removeObjTitle); confirmRemove.appendChild(createButton('yes', 'yes', objId, handleConfirmRemoveClick, obj, name)); confirmRemove.appendChild(createButton('no', 'no', objId, handleDoNotConfirmRemoveClick)); wrap.appendChild(confirmRemove); } function createButton(btnId, value, dataId, handler, obj, name) { const attributes = [{ name: 'data-id', value: dataId }, { name: 'type', value: 'button' }, { name: 'name', value: 'button' }, { name: 'value', value: value }, { name: 'id', value: btnId }]; const btn = createElement('input', attributes, null); btn.obj = obj; btn.name = name; btn.addEventListener('click', handler); return btn; } function createUser() { checkElementToRemove('form'); const users = JSON.parse(localStorage.getItem('users')); let maxId = 1; users.find(function (user) { const idInNum = parseInt(user.id); if (idInNum > maxId) { maxId = idInNum; } }); const autoGeneratedId = maxId + 1 + ''; const wrap = document.getElementById('wrapper'); const createUserTitle = createElement('h2', null, 'Create New user'); const form = createFormForObj(createUserTitle, autoGeneratedId, handleSaveNewUser); form.elements.userId.value = autoGeneratedId; form.elements.userId.readOnly = true; wrap.appendChild(form); } function handleSaveNewUser(event) { const form = event.target.parentNode; const users = JSON.parse(localStorage.getItem('users')); const isMistake = validate(form); if (!isMistake) { const newUser = { id: form.elements.userId.value, name: form.elements.userName.value, age: form.elements.userAge.value, mail: form.elements.userMail.value, phone: form.elements.userPhone.value, card: form.elements.userCard.value } users.push(newUser); localStorage.setItem('users', JSON.stringify(users)); showElementBlock(users); } } function validate(form) { const idPattern = /^\d{1,}$/; const namePattern = /[A-Z][a-z]{1,} [A-Z][a-z]{1,}/; const agePattern = /^\d{1,2}$/; const mailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; const phonePattern = /^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$/; const cardPattern = /^\d{4}-\d{4}-\d{4}-\d{4}$/; const validations = { userId: function (field) { return idPattern.test(field.value); }, userName: function (field) { return namePattern.test(field.value); }, userAge: function (field) { return agePattern.test(field.value); }, userMail: function (field) { return mailPattern.test(field.value); }, userPhone: function (field) { return phonePattern.test(field.value); }, userCard: function (field) { return cardPattern.test(field.value); } } let isMistake = false; for (let i = 0; i < form.elements.length - 1; i++) { const field = form.elements[i]; const validator = validations[field.name]; if (validator && !validator(field)) { field.classList.add('error'); isMistake = true; } else { field.classList.remove('error'); } } return isMistake; } function handlerSaveClick(event) { const userId = event.target.getAttribute('data-id'); const form = event.target.parentNode; const users = JSON.parse(localStorage.getItem('users')); const isMistake = validate(form); const isUniqId = checkUniqIdForUpdate(form, users, userId); if (!isMistake && isUniqId) { users.find(function (user) { if (user.id === userId) { user.id = form.elements.userId.value; user.name = form.elements.userName.value; user.age = form.elements.userAge.value; user.mail = form.elements.userMail.value; user.phone = form.elements.userPhone.value; user.card = form.elements.userCard.value; } }); localStorage.setItem('users', JSON.stringify(users)); showElementBlock(users); } } function checkUniqIdForUpdate(form, users, userId) { let isUniqId = true; const formIdValue = form.elements.userId.value; users.find(function (user) { if (formIdValue === user.id && formIdValue !== userId) { isUniqId = false; form.elements.userId.classList.add('error'); } }); return isUniqId; } function handleDoNotConfirmRemoveClick() { appStart(); } function handleConfirmRemoveClick(event) { const objId = event.target.getAttribute('data-id'); const objName = event.target.name; const objs = JSON.parse(localStorage.getItem(objName)); const newObjs = []; objs.find(function (obj) { if (obj.id !== objId) { newObjs.push(obj); } }); localStorage.setItem(objName, JSON.stringify(newObjs)); showElementBlock(newObjs); } function checkElementToRemove(id) { const elem = document.getElementById(id); if (elem) { elem.remove(); } } function showObjEditForm(user) { const wrap = document.getElementById('wrapper'); const EditUserTitle = createElement('h2', [{name: 'id', value: 'view-user-title'}], user.name + '`s Edit Form'); const form = createFormForObj(EditUserTitle, user.id, handlerSaveClick); setFormFields(form, user); wrap.appendChild(form); } function createInput(name) { const inputField = document.createElement('input'); inputField.type = 'text'; inputField.setAttribute('name', name); return inputField; } function createElement(element, attributes, innerHTML) { const newElement = document.createElement(element); if (attributes) { for (let i = 0; i < attributes.length; i++) { newElement.setAttribute(attributes[i].name, attributes[i].value); } } if (innerHTML) { newElement.innerHTML = innerHTML; } return newElement; } <file_sep>/src/hw18/js/app.js const url = 'answers.json'; const startSendButtonListener = () => { $('#send-btn').click(sendButtonListener); } const intervalForGoodBue = setInterval(() => { const rnd = rand(1, 100); if (rnd > 50 && rnd < 55) { const textField = $('#text-field'); const wrap = $('#wrapper'); goodBue(textField, wrap); clearInterval(intervalForGoodBue); } }, 3000); const sendButtonListener = () => { const textField = $('#text-field'); const message = textField.val(); textField.val(''); const wrap = $('#wrapper'); const userBlock = $('<div/>', {text: message}).addClass('user-block'); if (!message) { return; } else if (message === 'My watch has ended') { goodBue(textField, wrap, userBlock); clearInterval(intervalForGoodBue); return; } userBlock.appendTo(wrap); wrap.stop().animate({ scrollTop: wrap[0].scrollHeight }, 800); startBot().then(block => { wrap.append(block); }); } const startBot = async () => { const messages = await fetch('answers.json') .then(response => response.json()); return await createAnswer(messages); } const createAnswer = messages => { const wrap = $('#wrapper'); return new Promise(done => { const botBlock = $('<div/>').addClass('bot-block'); setTimeout(() => { done(botBlock.text(messages[rand(1, 10)])); wrap.stop().animate({ scrollTop: wrap[0].scrollHeight }, 800); }, rand(1, 5) * 1000); return botBlock; }); } const rand = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min; } const goodBue = (textField, wrap, userBlock) => { textField.attr('readonly', true); $('#send-btn').prop('disabled', true); if (userBlock) { userBlock.text('My watch has ended').appendTo(wrap); wrap.stop().animate({ scrollTop: wrap[0].scrollHeight }, 800); } setTimeout(() => { fetch(url) .then(res => res.json()) .then(messages => { $('<div/>', {text: messages[0]}).addClass('bot-block').appendTo(wrap); wrap.stop().animate({ scrollTop: wrap[0].scrollHeight }, 800); }); }, 2000); } startSendButtonListener(); <file_sep>/src/hw16/js/functions.js 'use strict'; const start = tasks => { if (!localStorage.getItem('tasks')) { localStorage.setItem('tasks', JSON.stringify(tasks)); } showTasksBoard(); } const showTasksBoard = () => { const wrap = $('#wrapper').html(''); $('<button/>', {id: 'create-task', text: 'Create new Task'}).click(createNewTask).appendTo(wrap); $(wrap).append($('<div/>', {id: 'tasks'})); const tasks = JSON.parse(localStorage.getItem('tasks')); sendRequest(tasks); } const sendRequest = tasks => { fetch('priorities-and-statuses.json') .then(res => { return res.json(); }) .then(res => { tasks.forEach(task => createTaskBlock(task, res)); }); } const createNewTask = () => { const wrap = $('#wrapper').html(''); const newBlock = $('<div/>', {id: 'new-block'}).appendTo(wrap); fetch('priorities-and-statuses.json') .then(res => { return res.json(); }) .then(props => { createForm(newBlock, 'New', 'Create new Task'); setSelects(null, props); $('<button/>', {id: 'new-btn-save', text: 'Save'}).click(saveNewTask).appendTo(newBlock); }) } const saveNewTask = () => { const tasks = JSON.parse(localStorage.getItem('tasks')); let maxId = 0; tasks.forEach(task => { if (task.taskId > maxId) { maxId = task.taskId; } }); const taskName = $('#task-name').val(); const statusId = parseInt($('#select-status option:selected').val()); const priorityId = parseInt($('#select-priority option:selected').val()); const newTask = new TodoTask(++maxId, taskName, statusId, priorityId); tasks.push(newTask); localStorage.setItem('tasks', JSON.stringify(tasks)); showTasksBoard(); } const createTaskBlock = (task, props) => { const {taskId, taskName, statusId, priorityId} = task; const taskBlock = $('<div/>', {'data-id': taskId}).addClass('task'); $('<h5/>', {text: 'Task Name'}).appendTo(taskBlock); $('<input/>', {type: 'text', value: taskName}).attr('readonly', true).addClass('input').appendTo(taskBlock); setFieldOfTask(statusId, priorityId, taskBlock, props); const buttonsOfTaskBlock = $('<div/>').addClass('taskButtons').css('display', 'flex').appendTo(taskBlock); $('<button/>', { 'data-id': taskId, text: 'Edit', 'data-name': taskName }).click(editTask).appendTo(buttonsOfTaskBlock); $('<button/>', { 'data-id': taskId, text: 'Remove', 'data-name': taskName }).click(removeTask).appendTo(buttonsOfTaskBlock); $('#tasks').append(taskBlock); } const setFieldOfTask = (statusId, priorityId, taskBlock, props) => { let statusName = 'Not Defined'; let priorityName = 'Not Defined'; $('<h5/>', {text: 'Task Status'}).appendTo(taskBlock); const inpSt = $('<input/>', {type: 'text'}).attr('readonly', true).addClass('input').appendTo(taskBlock); $('<h5/>', {text: 'Task Priority'}).appendTo(taskBlock); const inpPr = $('<input/>', {type: 'text'}).attr('readonly', true).addClass('input').appendTo(taskBlock); props.statuses.forEach(item => { if (item.id === statusId) { statusName = item.status; } }); props.priorities.forEach(item => { if (item.id === priorityId) { priorityName = item.priority; } }); $(inpSt).val(statusName); $(inpPr).val(priorityName); } const removeTask = event => { const id = event.target.dataset.id; const name = event.target.dataset.name; const questionBlock = $('#wrapper').html('').append($('<div/>', {id: 'question-block'})); $('<h2/>', {text: `Remove task ${name}`}).appendTo(questionBlock); $('<button/>', {'data-id': id, text: 'Yes'}).click(confirmRemove).appendTo(questionBlock); $('<button/>', {'data-id': id, text: 'No'}).click(notConfirmRemove).appendTo(questionBlock); } const notConfirmRemove = () => { showTasksBoard(); } const confirmRemove = event => { const id = parseInt(event.target.dataset.id); const tasks = JSON.parse(localStorage.getItem('tasks')); const tasksWithOutRemoved = []; tasks.find(function (task) { if (task.taskId !== id) { tasksWithOutRemoved.push(task); } }) localStorage.setItem('tasks', JSON.stringify(tasksWithOutRemoved)); showTasksBoard(); } const editTask = event => { const id = parseInt(event.target.dataset.id); const wrapper = $('#wrapper'); wrapper.html('').append($('<div/>', {id: 'edit-block'})); const tasks = JSON.parse(localStorage.getItem('tasks')); const task = tasks.find(task => { if (task.taskId === id) { return task; } }); createFormForEditAndSetFields(task, '#edit-block'); } const createFormForEditAndSetFields = (task, block) => { const {taskName: myTaskName, taskId: myTaskId} = task; fetch('priorities-and-statuses.json') .then(res => { return res.json(); }) .then(props => { createForm(block, 'Edit', `Edit task ${myTaskName}`); $('#task-name').val(myTaskName); setSelects(task, props); $('<button/>', {id: 'edit-btn-save', 'data-id': myTaskId, text: 'Save'}).click(saveTask).appendTo(block); }) } const createForm = (block, action, title) => { $('<h2/>', {text: title}).appendTo(block); $('<div/>', {text: 'Task Name'}).appendTo(block); $('<input/>', {type: 'text', id: 'task-name'}).appendTo(block); $('<div/>', {text: 'Task Status'}).appendTo(block); $('<select/>', {id: 'select-status'}).appendTo(block); $('<div/>', {text: 'Task Priority'}).appendTo(block); $('<select/>', {id: 'select-priority'}).appendTo(block); } const setSelects = (task, props) => { const statusSelector = $('#select-status'); const prioritySelector = $('#select-priority'); props.statuses.forEach(status => { const option = $('<option/>', {value: status.id, text: status.status}) statusSelector.append(option); if (task && task.statusId === status.id) { $(option).attr('selected', true); } }); props.priorities.forEach(priority => { const option = $('<option/>', {value: priority.id, text: priority.priority}); prioritySelector.append(option); if (task && task.priorityId === priority.id) { $(option).attr('selected', true); } }) } const saveTask = event => { const id = parseInt(event.target.dataset.id); const tasks = JSON.parse(localStorage.getItem('tasks')); tasks.find(task => { if (task.taskId === id) { task.taskName = $('#task-name').val(); task.statusId = parseInt($('#select-status').val()); task.priorityId = parseInt($('#select-priority').val()); } }); localStorage.setItem('tasks', JSON.stringify(tasks)); showTasksBoard(); } start(tasks);<file_sep>/src/hw14/js/Company.js function Company(id, name, cars, balance) { this.id = id; this.name = name; this.cars = cars; this.balance = balance; }<file_sep>/src/hw14/js/Car.js function Car(id, model, isInGarage, price, owner) { this.id = id; this.model = model; this.isInGarage = isInGarage; this.price = price; this.owner = owner; }<file_sep>/src/hw10/js/app.js 'use strict'; let selectedCategory; let selectedProduct; showCategories();
0b0faafa528f2db8459bffad47cd10d9464db24c
[ "JavaScript", "Markdown" ]
14
JavaScript
rickdemonn/Hillel-Front-End
2b9558723696c08220b4d5ababaab5648453f204
5dc23788e528a2f310624a29335d02beff6b9a1e
refs/heads/master
<repo_name>dangconnie/portfolio-react<file_sep>/src/Nav/navbar.js // import React, { Component } from 'react'; // class Nav extends Component{ // render(){ // return( // <div> // Nav // </div> // ) // } // } // export default Nav; // <ul id="sidebar" className="nav nav-pills nav-stacked"> // <li className="active"><a href="#"><span className="glyphicon glyphicon-off"></span> Overview</a></li> // <li><a href="#"><span className="glyphicon glyphicon-user"></span> Profile</a></li> // <li><a href="#"><span className="glyphicon glyphicon-lock"></span> Access</a></li> // <li><a href="#"><span className="glyphicon glyphicon-envelope"></span> Message</a></li> // <li><a href="#"><span className="glyphicon glyphicon-list"></span> Schedule</a></li> // <li><a href="#"><span className="glyphicon glyphicon-signal"></span> Statistics</a></li> // <li><a href="#"><span className="glyphicon glyphicon-comment"></span> Chat</a></li> // <li><a href="#"><span className="glyphicon glyphicon-earphone"></span> Contacts</a></li> // </ul><file_sep>/src/App.js import React, { Component } from 'react'; import './App.css'; import About from './About/about.js'; import Contact from './Contact/contact.js'; import Projects from './Projects/projects.js'; import Skills from './Skills/skills.js'; // import Nav from './Nav/navbar.js'; import Home from './Home/home.js'; class App extends Component { render(){ return( <div> <Home /> <About /> <Projects /> <Skills /> <Contact /> </div> ) } } export default App; <file_sep>/src/Contact/contact.js import React, {Component} from 'react'; // import './contact.css'; // import { IndexLink, Link } from 'react-router' class Contact extends Component{ render(){ return( <div className="col-sm-12 contact"> <h2>This is contact section</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquet sem ut massa aliquet molestie. Suspendisse eu nunc sem. Donec at nisl mauris. Morbi feugiat ligula id nisl lobortis, et fermentum velit faucibus. Etiam pretium elementum metus in consequat. Curabitur interdum lectus ut velit consequat porta. In porta lorem non quam tristique, vel pharetra massa dapibus. Donec nec lectus venenatis, mollis arcu sed, interdum quam. Curabitur gravida molestie ultrices. Donec dictum nibh eu neque aliquet, at volutpat massa malesuada. Cras vel nunc tristique elit vehicula fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut molestie turpis ex, vel scelerisque augue consectetur sit amet. Fusce iaculis ac ipsum eu malesuada. Etiam sodales ut diam in accumsan.</p> </div> ) } } export default Contact;<file_sep>/src/About/about.js import React, { Component } from 'react'; // import { IndexLink, Link } from 'react-router' class About extends Component{ render(){ return( <div className="about"> <h1>about me section </h1> <div className="col-sm-6 backgroundInfo"> <h3>Background</h3> <p></p> </div> <div className="col-sm-6 webDevInfo"> <h3>Web Development</h3> <p>I'm an aspiring developer. I want a chance to learn and improve my skills. I know I'm in the right field because the learning is neverending. </p> </div> </div> ) } } export default About; <file_sep>/src/Projects/projects.js import React, {Component} from 'react'; import '../App.css'; import storyTranslate from '../img/storyTranslatemini.png'; import upd8ed from '../img/upd8ed2.png'; import movieApp from '../img/movie.png'; import Button from 'react-bootstrap/lib/Button'; import FontAwesome from 'react-fontawesome'; class Projects extends Component{ render(){ return( <div className="projects-wrapper"> <h2>Projects</h2> <div className="col-sm-12 project1"> <div className="col-sm-6 screenshot"> <img src={storyTranslate} alt="" /> </div> <div className="col-sm-6 description"> <h2>Translation Station</h2> <p>The Translation Station was built for <a href="https://newstorycharity.org/" target="__blank">New Story</a> administrators to upload, translate and review videos for their organization. New Story builds homes and communities for those in need providing a fresh approach to philanthropy. <strong> This is a full stack app designed for internal use only. The demo site username and password are "<PASSWORD>" and "<PASSWORD>".</strong></p> <Button href="http://dangconnie.com/new_story/#/login" target="__blank">Demo</Button> <Button href="https://github.com/dangconnie/Story-Translate" target="__blank" className="repoGithubLogo"><FontAwesome name='github'size="lg"/> Repo</Button> <hr /> <div className="eachSkill">HTML/CSS</div> <div className="eachSkill">Sass/Materialize</div> <div className="eachSkill">Javascript</div> <div className="eachSkill">Angular</div> <div className="eachSkill">jQuery</div> <div className="eachSkill">Responsive Design</div> <div className="eachSkill">Agile Development</div> </div> </div> <div className="col-sm-12 project1"> <div className="col-sm-6 description"> <h2>Upd8ed</h2> <p>Upd8ed is a news aggregator built in React as a frontend project. This app pulls the latest business, entertainment, global, sports news from a variety of sources for the viewer from different APIs. </p> <Button href="http://dangconnie.com/upd8ed/#/" target="__blank">Demo</Button> <Button href="https://github.com/mason0958/News-Aggregator" target="__blank" className="repoGithubLogo"><FontAwesome name='github'size="lg"/> Repo</Button> <hr /> <div className="eachSkill">HTML/CSS</div> <div className="eachSkill">Javascript</div> <div className="eachSkill">React</div> <div className="eachSkill">jQuery</div> <div className="eachSkill">Node.js</div> <div className="eachSkill">News API</div> <div className="eachSkill">OpenWeatherMap API</div> <div className="eachSkill">Yahoo! Finance API</div> <div className="eachSkill">Responsive Design</div> <div className="eachSkill">Agile Development</div> </div> <div className="col-sm-6 screenshot"> <img src={upd8ed} alt="" /> </div> </div> <div className="col-sm-12 project1"> <div className="col-sm-6 screenshot"> <img src={movieApp} alt="" /> </div> <div className="col-sm-6 description"> <h2>Popcorn Bits Cinema</h2> <p> Info about app</p> <Button href="http://dangconnie.com/movie-app/" target="__blank">Demo</Button> <Button href="https://github.com/dangconnie/movie-app" target="__blank" className="repoGithubLogo"><FontAwesome name='github'size="lg"/> Repo</Button> <hr /> <div className="eachSkill">HTML/CSS</div> <div className="eachSkill">Javascript</div> <div className="eachSkill">jQuery</div> <div className="eachSkill">Bootstrap</div> <div className="eachSkill">The Movie Database API</div> </div> </div> </div> ) } } export default Projects;
009bc7abc1622b31612212d5112ec4d5520db13d
[ "JavaScript" ]
5
JavaScript
dangconnie/portfolio-react
97ba92dbd06bb031b0295d42c4939aa2cf72bc29
4fdb09aaa3f9bef6486e581076b1803903e587fc
refs/heads/master
<repo_name>types140/types140.github.io<file_sep>/modules/apis.js Object.defineProperty(Object.prototype, 'loadMissions',{ value : function(){ if (!window.sessionStorage.hasOwnProperty('aMissions') || JSON.parse(window.sessionStorage.aMissions).lastUpdate < (new Date().getTime() - 5 * 1000 * 60)) fetch('/einsaetze.json') .then(res => res.json()) .then(data => window.sessionStorage.setItem('aMissions',JSON.stringify({lastUpdate: new Date().getTime(),value: data}))); return JSON.parse(sessionStorage.aMissions).value; }, enumerable : false });
4fdfc9ddecee7de30284a042ae724325ea706b58
[ "JavaScript" ]
1
JavaScript
types140/types140.github.io
fe7706d872d4be29b0b79a73e689332563434bd6
61a891976ea547f2bce77adda347124b4a7f7eca
refs/heads/master
<repo_name>challengezhou/repository<file_sep>/testCpp/hellos.h #ifndef _HELLO_S_H #define _HELLO_S_H void printS(char *str); #endif <file_sep>/testCpp/testpointer.cpp #include <iostream> using namespace std; typedef string* pstring; int main(){ string s = "hello world"; const size_t arr_sz = 5; int int_arr[arr_sz] = {0,1,2,3,4}; string *sp = &s; cout << "string : " << *sp <<endl; for(int *pbegin = int_arr,*pend = int_arr+arr_sz;pbegin!=pend;pbegin++){ cout << *pbegin << endl; } return 0; } <file_sep>/testC/tstructarrpointer.c #include <stdio.h> struct stu{ int num; char *name; char sex; float score; }boy[5]={ {101,"zhang",'m',2.3}, {102,"lisi",'f',22.3}, {103,"wangwu",'f',1012.3}, {104,"taihang",'m',212.3}, }; main(){ struct stu *ps; printf("Num\tName\tSex\tScore\t\n"); for(ps=boy;ps<boy+4;ps++){ printf("%d\t%s\t\t%c\t%f\t\n",ps->num,ps->name,ps->sex,ps->score); } } <file_sep>/testCpp/testusing.cpp #include <iostream> using namespace std; int main(){ string s; //cin >> s; //cout << s << endl; //return 1; while(getline(cin,s)){ cout << "input is " <<s << endl; } cout << "s.empty() = " << s.empty() << endl; cout << "s.size() = " << s.size() << endl; return 0; } <file_sep>/testCpp/associativecontainer/multicon.cpp #include <map> #include <set> #include <iostream> using namespace std; int main(){ multimap<string,string> author; author.insert(make_pair("zhoujian","diyibenshu")); author.insert(make_pair("zhoujian","di2222benshu")); author.insert(make_pair("zhoujian","diyibenshu")); author.insert(make_pair("zhangsan","diyibenshu")); author.insert(make_pair("zhangsan","diyibenshu")); author.insert(make_pair("lisi","diyibenshu")); author.insert(make_pair("lisi","diyibe")); author.insert(make_pair("lisi","diy")); string search_item1("zhoujian"); //key to search cout << "find() and count() to show the map" << endl; multimap<string,string>::size_type cous = author.count(search_item1); multimap<string,string>::iterator iter = author.find(search_item1); for(multimap<string,string>::size_type ix = 0;ix!=cous;++ix,++iter){ cout << search_item1 << " : " << iter->second << endl; } string search_item2("zhangsan"); multimap<string,string>::iterator beg = author.lower_bound(search_item2); multimap<string,string>::iterator end = author.upper_bound(search_item2); cout << "lower and upper_bound to show the map" << endl; while(beg!=end){ cout << search_item2 << " : " << beg->second << endl; ++beg; } string search_item3("lisi"); cout << "equal_range() to show the map" << endl; typedef multimap<string,string>::iterator author_it; pair<author_it,author_it> pos = author.equal_range(search_item3); while(pos.first!=pos.second){ cout << search_item3 << " : " << pos.first->second << endl; ++pos.first; } //cout << author.size() << endl; return 0; } <file_sep>/testCpp/associativecontainer/textquery/TextQuery.h #include <vector> #include <set> #include <map> #include <fstream> class TextQuery{ public: typedef std::vector<std::string>::size_type line_no; void read_file(std::ifstream &infile){ store_file(infile); build_map(); } std::set<line_no> run_query(const std::string&) const; std::string text_line(line_no) const; private: void store_file(std::ifstream&); void build_map(); std::vector<std::string> lines_of_text; std::map<std::string,std::set<line_no> > word_map; }; <file_sep>/testCpp/testio.cpp #include <iostream> #include <stdexcept> using namespace std; int main(){ int ival; while(cin >> ival,!cin.eof()){ if(cin.bad()){ throw runtime_error("IO Stream Corrupted!"); } if(cin.fail()){ cerr << "bad data,try again" << endl; cin.clear(istream::goodbit); cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); continue; } } } <file_sep>/testCpp/testwhile.cpp #include <iostream> int main(){ int value,sum=0; std::cout << "input numbers:" << std::endl; while(std::cin >> value){ sum+=value; } std::cout << "The sum of input number is " << sum; } <file_sep>/testCpp/associativecontainer/testmap.cpp #include <iostream> #include <map> using namespace std; int main(){ map<string,int> wordcount; //wordcount["test"]=1; string word; while(cin >> word){ pair<map<string,int>::iterator,bool> ret = wordcount.insert(make_pair(word,1)); if(!ret.second){ ++ret.first->second; } } map<string,int>::iterator iter = wordcount.begin(); for(iter;iter!=wordcount.end();++iter){ cout << "word----" << iter->first << " count---" << iter->second << endl; } return 0; } <file_sep>/testCpp/testbitset.cpp #include <iostream> #include <bitset> using namespace std; int main(){ string strval("1110110001"); bitset<32> bitvec(strval,3,3); //包括strval[3],后3个 ==110 bitvec[2]; //访问位置2的二进制位 cout << "注意高阶位和低阶位的问题 :bitvec[2]=" << bitvec[2] <<endl; bitvec.any(); //存在某位为1 bitvec.none(); //不存在某位为1 //size_t类型 bitvec.count(); //为1的二进制位的个数 bitvec.size(); //二进制位的个数 bitvec.test(2); //在2的位置上的位是否为1 bitvec.set(); //位全设为1 cout << "set()=" << bitvec <<endl; bitvec.set(2); //位置2设为1 cout << "set(2)=" << bitvec <<endl; bitvec.reset(); //全设为0 cout << "reset()=" << bitvec <<endl; bitvec.reset(2); //位置2设为0 cout << "reset(2)=" << bitvec <<endl; bitvec.flip(); //全部取反 cout << "flip()=" << bitvec <<endl; bitvec.flip(2); //位置2取反 cout << "flip(2)=" << bitvec <<endl; bitvec.to_ulong(); //转化为无符号long cout << "to_ulong()=" << bitvec.to_ulong() <<endl; //输出到os流 return 0; } <file_sep>/testCpp/sequentialcontainer/container.cpp #include <vector> #include <list> #include <deque> #include <string> #include <iostream> using namespace std; int main(){ char *ia[] = {"311","1222","533","344","455"}; vector<string> svec(ia+1,ia+3); //vector<char *> cvec(svec); vector<string>::iterator iter = svec.begin(); //vector<char *>::iterator iterc = cvec.begin(); for(iter;iter!=svec.end();++iter){ cout << "string vec is " << *iter << endl; } return 0; } <file_sep>/testC/mainargs.c #include <stdio.h> main(int argc,char *argv[]){ printf("argc=%d\n",argc); printf("first args is %s\n",*argv); printf("last args is %s\n",*(argv+argc-1)); while(argc-->1){ printf("%s\n",*++argv); } } <file_sep>/testCpp/fileio.cpp #include <iostream> #include <fstream> using namespace std; int main(){ ifstream infile; infile.open("e:/test.txt"); if(!infile){ cout << "file open error ,check the filename and path" << endl; return -1; } string s; while(getline(infile,s),!infile.eof()){ cout << s << endl; } infile.close(); infile.clear(); ofstream out; out.open("e:/test.txt",ofstream::app); string ss("\nwokaoshenm what't this\n"); out << ss; out.close(); out.clear(); return 0; } <file_sep>/testC/tfile.c #include <stdio.h> main(){ FILE *fp; fp=fopen("E:\\test.txt","r"); if(fp==NULL){ printf("error open file\n"); exit(0); } char c=fgetc(fp); while(c!=EOF){ putchar(c); c=fgetc(fp); } fclose(fp); } <file_sep>/testCpp/TestClass/Persion.cpp #include "Persion.h" using namespace std; string Persion::getName() const{ return Persion::name; } string Persion::getAddress() const{ return Persion::address; } <file_sep>/testCpp/associativecontainer/textquery/TextQuery.cpp #include "TextQuery.h" #include <map> #include <sstream> #include <vector> #include <set> using namespace std; void TextQuery::store_file(ifstream &infile){ string str; while(getline(infile,str)){ lines_of_text.push_back(str); } } void TextQuery::build_map(){ for(line_no line_num = 0;line_num!=lines_of_text.size();++line_num){ istringstream sin(lines_of_text[line_num]); string word; while(sin>>word){ word_map[word].insert(line_num); } } } set<TextQuery::line_no> TextQuery::run_query(const string &str) const{ map<string,set<line_no> >::const_iterator loc = word_map.find(str); if(loc==word_map.end()){ return set<line_no>(); }else return loc->second; } string TextQuery::text_line(const line_no ln) const{ if(ln<lines_of_text.size()){ return lines_of_text[ln]; } return "lines out of range"; } <file_sep>/testCpp/myfirst.cpp //myfirst.cpp -- display a message #include <iostream> int main(){ //using namespace std; //std::cout << /* "*/; int v1,v2; std::cout << "please input two number:" << std::endl; std::cin >> v1 >> v2; std::cout << "The sum of " << v1 << " and " <<v2 <<" is " << v1+v2 << std::endl; return 0; //echo %errorlevel% } <file_sep>/testCpp/test.cpp #include <iostream> using namespace std; int main(){ cout << "input two number:" << endl; int i,j; cin >> i >> j; swap (i,j); cout << "after swap : " << i << " , " << j << endl; } void swap(int &v1,int &v2){ int temp = v2; v2=v1; v1=v2; } <file_sep>/testCpp/teststring.cpp #include <iostream> #include <sstream> using namespace std; int main(){ string s1; string s2; char c3; cout << "input a string : "; cin >> s1; cout << "you input string is " << s1 << endl; for(string::size_type ix=0;ix!=s1.size();ix++){ cout << "s1[" << ix << "] = " << s1[ix] << endl; } cout << "string index could be the leftvalue " << endl << "like replace a character of string " << endl << "input a index to replaced and a character separate by whitespace:" <<endl; cin >> s2 >> c3; int i; stringstream ss(s2); ss >> i; s1[i] = c3; cout << "after replace : " << s1; return 0; } <file_sep>/testC/malloc.c #include <stdio.h> #include <stdlib.h> struct stu{ int num; char *name; }; main(){ struct stu *ps; ps=(struct stu*)malloc(sizeof(struct stu)); ps->num=11; ps->name="zhangsan"; printf("Num=%d\nName=%s\n",ps->num,ps->name); free(ps); } <file_sep>/testC/swap.c #include <stdio.h> main(){ int i=11,j=23; void swap(int *,int *); swap(&i,&j); printf("after swap %d %d",i,j); } void swap(int *a,int *b){ int temp; temp=*b; *b=*a; *a=temp; } <file_sep>/testC/test.c #include <stdio.h> #define PRICE 30 main(){ int num,total; num = -327671; char c[] = "ĪŅ"; float a = 33333.33333; float b = 33333333.333333333333333; //total=num*PRICE; //printf("total=%d",total); scanf("%d%d",&num,&total); printf("%d\n",num); printf("%d",total); } <file_sep>/testCpp/main.c #include <stdio.h> #include "hellos.h" main(){ char *text = "Hello World!"; printS(text); } <file_sep>/testCpp/associativecontainer/wordtrans.cpp #include <iostream> #include <fstream> #include <sstream> #include <map> #include <stdexcept> using namespace std; int main(int argc,char **argv){ ifstream &openfile(ifstream &,const char *); //throw runtime_error("error interupt"); if(argc!=2){ cout << "parameters error please run like \"a file1 file2\"" << endl; //throw runtime_error("wrong number of arguments!"); return 0; } map<string,string> maps; string key,value; ifstream mapfile; ifstream infile; char *file1 = argv[1]; char *file2 = argv[2]; if(!openfile(mapfile,string("filemap").c_str())){ throw runtime_error("map file does not exist!"); } while(mapfile >> key >> value){ maps.insert(make_pair(key,value)); } if(!openfile(infile,file1)){ throw runtime_error("first file open failed"); } string line; while(getline(infile,line)){ istringstream iss(line); string word; bool firstword = true; while(iss >> word){ map<string,string>::iterator map_it = maps.find(word); if(map_it!=maps.end()){ word = map_it->second; } if(firstword){ firstword = false; }else{ cout << " "; } cout << word; } cout << endl; } return 0; } ifstream &openfile(ifstream &infile,const char *filename){ infile.close(); infile.clear(); infile.open(filename); return infile; } <file_sep>/testCpp/template/functemp.cpp #include <iostream> using namespace std; template <typename T1,typename T> T1 compare(const T &v1,const T &v2){ if(v1>v2) return 1; if(v1<v2) return -1; return 0; } int main(){ string s1 = "abc"; string s2 = "ab"; cout << "int compare<int>(1,2) " << compare<int>(1,2) << endl; //"abc" is const char[] not string, so if the size diffrent ,the two arguments will not simple type cout << "str conpare<int>(abc,ab) " << compare<int>(s1,s2) << endl; return 0; } <file_sep>/testCpp/lifecycle/Tlife.cpp #include <iostream> #include "Tlife.h" using namespace std; int Tlife::getI() const{ return i; } <file_sep>/testCpp/associativecontainer/testset.cpp #include <iostream> #include <set> #include <vector> using namespace std; int main(){ vector<int> ivec; for(vector<int>::size_type i=0;i!=10;++i){ ivec.push_back(i); ivec.push_back(i); } set<int> iset(ivec.begin(),ivec.end()); cout << ivec.size() << endl; cout << iset.size() << endl; } <file_sep>/testCpp/testarray.cpp #include <iostream> using namespace std; int main(){ const unsigned array_size = 3; int staff_size=27; //const unsigned sz = get_size(); //char vals[sz]; //运行期才能确认值的常量不可以定义数组维数 int ia[array_size]={0,1,2}; char fileTable[array_size+1]; //常量表达式可以 char str[]="test"; //长度为5,注意\0 //fileTable=str 不能直接赋值和复制,类型长度相同也不行 return 0; } <file_sep>/testC/tstruct.c #include <stdio.h> #define STU struct stu main(){ STU{ int num; char *name; char *sex; float score; }; STU boy1,boy2; boy1.name="zhangsan"; boy1.num=10; char c[100]; boy1.sex=c; printf("input sex and score:\n"); scanf("%s %f",c,&boy1.score); boy2=boy1; printf("Number = %d,Name = %s\n",boy2.num,boy2.name); printf("Sex = %s,Score = %f\n",boy2.sex,boy2.score); } <file_sep>/testCpp/tsstream.cpp #include <sstream> #include <iostream> using namespace std; int main(){ int val1=512,val2=1024; ostringstream format_str; format_str << "val1: " << val1 << " val2: " << val2; cout << "ostringstream format_str: " << format_str.str() << endl; //string str = "val1: 512\nval2:1024"; istringstream input_str(format_str.str()); string dump; input_str >> dump >> val2 >> dump >> val1; cout << "istringstream input_str val1 in val2 val1= " << val1 << "\n val2= " << val2 << endl; return 0; } <file_sep>/testCpp/genericalgorithm/insert_iterator.cpp #include <iterator> #include <iostream> #include <list> using namespace std; int main(){ list<int> ilst1,ilst2,ilst3; for(int i=0;i!=4;++i){ ilst1.push_front(i); } cout << " push_front "; for(list<int>::iterator iter = ilst1.begin();iter!=ilst1.end();++iter){ cout << *iter << " "; } cout << endl; copy(ilst1.begin(),ilst1.end(),front_inserter(ilst2)); cout << " front_inserter "; for(list<int>::iterator iter = ilst2.begin();iter!=ilst2.end();++iter){ cout << *iter << " "; } cout << endl; copy(ilst1.begin(),ilst1.end(),inserter(ilst3,ilst3.begin())); cout << " inserter "; for(list<int>::iterator iter = ilst3.begin();iter!=ilst3.end();++iter){ cout << *iter << " "; } cout << endl; return 0; } <file_sep>/testC/testLoop.c #include <stdio.h> main(){ int i,sum=0; i=1; loop: if(i<100){ sum+=i; i++; goto loop; } printf("sum=%d",sum); } <file_sep>/testCpp/hellos.c #include <stdio.h> #include "hellos.h" void printS(char *str){ printf("print in static way:%s",str); } <file_sep>/testCpp/lifecycle/test.cpp #include <iostream> #include "Tlife.h" using namespace std; ostream &operator<<(ostream &os,const Tlife &t){ os << t.i; return os; } Tlife t(1); Tlife *test(){ Tlife *t = new Tlife(3); Tlife tttt(4); //delete(t); return t; } int main(){ Tlife tt(2); Tlife *ttt = test(); cout << *ttt << endl; delete(ttt); return 0; } <file_sep>/testC/tpointer.c #include <stdio.h> main(){ void swap(int*,int*); printf("input two number!\n"); int a,b; scanf("%d %d",&a,&b); if(a<b) swap(&a,&b); printf("%d,%d\n",a,b); } void swap(int *a,int *b){ int temp; temp=*a; *a=*b; *b=temp; } <file_sep>/CodeTest/SQLBK/scott.sql create table EMP ( EMPNO int PRIMARY KEY, ENAME VARCHAR(10), JOB VARCHAR(9), MGR int, HIREDATE DATE, SAL DECIMAL(7,2), COMM DECIMAL(7,2), DEPNO int ); CREATE TABLE Depth( DEPTNO int, DNAME VARCHAR(14), LOC VARCHAR(13) ); CREATE TABLE Salgrade ( GRADE DECIMAL, LOSAL DECIMAL, HISAL DECIMAL ); CREATE TABLE Bonus ( ENAME VARCHAR(10), JOB VARCHAR(9), SAL DECIMAL, COMM DECIMAL ); INSERT into Depth VALUES(10,'ACCOUNTING','NEW YORK'); INSERT into Depth VALUES(20,'RESEARCH','DALLAS'); INSERT into Depth VALUES(30,'SALES','CHICAGO'); INSERT into Depth VALUES(40,'OPERATIONS','BOSTON'); SELECT * FROM DEPTH; INSERT into EMP VALUES(7369,'SMITH','CLERK',7902,'1980-12-17',800,null,20); INSERT into EMP VALUES(7499,'ALLEN','SALESMAN',7698,'1981-2-20',1600,300,30); INSERT into EMP VALUES(7521,'WARD','SALESMAN',7698,'1981-2-22',1250,500,30); INSERT into EMP VALUES(7566,'JONES','MANAGER',7839,'1981-4-2',2975,NULL,20); INSERT into EMP VALUES(7654,'MARTIN','SALESMAN',7698,'1981-9-28',1250,1400,30); INSERT into EMP VALUES(7698,'BLAKE','MANAGER',7839,'1981-5-1',2850,NULL,30); INSERT into EMP VALUES(7782,'CLARK','MANAGER',7839,'1981-6-9',2450,NULL,10); INSERT into EMP VALUES(7839,'KING','PRESIDENT',NULL,'1981-11-17',5000,NULL,10); INSERT into EMP VALUES(7844,'TURNER','SALESMAN',7698,'1981-9-8',1500,0,30); INSERT into EMP VALUES(7900,'JAMES','CLERK',7698,'1981-12-3',950,NULL,30); INSERT into EMP VALUES(7902,'FORD','ANALYST',7566,'1981-12-3',3000,NULL,20); INSERT into EMP VALUES(7934,'MILLER','CLERK',7782,'1982-1-23',1300,NULL,10); select * from emp; INSERT into SALGRADE VALUES(1,700,1200); INSERT into SALGRADE VALUES(2,1201,1400); INSERT into SALGRADE VALUES(3,1401,2000); INSERT into SALGRADE VALUES(4,2001,3000); INSERT into SALGRADE VALUES(5,3001,9999); select * from salgrade<file_sep>/testCpp/associativecontainer/textquery/test.cpp #include <iostream> #include <fstream> #include "TextQuery.h" #include <set> using namespace std; int main(int argc,char **argv){ ifstream infile; ifstream &openfile(ifstream&,const char*); if(argc!=2||!openfile(infile,argv[1])){ cout << "arguments error or file open failed!" << endl; return 0; } TextQuery tq; tq.read_file(infile); while(true){ cout << "input word to search or 'q' to quit" << endl; string s; cin >> s; if(!cin||s=="q") break; set<TextQuery::line_no> locs = tq.run_query(s); set<TextQuery::line_no>::iterator it = locs.begin(); for(;it!=locs.end();++it){ cout << "\t(line " << (*it)+1 << ")" << tq.text_line(*it) << endl; } } cout << "end" << endl; } ifstream &openfile(ifstream &infile,const char *file_name){ infile.close(); infile.clear(); infile.open(file_name); return infile; } <file_sep>/javautils/TestBase64.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.commons.io.FileUtils; import sun.misc.BASE64Encoder; public class TestBase64{ public static void main(String[] args) throws Exception { // BASE64Encoder encoder = new BASE64Encoder(); // byte[] bs = getBytes("E:\\Picture\\Photos\\123.jpg"); // ByteBuffer bb = ByteBuffer.wrap(bs); // encoder.encodeBuffer(bb, System.out); String str = FileUtils.readFileToString(new File("E:\\temp.txt"),"utf-8"); new MobileBusinessServiceImpl().GenerateImage(str); } public static byte[] getBytes(String filePath) throws Exception{ byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } private ByteBuffer getByteBuffer(String fileName) { ByteBuffer bb = null; String path = getRealPath(); fileName = path+"../../"+"tidingsfilesuploadfolder/"+fileName; File file = new File(fileName); try { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] temp = new byte[1024]; int size = 0; while ((size = in.read(temp)) != -1) { out.write(temp, 0, size); } in.close(); byte[] bytes = out.toByteArray(); bb = ByteBuffer.wrap(bytes); } catch (Exception e) { e.printStackTrace(); } return bb; } private void generateFileByByteBuffer(ByteBuffer bb, String path, String fileName) { FileChannel writeChannel = null; path = getRealPath() + "../../" + path + "/" +fileName; System.out.println(path); File file = new File(path); try { writeChannel = new FileOutputStream(file, false).getChannel(); writeChannel.write(bb); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != writeChannel) writeChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } //toURI()处理路径中的空格,避免变成%20 private String getRealPath() { String path = ""; try { path = MobileBusinessServiceImpl.class.getClassLoader() .getResource("").toURI().getPath(); } catch (Exception e) { e.printStackTrace(); } return path; } }<file_sep>/testCpp/genericalgorithm/wordscount.cpp #include <iostream> #include <algorithm> #include <vector> #include <numeric> using namespace std; bool isShorter(const string &str1,const string &str2){ return str1.size()<str2.size(); } bool GT6(const string &str){ return str.size()>=6; } string make_plural(size_t size,const string &str1,const string &str2){ return (size==1)?str1:(str1+str2); } int main(){ string word; vector<string> words; while(cin >> word){ words.push_back(word); } sort(words.begin(),words.end()); vector<string>::iterator end_iter = unique(words.begin(),words.end()); words.erase(end_iter,words.end()); stable_sort(words.begin(),words.end(),isShorter); vector<string>::size_type cnt = count_if(words.begin(),words.end(),GT6); cout << cnt << " " << make_plural(cnt,"word","s") << " 6 character or longer!" << endl; } <file_sep>/testCpp/testnew.cpp #include <iostream> using namespace std; int main(){ //数组动态分配 int *ss = new string[10];//动态分配的数组 元素为类类型,默认构造方法 int *is = new int[10]; //内置类型不初始化 int *is2 = new int[10](); //加()默认初始化为0 int *is3 = new int[0]; //允许动态分配空数组,加减0或减自身得0值,不能解引用 //动态空间释放 delete [] ss; //[]不可少,表示为自由存储区(堆)上的数组,若不加为单个对象 delete [] is; delete [] is2; delete [] is3; return 0; }<file_sep>/testC/tscanf.c #include <stdio.h> #include <stdlib.h> main(){ //指针在使用前必须初始化,这里不能用字符串指针 char c; char str[1]; printf("input:\n"); scanf("%s",str); printf("back input char size %d\n",sizeof(str)); printf("input is %s\n",str); //printf("back size of str %d",sizeof(str)); } <file_sep>/CodeTest/Java/Stream/DirList.java import java.io.*; public class DirList{ public static void main(String[] args){ try{ File path=new File("."); String[] list; if(args.length==0) list=path.list(); else list=path.list(new DirFilter(args[0])); for(int i=0;i<list.length;i++){ System.out.println(list[i]); } }catch(Exception e){ e.printStackTrace(); } } } class DirFilter implements FilenameFilter{ String afn; DirFilter(String afn){this.afn=afn;} public boolean accept(File dir,String name){ System.out.println(dir.getName()); String f=new File(name).getName(); return f.indexOf(afn)!=-1; } }<file_sep>/testCpp/testdll/mydll.cpp #define BUILD_XXX_DLL #ifdef BUILD_XXX_DLL #define EXPORT __dedspec(dllexport) #else #define EXPORT __dedspec(dllimport) #endif extern "C"{ EXPORT int testcall(); } #include <iostream> using namespace std; int testcall(){ cout << "function call" << endl; } <file_sep>/testCpp/lifecycle/Tlife.h #ifndef _TLIFE_H_ #define _TLIFE_H_ #include <iostream> class Tlife{ public: friend std::ostream &operator<<(std::ostream &,const Tlife &); int getI() const; Tlife(){ std::cout << "member" << i << "construct" << std::endl; } Tlife(int ii){ i=ii; std::cout << "member" << i << "construct" << std::endl; } ~Tlife(){ std::cout << "member" << i <<"deconstruct" << std::endl; } private: int i; }; #endif <file_sep>/testC/testPointer1.c #include <stdio.h> main(){ int a,b; int *a_pointer,*b_pointer; a=10; b=120; a_pointer=&a; b_pointer=&b; printf("%d,%d\n",a,b); printf("%d,%d\n",*a_pointer,*b_pointer); } <file_sep>/testCpp/operator/test.cpp #include <iostream> #include "Data.h" using namespace std; ostream &operator<<(ostream &os,const Data &da){ os<<da.num; return os; } int main(){ Data d1(10); Data d2(20); cout << d1+d2 << endl; } <file_sep>/testCpp/genericalgorithm/accumulateandfind_first_of.cpp #include <vector> #include <algorithm> #include <numeric> #include <iostream> using namespace std; int main(){ vector<int> ivec1; vector<int> ivec2; int sum; int count = 0; ivec1.push_back(2); ivec1.push_back(23); ivec1.push_back(21); ivec1.push_back(11); ivec1.push_back(7); ivec2.push_back(23); ivec2.push_back(2); ivec2.push_back(99); cout << "ivec1 size is " << ivec1.size() << endl; cout << "ivec1 capacity is " << ivec1.capacity() << endl; ivec1.reserve(ivec1.capacity()+20); cout << "after reserve 20 capacity is " << ivec1.capacity() << endl; sum = accumulate(ivec1.begin(),ivec1.end(),0); cout << "sum is " << sum << endl; vector<int>::iterator it = ivec1.begin(); while((it=(find_first_of(it,ivec1.end(),ivec2.begin(),ivec2.end())))!=ivec1.end()){ ++count; ++it; } cout << "count is " << count << endl; return 0; } <file_sep>/testCpp/TestClass/swap.cpp #include <iostream> using namespace std; int main(){ int i=10,j=19; swap(i,j); cout << "afer swap" << i << j << endl; } void swap(int &i1,int &i2){ int temp=i2; i2=i1; i1=temp; } <file_sep>/testCpp/operator/Data.h #ifndef _DATA_H_ #define _DATA_H_ #include <iostream> class Data{ public: friend std::ostream &operator<<(std::ostream &,const Data &); int getNum() const; Data operator+(const Data&); Data(const int it):num(it){} private: int num; }; #endif <file_sep>/testCpp/testcstylestr.cpp #include <iostream> #include <vector> using namespace std; int main(){ char *cp = "C++"; int ip[4] = {0,1,2,3}; vector<int> ivec(ip+1,ip+3); vector<int>::iterator iter=ivec.begin(); for(iter;iter!=ivec.end();++iter){ cout << *iter <<endl; } cout << cp[1] << endl; return 0; } <file_sep>/testCpp/TestClass/TestClass.cpp #include <iostream> #include <string> using namespace std; class TestClass{ public: bool isSame(string s1,string s2) const{ return s1==s2; } void printSomething(string s) const{ cout << s << endl; } int getCount(){ return count; } void defineOutOfClass() const; TestClass():className("TestClass"),count(1){ cout << "construct" << endl; } private: string className; int count; }; void TestClass::defineOutOfClass() const{ cout << "this is the function define out of class called" << endl; } int main(){ TestClass t; cout << "isSame call " << t.isSame("ss","ss") << endl; cout << "getCount = " << t.getCount() << endl; cout << "printSomeThing = "; t.printSomething("something"); cout << endl; cout << "defineOutOfClass class = "; t.defineOutOfClass(); cout << endl; } <file_sep>/testCpp/associativecontainer/testfor.cpp #include <iostream> #include <sstream> using namespace std; int main(int argc,char **argv){ int j=10; int ix; istringstream is(argv[1]); is >> ix; for(int i=0;i<ix;++i,++j){ cout << "i : " << i << endl; cout << "j : " << j << endl; } cout << "here over" << endl; return 0; } <file_sep>/testCpp/TestClass/Persion.h #include <string> class Persion{ public: std::string getName() const; std::string getAddress() const; Persion(const std::string name,const std::string address){ (*this).name = name; (*this).address = address; } private: std::string name; std::string address; }; <file_sep>/testCpp/operator/Data.cpp #include <iostream> #include "Data.h" using namespace std; int Data::getNum() const{ return num; } Data Data::operator+(const Data &da){ this->num+=da.num; return *this; } <file_sep>/testC/strutpointerasargs.c #include <stdio.h> struct stu{ int num; char *name; char sex; float score; }boy[5]={ {11,"zhangsan",'f',76}, {11,"zhangsan",'f',56}, {11,"zhangsan",'f',96}, {11,"zhangsan",'f',70}, }; main(){ struct stu *pstu; void ave(struct stu *ps); pstu=boy; ave(pstu); } void ave(struct stu *pstu){ int c=0,i; float ave,s=0; for(i=0;i<4;i++,pstu++){ s+=pstu->score; if(pstu->score<60) c++; } printf("s=%f\n",s); ave=s/4; printf("average=%f\ncount=%d\n",ave,c); } <file_sep>/testCpp/testvector.cpp #include <iostream> #include <vector> using namespace std; int main(){ vector<string> svec; //svec.size(); //svec.empty(); //svec.push_back("abc"); //在容器末尾加元素 //v[n]; //返回位置为n的元素 //v1=v2; //v1==v2; string str; cout << "input string and push to the vectot" << endl; while(cin >> str) svec.push_back(str); cout << "the vector size is " << svec.size() << endl << "all the elements : " << endl; //for(vector<string>::size_type ix=0;ix!=svec.size();ix++){ //更推荐使用迭代器操作,不是所有的容器都支持下标操作 //cout << "vector[" << ix << "] = " << svec[ix] << endl; //} vector<string>::iterator iter = svec.begin(); for(iter;iter!=svec.end();iter++){ cout << *iter << endl; } return 0; } <file_sep>/testC/longlongago.c #include <stdio.h> #include <stdbool.h> main(){ _Bool b; char c; short s; int i; long l; long long ago; printf("_Bool size %d\n",sizeof(b)); printf("char size %d\n",sizeof(c)); printf("short size %d\n",sizeof(s)); printf("int size %d\n",sizeof(i)); printf("long size %d\n",sizeof(l)); printf("long long size %d\n",sizeof(ago)); } <file_sep>/testCpp/mainargs.cpp #include <iostream> using namespace std; int main(int argc,char **argv){ int i = argc; cout << "args count : " << argc << endl; while(--argc){ cout << "args" << i-argc << " = " << *++argv << endl; } return 0; }
7578f0d8d69eb861f857cd09019cf3990e00e7a0
[ "Java", "C", "C++", "SQL" ]
58
C
challengezhou/repository
4154aba7d9fbd0e7e4e2eaf6079cfa212a6d61d0
c86c7e41a66e310b4d364ac822b8832da7efa9c6
refs/heads/master
<file_sep>from django.conf.urls import patterns, url urlpatterns = patterns('common.views', url(r'^_ah/warmup', 'warmup', name='warmup'), url(r'^$', 'home', name='home'), )<file_sep>from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'', include('common.urls', namespace='common')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>var djangoApp = angular.module('djangoApp', []); djangoApp.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/', { templateUrl: 'template/home.html', controller: 'HomeController' }); $routeProvider.when('/about/', { templateUrl: 'template/about.html', controller: 'AboutController' }); }]); djangoApp.controller('HomeController', function($scope){ $scope.resources = [{ 'name': '<NAME>\'s Angular 60ish Minute Overview', 'url': 'http://www.youtube.com/watch?v=i9MHigUZKEM', },{ 'name': 'Angular Website', 'url': 'http://angularjs.org' }] }); djangoApp.controller('AboutController', function($scope){ }); <file_sep>django-angular-gae-skeleton ======================= A Skeleton Repo to get you started using Django, Google App Engine and Angular JS This skeleton is going to use the script.directive to host the template files on the base.html page to remove any ajax calls for templates. Some things to make note of: 1) Make sure your settings.local.py is setup for your local database settings. Google App Engine doesn't like SQLite so I've used a local mySQL. 2) Make sure you update your app.yaml with your settings. 3) If you haven't used Google App Engine with Django you'll need to collectstatic every time you make a change to your javascript or CSS. (if anyone knows a way around this please... PLEASE let me know) 4) pip install -r deps.txt to get local dependancies. For instance PIL. dev_appserver.py (or devappserver2.py) doesn't come bundled with PIL.<file_sep># this file should be used as a symlink to your personal settings file import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': '', 'HOST': '', 'NAME': 'test', }, }<file_sep>from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'base.html', {}) def warmup(request): return HttpResponse('warmed up')<file_sep>try: from djangoappengine.settings_base import * has_djangoappengine = True except ImportError: has_djangoappengine = False DEBUG = True TEMPLATE_DEBUG = DEBUG import os import sys from django.contrib.messages import constants as messages DEPLOYMENT_NAME = os.environ.get('USER', 'unspecified') SITE_ROOT = os.path.join(os.path.realpath(os.path.dirname(__file__)), '../') # include ext for external deps sys.path.append(os.path.join(SITE_ROOT, 'ext')) TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = os.path.join(SITE_ROOT, 'media/') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(SITE_ROOT, 'static/') STATIC_URL = '/static/' TEMPLATE_DIRS = ( os.path.join(SITE_ROOT, 'templates'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #'compressor.finders.CompressorFinder', ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.gzip.GZipMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.request", "django.contrib.messages.context_processors.messages", "django.core.context_processors.tz", ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) #AUTH_PROFILE_MODULE = '' ROOT_URLCONF = 'urls' LOGIN_REDIRECT_URL = '/login/' LOGIN_URL = '/login/' INTERNAL_IPS = ['127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.humanize', 'common', #'south' ] if has_djangoappengine: INSTALLED_APPS = ('djangoappengine',) + INSTALLED_APPS CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } DEBUG = True SECRET_KEY = 'probablyshoulduseyourownuniquekeyhere' if (os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine') or os.getenv('SETTINGS_MODE') == 'prod'): DEBUG = False DEPLOYMENT_NAME = 'production' DEPLOYMENT_VERSION = os.environ.get('CURRENT_VERSION_ID', 'developer') CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'TIMEOUT': 0, } } DATABASES = { 'default': { 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 'INSTANCE': '', # GAE mySQL instance 'NAME': '' # GAE mySQL name }, } SECRET_KEY = 'probablyshoulduseanotheruniquekeyhere' MINIMUM_CLIENT_VERSIONS = { 'Nalu': [3, 0, 15], 'android': None, 'web': None, } else: from settings.local import *
d75548d6939ad5fcb56309332867ad7f14ce7521
[ "JavaScript", "Python", "Markdown" ]
7
Python
robrocker7/django-angular-gae-skeleton
16b01cb7c811a9865b679d2bf559b4179a72d352
0656c0fe398b6a5250023aab2623171742af5f91
refs/heads/main
<repo_name>tud-cor/navigation_experiments_mc_bts_pddl<file_sep>/navigation_experiments_mc_bts/include/navigation_experiments_mc_bts/behavior_tree_nodes/CheckComponent.hpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__CHECKCOMPONENT_HPP_ #define navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__CHECKCOMPONENT_HPP_ #include <string> #include <memory> #include "behaviortree_cpp_v3/behavior_tree.h" #include "behaviortree_cpp_v3/bt_factory.h" #include "rclcpp/rclcpp.hpp" namespace navigation_experiments_mc_bts { class CheckComponent : public BT::SyncActionNode { public: explicit CheckComponent( const std::string & action_name, const BT::NodeConfiguration & conf); BT::NodeStatus tick() override; static BT::PortsList providedPorts() { return { BT::InputPort<std::string>("component") }; } std::string component_name_; private: rclcpp::Node::SharedPtr node_; }; } // namespace navigation_experiments_mc_bts #endif // navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__CHECKCOMPONENT_HPP_ <file_sep>/navigation_experiments_mc_bts_pddl_base/CMakeLists.txt cmake_minimum_required(VERSION 3.5) project(navigation_experiments_mc_bts_pddl_base) set(CMAKE_BUILD_TYPE DEBUG) # find dependencies find_package(ament_cmake REQUIRED) find_package(rclcpp REQUIRED) find_package(rclpy REQUIRED) install(DIRECTORY launch DESTINATION share/${PROJECT_NAME}) install(DIRECTORY params DESTINATION share/${PROJECT_NAME}) install(DIRECTORY maps DESTINATION share/${PROJECT_NAME}) install(DIRECTORY rviz DESTINATION share/${PROJECT_NAME}) install(DIRECTORY worlds DESTINATION share/${PROJECT_NAME}) ament_export_dependencies(${dependencies}) ament_package() <file_sep>/navigation_experiments_mc_bts_pddl_log/navigation_experiments_mc_bts_pddl_log/topics_2_csv.py # Copyright 2019 Intelligent Robotics Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import os.path import rclpy from rclpy.node import Node from rclpy.duration import Duration from rclpy.executors import MultiThreadedExecutor from rclpy.callback_groups import ReentrantCallbackGroup from rclpy.action import ActionServer, CancelResponse, GoalResponse from rclpy.qos import QoSProfile, QoSDurabilityPolicy, QoSReliabilityPolicy from std_msgs.msg import Float64, Empty, Int16 from geometry_msgs.msg import Twist, PoseWithCovarianceStamped from sensor_msgs.msg import LaserScan from tf2_ros import TransformBroadcaster, TransformListener, TransformStamped, Buffer import math import csv from datetime import datetime class Topics2csv(Node): def __init__(self, last_contexts=None): super().__init__('topics_2_csv') self.tfBuffer = Buffer() self.listener = TransformListener(self.tfBuffer, self) self.reconfig_time_sub_ = self.create_subscription( Float64, "/navigation_experiments_mc_bts_pddl/reconfig_time", self.reconfig_time_cb, 1) self.vel_sub_ = self.create_subscription( Twist, "/cmd_vel", self.vel_cb, 1) self.distance_ = 0.0 self.old_x_ = 0.0 self.old_y_ = 0.0 self.robot_x_ = 0.0 self.robot_y_ = 0.0 self.reconfig_time_ = 0.0 self.vel_ = Twist() #self.get_logger().info("DF_CLIENT: Ready!") self.fieldnames_ = ['time', 'distance', 'robot_x', 'robot_y', 'vel_x', 'vel_theta', 'reconfig_time'] username = os.environ['USER'] self.path = "/home/" + username + "/tud_iros2021/csv/run/" self.update_csv_file_name() with open(self.path + self.csv_filename , mode='w+') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=self.fieldnames_) writer.writeheader() timer_period = 0.1 # seconds self.create_timer(timer_period, self.step) def destroy(self): super().destroy_node() def get_robot_position(self): dur = Duration() dur.sec = 3 dur.nsec = 0 try: trans = self.tfBuffer.lookup_transform('map', 'base_footprint', rclpy.time.Time(seconds=0), dur) self.robot_x_ = trans.transform.translation.x self.robot_y_ = trans.transform.translation.y except: print("tf2 exception") meters = 0.0 if self.old_x_ != 0.0 and self.old_y_ != 0.0: meters = self.calculate_distance(self.robot_x_, self.robot_y_, self.old_x_, self.old_y_) self.old_x_ = self.robot_x_ self.old_y_ = self.robot_y_ #miles = metersToMiles(meters_); else: self.old_x_ = self.robot_x_ self.old_y_ = self.robot_y_ self.distance_ = meters def reconfig_time_cb(self, msg): self.reconfig_time_ = msg.data def path_distance_cb(self, msg): self.path_distance_ = msg.data def vel_cb(self, msg): self.vel_ = msg def update_csv_file_name(self): filename_list = [] for file in os.listdir(self.path): filename_list.append(int(file[:-4])) filename_list_sorted = sorted(filename_list) if len(filename_list_sorted) == 0: self.csv_filename = str(1) + ".csv" else: self.last_file_number = filename_list_sorted[-1] self.csv_filename = str(self.last_file_number + 1) + ".csv" def calculate_distance(self, current_x, current_y, old_x, old_y): return math.sqrt((pow(current_x - old_x, 2) + pow(current_y - old_y, 2))) def step(self): self.get_robot_position() with open(self.path + self.csv_filename, mode='a+') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=self.fieldnames_) time = self.get_clock().now() writer.writerow({ 'time': time.to_msg().sec + (time.to_msg().nanosec / 1000000000), 'distance': self.distance_, 'robot_x' : self.robot_x_, 'robot_y' : self.robot_y_, 'vel_x': self.vel_.linear.x, 'vel_theta':self.vel_.angular.z, 'reconfig_time': self.reconfig_time_}) self.distance_ = 0.0 self.path_distance_ = 0.0 self.scan_min_ = 0.0 self.reconfig_time_ = 0.0 def main(args=None): rclpy.init(args=args) node = Topics2csv() rclpy.spin(node) node.destroy() rclpy.shutdown() if __name__ == '__main__': main()<file_sep>/navigation_experiments_mc_bts_pddl_log/setup.py #!/usr/bin/env python from setuptools import find_packages from setuptools import setup package_name = 'navigation_experiments_mc_bts_pddl_log' setup( name=package_name, version='0.0.1', packages=find_packages(exclude=['test']), data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], install_requires=['setuptools'], zip_safe=True, author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', keywords=['ROS2', 'csv'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Topic :: Software Development', ], description=( 'The navigation_experiments_mc_bts_pddl_log package' ), license='Apache License, Version 2.0', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'topics_2_csv = navigation_experiments_mc_bts_pddl_log.topics_2_csv:main', 'reconfig_time = navigation_experiments_mc_bts_pddl_log.reconfig_time:main' ], }, ) <file_sep>/navigation_experiments_mc_bts_pddl_log/navigation_experiments_mc_bts_pddl_log/reconfig_time.py # Copyright 2019 Intelligent Robotics Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import os.path import rclpy from rclpy.node import Node from rclpy.duration import Duration from rclpy.executors import MultiThreadedExecutor from rclpy.callback_groups import ReentrantCallbackGroup from rclpy.qos import QoSProfile, QoSDurabilityPolicy, QoSReliabilityPolicy from std_msgs.msg import Float64, Empty, Int16 from diagnostic_msgs.msg import DiagnosticArray from system_modes.msg import ModeEvent import math from datetime import datetime class ReconfigTime(Node): def __init__(self, last_contexts=None): super().__init__('reconfig_time') self.diagnostics_sub_ = self.create_subscription( DiagnosticArray, "/diagnostics", self.diagnostics_cb, 1) self.mode_sub_ = self.create_subscription( ModeEvent, "/pilot/mode_request_info", self.mode_cb, 1) self.pub_ = self.create_publisher( Float64, '/navigation_experiments_mc_bts_pddl/reconfig_time', 10) self.reconfig_time_ = 0.0 self.component_in_error_time_ = 0.0 self.last_mode_ = "" def destroy(self): super().destroy_node() def mode_cb(self, msg): if self.last_mode_ != msg.goal_mode.label: if msg.goal_mode.label == 'f_energy_saving_mode' \ or msg.goal_mode.label == 'f_degraded_mode': self.last_mode_ = msg.goal_mode.label self.reconfig_time_ = self.get_clock().now() - \ self.component_in_error_time_ time_msg = Float64() time_msg.data = self.reconfig_time_.to_msg().sec + (self.reconfig_time_.to_msg().nanosec / 1000000000) self.pub_.publish(time_msg) def diagnostics_cb(self, msg): for diagnostic_status in msg.status: # 2 types of diagnostics considered: about bindings in error (TODO not implemented yet) or about QAs if diagnostic_status.message == "binding error": self.get_logger().warning("Diagnostics message received for %s with level %d, nothing done about it." % (diagnostic_status.name, diagnostic_status.level)) # Component error elif diagnostic_status.message == "Component status": self.get_logger().info("\nCS Message received!\tTYPE: {0}\tVALUE: {1}".format(diagnostic_status.values[0].key, diagnostic_status.values[0].value)) component = diagnostic_status.values[0].key value = diagnostic_status.values[0].value self.get_logger().info("Component: {0} - Value {1}".format(component, value)) if component == "battery": if value == "FALSE": self.component_in_error_time_ = self.get_clock().now() elif component == "laser_resender": if value == "FALSE": self.component_in_error_time_ = self.get_clock().now() def main(args=None): rclpy.init(args=args) node = ReconfigTime() rclpy.spin(node) node.destroy() rclpy.shutdown() if __name__ == '__main__': main()<file_sep>/navigation_experiments_mc_bts/include/navigation_experiments_mc_bts/behavior_tree_nodes/Reconfigure.hpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__RECONFIGURE_HPP_ #define navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__RECONFIGURE_HPP_ #include <string> #include <memory> #include "behaviortree_cpp_v3/behavior_tree.h" #include "behaviortree_cpp_v3/bt_factory.h" #include "system_modes/srv/change_mode.hpp" #include "rclcpp/rclcpp.hpp" namespace navigation_experiments_mc_bts { class Reconfigure : public BT::AsyncActionNode { public: explicit Reconfigure( const std::string & action_name, const BT::NodeConfiguration & conf); BT::NodeStatus tick() override; static BT::PortsList providedPorts() { return { BT::InputPort<std::string>("mode") }; } static BT::PortsList providedBasicPorts(BT::PortsList addition) { BT::PortsList basic = { BT::InputPort<std::chrono::milliseconds>("server_timeout") }; basic.insert(addition.begin(), addition.end()); return basic; } private: rclcpp::Node::SharedPtr node_; rclcpp::Client<system_modes::srv::ChangeMode>::SharedPtr client_; bool reconfigure_srv_call(std::string new_mode); }; } // namespace navigation_experiments_mc_bts #endif // navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__RECONFIGURE_HPP_ <file_sep>/navigation_experiments_mc_pddl/src/patrolling_controller_node.cpp // Copyright 2019 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "plansys2_msgs/msg/action_execution_info.hpp" #include "plansys2_executor/ExecutorClient.hpp" #include "plansys2_problem_expert/ProblemExpertClient.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" class PatrollingController : public rclcpp::Node { public: PatrollingController() : rclcpp::Node("patrolling_controller"), state_(STARTING) { } void init() { problem_expert_ = std::make_shared<plansys2::ProblemExpertClient>(shared_from_this()); executor_client_ = std::make_shared<plansys2::ExecutorClient>(shared_from_this()); init_knowledge(); } void init_knowledge() { problem_expert_->addInstance(plansys2::Instance{"r2d2", "robot"}); problem_expert_->addInstance(plansys2::Instance{"wp_control", "waypoint"}); problem_expert_->addInstance(plansys2::Instance{"wp1", "waypoint"}); problem_expert_->addInstance(plansys2::Instance{"wp2", "waypoint"}); problem_expert_->addInstance(plansys2::Instance{"wp3", "waypoint"}); problem_expert_->addInstance(plansys2::Instance{"wp4", "waypoint"}); problem_expert_->addInstance(plansys2::Instance{"wp_aux", "waypoint"}); problem_expert_->addInstance(plansys2::Instance{"f_normal_mode", "mode"}); problem_expert_->addPredicate(plansys2::Predicate("(robot_at r2d2 wp_control)")); problem_expert_->addPredicate(plansys2::Predicate("(battery_enough r2d2)")); problem_expert_->addPredicate(plansys2::Predicate("(normal_mode f_normal_mode)")); problem_expert_->addPredicate(plansys2::Predicate("(charging_point_at wp_control)")); problem_expert_->addPredicate(plansys2::Predicate("(current_system_mode f_normal_mode)")); } void step() { switch (state_) { case STARTING: // Set the goal for next state, and execute plan problem_expert_->setGoal(plansys2::Goal("(and(robot_at r2d2 wp1))")); if (executor_client_->executePlan()) { state_ = PATROL_WP1; } break; case PATROL_WP1: { auto feedback = executor_client_->getFeedBack(); for (const auto & action_feedback : feedback.action_execution_status) { std::cout << "[" << action_feedback.action << " " << action_feedback.completion * 100.0 << "%]"; } std::cout << std::endl; if (executor_client_->getResult()) { if (executor_client_->getResult().value().success) { std::cout << "Successful finished " << std::endl; // Set the goal for next state, and execute plan problem_expert_->setGoal(plansys2::Goal("(and(robot_at r2d2 wp2))")); if (executor_client_->executePlan()) { state_ = PATROL_WP2; } } else { for (const auto & action_feedback : feedback.action_execution_status) { if (action_feedback.status == plansys2_msgs::msg::ActionExecutionInfo::FAILED) { std::cout << "[" << action_feedback.action << "] finished with error: " << action_feedback.message_status << std::endl; } } executor_client_->executePlan(); // replan and execute } } } break; case PATROL_WP2: { auto feedback = executor_client_->getFeedBack(); for (const auto & action_feedback : feedback.action_execution_status) { std::cout << "[" << action_feedback.action << " " << action_feedback.completion * 100.0 << "%]"; } std::cout << std::endl; if (executor_client_->getResult()) { if (executor_client_->getResult().value().success) { std::cout << "Successful finished " << std::endl; // Set the goal for next state, and execute plan problem_expert_->setGoal(plansys2::Goal("(and(robot_at r2d2 wp3))")); if (executor_client_->executePlan()) { state_ = PATROL_WP3; } } else { for (const auto & action_feedback : feedback.action_execution_status) { if (action_feedback.status == plansys2_msgs::msg::ActionExecutionInfo::FAILED) { std::cout << "[" << action_feedback.action << "] finished with error: " << action_feedback.message_status << std::endl; } } executor_client_->executePlan(); // replan and execute } } } break; case PATROL_WP3: { auto feedback = executor_client_->getFeedBack(); for (const auto & action_feedback : feedback.action_execution_status) { std::cout << "[" << action_feedback.action << " " << action_feedback.completion * 100.0 << "%]"; } std::cout << std::endl; if (executor_client_->getResult()) { if (executor_client_->getResult().value().success) { std::cout << "Successful finished " << std::endl; // Set the goal for next state, and execute plan problem_expert_->setGoal(plansys2::Goal("(and(robot_at r2d2 wp4))")); if (executor_client_->executePlan()) { state_ = PATROL_WP4; } } else { for (const auto & action_feedback : feedback.action_execution_status) { if (action_feedback.status == plansys2_msgs::msg::ActionExecutionInfo::FAILED) { std::cout << "[" << action_feedback.action << "] finished with error: " << action_feedback.message_status << std::endl; } } executor_client_->executePlan(); // replan and execute } } } break; case PATROL_WP4: { auto feedback = executor_client_->getFeedBack(); for (const auto & action_feedback : feedback.action_execution_status) { std::cout << "[" << action_feedback.action << " " << action_feedback.completion * 100.0 << "%]"; } std::cout << std::endl; if (executor_client_->getResult()) { if (executor_client_->getResult().value().success) { std::cout << "Successful finished " << std::endl; // Set the goal for next state, and execute plan problem_expert_->setGoal(plansys2::Goal("(and(robot_at r2d2 wp1))")); if (executor_client_->executePlan()) { // Loop to WP1 state_ = PATROL_WP1; } } else { for (const auto & action_feedback : feedback.action_execution_status) { if (action_feedback.status == plansys2_msgs::msg::ActionExecutionInfo::FAILED) { std::cout << "[" << action_feedback.action << "] finished with error: " << action_feedback.message_status << std::endl; } } executor_client_->executePlan(); // replan and execute } } } break; default: break; } } private: typedef enum {STARTING, PATROL_WP1, PATROL_WP2, PATROL_WP3, PATROL_WP4} StateType; StateType state_; std::shared_ptr<plansys2::ProblemExpertClient> problem_expert_; std::shared_ptr<plansys2::ExecutorClient> executor_client_; }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto node = std::make_shared<PatrollingController>(); node->init(); rclcpp::Rate rate(5); while (rclcpp::ok()) { node->step(); rate.sleep(); rclcpp::spin_some(node->get_node_base_interface()); } rclcpp::shutdown(); return 0; } <file_sep>/navigation_experiments_mc_bts/include/navigation_experiments_mc_bts/behavior_tree_nodes/NavigateToWp.hpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__NAVIGATETOWP_HPP_ #define navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__NAVIGATETOWP_HPP_ #include <string> #include <memory> #include "behaviortree_cpp_v3/behavior_tree.h" #include "behaviortree_cpp_v3/bt_factory.h" #include "nav2_msgs/action/navigate_to_pose.hpp" #include "mros2_msgs/action/navigate_to_pose_qos.hpp" #include "navigation_experiments_mc_bts/BTActionNode.hpp" #include "rclcpp/rclcpp.hpp" using NavigateToPoseQos = mros2_msgs::action::NavigateToPoseQos; namespace navigation_experiments_mc_bts { class NavigateToWp : public BtActionNode<NavigateToPoseQos> { public: explicit NavigateToWp( const std::string & xml_tag_name, const std::string & action_name, const BT::NodeConfiguration & conf); void on_tick() override; void on_wait_for_result() override; BT::NodeStatus on_success() override; static BT::PortsList providedPorts() { return { BT::InputPort<std::string>("server_name", "Action server name"), BT::InputPort<std::string>("goal") }; } private: rclcpp::Node::SharedPtr node_; geometry_msgs::msg::Pose wp_; }; } // namespace navigation_experiments_mc_bts #endif // navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__NAVIGATETOWP_HPP_ <file_sep>/navigation_experiments_mc_pddl/src/patrol_action_node.cpp // Copyright 2019 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "geometry_msgs/msg/twist.hpp" #include "plansys2_executor/ActionExecutorClient.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" #include "lifecycle_msgs/msg/state.hpp" using namespace std::chrono_literals; class Patrol : public plansys2::ActionExecutorClient { public: Patrol() : plansys2::ActionExecutorClient("patrol", 1s) { } rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) { progress_ = 0.0; cmd_vel_pub_ = this->create_publisher<geometry_msgs::msg::Twist>("/cmd_vel", 10); cmd_vel_pub_->on_activate(); return ActionExecutorClient::on_activate(previous_state); } rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) { cmd_vel_pub_->on_deactivate(); return ActionExecutorClient::on_deactivate(previous_state); } private: void do_work() { //if (progress_ < 1.0) { // progress_ += 0.1; // // send_feedback(progress_, "Patrol running"); // // geometry_msgs::msg::Twist cmd; // cmd.linear.x = 0.0; // cmd.linear.y = 0.0; // cmd.linear.z = 0.0; // cmd.angular.x = 0.0; // cmd.angular.y = 0.0; // cmd.angular.z = 0.5; // // cmd_vel_pub_->publish(cmd); //} else { // geometry_msgs::msg::Twist cmd; // cmd.linear.x = 0.0; // cmd.linear.y = 0.0; // cmd.linear.z = 0.0; // cmd.angular.x = 0.0; // cmd.angular.y = 0.0; // cmd.angular.z = 0.0; // // cmd_vel_pub_->publish(cmd); // // finish(true, 1.0, "Patrol completed"); //} finish(true, 1.0, "Patrol completed"); } float progress_; rclcpp_lifecycle::LifecyclePublisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_pub_; }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto node = std::make_shared<Patrol>(); node->set_parameter(rclcpp::Parameter("action_name", "patrol")); node->trigger_transition(lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); rclcpp::spin(node->get_node_base_interface()); rclcpp::shutdown(); return 0; } <file_sep>/navigation_experiments_mc_bts/test/navigate_to_barman_test.cpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <memory> #include "behaviortree_cpp_v3/behavior_tree.h" #include "behaviortree_cpp_v3/bt_factory.h" #include "behaviortree_cpp_v3/utils/shared_library.h" #include "behaviortree_cpp_v3/blackboard.h" #include "nav2_msgs/action/navigate_to_pose.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" #include "gtest/gtest.h" using namespace std::placeholders; class MoveServer : public rclcpp::Node { using NavigateToPose = nav2_msgs::action::NavigateToPose; using GoalHandleNavigateToPose = rclcpp_action::ServerGoalHandle<NavigateToPose>; public: MoveServer() : Node("move_server") {} void start_server() { move_action_server_ = rclcpp_action::create_server<NavigateToPose>( shared_from_this(), "navigate_to_pose", std::bind(&MoveServer::handle_goal, this, _1, _2), std::bind(&MoveServer::handle_cancel, this, _1), std::bind(&MoveServer::handle_accepted, this, _1)); } geometry_msgs::msg::PoseStamped goal_; private: rclcpp_action::Server<NavigateToPose>::SharedPtr move_action_server_; rclcpp_action::GoalResponse handle_goal( const rclcpp_action::GoalUUID &, std::shared_ptr<const NavigateToPose::Goal>) { return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE; } rclcpp_action::CancelResponse handle_cancel( const std::shared_ptr<GoalHandleNavigateToPose>) { return rclcpp_action::CancelResponse::ACCEPT; } void handle_accepted(const std::shared_ptr<GoalHandleNavigateToPose> goal_handle) { std::thread{std::bind(&MoveServer::execute, this, _1), goal_handle}.detach(); } void execute(const std::shared_ptr<GoalHandleNavigateToPose> goal_handle) { auto feedback = std::make_shared<NavigateToPose::Feedback>(); auto result = std::make_shared<NavigateToPose::Result>(); goal_ = goal_handle->get_goal()->pose; goal_handle->succeed(result); } }; TEST(navigate_to_barman_test, basic_usage) { auto move_server_node = std::make_shared<MoveServer>(); move_server_node->start_server(); bool finish = false; std::thread t([&]() { while (!finish) {rclcpp::spin_some(move_server_node);} }); BT::BehaviorTreeFactory factory; BT::SharedLibrary loader; factory.registerFromPlugin(loader.getOSName("navigation_experiments_mc_bts_navigate_to_barman_bt_node")); std::string bt_xml = R"( <root main_tree_to_execute = "MainTree" > <BehaviorTree ID="MainTree"> <Sequence name="root_sequence"> <NavigateToBarman name="navigate_to_barman"/> </Sequence> </BehaviorTree> </root> )"; auto blackboard = BT::Blackboard::create(); auto node = rclcpp::Node::make_shared("bt_node"); blackboard->set("node", node); BT::Tree tree = factory.createTreeFromText(bt_xml, blackboard); auto start = node->now(); while ((node->now() - start).seconds() < 0.5) {} while (!finish) { finish = tree.rootNode()->executeTick() == BT::NodeStatus::SUCCESS; } start = node->now(); while ((node->now() - start).seconds() < 0.5) {} ASSERT_TRUE(finish); geometry_msgs::msg::PoseStamped goal; goal.pose.position.x = 0.636; goal.pose.position.y = 0.545; goal.header.frame_id = "map"; ASSERT_EQ(goal, move_server_node->goal_); t.join(); } int main(int argc, char ** argv) { rclcpp::init(argc, argv); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <file_sep>/navigation_experiments_mc_pddl/CMakeLists.txt cmake_minimum_required(VERSION 3.5) project(navigation_experiments_mc_pddl) find_package(ament_cmake REQUIRED) find_package(rclcpp REQUIRED) find_package(rclcpp_action REQUIRED) find_package(plansys2_msgs REQUIRED) find_package(geometry_msgs REQUIRED) find_package(nav2_msgs REQUIRED) find_package(mros2_msgs REQUIRED) find_package(std_srvs REQUIRED) find_package(system_modes REQUIRED) find_package(plansys2_executor REQUIRED) find_package(plansys2_domain_expert REQUIRED) set(CMAKE_CXX_STANDARD 17) set(dependencies rclcpp rclcpp_action plansys2_msgs nav2_msgs plansys2_executor plansys2_problem_expert plansys2_domain_expert mros2_msgs std_srvs system_modes ) add_executable(move_action_node src/move_action_node.cpp) ament_target_dependencies(move_action_node ${dependencies}) add_executable(patrol_action_node src/patrol_action_node.cpp) ament_target_dependencies(patrol_action_node ${dependencies}) add_executable(charge_action_node src/charge_action_node.cpp) ament_target_dependencies(charge_action_node ${dependencies}) add_executable(ask_charge_action_node src/ask_charge_action_node.cpp) ament_target_dependencies(ask_charge_action_node ${dependencies}) add_executable(degraded_move_action_node src/degraded_move_action_node.cpp) ament_target_dependencies(degraded_move_action_node ${dependencies}) add_executable(reconfigure_action_node src/reconfigure_action_node.cpp) ament_target_dependencies(reconfigure_action_node ${dependencies}) add_executable(recover_nav_sensor_node src/recover_nav_sensor_node.cpp) ament_target_dependencies(recover_nav_sensor_node ${dependencies}) add_executable(patrolling_controller_node src/patrolling_controller_node.cpp) ament_target_dependencies(patrolling_controller_node ${dependencies}) add_executable(patrolling_reconfig_controller_node src/patrolling_reconfig_controller_node.cpp) ament_target_dependencies(patrolling_reconfig_controller_node ${dependencies}) install(DIRECTORY launch pddl DESTINATION share/${PROJECT_NAME}) install(TARGETS move_action_node patrol_action_node charge_action_node ask_charge_action_node degraded_move_action_node reconfigure_action_node recover_nav_sensor_node patrolling_controller_node patrolling_reconfig_controller_node ARCHIVE DESTINATION lib LIBRARY DESTINATION lib RUNTIME DESTINATION lib/${PROJECT_NAME} ) if(BUILD_TESTING) find_package(ament_lint_auto REQUIRED) ament_lint_auto_find_test_dependencies() find_package(ament_cmake_gtest REQUIRED) endif() ament_export_dependencies(${dependencies}) ament_package()<file_sep>/navigation_experiments_mc_bts/src/behavior_tree_nodes/CheckComponent.cpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <memory> #include "navigation_experiments_mc_bts/behavior_tree_nodes/CheckComponent.hpp" using namespace std::chrono_literals; namespace navigation_experiments_mc_bts { CheckComponent::CheckComponent( const std::string & action_name, const BT::NodeConfiguration & conf) : BT::SyncActionNode(action_name, conf) { node_ = config().blackboard->get<rclcpp::Node::SharedPtr>("node"); } BT::NodeStatus CheckComponent::tick() { auto component_map = config().blackboard->get<std::unordered_map<std::string, bool>>("component_map"); std::string requested_component; if (!getInput<std::string>("component", requested_component)) { throw BT::RuntimeError("missing required input [component]"); } RCLCPP_ERROR(node_->get_logger(), "Component %s - state %s", requested_component.c_str(), component_map[requested_component] ? "true" : "false"); if (component_map[requested_component] == true) { return BT::NodeStatus::SUCCESS; } else { return BT::NodeStatus::FAILURE; } } } // namespace navigation_experiments_mc_bts #include "behaviortree_cpp_v3/bt_factory.h" BT_REGISTER_NODES(factory) { BT::NodeBuilder builder = [](const std::string & name, const BT::NodeConfiguration & config) { return std::make_unique<navigation_experiments_mc_bts::CheckComponent>( name, config); }; factory.registerBuilder<navigation_experiments_mc_bts::CheckComponent>( "CheckComponent", builder); } <file_sep>/navigation_experiments_mc_bts/CMakeLists.txt cmake_minimum_required(VERSION 3.5) project(navigation_experiments_mc_bts) set(CMAKE_BUILD_TYPE DEBUG) if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") add_compile_options(-Wall -Wextra -Wpedantic) endif() # find dependencies find_package(rclcpp REQUIRED) find_package(rclcpp_action REQUIRED) find_package(rclcpp_lifecycle REQUIRED) find_package(ros2_knowledge_graph REQUIRED) find_package(ament_index_cpp REQUIRED) find_package(nav2_msgs REQUIRED) find_package(behaviortree_cpp_v3 REQUIRED) find_package(mros2_msgs REQUIRED) find_package(std_srvs REQUIRED) find_package(system_modes REQUIRED) include_directories( include ) set(dependencies rclcpp rclcpp_action rclcpp_lifecycle ros2_knowledge_graph ament_index_cpp nav2_msgs behaviortree_cpp_v3 mros2_msgs std_srvs system_modes ) add_library(navigation_experiments_mc_bts_navigate_to_wp_bt_node SHARED src/behavior_tree_nodes/NavigateToWp.cpp ) list(APPEND plugin_libs navigation_experiments_mc_bts_navigate_to_wp_bt_node) add_library(navigation_experiments_mc_bts_recharge_bt_node SHARED src/behavior_tree_nodes/Recharge.cpp ) list(APPEND plugin_libs navigation_experiments_mc_bts_recharge_bt_node) add_library(navigation_experiments_mc_bts_reconfigure_bt_node SHARED src/behavior_tree_nodes/Reconfigure.cpp ) list(APPEND plugin_libs navigation_experiments_mc_bts_reconfigure_bt_node) add_library(navigation_experiments_mc_bts_check_component_bt_node SHARED src/behavior_tree_nodes/CheckComponent.cpp ) list(APPEND plugin_libs navigation_experiments_mc_bts_check_component_bt_node) foreach(bt_plugin ${plugin_libs}) ament_target_dependencies(${bt_plugin} ${dependencies}) target_compile_definitions(${bt_plugin} PRIVATE BT_PLUGIN_EXPORT) endforeach() add_executable(bt_controller src/bt_controller.cpp) ament_target_dependencies(bt_controller ${dependencies}) target_link_libraries(bt_controller) if(BUILD_TESTING) find_package(ament_lint_auto REQUIRED) ament_lint_auto_find_test_dependencies() find_package(ament_cmake_gtest REQUIRED) add_subdirectory(test) endif() install(DIRECTORY behavior_trees DESTINATION share/${PROJECT_NAME}) install(DIRECTORY launch DESTINATION share/${PROJECT_NAME}) install(TARGETS ${plugin_libs} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib RUNTIME DESTINATION bin ) install(TARGETS bt_controller DESTINATION lib/${PROJECT_NAME} ) ament_package() <file_sep>/navigation_experiments_mc_bts/src/bt_controller.cpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* Author: <NAME> <EMAIL> */ /* Mantainer: <NAME> <EMAIL> */ #include <math.h> #include <iostream> #include <memory> #include <string> #include <map> #include "behaviortree_cpp_v3/behavior_tree.h" #include "behaviortree_cpp_v3/bt_factory.h" #include "behaviortree_cpp_v3/utils/shared_library.h" #include "behaviortree_cpp_v3/blackboard.h" #include "ament_index_cpp/get_package_share_directory.hpp" #include "ros2_knowledge_graph/GraphNode.hpp" #include "nav2_util/geometry_utils.hpp" #include "rclcpp/rclcpp.hpp" int main(int argc, char ** argv) { rclcpp::init(argc, argv); std::string pkgpath = ament_index_cpp::get_package_share_directory("navigation_experiments_mc_bts"); std::string xml_file = pkgpath + "/behavior_trees/bt_mc.xml"; BT::BehaviorTreeFactory factory; BT::SharedLibrary loader; factory.registerFromPlugin(loader.getOSName("navigation_experiments_mc_bts_navigate_to_wp_bt_node")); factory.registerFromPlugin(loader.getOSName("navigation_experiments_mc_bts_recharge_bt_node")); factory.registerFromPlugin(loader.getOSName("navigation_experiments_mc_bts_reconfigure_bt_node")); factory.registerFromPlugin(loader.getOSName("navigation_experiments_mc_bts_check_component_bt_node")); auto blackboard = BT::Blackboard::create(); auto node = rclcpp::Node::make_shared("pilot_node"); auto graph = std::make_shared<ros2_knowledge_graph::GraphNode>("pilot_graph"); graph->start(); blackboard->set("node", node); blackboard->set("pilot_graph", graph); std::unordered_map<std::string, geometry_msgs::msg::Pose> wp_map; geometry_msgs::msg::Pose wp; wp.position.x = 1.0; // URJC Real scenario 9.0 wp.position.y = -1.0; // 47.0 wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(M_PI_2); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("wp_1", wp)); wp.position.x = -1.0; // URJC Real scenario 20.0 wp.position.y = 1.0; // 47.0 wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(M_PI); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("wp_2", wp)); wp.position.x = -3.5; wp.position.y = 1.0; wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(M_PI); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("wp_3", wp)); wp.position.x = -6.25; wp.position.y = 2.66; wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(-M_PI_2); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("wp_4", wp)); wp.position.x = -6.40; wp.position.y = -2.81; wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(-M_PI_2); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("wp_5", wp)); wp.position.x = -6.25; wp.position.y = 2.66; wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(M_PI_2); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("wp_6", wp)); wp.position.x = -1.5; wp.position.y = 1.5; wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(0.0); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("wp_7", wp)); wp.position.x = 4.0; wp.position.y = -3.0; wp.orientation = nav2_util::geometry_utils::orientationAroundZAxis(0.0); wp_map.insert(std::pair<std::string, geometry_msgs::msg::Pose>("recharge_station", wp)); blackboard->set("wp_map", wp_map); // Create blackboar for component status std::unordered_map<std::string, bool> component_map; component_map.insert(std::pair<std::string, bool>("battery", true)); component_map.insert(std::pair<std::string, bool>("camera", true)); component_map.insert(std::pair<std::string, bool>("laser", true)); blackboard->set("component_map", component_map); BT::Tree tree = factory.createTreeFromFile(xml_file, blackboard); rclcpp::Rate rate(1.0); bool finished = false; while (rclcpp::ok() && !finished) { finished = tree.rootNode()->executeTick() == BT::NodeStatus::SUCCESS; rclcpp::spin_some(node); rate.sleep(); } RCLCPP_INFO(node->get_logger(), "Pilot execution finished"); rclcpp::shutdown(); return 0; } <file_sep>/navigation_experiments_mc_bts/src/behavior_tree_nodes/NavigateToWp.cpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <memory> #include "navigation_experiments_mc_bts/behavior_tree_nodes/NavigateToWp.hpp" namespace navigation_experiments_mc_bts { NavigateToWp::NavigateToWp( const std::string & xml_tag_name, const std::string & action_name, const BT::NodeConfiguration & conf) : BtActionNode<NavigateToPoseQos>(xml_tag_name, action_name, conf) { node_ = config().blackboard->get<rclcpp::Node::SharedPtr>("node"); } void NavigateToWp::on_tick() { auto wp_map = config().blackboard->get<std::unordered_map<std::string, geometry_msgs::msg::Pose>>("wp_map"); auto res = getInput<std::string>("goal").value(); wp_ = wp_map[res]; RCLCPP_INFO(node_->get_logger(), "Navigating to... [%s -- %f %f]", res.c_str(), wp_.position.x, wp_.position.y); goal_.pose.pose.position = wp_.position; goal_.pose.pose.orientation = wp_.orientation; //goal_.pose.pose = wp_; goal_.qos_expected.objective_type = "f_navigate"; // should be mros_goal->qos_expected.objective_type = "f_navigate"; diagnostic_msgs::msg::KeyValue energy_qos; energy_qos.key = "energy"; energy_qos.value = "0.7"; diagnostic_msgs::msg::KeyValue safety_qos; safety_qos.key = "safety"; safety_qos.value = "0.5"; goal_.qos_expected.qos.clear(); goal_.qos_expected.qos.push_back(energy_qos); goal_.qos_expected.qos.push_back(safety_qos); } void NavigateToWp::on_wait_for_result() { std::string goal_id = rclcpp_action::to_string(goal_handle_->get_goal_id()); if (!goal_id.compare(feedback_->qos_status.objective_id) == 0){ RCLCPP_INFO(node_->get_logger(), "goal id and feedback are diferent"); rclcpp::Rate(1).sleep(); // Wait for the goal to finish return; } RCLCPP_INFO(node_->get_logger(), "Curr mode: %s ", feedback_->qos_status.selected_mode.c_str()); // check selected_mode, f_energy_saving_mode means the robot needs battery. if (feedback_->qos_status.selected_mode == "f_energy_saving_mode" && getInput<std::string>("goal").value() != "recharge_station") { RCLCPP_ERROR(node_->get_logger(), "Not enough energy"); auto component_map = config().blackboard->get<std::unordered_map<std::string, bool>>("component_map"); auto battery_component = component_map.find("battery"); if (battery_component->second) { RCLCPP_ERROR(node_->get_logger(), "Set battery to false"); battery_component->second = false; halt(); config().blackboard->set("component_map", component_map); result_.code = rclcpp_action::ResultCode::ABORTED; goal_result_available_ = true; } } else if (feedback_->qos_status.selected_mode == "f_degraded_mode") { RCLCPP_ERROR(node_->get_logger(), "Laser Scanner failed"); auto component_map = config().blackboard->get<std::unordered_map<std::string, bool>>("component_map"); auto laser_component = component_map.find("laser"); if (laser_component->second) { RCLCPP_ERROR(node_->get_logger(), "Set laser to false"); laser_component->second = false; halt(); config().blackboard->set("component_map", component_map); result_.code = rclcpp_action::ResultCode::ABORTED; goal_result_available_ = true; } } } BT::NodeStatus NavigateToWp::on_success() { return BT::NodeStatus::SUCCESS; } } // namespace navigation_experiments_mc_bts #include "behaviortree_cpp_v3/bt_factory.h" BT_REGISTER_NODES(factory) { BT::NodeBuilder builder = [](const std::string & name, const BT::NodeConfiguration & config) { return std::make_unique<navigation_experiments_mc_bts::NavigateToWp>( name, "navigate_to_pose_qos", config); }; factory.registerBuilder<navigation_experiments_mc_bts::NavigateToWp>( "NavigateToWp", builder); } <file_sep>/navigation_experiments_mc_pddl/src/reconfigure_action_node.cpp // Copyright 2019 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <algorithm> #include "plansys2_executor/ActionExecutorClient.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" #include "std_srvs/srv/empty.hpp" #include "system_modes/srv/change_mode.hpp" using namespace std::chrono_literals; class ReconfigureAction : public plansys2::ActionExecutorClient { public: ReconfigureAction() : plansys2::ActionExecutorClient("reconfig_system", 500ms) { mode_ = ""; client_ = create_client<system_modes::srv::ChangeMode>("/pilot/change_mode"); } private: void do_work() { mode_ = get_arguments()[2]; RCLCPP_INFO(get_logger(), "Reconfiguring system mode to %s", mode_.c_str()); if (srvCall()) finish(true, 1.0, "System reconfigured"); } bool srvCall() { auto request = std::make_shared<system_modes::srv::ChangeMode::Request>(); request->mode_name = mode_; while (!client_->wait_for_service(1s)) { if (!rclcpp::ok()) { RCLCPP_ERROR(get_logger(), "Interrupted while waiting for the service. Exiting."); return false; } RCLCPP_INFO(get_logger(), "service not available, waiting again..."); } auto result = client_->async_send_request(request); return true; } rclcpp::Client<system_modes::srv::ChangeMode>::SharedPtr client_; std::string mode_; }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto node = std::make_shared<ReconfigureAction>(); node->set_parameter(rclcpp::Parameter("action_name", "reconfig_system")); node->trigger_transition(lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); rclcpp::spin(node->get_node_base_interface()); rclcpp::shutdown(); return 0; } <file_sep>/navigation_experiments_mc_pddl/launch/pddl_controller_launch.py # Copyright 2019 Intelligent Robotics Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, SetEnvironmentVariable from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node import launch # noqa: E402 import launch.actions # noqa: E402 import launch.events # noqa: E402 import launch_ros.actions # noqa: E402 import launch_ros.events # noqa: E402 import launch_ros.events.lifecycle # noqa: E402 def generate_launch_description(): # Get the launch directory example_dir = get_package_share_directory('navigation_experiments_mc_pddl') stdout_linebuf_envvar = SetEnvironmentVariable( 'RCUTILS_CONSOLE_STDOUT_LINE_BUFFERED', '1') plansys2_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join( get_package_share_directory('plansys2_bringup'), 'launch', 'plansys2_bringup_launch_distributed.py')), launch_arguments={'model_file': example_dir + '/pddl/patrol_w_recharge.pddl'}.items() ) # Specify the actions move_cmd = Node( package='navigation_experiments_mc_pddl', executable='move_action_node', name='move_action_node', output='screen', parameters=[]) patrol_cmd = Node( package='navigation_experiments_mc_pddl', executable='patrol_action_node', name='patrol_action_node', output='screen', parameters=[]) charge_cmd = Node( package='navigation_experiments_mc_pddl', executable='charge_action_node', name='charge_action_node', output='screen', parameters=[]) ask_charge_cmd = Node( package='navigation_experiments_mc_pddl', executable='ask_charge_action_node', name='ask_charge_action_node', output='screen', parameters=[]) #pddl_controller_cmd = Node( # package='navigation_experiments_mc_pddl', # executable='patrolling_controller_node', # name='patrolling_controller_node', # output='screen', # parameters=[]) # Create the launch description and populate ld = LaunchDescription() # Set environment variables ld.add_action(stdout_linebuf_envvar) # Declare the launch options ld.add_action(plansys2_cmd) ld.add_action(move_cmd) ld.add_action(patrol_cmd) ld.add_action(charge_cmd) ld.add_action(ask_charge_cmd) #ld.add_action(pddl_controller_cmd) return ld <file_sep>/navigation_experiments_mc_bts/src/behavior_tree_nodes/Recharge.cpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <memory> #include "navigation_experiments_mc_bts/behavior_tree_nodes/Recharge.hpp" using namespace std::chrono_literals; namespace navigation_experiments_mc_bts { Recharge::Recharge( const std::string & action_name, const BT::NodeConfiguration & conf) : BT::AsyncActionNode(action_name, conf) { node_ = config().blackboard->get<rclcpp::Node::SharedPtr>("node"); client_ = node_->create_client<std_srvs::srv::Empty>("battery_contingency/battery_charged"); } BT::NodeStatus Recharge::tick() { while(rclcpp::ok()) { RCLCPP_INFO(node_->get_logger(), "Recharging battery for 10 seconds"); rclcpp::Rate(0.2).sleep(); srv_call(); rclcpp::Rate(0.2).sleep(); break; } RCLCPP_INFO(node_->get_logger(), "Battery fully recharged"); auto component_map = config().blackboard->get<std::unordered_map<std::string, bool>>("component_map"); RCLCPP_ERROR(node_->get_logger(), "Set battery to true"); auto battery_component = component_map.find("battery"); battery_component->second = true; config().blackboard->set("component_map", component_map); return BT::NodeStatus::SUCCESS; } void Recharge::srv_call() { auto request = std::make_shared<std_srvs::srv::Empty::Request>(); while (!client_->wait_for_service(1s)) { if (!rclcpp::ok()) { RCLCPP_ERROR(node_->get_logger(), "Interrupted while waiting for the service. Exiting."); return; } RCLCPP_INFO(node_->get_logger(), "service not available, waiting again..."); } auto result = client_->async_send_request(request); } } // namespace navigation_experiments_mc_bts #include "behaviortree_cpp_v3/bt_factory.h" BT_REGISTER_NODES(factory) { BT::NodeBuilder builder = [](const std::string & name, const BT::NodeConfiguration & config) { return std::make_unique<navigation_experiments_mc_bts::Recharge>( name, config); }; factory.registerBuilder<navigation_experiments_mc_bts::Recharge>( "Recharge", builder); } <file_sep>/README.md # navigation_experiments_mc_bts_pddl_base A tutorial to get the MROS ecosystem fully working to perform the experiments programming a navigation task with metacontrol, with behavior trees and PDDL. ## Table of Contents 1. [Installing MROS Ecosystem](#installing-mros-ecosystem) 2. [Starting with a Turtlebo3 in Gazebo](#starting-with-a-turtlebo3-in-gazebo) 3. [Navigation system](#navigation-launcher) 4. [The metacontroller](#launch-the-mros2-metacontroller) 5. [Patrol mission](#autonomous-navigation-patrol-mission) 6. [MROS managing contingencies](#mros-managing-contingencies) - [Laser failure](#laser-failure-management) - [Low battery](#low-battery-management) ## Installing MROS Ecosystem MROS is develop under Ubuntu20.04 and ROS2 Foxy, you can find the ROS2 installation steps and the environment setup [here](https://index.ros.org/doc/ros2/Installation/Foxy/), [here](https://index.ros.org/doc/ros2/Tutorials/Colcon-Tutorial/#colcon) and [here](https://index.ros.org/doc/ros2/Tutorials/Colcon-Tutorial/#create-a-workspace). The mros_reasoner uses [Owlready2](https://owlready2.readthedocs.io/en/latest/index.html) and Java to handle the ontologies and perform reasoning. ```console sudo apt-get update sudo apt-get install openjdk-13-jre sudo apt-get install python3-pip pip3 install owlready2 ``` We are focus in mobile robots and we are using the navigation2 package. Fetch, build and install navigation2 stack: ```console source /opt/ros/foxy/setup.bash sudo apt install ros-foxy-slam-toolbox ros-foxy-gazebo-ros-pkgs python3-vcstool python3-rosdep2 python3-colcon-common-extensions cd [ros2_ws]/src wget https://raw.githubusercontent.com/meta-control/navigation_experiments_mc_bts_pddl/main/resources.repos vcs import < resources.repos cd .. rosdep install -y -r -q --from-paths src --ignore-src --rosdistro foxy --skip-keys="turtlebot2_drivers map_server astra_camera amcl" colcon build --symlink-install ``` ## Starting with a Turtlebo3 in Gazebo. Let's start opening Gazebo with a tb3. This launcher includes gazebo, pointcloud_to_laser, laser_driver_wrapper, and **[system-modes](https://github.com/micro-ROS/system_modes)**. The **system_modes mode_manager** takes the modes description from `navigation_experiments_mc_bts_pddl_base/params/pilot_modes.yaml`. ```console export GAZEBO_MODEL_PATH=$GAZEBO_MODEL_PATH:[ros2_ws]/src/turtlebot3/turtlebot3_simulations/turtlebot3_gazebo/models:[ros2_ws]/src/navigation_experiments_mc_bts_pddl/navigation_experiments_mc_bts_pddl_base/worlds/models export TURTLEBOT3_MODEL=${TB3_MODEL} ros2 launch navigation_experiments_mc_bts_pddl_base tb3_sim_launch.py ``` - After the last command, Gazebo window is opened and you should see a tb3 in a domestic scenario. ## Navigation launcher. This launcher includes rviz, nav2, amcl, and map-server. ```console ros2 launch navigation_experiments_mc_bts_pddl_base nav2_turtlebot3_launch.py ``` - RVIz opens, and the navigation system is waiting for the activation of the laser_driver. This activation will be made automatically by the metacontroller in the next step. It is not necessary to set an initial robot position with the 2D Pose Estimate tool. When the laser_driver is up, the pose will be set automatically. ## Launch the mros2 metacontroller. This step launches the `mros2_metacontroller`, it launches by default the `kb.owl` ontology and connects to the system_modes created by the pilot_urjc. - The names of the modes there have been changed to match the `fd` names of the `kb.owl` ontology. ```console ros2 launch mros2_reasoner launch_reasoner.launch.py ``` - The reasoner does not have an objective defined at this point. So you will not see anything happenning until you launch the mission in the next step. ## Autonomous navigation. ![waypoints](resources/waypoints.png) ### Behavior tree patrol mission. We have developed a behavior to go through a set of waypoints autonomously. It is implemented using a simple [BehaviorTree](https://github.com/tud-cor/navigation_experiments_mc_bts_pddl_base/blob/main/navigation_experiments_mc_bts/behavior_trees/bt.xml) ```console ros2 launch navigation_experiments_mc_bts bt_controller_launch.py ``` ### PDDL patrol mission. In this case the controller is implemented using [pddl](https://github.com/tud-cor/navigation_experiments_mc_bts_pddl_base/blob/main/navigation_experiments_mc_pddl/pddl/patrol_w_recharge.pddl) ```console ros2 launch navigation_experiments_mc_pddl pddl_controller_launch.py ros2 run navigation_experiments_mc_pddl patrolling_controller_node ``` ## MROS managing contingencies. Currently, we are supporting two contingencies, a laser sensor failure and battery low. ### Laser failure management. #### Simulating a laser failure. We have develop a RVIz tool to simulate a laser failure and its consequences. It injects all-zero laser messages in the system and forces the laser_wrapper to switch to error_processing state. ![rviz_cont_tool](resources/contingency_tool.png) #### Managing the laser failure. The [mros_modes_observer](https://github.com/MROS-RobMoSys-ITP/mros_modes_observer) package is used to monitor the status of the components (i.e. laser or other sensors) by subscribing to the [`[component_node]/transition_event`](https://github.com/ros2/rcl_interfaces/blob/master/lifecycle_msgs/msg/TransitionEvent.msg). When the laser failure is detected, a message is sent to the metacontroller using the `/diagnostic` topic. ```console mros2_reasoner_node-1] [INFO] [1603183654.050846253] [mros2_reasoner_node]: Entered timer_cb for metacontrol reasoning [mros2_reasoner_node-1] [INFO] [1603183654.052244011] [mros2_reasoner_node]: >> Started MAPE-K ** Analysis (ontological reasoning) ** [mros2_reasoner_node-1] [WARN] [1603183654.625280278] [mros2_reasoner_node]: QA value received for TYPE: laser_resender VALUE: false [mros2_reasoner_node-1] [INFO] [1603183654.781046611] [mros2_reasoner_node]: QA value received! TYPE: laser_resender VALUE: false [mros2_reasoner_node-1] [INFO] [1603183654.781165253] [mros2_reasoner_node]: >> Finished ontological reasoning) ``` - The metacontroller then sets all the modes that use this component as not realisable. This is done through `fd_realisability` with value `false`. - If the current mode is using this component, a reconfiguration is trigger. This is because the current mode is a function grounding of a not realisable function design. - The metacontroller searchs the for a new mode that does not use the component in error, for this pilot it's only the `f_degraded_mode`. ### Low battery management. #### Simulating the battery drining. The battery of the robot is drining based on the movements of the robot. tb3_sim window shows the battery level (1.0 - 0.0). This battery level represents the Energy QA for the metacontroller. - The battery level is sent to the metacontroller as a QA value using the `/diagnostic` topic (See https://github.com/ros2/common_interfaces/blob/foxy/diagnostic_msgs/msg/DiagnosticArray.msg) ``` mros2_reasoner_node-1] [INFO] [1603183654.050846253] [mros2_reasoner_node]: Entered timer_cb for metacontrol reasoning [mros2_reasoner_node-1] [INFO] [1603183654.052244011] [mros2_reasoner_node]: >> Started MAPE-K ** Analysis (ontological reasoning) ** [mros2_reasoner_node-1] [WARN] [1603183654.625280278] [mros2_reasoner_node]: QA value received for TYPE: energy VALUE: 0.493473 [mros2_reasoner_node-1] [INFO] [1603183654.781046611] [mros2_reasoner_node]: QA value received! TYPE: energy VALUE: 0.493473 [mros2_reasoner_node-1] [INFO] [1603183654.781165253] [mros2_reasoner_node]: >> Finished ontological reasoning) ``` - When the battery goes over a threshold `0.5` a reconfiguration is required. The battery_contingency_node sents a diagnostics msg to the metacontroller advertising that the battery is not enough. - The metacontroller searchs the for a new mode, and marks the current one as failed. ``` [mros2_reasoner_node-1] [INFO] [1613476795.519762331] [mros2_reasoner_node]: >> Started MAPE-K ** Analysis (ontological reasoning) ** [mros2_reasoner_node-1] [WARN] [1613476796.161156157] [mros2_reasoner_node]: Objective e51f829f591afb02b19efe375bf2f90 in status: IN_ERROR_COMPONENT [mros2_reasoner_node-1] [INFO] [1613476796.161521288] [mros2_reasoner_node]: >> Started MAPE-K ** PLAN adaptation ** [mros2_reasoner_node-1] [INFO] [1613476796.161860404] [mros2_reasoner_node]: >> Reasoner searches an FD ``` - The new mode is changed using the `/change mode` service provided by the system modes. ``` [mros2_reasoner_node-1] WARNING:root: == Obatin Best Function Design == [mros2_reasoner_node-1] WARNING:root:== FunctionDesigns AVAILABLE: ['f_degraded_mode', 'f_energy_saving_mode', 'f_normal_mode', 'f_performance_mode', 'f_slow_mode'] [mros2_reasoner_node-1] WARNING:root:== FunctionDesigns REALISABLE: ['f_energy_saving_mode'] [mros2_reasoner_node-1] WARNING:root:== FunctionDesigns NOT IN ERROR LOG: ['f_energy_saving_mode'] [mros2_reasoner_node-1] WARNING:root:== FunctionDesigns also meeting NFRs: ['f_energy_saving_mode'] [mros2_reasoner_node-1] WARNING:root:== Utility for f_energy_saving_mode : 0.300000 [mros2_reasoner_node-1] WARNING:root: == Best FD available f_energy_saving_mode [mros2_reasoner_node-1] [INFO] [1613476796.162774887] [mros2_reasoner_node]: >> Started MAPE-K ** EXECUTION ** [mros2_reasoner_node-1] [WARN] [1613476796.163110077] [mros2_reasoner_node]: New Configuration requested: f_energy_saving_mode [mros2_reasoner_node-1] [INFO] [1613476796.166859840] [mros2_reasoner_node]: Got Reconfiguration result True [mros2_reasoner_node-1] [INFO] [1613476796.168155123] [mros2_reasoner_node]: Exited timer_cb after successful reconfiguration - Obj set to None [mros2_reasoner_node-1] [INFO] [1613476797.016818483] [mros2_reasoner_node]: QA value received! TYPE: energy VALUE: 0.473608 [mros2_reasoner_node-1] [INFO] [1613476797.274176134] [mros2_reasoner_node]: Cancel Action Callback! [mros2_reasoner_node-1] WARNING:root: >>> Ontology Status <<< [mros2_reasoner_node-1] WARNING:root: [mros2_reasoner_node-1] Component Status: [('battery', 'FALSE')] [mros2_reasoner_node-1] WARNING:root: [mros2_reasoner_node-1] FG: fg_f_energy_saving_mode Status: None Solves: e51f829f591afb02b19efe375bf2f90 FD: f_energy_saving_mode QAvalues: [('energy', 0.473608)] [mros2_reasoner_node-1] WARNING:root: [mros2_reasoner_node-1] OBJECTIVE: e51f829f591afb02b19efe375bf2f90 Status: None NFRs: [('energy', 0.5), ('safety', 0.5)] ``` #### Recharging behavior. Once the `f_energy_saving_mode` is set, the current action should be canceled and the recharge protocol takes action. The robot goes to the recharge station, waits until the battery is recharged, and then it returns to the patrolling mission. <file_sep>/navigation_experiments_mc_pddl/src/recover_nav_sensor_node.cpp // Copyright 2019 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "geometry_msgs/msg/twist.hpp" #include "plansys2_executor/ActionExecutorClient.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" #include "lifecycle_msgs/msg/state.hpp" using namespace std::chrono_literals; class RecoverNavSensor : public plansys2::ActionExecutorClient { public: RecoverNavSensor() : plansys2::ActionExecutorClient("recover_nav_sensor", 1s) { } private: void do_work() { finish(true, 1.0, "Sensor recovered"); } }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto node = std::make_shared<RecoverNavSensor>(); node->set_parameter(rclcpp::Parameter("action_name", "recover_nav_sensor")); node->trigger_transition(lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); rclcpp::spin(node->get_node_base_interface()); rclcpp::shutdown(); return 0; } <file_sep>/navigation_experiments_mc_bts/include/navigation_experiments_mc_bts/behavior_tree_nodes/Recharge.hpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__RECHARGE_HPP_ #define navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__RECHARGE_HPP_ #include <string> #include <memory> #include "behaviortree_cpp_v3/behavior_tree.h" #include "behaviortree_cpp_v3/bt_factory.h" #include "std_srvs/srv/empty.hpp" #include "rclcpp/rclcpp.hpp" namespace navigation_experiments_mc_bts { class Recharge : public BT::AsyncActionNode { public: explicit Recharge( const std::string & action_name, const BT::NodeConfiguration & conf); BT::NodeStatus tick() override; static BT::PortsList providedPorts() { return providedBasicPorts({}); } static BT::PortsList providedBasicPorts(BT::PortsList addition) { BT::PortsList basic = { BT::InputPort<std::chrono::milliseconds>("server_timeout") }; basic.insert(addition.begin(), addition.end()); return basic; } private: rclcpp::Node::SharedPtr node_; rclcpp::Client<std_srvs::srv::Empty>::SharedPtr client_; void srv_call(); }; } // namespace navigation_experiments_mc_bts #endif // navigation_experiments_mc_bts__BEHAVIOR_TREE_NODES__RECHARGE_HPP_ <file_sep>/navigation_experiments_mc_bts_pddl_base/launch/tiago/tiago_mros_launch.py # Copyright (c) 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This is all-in-one launch script intended for use by nav2 developers.""" import os from ament_index_python.packages import get_package_share_directory, get_package_prefix from launch import LaunchDescription from launch.actions import DeclareLaunchArgument, ExecuteProcess, EmitEvent from launch.conditions import IfCondition from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import LaunchConfiguration, PythonExpression from launch_ros.actions import Node, LifecycleNode from launch_ros.events.lifecycle import ChangeState import launch.events import lifecycle_msgs.msg def generate_launch_description(): # Get the launch directory nav2_bringup_dir = get_package_share_directory('nav2_bringup') pilot_bringup_dir = get_package_share_directory('navigation_experiments_mc_bts_pddl_base') launch_dir = os.path.join(nav2_bringup_dir, 'launch') # Create the launch configuration variables namespace = LaunchConfiguration('namespace') use_sim_time = LaunchConfiguration('use_sim_time') remappings = [('/tf', 'tf'), ('/tf_static', 'tf_static')] declare_namespace_cmd = DeclareLaunchArgument( 'namespace', default_value='', description='Top-level namespace') declare_use_sim_time_cmd = DeclareLaunchArgument( 'use_sim_time', default_value='True', description='Use simulation (Gazebo) clock if true') pcl2laser_cmd = LifecycleNode( package='pointcloud_to_laserscan', executable='pointcloud_to_laserscan_managed', name='pointcloud_to_laser', remappings=[('cloud_in', '/xtion/depth_registered/points'), ('scan', '/mros_scan')], parameters=[{ 'target_frame': 'base_footprint', 'transform_tolerance': 0.01, 'min_height': 0.0, 'max_height': 1.0, 'angle_min': -1.5708, # -M_PI/2 'angle_max': 1.5708, # M_PI/2 'angle_increment': 0.0087, # M_PI/360.0 'scan_time': 0.3333, 'range_min': 0.45, 'range_max': 4.0, 'use_inf': True, 'inf_epsilon': 1.0 }], ) emit_event_to_request_that_pcl2laser_configure_transition = EmitEvent( event=ChangeState( lifecycle_node_matcher=launch.events.matches_action(pcl2laser_cmd), transition_id=lifecycle_msgs.msg.Transition.TRANSITION_CONFIGURE, ) ) laser_resender_cmd = LifecycleNode( name='laser_resender', package='laser_resender', executable='laser_resender_node', output='screen') battery_contingency_cmd = Node( name='battery_contingency_sim', package='mros_contingencies_sim', executable='battery_contingency_sim_node', output='screen') components_file_path = (get_package_share_directory('mros_modes_observer') + '/params/components.yaml') modes_observer_node = Node( package='mros_modes_observer', executable='modes_observer_node', parameters=[{'componentsfile': components_file_path}], output='screen') emit_event_to_request_that_laser_resender_configure_transition = EmitEvent( event=ChangeState( lifecycle_node_matcher=launch.events.matches_action(laser_resender_cmd), transition_id=lifecycle_msgs.msg.Transition.TRANSITION_CONFIGURE, ) ) shm_model_path = (get_package_share_directory('navigation_experiments_mc_bts_pddl_base') + '/params/pilot_modes.yaml') # Start as a normal node is currently not possible. # Path to SHM file should be passed as a ROS parameter. mode_manager_node = Node( package='system_modes', executable='mode_manager', parameters=[{'modelfile': shm_model_path}], output='screen') ld = LaunchDescription() # Declare the launch options ld.add_action(declare_namespace_cmd) ld.add_action(declare_use_sim_time_cmd) # Add system modes manager ld.add_action(mode_manager_node) # Add system modes observer node ld.add_action(modes_observer_node) ld.add_action(pcl2laser_cmd) ld.add_action(laser_resender_cmd) ld.add_action(battery_contingency_cmd) ld.add_action(emit_event_to_request_that_pcl2laser_configure_transition) ld.add_action(emit_event_to_request_that_laser_resender_configure_transition) return ld <file_sep>/navigation_experiments_mc_pddl/src/move_action_node.cpp // Copyright 2019 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <math.h> #include <memory> #include <string> #include <map> #include <algorithm> #include "geometry_msgs/msg/pose_stamped.hpp" #include "geometry_msgs/msg/pose.hpp" #include "geometry_msgs/msg/pose_with_covariance_stamped.hpp" #include "mros2_msgs/action/navigate_to_pose_qos.hpp" #include "nav2_msgs/action/navigate_to_pose.hpp" #include "nav2_util/geometry_utils.hpp" #include "plansys2_executor/ActionExecutorClient.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" using namespace std::chrono_literals; using NavigateToPoseQos = mros2_msgs::action::NavigateToPoseQos; class MoveAction : public plansys2::ActionExecutorClient { public: MoveAction() : plansys2::ActionExecutorClient("move", 500ms) { geometry_msgs::msg::PoseStamped wp; wp.header.frame_id = "/map"; wp.pose.position.x = 1.0; wp.pose.position.y = -1.0; wp.pose.position.z = 0.0; wp.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(M_PI_2); waypoints_["wp1"] = wp; wp.pose.position.x = -1.0; wp.pose.position.y = 1.0; wp.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(M_PI); waypoints_["wp2"] = wp; wp.pose.position.x = -3.5; wp.pose.position.y = 1.0; wp.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(M_PI); waypoints_["wp3"] = wp; wp.pose.position.x = -6.25; wp.pose.position.y = 2.66; wp.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(-M_PI_2); waypoints_["wp4"] = wp; wp.pose.position.x = 4.0; wp.pose.position.y = -3.0; wp.pose.orientation = nav2_util::geometry_utils::orientationAroundZAxis(0.0); waypoints_["wp_control"] = wp; using namespace std::placeholders; pos_sub_ = create_subscription<geometry_msgs::msg::PoseWithCovarianceStamped>( "/amcl_pose", 10, std::bind(&MoveAction::current_pos_callback, this, _1)); private_node_ = rclcpp::Node::make_shared("pr_move_node"); problem_expert_ = std::make_shared<plansys2::ProblemExpertClient>(private_node_); sys_issue_detected_ = false; } void current_pos_callback(const geometry_msgs::msg::PoseWithCovarianceStamped::SharedPtr msg) { current_pos_ = msg->pose.pose; } rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) { sys_issue_detected_ = false; goal_sended_stamp_ = now(); send_feedback(0.0, "Move starting"); navigation_action_client_ = rclcpp_action::create_client<NavigateToPoseQos>( shared_from_this(), "navigate_to_pose_qos"); bool is_action_server_ready = false; do { RCLCPP_INFO(get_logger(), "Waiting for navigation action server..."); is_action_server_ready = navigation_action_client_->wait_for_action_server(std::chrono::seconds(5)); } while (!is_action_server_ready); RCLCPP_INFO(get_logger(), "Navigation action server ready"); wp_to_navigate_ = get_arguments()[2]; // The goal is in the 3rd argument of the action current_mode_ = get_arguments()[3]; // The mode is in the 4rd argument of the action RCLCPP_INFO(get_logger(), "Start navigation to [%s]", wp_to_navigate_.c_str()); goal_pos_ = waypoints_[wp_to_navigate_]; navigation_goal_.pose = goal_pos_; navigation_goal_.qos_expected.objective_type = "f_navigate"; // should be mros_goal->qos_expected.objective_type = "f_navigate"; diagnostic_msgs::msg::KeyValue energy_qos; energy_qos.key = "energy"; energy_qos.value = "0.7"; diagnostic_msgs::msg::KeyValue safety_qos; safety_qos.key = "safety"; safety_qos.value = "0.5"; navigation_goal_.qos_expected.qos.clear(); navigation_goal_.qos_expected.qos.push_back(energy_qos); navigation_goal_.qos_expected.qos.push_back(safety_qos); dist_to_move = getDistance(goal_pos_.pose, current_pos_); auto send_goal_options = rclcpp_action::Client<NavigateToPoseQos>::SendGoalOptions(); if (current_mode_ == "f_normal_mode") { send_goal_options.feedback_callback = [this]( NavigationGoalHandle::SharedPtr, NavigationFeedback feedback) { if (feedback->qos_status.selected_mode == "f_energy_saving_mode" && now() - goal_sended_stamp_ > rclcpp::Duration::from_seconds(2.0)) { problem_expert_->removePredicate(plansys2::Predicate("(battery_enough r2d2)")); problem_expert_->addPredicate(plansys2::Predicate("(battery_low r2d2)")); problem_expert_->addPredicate(plansys2::Predicate("(robot_at r2d2 wp_aux)")); sys_issue_detected_ = true; return; } else if (feedback->qos_status.selected_mode == "f_degraded_mode") { problem_expert_->addPredicate(plansys2::Predicate("(robot_at r2d2 wp_aux)")); problem_expert_->removePredicate(plansys2::Predicate("(nav_sensor r2d2)")); sys_issue_detected_ = true; } send_feedback( std::min(1.0, std::max(0.0, 1.0 - (feedback->distance_remaining / dist_to_move))), "Move running"); }; } else { send_goal_options.feedback_callback = [this]( NavigationGoalHandle::SharedPtr, NavigationFeedback feedback) { send_feedback( std::min(1.0, std::max(0.0, 1.0 - (feedback->distance_remaining / dist_to_move))), "Move running"); }; } send_goal_options.result_callback = [this](auto) { finish(true, 1.0, "Move completed"); }; future_navigation_goal_handle_ = navigation_action_client_->async_send_goal(navigation_goal_, send_goal_options); return ActionExecutorClient::on_activate(previous_state); } private: double getDistance(const geometry_msgs::msg::Pose & pos1, const geometry_msgs::msg::Pose & pos2) { return sqrt( (pos1.position.x - pos2.position.x) * (pos1.position.x - pos2.position.x) + (pos1.position.y - pos2.position.y) * (pos1.position.y - pos2.position.y)); } void do_work() { if (sys_issue_detected_) { RCLCPP_WARN(get_logger(), "System issue detected, cancelling move action ..."); finish(false, 0.0, "System issue detected"); navigation_action_client_->async_cancel_all_goals(); } } std::map<std::string, geometry_msgs::msg::PoseStamped> waypoints_; using NavigationGoalHandle = rclcpp_action::ClientGoalHandle<NavigateToPoseQos>; using NavigationFeedback = const std::shared_ptr<const NavigateToPoseQos::Feedback>; rclcpp_action::Client<NavigateToPoseQos>::SharedPtr navigation_action_client_; std::shared_future<NavigationGoalHandle::SharedPtr> future_navigation_goal_handle_; NavigationGoalHandle::SharedPtr navigation_goal_handle_; rclcpp::Subscription<geometry_msgs::msg::PoseWithCovarianceStamped>::SharedPtr pos_sub_; geometry_msgs::msg::Pose current_pos_; geometry_msgs::msg::PoseStamped goal_pos_; NavigateToPoseQos::Goal navigation_goal_; std::shared_ptr<plansys2::ProblemExpertClient> problem_expert_; std::shared_ptr<rclcpp::Node> private_node_; double dist_to_move; std::string wp_to_navigate_, current_mode_; bool sys_issue_detected_; rclcpp::Time goal_sended_stamp_; }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto node = std::make_shared<MoveAction>(); node->set_parameter(rclcpp::Parameter("action_name", "move")); node->trigger_transition(lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); rclcpp::spin(node->get_node_base_interface()); rclcpp::shutdown(); return 0; } <file_sep>/navigation_experiments_mc_bts/src/behavior_tree_nodes/Reconfigure.cpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <memory> #include "navigation_experiments_mc_bts/behavior_tree_nodes/Reconfigure.hpp" using namespace std::chrono_literals; namespace navigation_experiments_mc_bts { Reconfigure::Reconfigure( const std::string & action_name, const BT::NodeConfiguration & conf) : BT::AsyncActionNode(action_name, conf) { node_ = config().blackboard->get<rclcpp::Node::SharedPtr>("node"); client_ = node_->create_client<system_modes::srv::ChangeMode>("/pilot/change_mode"); } BT::NodeStatus Reconfigure::tick() { auto new_mode = getInput<std::string>("mode").value(); RCLCPP_INFO(node_->get_logger(), "Reconfiguring system mode to %s", new_mode.c_str()); if (reconfigure_srv_call(new_mode)) { rclcpp::Rate(1.0).sleep(); return BT::NodeStatus::SUCCESS; } else { return BT::NodeStatus::FAILURE; } } bool Reconfigure::reconfigure_srv_call(std::string new_mode) { auto request = std::make_shared<system_modes::srv::ChangeMode::Request>(); request->mode_name = new_mode; while (!client_->wait_for_service(1s)) { if (!rclcpp::ok()) { RCLCPP_ERROR(node_->get_logger(), "Interrupted while waiting for the service. Exiting."); return false; } RCLCPP_INFO(node_->get_logger(), "service not available, waiting again..."); } auto result = client_->async_send_request(request); // Wait for the result. if (rclcpp::spin_until_future_complete(node_, result) == rclcpp::FutureReturnCode::SUCCESS) { RCLCPP_INFO(node_->get_logger(), "System mode correctly changed"); return true; } else { RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Failed to call service change_mode"); return false; } } } // namespace navigation_experiments_mc_bts #include "behaviortree_cpp_v3/bt_factory.h" BT_REGISTER_NODES(factory) { BT::NodeBuilder builder = [](const std::string & name, const BT::NodeConfiguration & config) { return std::make_unique<navigation_experiments_mc_bts::Reconfigure>( name, config); }; factory.registerBuilder<navigation_experiments_mc_bts::Reconfigure>( "Reconfigure", builder); } <file_sep>/navigation_experiments_mc_bts/test/check_order_test.cpp // Copyright 2020 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <memory> #include "behaviortree_cpp_v3/behavior_tree.h" #include "behaviortree_cpp_v3/bt_factory.h" #include "behaviortree_cpp_v3/utils/shared_library.h" #include "behaviortree_cpp_v3/blackboard.h" #include "ros2_knowledge_graph/GraphNode.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" #include "gtest/gtest.h" TEST(check_order_test, basic_usage) { BT::BehaviorTreeFactory factory; BT::SharedLibrary loader; factory.registerFromPlugin(loader.getOSName("navigation_experiments_mc_bts_check_order_bt_node")); std::string bt_xml = R"( <root main_tree_to_execute = "MainTree" > <BehaviorTree ID="MainTree"> <CheckOrder name="check_order"/> </BehaviorTree> </root> )"; auto blackboard = BT::Blackboard::create(); auto node = rclcpp::Node::make_shared("bt_node"); blackboard->set("node", node); BT::Tree tree = factory.createTreeFromText(bt_xml, blackboard); auto start = node->now(); while ((node->now() - start).seconds() < 0.5) {} auto finish = tree.rootNode()->executeTick() == BT::NodeStatus::SUCCESS; start = node->now(); while ((node->now() - start).seconds() < 0.5) {} ASSERT_TRUE(finish); } int main(int argc, char ** argv) { rclcpp::init(argc, argv); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
e6c9986f9f064bce24b7348df11af7d110bd6284
[ "Markdown", "Python", "CMake", "C++" ]
25
C++
tud-cor/navigation_experiments_mc_bts_pddl
b4bc43f101dfbac19f265199ce4739e709268f2b
d8569fe2c70d87684dcbe40350a855831f26a70a
refs/heads/master
<repo_name>MollieS/ClojureWebTTT<file_sep>/src/main/java/tttweb/Application.java package tttweb; import httpserver.SocketServer; import httpserver.routing.Route; import httpserver.routing.Router; import httpserver.server.HTTPLogger; import httpserver.server.HTTPServer; import httpserver.server.HTTPSocketServer; import httpserver.sessions.HTTPSessionFactory; import httpserver.sessions.SessionExpirationDateGenerator; import httpserver.sessions.SessionManager; import httpserver.sessions.SessionTokenGenerator; import tttweb.controllers.GameController; import tttweb.controllers.MenuController; import tttweb.controllers.NewGameController; import tttweb.controllers.UpdateBoardController; import java.io.IOException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Application { public static void start() { Router router = createRouter(); HTTPLogger logger = new HTTPLogger("./logs"); ExecutorService executorService = Executors.newFixedThreadPool(40); SocketServer socketServer = getSocketServer(); HTTPServer httpServer = new HTTPServer(socketServer, router, logger); try { httpServer.start(executorService); } finally { executorService.shutdown(); } } private static SocketServer getSocketServer() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(5000); } catch (IOException e) { e.printStackTrace(); } return new HTTPSocketServer(serverSocket); } private static Router createRouter() { List<Route> routes = new ArrayList(); SessionManager sessionManager = new SessionManager(new HTTPSessionFactory()); routes.add(new MenuController(new SessionTokenGenerator(), new SessionExpirationDateGenerator())); routes.add(new NewGameController(sessionManager)); routes.add(new GameController(sessionManager)); routes.add(new UpdateBoardController(sessionManager)); return new Router(routes); } } <file_sep>/src/test/java/tttweb/doubles/SessionFactorySpy.java package tttweb.doubles; import httpserver.sessions.HTTPSession; import httpserver.sessions.Session; import httpserver.sessions.SessionFactory; public class SessionFactorySpy implements SessionFactory { public HTTPSession createdSession; public int timesCalled = 0; @Override public Session createSession(String id) { timesCalled++; createdSession = new HTTPSession(id); return createdSession; } } <file_sep>/src/main/java/tttweb/controllers/GameController.java package tttweb.controllers; import httpserver.Request; import httpserver.Response; import httpserver.httprequests.RequestHeader; import httpserver.httpresponse.HTTPResponse; import httpserver.httpresponse.ResponseHeader; import httpserver.resourcemanagement.HTMLResource; import httpserver.routing.Route; import httpserver.sessions.Session; import httpserver.sessions.SessionManager; import tttweb.Game; import tttweb.view.GamePresenter; import tttweb.view.GameView; import java.util.HashMap; import static httpserver.httpresponse.StatusCode.OK; import static httpserver.httpresponse.StatusCode.REDIRECT; import static httpserver.routing.Method.POST; public class GameController extends Route { private final SessionManager sessionManager; public GameController(SessionManager sessionManager) { super("/game", POST); this.sessionManager = sessionManager; } @Override public Response performAction(Request request) { if (invalidRequest(request)) { return redirect(); } String sessionId = request.getValue(RequestHeader.COOKIE); if (!sessionManager.exists(sessionId)) { return redirect(); } Session currentSession = sessionManager.getSession(sessionId); if (isInvalid(currentSession)) { return redirect(); } return validRequest(sessionId); } private Response validRequest(String sessionId) { Session currentSession = sessionManager.getSession(sessionId); String gameType = currentSession.getData().get("gameType"); String[] boardState = currentSession.getData().get("boardState").split(""); Game game = new Game(boardState, gameType); String gameView = GameView.createView(new GamePresenter(game)); HTMLResource htmlResource = new HTMLResource(gameView.getBytes()); return HTTPResponse.create(OK).withBody(htmlResource); } private boolean invalidRequest(Request request) { return !request.hasHeader(RequestHeader.COOKIE); } private boolean isInvalid(Session currentSession) { return !(currentSession.hasData("gameType") && currentSession.hasData("boardState")); } private Response redirect() { HashMap<ResponseHeader, byte[]> headers = new HashMap<>(); headers.put(ResponseHeader.LOCATION, "/".getBytes()); return HTTPResponse.create(REDIRECT).withHeaders(headers); } } <file_sep>/src/test/java/tttweb/doubles/SessionManagerStub.java package tttweb.doubles; import httpserver.sessions.HTTPSession; import httpserver.sessions.Session; import httpserver.sessions.SessionManager; public class SessionManagerStub extends SessionManager { private HTTPSession session; public SessionManagerStub() { super(new SessionFactorySpy()); this.session = new HTTPSession("1"); } @Override public Session getOrCreateSession(String sessionId) { session.addData("boardState", "---------"); session.addData("gameType", "hvh"); return session; } @Override public boolean exists(String sessionId) { return sessionId.equals("1"); } @Override public Session getSession(String sessionID) { return session; } } <file_sep>/src/main/java/tttweb/view/GamePresenter.java package tttweb.view; import tttweb.Game; public class GamePresenter { private final Game game; public GamePresenter(Game game) { this.game = game; } public boolean gameIsOver() { return game.isOver(); } public String gameType() { return game.gameType(); } public String getMark(int i) { String[] boardArray = game.getBoard(); if (boardArray[i].equals("-")) { return "-"; } return boardArray[i].toLowerCase(); } public String getResult() { if (game.isOver() && !game.isDraw()) { return (game.winningSymbol() + " wins!"); } else if (game.isDraw()) { return "It's a draw!"; } return ""; } } <file_sep>/src/main/java/tttweb/controllers/NewGameController.java package tttweb.controllers; import httpserver.Request; import httpserver.Response; import httpserver.httpresponse.HTTPResponse; import httpserver.httpresponse.ResponseHeader; import httpserver.routing.Route; import httpserver.sessions.Session; import httpserver.sessions.SessionManager; import java.util.HashMap; import static httpserver.httprequests.RequestHeader.COOKIE; import static httpserver.httprequests.RequestHeader.DATA; import static httpserver.httpresponse.StatusCode.REDIRECT; import static httpserver.routing.Method.POST; public class NewGameController extends Route { private final SessionManager sessionManager; public NewGameController(SessionManager sessionManager) { super("/new-game", POST); this.sessionManager = sessionManager; } @Override public Response performAction(Request request) { if (requestIsInvalid(request)) { return redirect("/"); } return createNewGame(request); } private Response createNewGame(Request request) { String sessionID = request.getValue(COOKIE); updateSession(sessionID, request); return redirect("/game"); } private boolean requestIsInvalid(Request request) { return !request.hasHeader(COOKIE) || !request.hasHeader(DATA); } private void updateSession(String sessionID, Request request) { Session currentSession = sessionManager.getOrCreateSession(sessionID); addGameTypeToSession(currentSession, request); addBoardStateToSession(currentSession); } private void addBoardStateToSession(Session currentSession) { currentSession.addData("boardState", "---------"); } private void addGameTypeToSession(Session currentSession, Request request) { String gameType = request.getValue(DATA); currentSession.addData("gameType", gameType); } private Response redirect(String url) { HashMap<ResponseHeader, byte[]> headers = new HashMap<>(); headers.put(ResponseHeader.LOCATION, url.getBytes()); return HTTPResponse.create(REDIRECT).withHeaders(headers); } } <file_sep>/settings.gradle rootProject.name = 'Clojure-TTT-Web' <file_sep>/README.md # Web Tic Tac Toe [![Build Status](https://travis-ci.org/MollieS/ClojureWebTTT.svg?branch=master)](https://travis-ci.org/MollieS/ClojureWebTTT) [![Coverage Status](https://coveralls.io/repos/github/MollieS/ClojureWebTTT/badge.svg?branch=master)](https://coveralls.io/github/MollieS/ClojureWebTTT?branch=master)<file_sep>/src/main/java/tttweb/controllers/MenuController.java package tttweb.controllers; import httpserver.Request; import httpserver.Response; import httpserver.httpresponse.HTTPResponse; import httpserver.httpresponse.ResponseHeader; import httpserver.resourcemanagement.HTMLResource; import httpserver.routing.Route; import httpserver.sessions.SessionExpirationDateGenerator; import httpserver.sessions.SessionTokenGenerator; import java.time.ZonedDateTime; import java.util.HashMap; import static httpserver.httpresponse.StatusCode.OK; import static httpserver.routing.Method.GET; import static httpserver.routing.Method.HEAD; public class MenuController extends Route { private final SessionTokenGenerator sessionTokenGenerator; private final SessionExpirationDateGenerator sessionExpiryDateGenerator; public MenuController(SessionTokenGenerator sessionTokenGenerator, SessionExpirationDateGenerator sessionExpirationDateGenerator) { super("/", GET, HEAD); this.sessionTokenGenerator = sessionTokenGenerator; this.sessionExpiryDateGenerator = sessionExpirationDateGenerator; } public Response performAction(Request request) { if (methodIsAllowed(request.getMethod())) { HTMLResource htmlResource = new HTMLResource("/menu"); return HTTPResponse.create(OK).withHeaders(addCookieToHeader()).withBody(htmlResource); } return methodNotAllowed(); } private HashMap<ResponseHeader, byte[]> addCookieToHeader() { HashMap<ResponseHeader, byte[]> headers = new HashMap<>(); String sessionToken = "sessionToken=" + sessionTokenGenerator.generateToken() + ";"; String expiryDate = "Expires=" + sessionExpiryDateGenerator.generateExpiryDate(ZonedDateTime.now()); headers.put(ResponseHeader.COOKIE, ((sessionToken + " " + expiryDate)).getBytes()); return headers; } } <file_sep>/src/test/java/tttweb/controllers/GameControllerTest.java package tttweb.controllers; import httpserver.Response; import httpserver.httpresponse.ResponseHeader; import httpserver.sessions.SessionManager; import org.junit.Test; import tttweb.doubles.RequestDouble; import tttweb.doubles.SessionManagerStub; import java.nio.charset.Charset; import static httpserver.routing.Method.GET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class GameControllerTest { private SessionManager sessionManager = new SessionManagerStub(); private GameController gameController = new GameController(sessionManager); @Test public void redirectsToMenuPageIfRequestHasNoCookie() { RequestDouble requestDouble = new RequestDouble("/game", GET); Response response = gameController.performAction(requestDouble); assertEquals(302, response.getStatusCode()); assertEquals("Found", response.getReasonPhrase()); assertTrue(response.hasHeader(ResponseHeader.LOCATION)); assertEquals("/", new String(response.getValue(ResponseHeader.LOCATION), Charset.defaultCharset())); } @Test public void redirectsToMenuPageIfRequestHasNoSessionAssociatedWithIt() { RequestDouble requestDouble = new RequestDouble("/game", GET); requestDouble.addCookie("3"); Response response = gameController.performAction(requestDouble); assertEquals(302, response.getStatusCode()); assertEquals("Found", response.getReasonPhrase()); assertTrue(response.hasHeader(ResponseHeader.LOCATION)); assertEquals("/", new String(response.getValue(ResponseHeader.LOCATION), Charset.defaultCharset())); } @Test public void redirectsToMenuPageIfRequestHasNoGameData() { RequestDouble requestDouble = new RequestDouble("/game", GET); requestDouble.addCookie("2"); Response response = gameController.performAction(requestDouble); assertEquals(302, response.getStatusCode()); assertEquals("Found", response.getReasonPhrase()); assertTrue(response.hasHeader(ResponseHeader.LOCATION)); assertEquals("/", new String(response.getValue(ResponseHeader.LOCATION), Charset.defaultCharset())); } @Test public void sendsA200ResponseWithBodyForAValidRequest() { sessionManager.getOrCreateSession("1"); RequestDouble requestDouble = new RequestDouble("/game", GET); requestDouble.addCookie("1"); Response reponse = gameController.performAction(requestDouble); assertEquals(200, reponse.getStatusCode()); assertEquals("OK", reponse.getReasonPhrase()); assertTrue(reponse.hasBody()); } } <file_sep>/src/test/java/tttweb/controllers/MenuControllerTest.java package tttweb.controllers; import httpserver.Request; import httpserver.Response; import httpserver.sessions.SessionExpirationDateGenerator; import httpserver.sessions.SessionTokenGenerator; import org.junit.Test; import tttweb.doubles.RequestDouble; import java.nio.charset.Charset; import static httpserver.httpresponse.ResponseHeader.COOKIE; import static httpserver.routing.Method.GET; import static httpserver.routing.Method.POST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class MenuControllerTest { private MenuController menuController = new MenuController(new SessionTokenGeneratorStub(), new SessionExpirationDateGenerator()); @Test public void sendsA200Response() { Request httpRequest = new RequestDouble("/", GET); Response response = menuController.performAction(httpRequest); assertEquals(200, response.getStatusCode()); assertEquals("OK", response.getReasonPhrase()); } @Test public void sendsA405IfMethodNotAllowed() { Request httpRequest = new RequestDouble("/", POST); Response response = menuController.performAction(httpRequest); assertEquals(405, response.getStatusCode()); assertEquals("Method Not Allowed", response.getReasonPhrase()); } @Test public void returnsASetCookieHeaderResponse() { Request httpRequest = new RequestDouble("/", GET); Response response = menuController.performAction(httpRequest); assertTrue(response.hasHeader(COOKIE)); } @Test public void addsASessionTokenAndExpiryDateForCookie() { Request httpRequest = new RequestDouble("/", GET); Response response = menuController.performAction(httpRequest); String cookie = new String(response.getValue(COOKIE), Charset.defaultCharset()); assertTrue(cookie.contains("sessionToken=1")); assertTrue(cookie.contains("Expires=")); } @Test public void addsBodyToResponse() { Request httpRequest = new RequestDouble("/", GET); Response response = menuController.performAction(httpRequest); assertTrue(response.hasBody()); } private class SessionTokenGeneratorStub extends SessionTokenGenerator { @Override public int generateToken() { return 1; } } } <file_sep>/src/test/java/tttweb/doubles/RequestDouble.java package tttweb.doubles; import httpserver.Request; import httpserver.httprequests.RequestHeader; import httpserver.routing.Method; import java.net.URI; public class RequestDouble implements Request { private final Method method; private final String url; private String cookie; private String data; public RequestDouble(String url, Method method) { this.url = url; this.method = method; } public boolean hasHeader(RequestHeader requestHeader) { if (requestHeader == RequestHeader.COOKIE) { return cookie != null; } else { return data != null; } } public String getValue(RequestHeader requestHeader) { if (requestHeader == RequestHeader.COOKIE) { return cookie; } else { return data; } } public Method getMethod() { return method; } public URI getRequestURI() { return null; } public void addCookie(String id) { this.cookie = id; } public void addData(String gameType) { this.data = gameType; } } <file_sep>/build.gradle plugins { id "com.github.kt3k.coveralls" version "2.6.3" id "jacoco" } group 'Clojure-TTT-Web' version '1.0-SNAPSHOT' apply plugin: 'java' sourceCompatibility = 1.8 repositories { mavenCentral() flatDir { dirs 'lib' } } dependencies { testCompile group: 'junit', name: 'junit', version: '4.11' compile name: 'Server-2.0' compile name: 'tic-tac-toe-0.2.0' compile name: 'clojure-1.8.0' } jacocoTestReport { reports { xml.enabled = true html.enabled = true } afterEvaluate { classDirectories = files(classDirectories.files.collect { fileTree(dir: it, exclude: ['**/Main.*', '**/Application.*' ]) }) } }
4c5ed525b4920e66be04ec50d7f0b4e9103748e8
[ "Markdown", "Java", "Gradle" ]
13
Java
MollieS/ClojureWebTTT
9b610f6d126cc864d6abde5e28b4621defce434c
73574b90bf117ee5946bda012949b6e2bdf11dc3
refs/heads/master
<repo_name>blizzard-esara/Spring-server<file_sep>/src/main/java/com/spring/blizzard/user/service/ContentsService.java package com.spring.blizzard.user.service; import com.spring.blizzard.user.dto.Explanation; import com.spring.blizzard.user.dto.Quiz; import com.spring.blizzard.user.mapper.ContentsMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class ContentsService { @Autowired ContentsMapper contentsMapper; public List<Quiz> getQuizList(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); String theme = request.getParameter("theme"); String level = request.getParameter("level"); List<Integer> solveArr = new ArrayList<>(); List<Quiz> quizlist; List<Map<String, Object>> solveList = contentsMapper.unlockExplanationList(id); if(solveList.size() >0) { for (int i = 0; i < solveList.size(); i++) { solveArr.add(Integer.parseInt(solveList.get(i).get("col").toString())); } HashMap<String, Object> maps = new HashMap<>(); maps.put("theme", theme); maps.put("level", level); maps.put("list", solveArr); quizlist = contentsMapper.getQuizList(maps); } else { quizlist = contentsMapper.getQuizListInit(theme, level); } for(int i = 0 ; i<quizlist.size() ; i++) { Quiz quiz = (Quiz)quizlist.get(i); quiz.setAttrCnt(contentsMapper.getQuizAttrSize(quiz.getCol())); if(quiz.getAttrCnt() > 0) { List<String> urlArr = new ArrayList<String>(); List<Map<String, Object>> source = contentsMapper.getQuestionAttr(quiz.getCol()); for(int k = 0 ; k < source.size() ; k++) { urlArr.add(source.get(k).get("url").toString()); } if(source.size() > 0) quiz.setAttrType(source.get(0).get("type").toString()); quiz.setUrl(urlArr); } } return quizlist; } public List<Explanation> explanationList(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); List<Map<String, Object>> unlockList = contentsMapper.unlockExplanationList(id); List<Explanation> explanation = contentsMapper.explanationList(); for(int i = 0 ; i < unlockList.size() ; i++) { for(int j = 0 ; j < explanation.size() ; j++) { if((int)unlockList.get(i).get("col") == explanation.get(j).getCol()) { Explanation tmpExplanation = explanation.get(j); tmpExplanation.setSolve(true); List<Map<String, Object>> source = contentsMapper.getAttr(tmpExplanation.getCol()); tmpExplanation.setAttrCnt(source.size()); List<String> urlArr = new ArrayList<String>(); if(source.size() > 0) tmpExplanation.setAttrType(source.get(0).get("type").toString()); for(int k = 0 ; k < source.size() ; k++) { urlArr.add(source.get(k).get("url").toString()); } tmpExplanation.setUrl(urlArr); break; } } } return explanation; } public Explanation explanationShow (HttpServletRequest request) throws Exception{ String id = request.getParameter("id"); int col = Integer.parseInt(request.getParameter("col")); ArrayList<String> urlList = new ArrayList<>(); contentsMapper.insertSolve(id, String.valueOf(col)); List<Explanation> explanationList = contentsMapper.explanationShow(col); Explanation explanation = explanationList.get(0); List<Map<String, Object>> maps = contentsMapper.getAttr(col); explanation.setAttrCnt(maps.size()); if(maps.size() > 0) { explanation.setAttrType(maps.get(0).get("type").toString()); } for(int i = 0 ; i < maps.size() ; i++) { urlList.add(maps.get(i).get("url").toString()); } explanation.setUrl(urlList); return explanation; } } <file_sep>/src/main/java/com/spring/blizzard/BlizzardApplication.java package com.spring.blizzard; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BlizzardApplication { public static void main(String[] args) { SpringApplication.run(BlizzardApplication.class, args); } } <file_sep>/src/main/java/com/spring/blizzard/user/controller/UserController.java package com.spring.blizzard.user.controller; import com.spring.blizzard.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; @Controller public class UserController { @Autowired UserService userService; @RequestMapping("/loginUser") public @ResponseBody List<Map<String, Object>> loginUser(HttpServletRequest request) throws Exception{ return userService.loginUser(request); } @RequestMapping("/checkId") public @ResponseBody boolean checkId(HttpServletRequest request) throws Exception { return userService.checkId(request); } @RequestMapping("/initalCheck") public @ResponseBody List<Map<String, Object>> initalCheck(HttpServletRequest request) throws Exception { return userService.initalCheck(request); } @RequestMapping("/signUp") public @ResponseBody boolean signUp(HttpServletRequest request) throws Exception { return userService.signUp(request); } @RequestMapping("/eggChoise") public @ResponseBody boolean eggChoise(HttpServletRequest request) throws Exception { return userService.eggChoise(request); } @RequestMapping("/mainMonsterImageURL") public @ResponseBody String mainMonsterImageURL(HttpServletRequest request) throws Exception { return userService.mainMonsterImageURL(request); } @RequestMapping("/buyItem") public @ResponseBody List<Map<String, Object>> buyItem(HttpServletRequest request) throws Exception { return userService.buyItem(request); } @RequestMapping("/monsterCollection") public @ResponseBody List<Map<String, Object>> monsterCollection(HttpServletRequest request) throws Exception { return userService.monsterCollection(request); } @RequestMapping("/monsterCount") public @ResponseBody List<Map<String, Object>> monsterCount(HttpServletRequest request) throws Exception { return userService.monsterCount(request); } @RequestMapping("/modifyUser") public @ResponseBody int modifyUser(HttpServletRequest request) throws Exception { return userService.modifyUser(request); } } <file_sep>/src/main/java/com/spring/blizzard/user/mapper/UserMapper.java package com.spring.blizzard.user.mapper; import com.spring.blizzard.user.dto.User; import java.util.List; import java.util.Map; public interface UserMapper { public List<Map<String, Object>> loginUserCheck(String id, String pw) throws Exception; public int signUp(User user) throws Exception; public int checkId(String id) throws Exception; public List<Map<String, Object>> initalCheck(String id) throws Exception; public int insertEggChoise(String id, String monster) throws Exception; public String mainMosterImageURL(String id, String mainMonster) throws Exception; public int updateItemPrice(Map<String, Object> map) throws Exception; public int addItem(String id, String item) throws Exception; public List<Map<String, Object>> getlockMonsterUrl() throws Exception; public List<Map<String, Object>> getUnLockUserMonster(String id) throws Exception; public List<Map<String, Object>> monsterCount(String id) throws Exception; public int modifyUser(String id, String email, String phone) throws Exception; } <file_sep>/src/main/java/com/spring/blizzard/user/mapper/ContentsMapper.java package com.spring.blizzard.user.mapper; import com.spring.blizzard.user.dto.Explanation; import com.spring.blizzard.user.dto.Quiz; import java.util.List; import java.util.Map; public interface ContentsMapper { public List<Map<String, Object>> unlockExplanationList(String id) throws Exception; public List<Explanation> explanationList() throws Exception; public List<Map<String, Object>> getAttr (int col) throws Exception; public List<Quiz> getQuizList(Map<String, Object> map) throws Exception; public List<Quiz> getQuizListInit(String theme, String level) throws Exception; public int getQuizAttrSize(int col) throws Exception; public List<Map<String, Object>> getQuestionAttr(int col) throws Exception; public void insertSolve(String id, String col) throws Exception; public List<Explanation> explanationShow(int col) throws Exception; } <file_sep>/src/main/java/com/spring/blizzard/user/service/UserService.java package com.spring.blizzard.user.service; import com.spring.blizzard.user.dto.User; import com.spring.blizzard.user.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.*; @Service public class UserService { @Autowired UserMapper userMapper; public List<Map<String, Object>> loginUser (HttpServletRequest request) throws Exception { String id = request.getParameter("id"); String pw = request.getParameter("pw"); return userMapper.loginUserCheck(id, pw); } public boolean checkId(HttpServletRequest request) throws Exception { boolean result = false; String id = request.getParameter("id"); if(userMapper.checkId(id) == 0) { result = true; } return result; } public List<Map<String, Object>> initalCheck(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); return userMapper.initalCheck(id); } public boolean signUp(HttpServletRequest request) throws Exception { boolean result = false; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date today = new Date(); String date = sdf.format(today); User user = new User(request.getParameter("id"), request.getParameter("pw"), request.getParameter("phone"), request.getParameter("gender"), Integer.parseInt(request.getParameter("age")), request.getParameter("email"), Integer.parseInt(request.getParameter("subscription")), date ); int dbResult = userMapper.signUp(user); if(dbResult == 1) result = true; return result; } public boolean eggChoise(HttpServletRequest request) throws Exception { boolean result = false; String id = request.getParameter("id"); String monster =request.getParameter("monster"); if(userMapper.insertEggChoise(id, monster) == 1) { result = true; } return result; } public String mainMonsterImageURL(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); String mainMonster = request.getParameter("mainMonster"); return userMapper.mainMosterImageURL(id, mainMonster); } public List<Map<String, Object>> buyItem(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); String item = request.getParameter("item"); int price = Integer.parseInt(request.getParameter("price")); Map<String, Object> map = new HashMap<String, Object>(); map.put("id", id); map.put("price",price); userMapper.updateItemPrice(map); userMapper.insertEggChoise(id, item); return userMapper.initalCheck(id); } public List<Map<String, Object>> monsterCollection(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); List<Map<String, Object>> urlList = userMapper.getlockMonsterUrl(); List<Map<String, Object>> unlockList = userMapper.getUnLockUserMonster(id); for(int i = 0 ; i < urlList.size() ; i++) { for(int j = 0 ; j< unlockList.size() ; j++) { if(urlList.get(i).get("monster_name").equals(unlockList.get(j).get("monster_name"))) { urlList.get(i).replace("url", unlockList.get(j).get("open_url")); } } } return urlList; } public List<Map<String, Object>> monsterCount(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); return userMapper.monsterCount(id); } public int modifyUser(HttpServletRequest request) throws Exception { String id = request.getParameter("id"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); return userMapper.modifyUser(id, email, phone); } } <file_sep>/src/main/java/com/spring/blizzard/user/controller/ContentsController.java package com.spring.blizzard.user.controller; import com.spring.blizzard.user.dto.Explanation; import com.spring.blizzard.user.dto.Quiz; import com.spring.blizzard.user.service.ContentsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class ContentsController { @Autowired ContentsService contentsService; @RequestMapping("/getQuizList") public @ResponseBody List<Quiz> getQuizList (HttpServletRequest request) throws Exception { return contentsService.getQuizList(request); } @RequestMapping("/explanationShow") public @ResponseBody Explanation explanationShow (HttpServletRequest request) throws Exception { return contentsService.explanationShow(request); } @RequestMapping("/explanationList") public @ResponseBody List<Explanation> explanationList(HttpServletRequest request) throws Exception { return contentsService.explanationList(request); } }
137abef1b6d8d8625f6923eedcfa7b7df4ff04b6
[ "Java" ]
7
Java
blizzard-esara/Spring-server
1d317d5b492c97fc79dffd7cf4c07867223cf1c4
b39d9a1fdffa3c72bc62d064749caf2e861eb636
refs/heads/master
<file_sep>/** * Login view model */ var app = app || {}; app.Login = (function () { 'use strict'; var loginViewModel = (function () { var isInMistSimulator = (location.host.indexOf('icenium.com') > -1); var $loginUsername; var $loginPassword; var isFacebookLogin = app.isKeySet(appSettings.facebook.appId) && app.isKeySet(appSettings.facebook.redirectUri); var isGoogleLogin = app.isKeySet(appSettings.google.clientId) && app.isKeySet(appSettings.google.redirectUri); var isLiveIdLogin = app.isKeySet(appSettings.liveId.clientId) && app.isKeySet(appSettings.liveId.redirectUri); var isAdfsLogin = app.isKeySet(appSettings.adfs.adfsRealm) && app.isKeySet(appSettings.adfs.adfsEndpoint); var isAnalytics = analytics.isAnalytics(); var init = function () { if (!app.isKeySet(appSettings.everlive.apiKey)) { app.mobileApp.navigate('views/noApiKey.html', 'fade'); } $loginUsername = $('#loginUsername'); $loginPassword = <PASSWORD>'); if (!isFacebookLogin) { $('#loginWithFacebook').addClass('disabled'); console.log('Facebook App ID and/or Redirect URI not set. You cannot use Facebook login.'); } if (!isGoogleLogin) { $('#loginWithGoogle').addClass('disabled'); console.log('Google Client ID and/or Redirect URI not set. You cannot use Google login.'); } if (!isLiveIdLogin) { $('#loginWithLiveID').addClass('disabled'); console.log('LiveID Client ID and/or Redirect URI not set. You cannot use LiveID login.'); } if (!isAdfsLogin) { $('#loginWithADSF').addClass('disabled'); console.log('ADFS Realm and/or Endpoint not set. You cannot use ADFS login.'); } if (!isAnalytics) { console.log('EQATEC product key is not set. You cannot use EQATEC Analytics service.'); } }; var show = function () { if (localStorage["isLoginSuccessfully"] === "true") { appSettings.api.user_email = localStorage["username"]; appSettings.api.auth_token = localStorage["auth_token"]; if (navigator.onLine) { app.mobileApp.navigate('views/activitiesView.html'); } else { // offline app.mobileApp.navigate('views/activityView.html'); } } else { // test $loginUsername.val('<EMAIL>'); $loginPassword.val('<PASSWORD>'); } }; // Authenticate to use Backend Services as a particular user var login = function () { var username = $loginUsername.val(); var password = $loginPassword.val(); //app.mobileApp.navigate('views/activitiesView.html'); var userLogin = { "user_login": { "email": username, "password": <PASSWORD> } }; app.showLoading(); $.ajax({ url: appSettings.api.url + 'api/users/sign_in.json', type: 'post', dataType: 'json', success: function (data) { app.hideLoading(); if (data.success) { appSettings.api.user_email = data.user_email; appSettings.api.auth_token = data.user_token; localStorage["username"] = username; localStorage["password"] = <PASSWORD>; localStorage["auth_token"] = data.user_token; localStorage["isLoginSuccessfully"] = true; app.mobileApp.navigate('views/activitiesView.html'); } else { alert("Email or passwork is incorrect. Please try again."); } }, data: userLogin, error: function (request, status, error) { app.mobileApp.hideLoading(); var obj = JSON.parse(request.responseText); alert(obj.message); } }); //// Authenticate using the username and password //app.everlive.Users.login(username, password) //.then(function () { // // EQATEC analytics monitor - track login type // if (isAnalytics) { // analytics.TrackFeature('Login.Regular'); // } // app.mobileApp.hideLoading(); // return app.Users.load(); //}) //.then(function () { // app.mobileApp.navigate('views/activitiesView.html'); //}) //.then(null, // function (err) { // app.mobileApp.hideLoading(); // app.showError(err.message); // } //); }; var showMistAlert = function () { alert(appSettings.messages.mistSimulatorAlert); }; return { init: init, show: show, getYear: app.getYear, login: login, }; }()); return loginViewModel; }()); <file_sep>/** * Activity view model */ var app = app || {}; //var areaTypeDropList = new kendo.data.DataSource({ // offlineStorage: "areaTypeDrop-list" //}); // offline //document.addEventListener("online", function () { // areaTypeDropList.online(true); //}); //document.addEventListener("offline", function () { // localStorage["areaTypeDrop-list"] = JSON.stringify(areaTypeDropList.view()); // //areaTypeDropList.online(false); //}); //$(window).on("online", function () { // areaTypeDropList.online(true); //}); //$(window).on("offline", function () { // areaTypeDropList.online(false); //}); app.Activity = (function () { 'use strict' var $commentsContainer, listScroller; var activityViewModel = (function () { var addressId, customerId, activity = {}, checklist_id; var areaTypeDropList, areaTypeList; var selectAreaType, selectAreaTypeElement; var selectActionItem, selectActionItemDescription, selectActionItemElement; var init = function (e) { }; var show = function (e) { listScroller = e.view.scroller; listScroller.reset(); // offline document.addEventListener("offline", function () { try { if (areaTypeDropList !== undefined && areaTypeDropList.view() !== undefined) { var stringObject = areaTypeDropList.view(); localStorage["areaTypeDrop-list"] = JSON.stringify(stringObject); localStorage["address"] = JSON.stringify(activity); //areaTypeDropList.online(false); } } catch (e) { // Do nothing } }); var areaTypeDropListData = []; //create dataSource var areaTypeListData = [ { area_type: "Kitchen", area_items: [ { area_item: "Cooker Hood", area_item_description: "N/A" }, { area_item: "Kitchen Table and C..", area_item_description: "N/A" }, { area_item: "Kitchen Floor", area_item_description: "N/A" } ] }, { area_type: "Bathroom", area_items: [ { area_item: "Bath", area_item_description: "N/A" }, { area_item: "Bathroom Floor", area_item_description: "N/A" }, { area_item: "Clean Shower Screen", area_item_description: "Hygienically cleaned, removal of any limescale/mildew deposits. Make sure no streaks are left." } ] }, { area_type: "Bedroom", area_items: [ { area_item: "Bedroom Floor", area_item_description: "N/A" } ] }, { area_type: "Custom Area Type", area_items: [ { area_item: "Floor", area_item_description: "N/A" }, { area_item: "Custom A", area_item_description: "N/A" } ] } ]; areaTypeList = new kendo.data.DataSource({ data: areaTypeListData }); //display dataSource's data through ListView $("#areaTypeList").kendoMobileListView({ dataSource: areaTypeList, template: "<div class='item'>#: area_type #</div>" }); if (localStorage["areaTypeDrop-list"] !== undefined) { // using data from local storage that has been stored when offline activity = JSON.parse(localStorage["address"]); kendo.bind(e.view.element, activity, kendo.mobile.ui); areaTypeDropList = JSON.parse(localStorage["areaTypeDrop-list"]); implementDragDrop(); } else { addressId = e.view.params.addressId; customerId = e.view.params.customerId; $.getJSON(appSettings.api.apiurl('franchisee/customers/' + customerId + '/addresses/' + addressId + '/checklists.json'), function (data) { activity = data.checklists[0].address; kendo.bind(e.view.element, activity, kendo.mobile.ui); //for (var propertyName in data.checklists[0].checklist_entries) { if (localStorage["areaTypeDrop-list"] === undefined) { var groupItems = {}, key; $.each(data.checklists[0].checklist_entries, function (index, val) { key = val['area_type']; if (!groupItems[key]) { groupItems[key] = []; } groupItems[key].push(val); }); for (var propertyName in groupItems) { //for (var i = 0; i < groupItems.length; i++) { var areaType = { "area_type": propertyName, 'values': groupItems[propertyName] }; areaTypeDropListData.push(areaType); } //} //for (var i = 0; i < data.checklists[0].checklist_entries.length; i++) { // checklist_id = data.checklists[0].checklist_entries[i].checklist_id; // areaTypeDropListData.push(data.checklists[0].checklist_entries[i]); //add the item to ListB //} areaTypeDropList = new kendo.data.DataSource({ data: areaTypeDropListData }); } else { areaTypeDropList = new kendo.data.DataSource({ data: areaTypeDropList }); } //for (var i = 0; i < areaTypeListData.length; i++) { // for (var j = 0; j < areaTypeListData[i].child.length; j++) { // var actionTypeGroup = { // group: areaTypeListData[i].name, // name: areaTypeListData[i].child[j] // } // areaTypeDropList.add(actionTypeGroup); //add the item to ListB // } //} // mockup for testing in VS /* for (var j = 0; j < areaTypeListData.length; j++) { var dataItem = areaTypeListData[j]; var values = []; for (var i = 0; i < dataItem.area_items.length; i++) { var item = dataItem.area_items[i]; var areaItem = { area_type: dataItem.area_type, action_item: item.area_item, action_item_description: item.area_item_description, id: -1, // for add new customer_reviews: [], checklist_id: checklist_id, is_draft: false, have_new_comment: false } values.push(areaItem); } var areaType = { "area_type": dataItem.area_type, 'values': values }; areaTypeDropList.add(areaType); //add the item to ListB }*/ implementDragDrop(); }); } }; var implementDragDrop = function () { $("#areaTypeDropList").kendoMobileListView({ dataSource: areaTypeDropList, template: $('#areaTypeDropTemplate').html(), //headerTemplate: $('#areaTypeDropHeaderTemplate').html(), }); function addStyling(e) { this.element.css({ "border-color": "#06c", "background-color": "#e0e0e0", "opacity": 0.6 }); } function resetStyling(e) { this.element.css({ "border-color": "black", "background-color": "transparent", "opacity": 1 }); } $("#areaTypeDropList").kendoDropTarget({ dragenter: addStyling, //add visual indication dragleave: resetStyling, //remove the visual indication drop: function (e) { //apply changes to the data after an item is dropped app.showLoading(); var draggableElement = e.draggable.currentTarget.parent(), dataItem = areaTypeList.getByUid(draggableElement.data("uid")); var groupAreaType = []; var view = areaTypeDropList.view(); for (var i = 0; i < view.length; i++) { groupAreaType.push(view[i].area_type.toLowerCase()); } var area_type = dataItem.area_type; var exists = $.inArray(area_type.toLowerCase(), groupAreaType) > -1; if (exists) { var numberOfAreaType = 1; for (var i = 0; i < groupAreaType.length; i++) { if (groupAreaType[i].toLowerCase().indexOf(area_type.toLowerCase()) != -1) { numberOfAreaType++; } } area_type = area_type + " Number " + numberOfAreaType; } var values = []; for (var i = 0; i < dataItem.area_items.length; i++) { var item = dataItem.area_items[i]; var areaItem = { area_type: area_type, action_item: item.area_item, action_item_description: item.area_item_description, id: -1, // for add new customer_reviews: [], checklist_id: checklist_id, is_draft: false, have_new_comment: false } values.push(areaItem); } var areaType = { "area_type": area_type, 'values': values }; areaTypeDropList.add(areaType); //add the item to ListB //areaTypeDropList.sync(); //$("#areaTypeDropList").kendoMobileListView({ // dataSource: areaTypeDropList, // template: $('#areaTypeDropTemplate').html() //}); resetStyling.call(this); //reset visual dropTarget indication that was added on dragenter app.hideLoading(); } }); //create a draggable for the parent container $("#areaTypeList").kendoDraggable({ filter: ".item", //specify which items will be draggable dragstart: function (e) { //var draggedElement = e.currentTarget.parent(); //get the DOM element that is being dragged //var dataItem = areaTypeList.getByUid(draggedElement.data("uid")); //get corresponding dataItem from the DataSource instance //console.log(dataItem); }, hint: function (element) { //create a UI hint, the `element` argument is the dragged item return element.clone().css({ //"opacity": 0.6, //"background-color": "#0cf" }); } }); } var deleteAreaType = function (areaType, element) { app.showLoading(); $("#" + areaType.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible").toggle(); var uid = element.parentElement.parentElement.parentElement.parentElement.getAttribute("data-uid"); var dataItem = areaTypeDropList.getByUid(uid); areaTypeDropList.remove(dataItem); app.hideLoading(); } var editAreaType = function (areaType, element) { selectAreaTypeElement = element; selectAreaType = areaType; var currentAreaType = $("#nameAreaType"); currentAreaType.val(areaType); currentAreaType.focus(); $("#" + areaType.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible").toggle(); $("#modalview-editAreaType").kendoMobileModalView("open"); } var saveAreaType = function () { app.showLoading(); var uid = selectAreaTypeElement.parentElement.parentElement.parentElement.parentElement.getAttribute("data-uid"); var dataItem = areaTypeDropList.getByUid(uid); var currentAreaType = $("#nameAreaType"); if (currentAreaType.val() !== dataItem.area_type) { dataItem.area_type = currentAreaType.val(); for (var i = 0; i < dataItem.values.length; i++) { dataItem.values[i].area_type = dataItem.area_type; } $("#areaTypeDropList").data("kendoMobileListView").setDataSource(areaTypeDropList); } setTimeout(function () { $("#modalview-editAreaType").kendoMobileModalView("close"); app.hideLoading(); }, 500); app.hideLoading(); } var deleteActionItem = function (actionItem, element) { app.showLoading(); var uid = element.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.getAttribute("data-uid"); var dataItem = areaTypeDropList.getByUid(uid); for (var i = 0; i < dataItem.values.length; i++) { if (dataItem.values[i].action_item === actionItem) { dataItem.values.remove(dataItem.values[i]); break; } } $("#areaTypeDropList").data("kendoMobileListView").setDataSource(areaTypeDropList); $("#" + dataItem.area_type.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible").expand(); app.hideLoading(); } var editActionItem = function (actionItem, actionItemDescription, element) { selectActionItem = actionItem; selectActionItemDescription = actionItemDescription != 'null' ? actionItemDescription : ''; selectActionItemElement = element; var currentActionItemNewName = $("#nameActionItem"); var currentActionItemNewDescription = $("#descriptionActionItem"); currentActionItemNewName.val(actionItem); currentActionItemNewDescription.val(selectActionItemDescription); currentActionItemNewName.focus(); $("#modalview-editActionItem").kendoMobileModalView("open"); } var saveActionItem = function () { app.showLoading(); var actionItemTrim = selectActionItem.replace(/ /g, '_'); var uid = selectActionItemElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.getAttribute("data-uid"); var dataItem = areaTypeDropList.getByUid(uid); var currentActionItemNewName = $("#nameActionItem"); var currentActionItemNewDescription = $("#descriptionActionItem"); var newActionItemValue = currentActionItemNewName.val(); var currentActionItemValue; for (var i = 0; i < dataItem.values.length; i++) { if (dataItem.values[i].action_item === selectActionItem) { currentActionItemValue = dataItem.values[i]; break; } } if (currentActionItemNewName.val() !== currentActionItemValue.action_item || (currentActionItemNewDescription.val() != 'null' && currentActionItemNewDescription.val() !== currentActionItemValue.action_item_description)) { currentActionItemValue.action_item = newActionItemValue; currentActionItemValue.action_item_description = currentActionItemNewDescription.val(); $("#areaTypeDropList").data("kendoMobileListView").setDataSource(areaTypeDropList); } $("#" + currentActionItemValue.area_type.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible").expand(); $("#" + newActionItemValue.replace(/ /g, '_') + "ActionItem").data("kendoMobileCollapsible").expand(); setTimeout(function () { $("#modalview-editActionItem").kendoMobileModalView("close"); app.hideLoading(); }, 500); } var saveNewActionItem = function () { app.showLoading(); var uid = selectAreaTypeElement.parentElement.parentElement.parentElement.parentElement.getAttribute("data-uid"); var dataItem = areaTypeDropList.getByUid(uid); var colappsibleAreaType = $("#" + dataItem.area_type.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible"); var isCollapsed = $("#" + dataItem.area_type.replace(/ /g, '_') + "AreaType").hasClass("km-collapsed"); var currentActionItemNewName = $("#nameNewActionItem"); var currentActionItemNewDescription = $("#descriptionNewActionItem"); var newActionItemValue = currentActionItemNewName.val(); if (newActionItemValue !== null && newActionItemValue !== '') { var actionItem = { area_type: dataItem.area_type, action_item: newActionItemValue, action_item_description: currentActionItemNewDescription.val(), id: -1, // for add new customer_reviews: [], checklist_id: checklist_id, is_draft: false, have_new_comment: false } dataItem.values.push(actionItem); $("#areaTypeDropList").data("kendoMobileListView").setDataSource(areaTypeDropList); //$("#areaTypeDropList").data("kendoMobileListView").refresh(); if (isCollapsed) { $("#" + dataItem.area_type.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible").collapse(); } else { $("#" + dataItem.area_type.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible").expand(); } setTimeout(function () { $("#modalview-addActionItem").kendoMobileModalView("close"); app.hideLoading(); }, 500); } } var addActionItem = function (areaType, element) { selectAreaType = areaType; selectAreaTypeElement = element; var currentActionItemNewName = $("#nameNewActionItem"); var currentActionItemNewDescription = $("#descriptionNewActionItem"); currentActionItemNewName.val(''); currentActionItemNewName.focus(); currentActionItemNewDescription.val(''); $("#" + areaType.replace(/ /g, '_') + "AreaType").data("kendoMobileCollapsible").toggle(); $("#modalview-addActionItem").kendoMobileModalView("open"); } return { init: init, show: show, deleteAreaType: deleteAreaType, editAreaType: editAreaType, saveAreaType: saveAreaType, deleteActionItem: deleteActionItem, editActionItem: editActionItem, saveActionItem: saveActionItem, saveNewActionItem: saveNewActionItem, addActionItem: addActionItem, save: function () { localStorage.clear(); }, activity: function () { return activity; } }; }()); return activityViewModel; }());
e602a710140efd3b1c0f0e7ad8e9e29d10cf98b4
[ "JavaScript" ]
2
JavaScript
qdev89/Cleanily
fd7cc6dabcb272d88e98eb3fafe59b475b907af0
831b7a70ece8635b396f789e55e3ee059aa3c19e
refs/heads/master
<file_sep>from django.test import TestCase from secmaps.models import * #test creations of models class ModelTests(TestCase): def create_dbids(self, dbid="shh2"): return Dbids.objects.create(dbid=dbid) def create_hguids(self, hguid="shh2"): return Hguids.objects.create(hguid=hguid) def create_hguidsfrequencies(self, mapped_hguid=None, num_sources=1, times_mapped=1): return HguidsFrequencies.objects.create(mapped_hguid=mapped_hguid, num_sources=num_sources, times_mapped=times_mapped) def test_model_creation(self): dbidm = self.create_dbids() self.assertTrue(isinstance(dbidm, Dbids)) hguidm = self.create_hguids() self.assertTrue(isinstance(hguidm, Hguids)) if dbidm: hguidfreqm = self.create_hguidsfrequencies(mapped_hguid = hguidm) self.assertTrue(isinstance(hguidfreqm, HguidsFrequencies)) <file_sep>from django.test import TestCase from django.contrib.auth.models import User # Create your tests here. class ViewTests(TestCase): def test_usageView(self): resp = self.client.get('/secmaps/usage', follow=True) self.assertEqual(resp.status_code, 200) self.assertIn(b'Purpose:', resp.content) self.assertIn(b'Main Tabs:', resp.content) self.assertIn(b'Databases:', resp.content) def test_databaseView(self): resp = self.client.get('/secmaps/databases', follow=True) self.assertEqual(resp.status_code, 200) self.assertIn(b'Secretome Databases', resp.content) self.assertIn(b'Database</TH><TH>count', resp.content) <file_sep>from django.shortcuts import render import csv # Create your views here. from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext, loader from django.views.generic.detail import DetailView from django.core.paginator import Paginator from django.shortcuts import render, render_to_response from django.core.files.uploadhandler import MemoryFileUploadHandler from django.core.files.uploadedfile import InMemoryUploadedFile, UploadedFile from os import remove from django.core.files import File from .forms import HguidForm, NameForm, PostForm, Hguid2Form, UploadFileForm from .models import Dbids, Hguids, MappedIds, HguidsFrequencies, MappedHguids from django.core.files.base import ContentFile from django.core.files.storage import default_storage import shutil from django.views.decorators.csrf import csrf_exempt from django.conf import settings # Default page lengths dbpagelen = 30 hgupagelen = 30 @csrf_exempt ############################################################################## def index(request): """Prints the main index page using template index.html The passing of the DatabaseNames is likely a relic. Commenting out. """ # DatabaseNames_list = Dbids.objects.all() template = loader.get_template('secmaps/index.html') context = RequestContext(request) # 'DatabaseNames_list': DatabaseNames_list, # 'BASE_RELPATH': settings.BASE_RELPATH, # }) return HttpResponse(template.render(context)) ############################################################################## def displayfilenamewithwts(request): """Returns filenames with wts. Likely defunct as we use new types of wts Used with testform Retaining for now. TTL until comments from Secretome team """ hids = request.FILES.get('file1', None) wts = request.FILES.get('file2', None) return HttpResponse(str(hids) + str(wts)) ############################################################################## def displayhguidsfromfile(request): """Displays HGUids from a list along with their database presence and scores Takes an input filename and treating its contents as HGUids, provides links and scores for each. Splitting of ids is done on comma and newline. Spaces are ignored. The rowmat part is superceded. Commented parts retained until we hear from Secretome folks """ # The following lines appear elsewhere too. This needs to be refactored # Wts for dbs provided here. This mode is likely to go away # dbwts = {'clark': 1.03, 'GO:0005576': 1.1, 'GO:0016020': 1.2, # 'gpcr.org_family': 1.4, 'gpcr.org_structure': 1.33, 'signal': 1.44, # 'spd': 1.6, 'Stanford': 1.7, 'Stanford_addl_list1': 1.92, # 'Stanford_addl_list2': 1.75, 'uniprot_secreted1': 1.67, 'Zhang': 1.31} # Revised wts based on email from <NAME> on 28 Nov 2016 dbwts = {'clark': 4, 'GO:0005576': 8, 'GO:0016020': 5, 'gpcr.org_family': 3, 'gpcr.org_structure': 3, 'signal': 4, 'spd': 8, 'Stanford': 6, 'Stanford_addl_list1': 6, 'Stanford_addl_list2': 6, 'uniprot_secreted1': 6, 'Zhang': 4} ## rowmat = [] # Read file and strip it into a list of HGUids y = request.FILES['file'] default_storage.save('tempfiles/' + str(y), ContentFile(y.read())) mytempfile = settings.MEDIA_ROOT + '/tempfiles/' + str(y) with open(mytempfile, 'r') as f: x = f.read() newx = x.replace('\n',',') newx2 = newx.replace(',,',',') x = newx2 HGUidslist = x.rstrip(',').split(',') # Start creating the output # Should use append format of concat ''.join(httplist) httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + '<B>Details for selected HGU ids</B><BR>' httplist = httplist + '<TABLE CLASS="sortable TFTABLE">' httplist = httplist + '<TR><TH>id</TH><TH class="rotate"><DIV><SPAN>Found in</SPAN></DIV></TH><TH class="rotate"><DIV><SPAN>Found times</SPAN></DIV></TH>' header_row = ['id','Found in','Found times'] for key in dbwts: httplist = httplist + '<TH class="rotate"><DIV><SPAN>' + key + '</SPAN></DIV></TH>' header_row.append(key) httplist = httplist + '<TH>Score</TH>' header_row.append('Score') ## rowmat.append(header_row) httplist = httplist + '</TR>' for hguid in HGUidslist: hguid = hguid.strip() hguidd3 = '<A HREF="' + settings.BASE_RELPATH + 'plotd3/' + hguid + '">' + hguid + '</A>' HguidsFrequencies_list = HguidsFrequencies.objects.filter(mapped_hguid=hguid) HguidsDB_list = MappedHguids.objects.filter(mapped_hguid=hguid) if len(HguidsFrequencies_list.values('num_sources')): numsources = HguidsFrequencies_list.values('num_sources')[0]['num_sources'] numtimes = HguidsFrequencies_list.values('times_mapped')[0]['times_mapped'] else: numsources = 0 numtimes = 0 ylist = [] for y in HguidsDB_list.values('mapped_db'): ylist.append(y['mapped_db']) xsum = 0 ## rowmatlist = [hguid, numsources, numtimes] xlist = [] for x in dbwts: if x in ylist: cumnum = MappedIds.objects.filter(mapped_hguid=hguid,mapped_db=x).count() appstr = '<A HREF="' + settings.BASE_RELPATH + 'get_beforemapping_names/' + x + '/' + hguid + '">' + str(cumnum) + '</A>' xlist.append(appstr) # rowmatlist.append('1') xsum = xsum + dbwts[x] else: xlist.append('0') ## rowmatlist.append('0') xsum = "%.2f" % xsum ## rowmatlist.append(xsum) ## rowmat.append(rowmatlist) template = loader.get_template('secmaps/hguids_ind.html') context = RequestContext(request, { 'hguid': hguidd3, 'numsources': numsources, 'numtimes': numtimes, 'xlist': xlist, 'xsum': xsum, }) httplist = httplist + template.render(context) httplist = httplist + '</TABLE>' httplist = httplist + '<A HREF="' + settings.BASE_RELPATH + 'csv_view/' + ','.join(HGUidslist) + '">Download CSV</A>' # httplist = httplist + rowmat[0][0] httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' remove(mytempfile) return HttpResponse(httplist) ############################################################################## def handle_uploaded_file(f): """Create temp file out of an uploaded file Used x.out in tempfiles as the default TODO: May have to use non-absolute filename to avoid clashes """ with open('tempfiles/x.out', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) ############################################################################## def copywtfile(request): """Allow user to upload a wt file Copy it to secmaps/copywtfile TODO: CHECK: Should it have a BASEREF defined? This is likely not being used. The inelegant multihguid2 is being used """ if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'secmaps/copywtfile.html', {'form': form}) ############################################################################## def usage(request): """Uses the usage template showing various options""" httplist = '' httplist = cssheader() + topmenu() + mainmenu() template = loader.get_template('secmaps/usage.html') context = RequestContext(request, { }) httplist = httplist + template.render(context) httplist = httplist + mainmenu() httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) ############################################################################## def databases(request): """Prints list of databases and could of ids through a template Includes NONE. Should these be removed? """ DatabaseNames_list = Dbids.objects.all() httplist = '' httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + '<B>Secretome Databases</B>' httplist = httplist + '<TABLE CLASS="sortable TFTable">' httplist = httplist + '<TR><TH>Database</TH><TH>count</TH></TR>' for db in DatabaseNames_list.values('dbid'): dbid = db['dbid'] rowcount = MappedIds.objects.filter(mapped_db=dbid).count() template = loader.get_template('secmaps/database_sing.html') context = RequestContext(request, { 'dbid': dbid, 'rowcount': rowcount, }) httplist = httplist + template.render(context) httplist = httplist + '</TABLE>' httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) ############################################################################## def database_detail(request,dbname,page,dbpagelen=dbpagelen): """Provides details on a selected database through a template Uses default dbpagelen defined globally. Can be changed """ flist = Paginator(MappedIds.objects.filter(mapped_db = dbname),dbpagelen) # print int(page) if int(page) > int(flist.num_pages) or int(page) < 1: return HttpResponse("Not that many pages") else: if int(page) > 1: menuaddl = '<A HREF="' + settings.BASE_RELPATH + 'databases/%s/%d/%d">Prev page </A>' %(dbname,int(page)-1,int(dbpagelen)) else: menuaddl = "" if int(page) < int(flist.num_pages): menuaddr = '<A HREF="' + settings.BASE_RELPATH + 'databases/%s/%d/%d">Next page </A>' %(dbname,int(page)+1,int(dbpagelen)) else: menuaddr = "" menuaddm = 'Page %d (of %d)' % (int(page),int(flist.num_pages)) menuadd = menuaddl + menuaddm + menuaddr httplist = '' httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + '<B>Database: %s<BR></B>' % dbname httplist = httplist + menuadd httplist = httplist + '<TABLE CLASS="sortable TFTable">' httplist = httplist + '<TR><TH>Gene/Protein ID</TH><TH>Mapped Affymetrix HGU133plus2 ID</TH></TR>' # print(flist.page(page).object_list.values()[0]['mapped_hguid_id']) template = loader.get_template('secmaps/dbdetail_page.html') context = RequestContext(request, { 'flist': flist.page(page).object_list, }) httplist = httplist + template.render(context) httplist = httplist + '</TABLE>' httplist = httplist + menuadd httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) ############################################################################## def hguids(request,page): """Provides list of HGUids""" flist = Paginator(Hguids.objects.all(),dbpagelen) # print int(page) if int(page) > int(flist.num_pages) or int(page) < 1: return HttpResponse("Not that many pages") else: if int(page) > 1: menuaddl = '<A HREF="' + settings.BASE_RELPATH + 'hguids/%d">Prev page </A>' %(int(page)-1) else: menuaddl = "" if int(page) < int(flist.num_pages): menuaddr = '<A HREF="' + settings.BASE_RELPATH + 'hguids/%d"> Next page</A>' %(int(page)+1) else: menuaddr = "" menuaddm = 'Page %d' % (int(page)) menuadd = menuaddl + menuaddm + menuaddr httplist = '' httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + '<B>List of HGU133plus2 ids in the Secretome database</B><BR>' httplist = httplist + menuadd httplist = httplist + '<TABLE ALIGN="center" CLASS="sortable TFTable">' httplist = httplist + '<TR><TH>HGU id</TH></TR>' template = loader.get_template('secmaps/hguids_page.html') context = RequestContext(request, { 'flist': flist.page(page).object_list, }) httplist = httplist + template.render(context) httplist = httplist + '</TABLE>' httplist = httplist + menuadd httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) #class HFDetailView(DetailView): # # model = HguidsFrequencies # # def get_context_data(self, **kwargs): # context = super(HFDetailView, self).get_context_data(**kwargs) # return context ############################################################################## def search_multihguid(request): """Returns number of dbs a list of HGUids are present in - along with number of appearances Takes a set of default wts defined below Also links to d3 graphics The rowmat part is superceded and can go. TTL comments from Secretome group about wts. """ # The following lines appear elsewhere too. This needs to be refactored # Wts for dbs provided here. This mode is likely to go away # dbwts = {'clark': 1.03, 'GO:0005576': 1.1, 'GO:0016020': 1.2, # 'gpcr.org_family': 1.4, 'gpcr.org_structure': 1.33, 'signal': 1.44, # 'spd': 1.6, 'Stanford': 1.7, 'Stanford_addl_list1': 1.92, # 'Stanford_addl_list2': 1.75, 'uniprot_secreted1': 1.67, 'Zhang': 1.31} # Revised wts based on email from <NAME> on 28 Nov 2016 dbwts = {'clark': 4, 'GO:0005576': 8, 'GO:0016020': 5, 'gpcr.org_family': 3, 'gpcr.org_structure': 3, 'signal': 4, 'spd': 8, 'Stanford': 6, 'Stanford_addl_list1': 6, 'Stanford_addl_list2': 6, 'uniprot_secreted1': 6, 'Zhang': 4} ## rowmat = [] if 'hguids' in request.GET: message = 'You searched for: %r' % request.GET['hguids'] HGUidslist = request.GET['hguids'].rstrip(',').split(',') httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + '<B>Details for selected HGU ids</B><BR>' httplist = httplist + '<TABLE CLASS="sortable TFTABLE">' httplist = httplist + '<TR><TH>id</TH><TH class="rotate"><DIV><SPAN>Found in</SPAN></DIV></TH><TH class="rotate"><DIV><SPAN>Found times</SPAN></DIV></TH>' header_row = ['id','Found in','Found times'] for key in dbwts: httplist = httplist + '<TH class="rotate"><DIV><SPAN>' + key + '</SPAN></DIV></TH>' header_row.append(key) httplist = httplist + '<TH>Score</TH>' header_row.append('Score') ## rowmat.append(header_row) httplist = httplist + '</TR>' for hguid in HGUidslist: hguid = hguid.strip() hguidd3 = '<A HREF="' + settings.BASE_RELPATH + 'plotd3/' + hguid + '">' + hguid + '</A>' HguidsFrequencies_list = HguidsFrequencies.objects.filter(mapped_hguid=hguid) HguidsDB_list = MappedHguids.objects.filter(mapped_hguid=hguid) if len(HguidsFrequencies_list.values('num_sources')): numsources = HguidsFrequencies_list.values('num_sources')[0]['num_sources'] numtimes = HguidsFrequencies_list.values('times_mapped')[0]['times_mapped'] else: numsources = 0 numtimes = 0 ylist = [] for y in HguidsDB_list.values('mapped_db'): ylist.append(y['mapped_db']) xsum = 0 ## rowmatlist = [hguid, numsources, numtimes] xlist = [] for x in dbwts: if x in ylist: cumnum = MappedIds.objects.filter(mapped_hguid=hguid,mapped_db=x).count() appstr = '<A HREF="' + settings.BASE_RELPATH + 'get_beforemapping_names/' + x + '/' + hguid + '">' + str(cumnum) + '</A>' xlist.append(appstr) # rowmatlist.append(cumnum) xsum = xsum + dbwts[x] else: xlist.append('0') ## rowmatlist.append('0') xsum = "%.2f" % xsum ## rowmatlist.append(xsum) ## rowmat.append(rowmatlist) template = loader.get_template('secmaps/hguids_ind.html') context = RequestContext(request, { 'hguid': hguidd3, 'numsources': numsources, 'numtimes': numtimes, 'xlist': xlist, 'xsum': xsum, }) httplist = httplist + template.render(context) httplist = httplist + '</TABLE>' httplist = httplist + '<A HREF="' + settings.BASE_RELPATH + 'csv_view/' + request.GET['hguids'] + '">Download CSV</A>' httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) else: message = 'You submitted an empty form.' return HttpResponse(message) ############################################################################## def cssheader(): """Just the CSS header""" mystr = "<HTML>" mystr = mystr + '<HEAD>' mystr = mystr + '<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">' mystr = mystr + '<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">' mystr = mystr + '<link rel="stylesheet" href="' + settings.STATIC_URL + 'css/secmaps.css">' mystr = mystr + '<script src="' + settings.STATIC_URL + 'css/sorttable.js"></script>' mystr = mystr + '</HEAD>' mystr = mystr + '<BODY>' return mystr ############################################################################## def topmenu(): """Just the top menu - excludes main menu""" mystr = '<P>' mystr = mystr + '<IMG SRC=' + settings.STATIC_URL + 'images/edrn.png>' mystr = mystr + '<H2>The Secretome Project</H2>' return mystr ############################################################################## def mainmenu(): """The main menu""" mystr = '<P>' mystr = mystr + '<DIV ALIGN="center">[' mystr = mystr + '<a href="' + settings.BASE_RELPATH + '">Home</a>|' mystr = mystr + '<a href="' + settings.BASE_RELPATH + 'usage">Usage</a>|' mystr = mystr + '<a href="' + settings.BASE_RELPATH + 'databases">Databases</a>|' mystr = mystr + '<a href="' + settings.BASE_RELPATH + 'hguids/1">HGU 133plus2 Ids</a>|' mystr = mystr + '<form action="' + settings.BASE_RELPATH + 'search-multihguid/" method="get">' mystr = mystr + '<input type="text" name="hguids">' mystr = mystr + '<input type="submit" value="Search HGU133plus2 IDs">' mystr = mystr + '</form>' mystr = mystr + '|<form enctype="multipart/form-data" method="post" action="' + settings.BASE_RELPATH + 'displayhguidsfromfile"><input id="id_file" name="file" type="file" /><input type="submit" value="Submit" /> </form>' mystr = mystr + ']</DIV>' mystr = mystr + '<P>' return mystr ############################################################################## def csv_view(request,hguidinlist): """Creates the HttpResponse object with the appropriate CSV header Some duplication with a couple of other functions. Subject to refactoring. """ # The following lines appear elsewhere too. This needs to be refactored # Wts for dbs provided here. This mode is likely to go away # dbwts = {'clark': 1.03, 'GO:0005576': 1.1, 'GO:0016020': 1.2, # 'gpcr.org_family': 1.4, 'gpcr.org_structure': 1.33, 'signal': 1.44, # 'spd': 1.6, 'Stanford': 1.7, 'Stanford_addl_list1': 1.92, # 'Stanford_addl_list2': 1.75, 'uniprot_secreted1': 1.67, 'Zhang': 1.31} # Revised wts based on email from <NAME> on 28 Nov 2016 dbwts = {'clark': 4, 'GO:0005576': 8, 'GO:0016020': 5, 'gpcr.org_family': 3, 'gpcr.org_structure': 3, 'signal': 4, 'spd': 8, 'Stanford': 6, 'Stanford_addl_list1': 6, 'Stanford_addl_list2': 6, 'uniprot_secreted1': 6, 'Zhang': 4} rowmat = [] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="details.csv"' HGUidslist = hguidinlist.split(',') header_row = ['id','Found in','Found times'] for key in dbwts: header_row.append(key) header_row.append('Score') rowmat.append(header_row) for hguid in HGUidslist: hguid = hguid.strip() HguidsFrequencies_list = HguidsFrequencies.objects.filter(mapped_hguid=hguid) HguidsDB_list = MappedHguids.objects.filter(mapped_hguid=hguid) if len(HguidsFrequencies_list.values('num_sources')): numsources = HguidsFrequencies_list.values('num_sources')[0]['num_sources'] numtimes = HguidsFrequencies_list.values('times_mapped')[0]['times_mapped'] else: numsources = 0 numtimes = 0 ylist = [] for y in HguidsDB_list.values('mapped_db'): ylist.append(y['mapped_db']) xsum = 0 rowmatlist = [hguid, numsources, numtimes] for x in dbwts: if x in ylist: cumnum = MappedIds.objects.filter(mapped_hguid=hguid,mapped_db=x).count() rowmatlist.append(cumnum) xsum = xsum + dbwts[x] else: rowmatlist.append('0') xsum = "%.2f" % xsum rowmatlist.append(xsum) rowmat.append(rowmatlist) writer = csv.writer(response) for row in rowmat: writer.writerow(row) return response ############################################################################## def get_beforemapping_names(request,dbname,hguid): """Returns before_mapping names along with uniprot ids Following sql query is used for the purpose: select before_mapping from secmaps_mappedids where mapped_hguid like '202493_x_at' and mapped_db like 'GO:0005576'; """ message = 'You searched for: %r' % hguid httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + '<B>Before Mapping Names for HGU id ' + hguid + ' in db ' + dbname + '</B><BR>' httplist = httplist + '<TABLE CLASS="sortable TFTABLE">' httplist = httplist + '<TR><TH>Before Mapping</TH></TR>' beforemappings_list = MappedIds.objects.filter(mapped_hguid=hguid,mapped_db=dbname) for y in beforemappings_list: httplist = httplist + '<TR><TD><A HREF=http://www.uniprot.org/uniprot/' + str(y.before_mapping) + '>' + str(y.before_mapping) + '</A></TD></TR>' httplist = httplist + '</TABLE>' httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) ############################################################################## def get_json(hguid): """Creates a json file that provides links to dbs and genes from HGNC id Makes use of a file called bigger_table in secretome_uploads The file was created through an API to uniprot by David If possible all this should be made more elegant The dbwts used here are not the same as used elsewhere. These are in inverse proportion to number of ids in a database. The wts are later combined with frequencies to provid a better weighing. The json file is later used with d3 to make connectivity plots """ details = {} for line in open(settings.MEDIA_ROOT + "/bigger_table","r"): rows = line.rstrip().split() if rows[0] in details: details[rows[0]] = details[rows[0]] + ",%s %s %s" % (rows[1],rows[2],rows[3]) else: details[rows[0]] = "%s %s %s" % (rows[1],rows[2],rows[3]) # dbwts = {"clark": 0.510, "GO:0005576": 0.224, "GO:0016020": 0.044, "gpcr.org_family": 0.548, "gpcr.org_structure": 3.571, "signal": 1.086, "spd": 0.167, "Stanford": 0.276, "Stanford_addl_list1": 0.896, "Stanford_addl_list2": 1.570, "uniprot_secreted1": 0.200, "Zhang": 0.145} # Revised wts based on email from <NAME> on 28 Nov 2016 dbwts = {'clark': 4, 'GO:0005576': 8, 'GO:0016020': 5, 'gpcr.org_family': 3, 'gpcr.org_structure': 3, 'signal': 4, 'spd': 8, 'Stanford': 6, 'Stanford_addl_list1': 6, 'Stanford_addl_list2': 6, 'uniprot_secreted1': 6, 'Zhang': 4} sumscore = 0 dbscores = [] knowndb = "" thisdb = 0 dbs = 0 hgncs = {} myjson = '{"name": "%s", "children": [{' % hguid for el in details[hguid].split(','): (db, hgnc, gene) = el.rstrip().split() if db != knowndb: # Change of db - could be first dbs = dbs + 1 if thisdb == 0: # First db encountered thisdb = 1 else: # New db but not first myjson =myjson + "]},{" this_score = dbwts[knowndb]*hgncs[knowndb]*len(dbgenes) dbscores.append([knowndb,dbwts[knowndb],hgncs[knowndb],dbgenes,this_score]) sumscore = sumscore + this_score knowndb = db hgncs[db] = 1 dbgenes = {} dbgenes[gene] = 1 myjson =myjson + '"name": "%s", "children": [' % db myjson =myjson + '{"name": "%s", "children": [{"name": "%s"}]}' % (hgnc, gene) else: # Same db as before hgncs[db] = hgncs[db] + 1 myjson =myjson + ',{"name": "%s", "children": [{"name": "%s"}]}' % (hgnc, gene) if gene not in dbgenes: dbgenes[gene] = 1 else: # New gene dbgenes[gene] = dbgenes[gene] + 1 myjson= myjson + "]}]}" this_score = dbwts[knowndb]*hgncs[knowndb]*len(dbgenes) dbscores.append([knowndb,dbwts[knowndb],hgncs[knowndb],dbgenes,this_score])# The final db sumscore = sumscore + this_score return (myjson,dbscores,sumscore) ############################################################################## def get_json2(hguid): """Creates a json file that provides links to dbs and genes from HGNC id Makes use of a file called bigger_table in secretome_uploads The file was created through an API to uniprot by David If possible all this should be made more elegant The json file is later used with d3 to make sankey plot Known failing: Does not behave properly for cases like 211616_s_at where hgnc id and gene id are the same (in this case in Stanford_addl_list1) """ details = {} for line in open(settings.MEDIA_ROOT + "/bigger_table","r"): rows = line.rstrip().split() if rows[0] in details: details[rows[0]] = details[rows[0]] + ",%s %s %s" % (rows[1],rows[2],rows[3]) else: details[rows[0]] = "%s %s %s" % (rows[1],rows[2],rows[3]) names = [hguid] links =[] vals = {} myjson = '\'{"nodes": [' for el in details[hguid].split(','): (db, hgnc, gene) = el.rstrip().split() if db not in names: names.append(db) link_tup = (0,names.index(db)) links.append(link_tup) vals[db] = 1 else: vals[db] += 1 if hgnc not in names: names.append(hgnc) link_tup = (names.index(db),names.index(hgnc)) links.append(link_tup) if gene not in names: names.append(gene) link_tup = (names.index(hgnc),names.index(gene)) links.append(link_tup) for el in range(len(names)): myjson += '{"name":"%s"},' % names[el] myjson = myjson[:-1] + '], "links":[ ' for el in range(len(links)): value = 1 if links[el][0] == 0: value = vals[names[links[el][1]]] myjson += '{"source":%s,"target":%s,"value":%s},' % (links[el][0],links[el][1],value) myjson = myjson[:-1] + ' ]}\'' return (myjson) ############################################################################## def plotd3(request,hguid): """Use d3.js to show connectivity for a given HGU id""" message = 'You searched for: %r' % hguid httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' (myjson, dbscores, sumscore) = get_json(hguid) myjson2 = get_json2(hguid) httplist = httplist + '</DIV>' httplist = httplist + '<DIV ALIGN="center">' template = loader.get_template('secmaps/scores.html') context = RequestContext(request, { 'hguid': hguid, 'dbscores': dbscores, 'sumscore': sumscore, }) httplist = httplist + template.render(context) httplist = httplist + '</DIV>' httplist = httplist + '<DIV ALIGN="center">' template = loader.get_template('secmaps/plot_sankey.html') context = RequestContext(request, { 'hguid': hguid, 'myjson': myjson2, }) httplist = httplist + template.render(context) httplist = httplist + '</DIV>' httplist = httplist + '<DIV ALIGN="center">' template = loader.get_template('secmaps/plotd3.html') context = RequestContext(request, { 'hguid': hguid, 'myjson': myjson, }) httplist = httplist + template.render(context) httplist = httplist + '</DIV>' httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) ############################################################### def search_multihguid2(request,hguids,wtfile): """Allow users to use their own wts (old weighing scheme) The usage page suggests changing url to execute this Very inelegant Needs to be refactored if this method of weighing is to be used Deferred until feedback from Secretome team The rowmat bits can go. Commented out for now """ mytempfile = settings.MEDIA_ROOT + '/tempfiles/' + wtfile with open(mytempfile, 'r') as f: x = f.read() dbwts = {} keyval = x.split('\n') for i in range(len(keyval)-1): (key,val) = keyval[i].split('=') message = key + str(i) dbwts[key] = val ## rowmat = [] if 'hguids': message = 'You searched for: %r' % hguids HGUidslist = hguids.rstrip(',').split(',') httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + '<DIV ALIGN="center">' httplist = httplist + '<B>Details for selected HGU ids</B><BR>' httplist = httplist + '<TABLE CLASS="sortable TFTABLE">' httplist = httplist + '<TR><TH>id</TH><TH class="rotate"><DIV><SPAN>Found in</SPAN></DIV></TH><TH class="rotate"><DIV><SPAN>Found times</SPAN></DIV></TH>' header_row = ['id','Found in','Found times'] for key in dbwts: httplist = httplist + '<TH class="rotate"><DIV><SPAN>' + key + '</SPAN></DIV></TH>' header_row.append(key) httplist = httplist + '<TH>Score</TH>' header_row.append('Score') ## rowmat.append(header_row) httplist = httplist + '</TR>' for hguid in HGUidslist: hguid = hguid.strip() HguidsFrequencies_list = HguidsFrequencies.objects.filter(mapped_hguid=hguid) HguidsDB_list = MappedHguids.objects.filter(mapped_hguid=hguid) if len(HguidsFrequencies_list.values('num_sources')): numsources = HguidsFrequencies_list.values('num_sources')[0]['num_sources'] numtimes = HguidsFrequencies_list.values('times_mapped')[0]['times_mapped'] else: numsources = 0 numtimes = 0 ylist = [] for y in HguidsDB_list.values('mapped_db'): ylist.append(y['mapped_db']) xsum = 0 ## rowmatlist = [hguid, numsources, numtimes] xlist = [] for x in dbwts: if x in ylist: cumnum = MappedIds.objects.filter(mapped_hguid=hguid,mapped_db=x).count() appstr = '<A HREF="' + settings.BASE_RELPATH + 'get_beforemapping_names/' + x + '/' + hguid + '">' + str(cumnum) + '</A>' xlist.append(appstr) xsum = xsum + float(dbwts[x]) else: xlist.append('0') ## rowmatlist.append('0') xsum = "%.2f" % xsum ## rowmatlist.append(xsum) ## rowmat.append(rowmatlist) template = loader.get_template('secmaps/hguids_ind.html') context = RequestContext(request, { 'hguid': hguid, 'numsources': numsources, 'numtimes': numtimes, 'xlist': xlist, 'xsum': xsum, }) httplist = httplist + template.render(context) httplist = httplist + '</TABLE>' httplist = httplist + '<A HREF="' + settings.BASE_RELPATH + 'csv_view/' + hguids + '">Download CSV</A>' httplist = httplist + mainmenu() httplist = httplist + '</DIV>' httplist = httplist + '</BODY></HTML>' return HttpResponse(httplist) else: message = 'You submitted an empty form.' return HttpResponse(message) ############################################################################## def copywtfileres(request): """Allow user to upload a wt file Copy it to secmaps/copywtfile TODO: CHECK: Should it have a BASEREF defined? This is likely not being used. The inelegant multihguid2 is being used """ y = request.FILES['file'] default_storage.save('tempfiles/' + str(y), ContentFile(y.read())) httplist = cssheader() + topmenu() + mainmenu() httplist = httplist + 'The wtfile ' + str(y) + ' was copied' return HttpResponse(httplist) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Dbids', fields=[ ('dbid', models.CharField(max_length=32, serialize=False, primary_key=True)), ], ), migrations.CreateModel( name='Hguids', fields=[ ('hguid', models.CharField(max_length=32, serialize=False, primary_key=True)), ], ), migrations.CreateModel( name='HguidsFrequencies', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('num_sources', models.IntegerField()), ('times_mapped', models.IntegerField()), ('mapped_hguid', models.ForeignKey(to='secmaps.Hguids', db_column='mapped_hguid')), ], ), migrations.CreateModel( name='MappedHguids', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('hgnc_symbol', models.CharField(max_length=32)), ('mapped_db', models.ForeignKey(to='secmaps.Dbids', db_column='mapped_db')), ('mapped_hguid', models.ForeignKey(to='secmaps.Hguids', db_column='mapped_hguid')), ], ), migrations.CreateModel( name='MappedIds', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('before_mapping', models.CharField(max_length=32)), ('mapped_db', models.ForeignKey(to='secmaps.Dbids', db_column='mapped_db')), ('mapped_hguid', models.ForeignKey(to='secmaps.Hguids', db_column='mapped_hguid')), ], ), ] <file_sep>from django.conf.urls import url from secmaps import views #from secmaps.views import HFDetailView urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^databases/([-:.a-zA-Z0-9_]+)/([0-9]+)/([0-9]+)$', views.database_detail, name='database_detail'), url(r'^databases/([-:.a-zA-Z0-9_]+)/([0-9]+)$', views.database_detail, name='database_detail'), url(r'^databases$', views.databases, name='databases'), url(r'^hguids/([0-9]+)/$', views.hguids, name='hguids'), url(r'^search-multihguid2/(.*)/(.*)$', views.search_multihguid2, name='search_multihguid2'), url(r'^search-multihguid/$', views.search_multihguid, name='search_multihguid'), url(r'^plotd3/([-:.a-zA-Z0-9_]+)$', views.plotd3, name='plotd3'), url(r'^usage$', views.usage, name='usage'), url(r'^copywtfileres$', views.copywtfileres, name='copywtfileres'), url(r'^copywtfile$', views.copywtfile, name='copywtfile'), url(r'^displayhguidsfromfile$', views.displayhguidsfromfile, name='displayhguidsfromfile'), url(r'^displayfilenamewithwts$', views.displayfilenamewithwts, name='displayfilenamewithwts'), url(r'^csv_view/(.*)$', views.csv_view, name='csv_view'), url(r'^get_beforemapping_names/(.*)/(.*)$', views.get_beforemapping_names, name='get_beforemapping_names'), ] # url(r'^readfromfile/([-:.a-zA-Z0-9_]+)$', views.readfromfile, name='readfromfile'), # url(r'^writetofile$', views.writetofile, name='writetofile'), # url(r'^testform$', views.testform, name='testform'), <file_sep># Secretome ## Getting your release up to speed 0. Install Django (1.8.3+), mysql and Apache configuration 1. Download a release from https://github.com/EDRN/Secretome 2. Extract the archive in /usr/local/edrn/secretome 3. Change into that directory 4. Add the local_settings.py if it does not exist (details below) 5. Add the wsgi.py to include appropriate paths (example below) 6. Obtain a mysql dump from AshishMahabal and load it 7. Copy the file "bigger_table" obtained from AshishMahabal in to the MEDIA_ROOT dir 8. Restart Apache 9. Go to http://{hostname}/secretome/ and have fun ### Specifics - local_settings.py should contain values for: SECRET_KEY DATABASES STATIC_URL MEDIA_ROOT # This should be outside the django area BASE_RELPATH DEBUG = False # For production mode - example line for wsgi.py: sys.path.append('/usr/local/python-3.5.0/lib/python3.5/site-packages') <file_sep>{% if form.is_multipart %} <form enctype="multipart/form-data" method="post" action="copywtfileres">{% csrf_token %} {% else %} <form method="post" action="/foo/">{% csrf_token %} {% endif %} Weightfile to copy: <input type="file" name="file"></input> <P> <input type='submit' value='Submit' /> </form> <file_sep>from django import forms from .models import Hguids class HguidForm(forms.ModelForm): class Meta: model = Hguids fields = ('hguid',) class Hguid2Form(forms.ModelForm): class Meta: model = Hguids fields = ('hguid',) class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=80) class PostForm(forms.Form): content = forms.CharField(max_length=256) created_at = forms.DateTimeField() class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() <file_sep>from django.contrib import admin # Register your models here. from secmaps.models import Dbids, Hguids, HguidsFrequencies, MappedHguids, MappedIds admin.site.register(Dbids) admin.site.register(Hguids) admin.site.register(HguidsFrequencies) admin.site.register(MappedHguids) admin.site.register(MappedIds) <file_sep>{% if flist %} {% for hguid in flist %} <TR> <TD><a href="{% url 'search_multihguid' %}?hguids={{ hguid.hguid }}">{{ hguid.hguid }}</a></TD> </TR> {% endfor %} {% else %} <p>No HGU ids in Secretome database.</p> {% endif %}
1fee78a6ab6f6f451936ec4f9db3cdafa10cacbb
[ "Markdown", "Python", "HTML" ]
10
Python
EDRN/Secretome
ba9a2ef2b6b21bc05df275ed46cc51e3f04eed7a
af905fef0ad115e34745345e514550adeb881c83
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <head> <title>form</title> <meta charset="UTF-8"> <meta name="description" content="web page"> </head> <body> <?php $name = ''; $email = ''; $phone = ''; $country = ''; $address = ''; $password = ''; $confirm_password = ''; if(isset($_POST['submit'])) { $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $country = $_POST['country']; $address = $_POST['address']; $password = $_POST['password']; $confirm_password = $_POST['confirm_password']; } $table = 0; if(isset($_POST['tableSubmit'])){ $table = $_POST['table']; for($i = 1; $i <= 10; $i++){ echo $table." x " . $i . " = " . $table*$i . "<br>"; } } ?> <form method="POST"> <input type="text" placeholder="Enter your number" name="table"> <input type="submit" name="tableSubmit"> </form> <form method="POST"> <div> <label for="name">Name</label> <input type="text" name="name" id="name"> </div> <div> <label for="email">Email</label> <input type="email" name="email" id="email"> </div> <div> <label for="phone">Phone</label> <input type="text" name="phone" id="phone"> </div> <div> <label for="country">Country</label> <input type="text" name="country" id="country"> </div> <div> <label for="address">Address</label> <input type="text" name="address" id="address"> </div> <div> <label for="password">Password</label> <input type="<PASSWORD>" name="password" id="password"> </div> <div> <label for="confirm_password">Confirm Password</label> <input type="password" name="confirm_password" id="confirm_password"> </div> <div> <input type="submit" name="submit"> </div> </form> <table> <thead> <tr> <th>Name</th> <th>email</th> <th>phone</th> <th>country</th> <th>address</th> <th>Password</th> </tr> <tr> <td><?php echo $name ?></td> <td><?php echo $email ?></td> <td><?php echo $phone ?></td> <td><?php echo $country ?></td> <td><?php echo $address ?></td> <td><?php echo password_hash($password, PASSWORD_DEFAULT); ?></td> </tr> </thead> </table> </body> </html><file_sep><html lang="en"> <head> <title>pyramid</title> <meta charset="UTF-8"> <meta name="description" content="web page"> </head> <body> <?php for($i=0;$i<=10;$i++){ for($j=0;$j<=$i;$j++){ echo "*"; } echo "<br/>"; } ?> <?php //Star Pyramid Size $size = 10; for($i=1;$i<=$size;$i++){ for($j=1;$j<=$size-$i;$j++){ echo "&nbsp;&nbsp;"; } for($k=1;$k<=$i;$k++){ echo "*&nbsp;&nbsp;"; } echo "<br />"; } ?> <?php echo "<pre>"; $n = 10; for ($i = 10; $i > 0; $i--) { for ($j = $n - $i; $j > 0; $j--) echo "&nbsp;&nbsp;"; for ($j = 2 * $i - 1; $j > 0; $j--) echo ("&nbsp;*"); echo "<br>"; } echo "</pre>"; ?> <?php echo "<pre>"; for ($i = 1; $i <= 8; $i++) { for ($k = 8; $k >= $i; $k--) { echo "&nbsp;"; } for ($j = 1; $j <= $i; $j++) { echo $i . " "; if ($j == $i) { echo "&nbsp;"; echo "<br/>"; } } } echo "</pre>"; ?> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <title>php</title> </head> <body> <?php //Display a tabular form echo "<table border=1>"; echo "<tr>"; echo "<th>Student Name</th>"; echo "<th>English</th>"; echo "<th>Urdu</th>"; echo "<th>Maths</th>"; echo "<th>Science</th>"; echo "<th>Islamiat</th>"; echo "</tr>"; // Declare and initialize array $names = array('Ali','Haider','Hassan','Daniyal','Tahir','Ahmed','Saeed','Raza' ); $english = array(50,45,23,54,54,24,56,78); $urdu = array(12,34,56,78,99,34,23,44); $maths = array(23,45,67,98,76,43,80,13); $science = array(87,54,21,24,56,75,12,43); $islamiat = array(32,34,56,22,34,56,77,54); // Use foreach loop to display array elements foreach( $names as $index => $name ) { echo "<tr>"; echo "<td>$name</td>"; echo "<td>$english[$index]</td>"; echo "<td>$urdu[$index]</td>"; echo "<td>$maths[$index]</td>"; echo "<td>$science[$index]</td>"; echo "<td>$islamiat[$index]</td>"; echo "</tr>"; } echo "</table>"; ?> </body> </html>
ee54c71d060513d5955fa03c7e7027392f3d9dbd
[ "PHP" ]
3
PHP
mehakmohsin/php
66956fd923cf77c0b6a04ad8ee27b0e476d643fa
993a9a122906ecf0e9e835d6f3c0990c64a46b92
refs/heads/master
<file_sep>package com.example.pkg.androidapp; import android.app.Activity; import android.content.Context; import android.hardware.Camera ; import android.net.Uri; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class locationActivity extends AppCompatActivity { Button btnShowLocation; TextView ltxt; Camera camera; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_location); final ActionsLauncher actions = new ActionsLauncher(this); btnShowLocation = (Button) findViewById(R.id.locationbtn); // show location button click event btnShowLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // create class object actions.getLocation(); // actions.takeSnapShots(); } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); // AppIndex.AppIndexApi.start(client, getIndexApiAction()); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. //AppIndex.AppIndexApi.end(client, getIndexApiAction()); client.disconnect(); } }
597427a5ca5be210ce0b8a2e3357e9a78a804e43
[ "Java" ]
1
Java
GerardoJRodriguez/App
868d9782c3501cd61d8adef721d37715607dd2b9
c697ba7367d662a4a1b2bc83bd0579669b65541f
refs/heads/master
<file_sep>import * as base from './base'; export const renderWrapper = () => { base.el.content.innerHTML = `<section class="list"></section>`; }; const renderTags = tags => { let markup = ''; tags.forEach(tag => markup += `<span class="tag">${tag}</span>`); return markup; }; const renderAsideLink = asideLinks => { let markup = ''; asideLinks.forEach((content) => { markup += `<li class="side-nav__item"><a href="#${content}" data-nav="${content}" class="side-nav__link">${content}</a></li>`; }); return markup; }; const calculateAndRenderStars = (likes, votes) => { const stars = 5; const fullStars = Math.round(likes/votes * stars); let output = ``; let i; for(i = 0; i < stars; i++) { output += `<svg class="icon icon--${(i < fullStars) ? 'primary' : 'blank'} icon--small"><use href="./assets/svgs/sprite.svg#icon-star"></use></svg>` } return output; }; const renderOffert = offert => { const markup = ` <article class="list__item" data-id="${offert.id}"> <div class="list__top"> <p class="list__date">${base.formatDate(offert.date)}</p> <figure class="list__image-box"> <img src="http://buildercorp.pl/wp-content/uploads/2017/05/BX.jpg" alt="Budimex" class="list__image"> </figure> <div class="list__content"> <h2 class="heading-secondary u-mb-big"> <a class="list__offer-link" href="#${offert.id}">${offert.title}</a> </h2> <a href="https://www.google.com/maps?q=${offert.location}" target="_blank" class="list__location"> <svg class="icon icon--primary"> <use href="./assets/svgs/sprite.svg#icon-location-pin"></use> </svg> <span>${offert.location}</span> </a> <p class="list__category-box">${renderTags(offert.tags)}</p> <label class="list__details-toggle" for="list-item-details-${offert.id}"> <svg class="icon"> <use href="./assets/svgs/sprite.svg#icon-info-with-circle"></use> </svg> </label> </div> </div> <input class="list__details-switcher" type="checkbox" id="list-item-details-${offert.id}"> <div class="list__bottom"> <p>${offert.text}</p> </div> </article> `; document.querySelector(`.${base.elStr.list}`).insertAdjacentHTML('beforeend', markup); }; const renderCompany = company => { const markup = ` <article class="list__item" data-id="${company.id}"> <div class="list__top"> <p class="list__rating"> ${calculateAndRenderStars(company.likes, company.votes)} </p> <figure class="list__image-box"> <img src="http://buildercorp.pl/wp-content/uploads/2017/05/BX.jpg" alt="Budimex" class="list__image"> </figure> <div class="list__content"> <h2 class="heading-secondary u-mb-big"> <a class="list__company-link" href="#${company.id}">${company.name}</a> </h2> <p class="paragraph">Polecenia: <span class="text-bold">${company.likes}</span></p> <p class="list__category-box">${renderTags(company.tags)}</p> <label class="list__details-toggle" for="${company.id}"> <svg class="icon"> <use href="./assets/svgs/sprite.svg#icon-info-with-circle"></use> </svg> </label> </div> </div> <input class="list__details-switcher" type="checkbox" id="${company.id}"> <div class="list__bottom"> <p>${company.text}</p> </div> </article> `; document.querySelector(`.${base.elStr.list}`).insertAdjacentHTML('beforeend', markup); }; export const renderAside = aside => { console.log(aside); const markup = ` <aside class="side-nav noselect"> <input class="side-nav__switcher" type="checkbox" id="toggle-list"> <section class="side-nav__list-box"> <label class="side-nav__list-label" for="toggle-list">Więcej...</label> <ul class="side-nav__list"> ${renderAsideLink(aside.categories)} </ul> </section> <section class="side-nav__list-box"> <label class="side-nav__list-label" for="toggle-list">Więcej...</label> <ul class="side-nav__list"> ${renderAsideLink(aside.popular)} </ul> </section> <section class="side-nav__list-box"> <label class="side-nav__list-label" for="toggle-list">Więcej...</label> <ul class="side-nav__list"> ${renderAsideLink(aside.places)} </ul> </section> </aside> `; document.querySelector(`.${base.elStr.list}`).insertAdjacentHTML('beforebegin', markup); }; export const renderOffers = offerts => { offerts.forEach(renderOffert); }; export const renderCompanies = companies => { companies.forEach(renderCompany); };<file_sep>import * as base from '../views/base'; import * as registrationView from '../views/registration'; import Registration from '../models/Registration'; import Form from '../models/Form'; import state from '../models/state'; export default function (form = 'user') { console.log('Register controller works'); base.clearContent(); // base.hideHeader(); base.renderLoader(); registrationView.renderSection(form); base.removeLoader(); addEvents(); }; function addEvents() { const forms = document.querySelectorAll(`.${base.elStr.registerContent} form`); const switchers = document.querySelectorAll(`.${base.elStr.registerNavButton}`); forms.forEach(el => { const form = new Form(el); form.init(); el.addEventListener('submit', ev => { ev.preventDefault(); if (!form.validForm()) return; createAccount(form); // afterSend(); }); }); switchers.forEach(el => { el.addEventListener('click', ev => { ev.preventDefault(); registrationView.switchForms(el, switchers); }); }); }; async function createAccount(form) { const type = form.form.dataset.form; const dataObj = form.getValues(); const registration = new Registration(); const response = await registration.createAccount(dataObj, type); console.log(response); // Validate response // - hide form // - show message && redirect 5sec after };<file_sep>const express = require('express'); const { validateOffer, Offer } = require('../models/offer'); const router = express.Router(); const offers = [ { id: 1, title: 'offer 1', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date(), location: 'Bogatynia', tags: ['remont', 'podłoga', 'pilne', 'wykończenie'] }, { id: 2, title: 'offer 2', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date('2019-03-09'), location: 'Wrocław', tags: ['dach'] }, { id: 3, title: 'offer 3', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date('2019-03-08'), location: 'Zgorzelec', tags: ['remont', 'ściana'] }, { id: 4, title: 'offer 4', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date('2019-03-07'), location: 'Warszawa', tags: ['remont', 'podłoga'] }, { id: 5, title: 'offer 5', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date(), location: 'Bogatynia', tags: ['remont', 'podłoga', 'pilne', 'wykończenie'] }, { id: 6, title: 'offer 6', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date('2019-03-09'), location: 'Wrocław', tags: ['dach'] }, { id: 7, title: 'offer 7', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date('2019-03-08'), location: 'Zgorzelec', tags: ['remont', 'ściana'] }, { id: 8, title: 'offer 8', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', details: { textDetails: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti dolorem necessitatibus totam modi suscipit mollitia ducimus minus a vel velit, excepturi sunt tempore architecto quasi consequuntur sequi autem beatae cum nostrum adipisci consequatur ipsam et at? Amet reprehenderit perspiciatis itaque consequuntur recusandae excepturi corporis minima veritatis aspernatur explicabo voluptate accusantium quibusdam, praesentium placeat consectetur porro obcaecati, at ullam temporibus nisi! Labore explicabo obcaecati voluptas sequi incidunt error reprehenderit deleniti totam.', name: '<NAME>', tel: '123-456-789', mail: '<EMAIL>', fb: 'marcincyboran' }, date: new Date('2019-03-07'), location: 'Warszawa', tags: ['remont', 'podłoga'] } ]; const aside = { categories: ['Kategoria 1', 'Kategoria 2', 'Kategoria 3', 'Kategoria 4'], popular: ['Popular 1', 'Popular 2', 'Popular 3', 'Popular 4', 'Popular 5', 'Popular 6', 'Popular 7', 'Popular 8', 'Popular 9', 'Popular 10' ], places: ['Miasto 1', 'Miasto 2', 'Miasto 3', 'Miasto 4'] }; router.get('/', (req, res) => { // Use fawn to get categories, popular and places then send both in response // Pretend database delay setTimeout(function() { res.send({offers, aside}); }, 1000); }); router.get('/:id', async (req, res) => { // TODO - db query // const offer = await Offer.findById(req.params.id); const index = offers.findIndex((el) => el.id === parseInt(req.params.id)); setTimeout(function() { res.send(offers[index]); }, 1000); }); router.post('/add', async (req, res) => { const { error } = validateOffer(req.body); if (error) return res.status(400).send(error.details[0].message); const offer = new Offer({ title: req.body.title, description: req.body.description, location: req.body.location, tags: req.body.tags, publisherID: req.body.publisherID }); await offer.save(); res.send(offer); }); module.exports = router;<file_sep>import * as base from '../views/base'; import * as offerView from '../views/offer'; import Offer from '../models/Offer'; import state from '../models/state'; export default async function (id = 1) { console.log('Offer Ctrl working!'); base.clearContent(); base.showHeader(); base.renderLoader(); const offer = new Offer(state.offerId || id); try { await offer.getOffer(); state.offer = offer; base.removeLoader(); offerView.renderOffer(offer.data); } catch (error) { console.log(error); } }; <file_sep>import * as base from '../views/base'; import * as listView from '../views/list'; import Offers from '../models/Offers'; import { navigate } from '../routing/router'; import state from '../models/state'; export default async function () { console.log('list offers controller works'); // Clear view base.clearContent(); base.showHeader(); // Prepare list listView.renderWrapper(); // Create offert class const offers = new Offers(); // Add loader base.renderLoader(); // Get results try { await offers.getOffers(); state.offers = offers.list; console.log(state); // Remove Loader base.removeLoader(); // Render results listView.renderAside(offers.aside); listView.renderOffers(offers.list); addEvents(); } catch (error) { console.log(error); } }; function addEvents () { document.querySelector(`.${base.elStr.list}`).addEventListener('click', ev => { const target = ev.target; if(target.classList.contains(base.elStr.listOfferLink)) { ev.preventDefault() navigate(`/offer:${target.getAttribute('href').replace('#','')}`); } }) }<file_sep>const express = require('express'); const router = express.Router(); // middleware auth function before router.get('/me', /* auth */ (req, res) => { res.send('/api/users/me - router'); }); router.post('/', (req, res) => { res.send('/api/users - adding user'); }); router.post('/add/:type', async (req, res) => { console.log(req.body.data); console.log(req.params.type); res.send(req.body.data); }); module.exports = router;<file_sep>import { el } from '../views/base'; export const navigate = (pathName) => { const matches = pathName.match(/:(.*(?=\/))|:(.*)/gi); const firstParam = matches ? matches[0].replace(':','') : undefined ; const clearPath = pathName.replace(`:${firstParam}`,''); const event = new CustomEvent('locationChanged', { detail: { param: firstParam, path: clearPath } }); window.history.pushState({param: firstParam}, null, window.location.origin + clearPath); window.dispatchEvent(event); }; document.addEventListener('click', (e) => { // sprawdzić czy można queryselectorall(top-nav a).click bez tego na dole if (e.target.getAttribute('data-nav') || (e.target.closest('a') !== null) && (e.target.closest('a').getAttribute('data-nav') !== null)) { const href = e.target.getAttribute('href') || e.target.closest('a').getAttribute('href'); console.log('navigation'); e.preventDefault(); navigate(href); } e.stopPropagation(); });<file_sep>import * as base from './base'; export const renderOffer = offer => { const markup = ` <section class="offer" data-id="${offer.id}"> <div class="offer__top"> <h2 class="heading-primary offer__top-title">${offer.title}</h2> </div> <div class="gallery"> <img src="" alt="gallery photo 1" class="gallery-item"> <img src="" alt="gallery photo 2" class="gallery-item"> <img src="" alt="gallery photo 3" class="gallery-item"> <img src="" alt="gallery photo 4" class="gallery-item"> </div> <div class="offer__content"> <div class="offer__description"> <h3 class="heading-secondary u-mb-medium">Opis:</h3> <p class="offer__description-text u-mb-big"> ${offer.text} </p> <p class="offer__description-text u-mb-huge"> ${offer.details.textDetails} </p> <a href="" class="button button--primary button--icon button--big" data-id="${offer.id}"> <span>Złóż ofertę</span> <svg class="icon"> <use href="./assets/svgs/sprite.svg#icon-plus"></use> </svg> </a> </div> <aside class="offer__sidebar"> <h3 class="heading-secondary u-mb-medium">Kontakt:</h3> <ul class="u-list u-mb-big"> <li class="u-list__item u-list__item--normal"> <svg class="icon icon--normal icon--secondary"><use href="./assets/svgs/sprite.svg#icon-user"></use></svg> ${offer.details.name} </li> <li class="u-list__item u-list__item--normal"> <svg class="icon icon--normal icon--secondary"><use href="./assets/svgs/sprite.svg#icon-old-phone"></use></svg> ${offer.details.tel} </li> <li class="u-list__item u-list__item--normal"> <svg class="icon icon--normal icon--secondary"><use href="./assets/svgs/sprite.svg#icon-email"></use></svg> ${offer.details.mail} </li> <li class="u-list__item u-list__item--normal"> <svg class="icon icon--normal icon--secondary"><use href="./assets/svgs/sprite.svg#icon-facebook"></use></svg> <a href="https://www.facebook.com/${offer.details.fb}" target="_blank">Profil</a> </li> </ul> <h3 class="heading-secondary u-mb-medium">Lokalizacja:</h3> <ul class="u-list u-mb-big"> <li class="u-list__item u-list__item--normal"> <svg class="icon icon--normal icon--secondary"><use href="./assets/svgs/sprite.svg#icon-location-pin"></use></svg> <a href="https://www.google.com/maps?q=${offer.location}" target="_blank">Bogatynia</a> </li> </ul> <iframe class="offer__map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d320513.1439457553!2d16.71168578074838!3d51.126743182413364!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x470fe9c2d4b58abf%3A0xb70956aec205e0f5!2zV3JvY8WCYXc!5e0!3m2!1sen!2spl!4v1551616973081" frameborder="0" style="border:0" allowfullscreen></iframe> </aside> </div> </section> `; base.el.content.insertAdjacentHTML('beforeend', markup); };<file_sep>import axios from 'axios'; export default class Offers { constructor(query = null) { this.query = query } async getOffers() { try { const response = await axios.get(`/api/offers`); this.list = response.data.offers; this.aside = response.data.aside; console.log(response); } catch (error) { console.warn(error); } } }<file_sep>import state from '../models/state'; import axios from 'axios'; export const el = { topNavigation: document.querySelector('.top-nav'), headerBottom: document.querySelector('.header__bottom'), content: document.querySelector('.content'), }; export const elStr = { list: `list`, listTags: 'list__category-box', loader: 'loader', content: 'content', listCompanyLink: 'list__company-link', listOfferLink: 'list__offer-link', registerContent: 'register__content', registerContentCompany: 'register__content--active-company', registerNavButton: 'register__nav-button', registerNavActive: 'register__nav-button--active', formBlock: 'form__block', loginForm: 'login__form' }; export function clearContent() { el.content.innerHTML = ''; }; export function renderLoader(parent = el.content) { const loader = ` <div class="loader"> <p class="heading-secondary u-mb-huge">Ładowanie...</p> <div class="loader__spinners"> <div class="loader__spinner"> <div class="loader__outer">&nbsp;</div> <div class="loader__inner">&nbsp;</div> </div> <div class="loader__spinner--reverse"> <div class="loader__middle">&nbsp;</div> <div class="loader__center">&nbsp;</div> </div> </div> </div>`; if (typeof parent === "string") { document.querySelector(`.${parent}`).insertAdjacentHTML('afterbegin', loader); } else { parent.insertAdjacentHTML('afterbegin', loader); } }; export function removeLoader() { const loader = document.querySelector(`.${elStr.loader}`); loader.parentNode.removeChild(loader); }; export function formatDate(rawDate) { const date = new Date(rawDate); // Get time from server and store it in state const today = new Date(state.time) || new Date(); if (today.getTime() - date.getTime() <= 86400000) { return `${(date.getHours() < 10) ? '0' + date.getHours() : date.getHours()}:${(date.getMinutes() < 10) ? '0' + date.getMinutes() : date.getMinutes()}`; } return `${(date.getDate() < 10) ? '0' + date.getDate() : date.getDate()}.${(date.getMonth() < 10) ? '0' + date.getMonth() : date.getMonth()}.${date.getFullYear()}` }; export function hideHeader() { el.headerBottom.classList.add('u-hidden'); // const animEl = el.headerBottom; // let height = getComputedStyle(animEl).getPropertyValue('height').replace('px', ''); // const id = setInterval(frame, 5); // function frame() { // if (height == 0) { // clearInterval(id); // } else { // height = height - 10; // console.log(height); // animEl.style.height = `${height}px`; // } // } }; export function showHeader() { el.headerBottom.classList.remove('u-hidden') }; const getTime = async () => { const result = await axios('/api/base/time'); state.time = result.data; console.log(state); }; getTime();<file_sep>import * as base from './base'; const calculateAndRenderStars = (rating) => { const stars = 5; let output = ``; let i; for(i = 0; i < stars; i++) { output += `<svg class="icon icon--${(i < rating) ? 'primary' : 'blank'} icon--small"><use href="./assets/svgs/sprite.svg#icon-star"></use></svg>` } return output; }; const createReview = review => { return ` <article class="company__review-item"> <header class="company__review-header"> <span class="company__review-person">${review.name}</span> <span class="company__review-date">${base.formatDate(review.date)}</span> </header> <p class="company__review-content"> <span class="company__review-rating"> ${calculateAndRenderStars(review.rating)} </span> <span class="company__review-text">${review.text}</span> </p> </article> `; }; const createBlankReview = () => { return ` <article class="company__review-item"> <header class="company__review-header"> <span class="company__review-person">System</span> <span class="company__review-date">brak recenzji</span> </header> <p class="company__review-content"> <span class="company__review-text">Jeżeli korzystałeś z usług tej firmy, napisz recenzję. (opcja dostępna z panelu użytkownika)</span> </p> </article> `; }; const createReviews = reviews => { if (!reviews) return createBlankReview(); let allReviews = ''; reviews.forEach(el => allReviews += createReview(el)); return allReviews; }; const createService = service => { return ` <li class="u-list__item"> <svg class="icon"><use href="./assets/svgs/sprite.svg#icon-chevron-down"></use></svg> ${service} </li> `; }; const createServices = services => { let output = ''; services.forEach(el => output += createService(el)); return output; }; export const renderCompany = company => { const markup = ` <section class="company"> <div class="company__top"> <h2 class="company__top-heading heading-primary">${company.name}</h2> <a href="https://www.google.com/maps?q=${company.location}" target="_blank" class="company__top-location"> <svg class="icon icon--primary"><use href="./assets/svgs/sprite.svg#icon-location-pin"></use></svg> <span>${company.location}</span> </a> <div class="company__top-rate"> <span>${((company.likes/company.votes)*10).toFixed(1)}</span> </div> </div> <div class="gallery"> <img src="" alt="gallery photo 1" class="gallery-item"> <img src="" alt="gallery photo 2" class="gallery-item"> <img src="" alt="gallery photo 3" class="gallery-item"> </div> <div class="company__content"> <div class="company__description"> <h3 class="heading-secondary u-mb-small">Opis:</h3> <p class="company__description-text u-mb-big">${company.text}</p> <h3 class="heading-secondary u-mb-small">Usługi:</h3> <ul class="u-list u-mb-big"> ${(company.services) ? createServices(company.services) : ''} </ul> <h3 class="heading-secondary u-mb-small">Informacje:</h3> <div class="adress-details u-mb-big"> <address> <span>${company.details.zipCode} ${company.location}</span> <span>ul. ${company.details.address}</span> <span>${company.details.country}</span> </address> <span>${(company.details.nip) ? 'NIP: '+ company.details.nip : ''}</span> <span>${(company.details.regon) ? 'REGON: '+ company.details.regon : ''}</span> </div> <h3 class="heading-secondary u-mb-small">Strona internetowa:</h3> <a class="company__site" href="http://${company.site}" target="_blank"> <svg class="icon"><use href="./assets/svgs/sprite.svg#icon-home"></use></svg> <span>${company.site}</span> </a> </div> <div class="company__review"> ${(company.reviews) ? createReviews(company.reviews) : createReviews()} </div> </div> <div class="company__bottom"> <a href="#lista" class="button button--primary button--icon button--big" data-company="${company.id}"> <span>Lista ofert</span> <svg class="icon"><use href="./assets/svgs/sprite.svg#icon-magnifying-glass"></use></svg> </a> <a href="#projekty" class="button button--secondary button--icon button--big" data-company="${company.id}"> <span>Projekty</span> <svg class="icon"><use href="./assets/svgs/sprite.svg#icon-camera"></use></svg> </a> <a href="#rezerwacja" class="button button--tertiary button--icon button--big" data-company="${company.id}"> <span>Zarezerwuj</span> <svg class="icon"><use href="./assets/svgs/sprite.svg#icon-calendar"></use></svg> </a> </div> </section> `; base.el.content.insertAdjacentHTML('beforeend', markup); };<file_sep>import * as base from '../views/base'; export default class Form { constructor(form, options = {} ) { this.form = form, this.inputs = form.querySelectorAll('input'), this.options = Object.assign({}, { errorClass: 'error', validClass: 'valid', textReg: new RegExp('^[a-zA-ZąĄćĆęĘłŁńŃóÓśŚźżŻŹ]{1,}$', 'i'), emailReg: new RegExp('^[0-9a-z_.-]+@[0-9a-z.-]+\.[a-z]{2,3}$', 'i'), passwordReg: new RegExp('^[a-zA-Z0-9<PASSWORD>śŚźżŻŹ]{8,14}$', 'i'), phoneReg: new RegExp('^[0-9\ \-\+]{9,30}$') }, options), this.values = {} }; init() { this.form.setAttribute('novalidate', 'novalidate'); this.inputs.forEach(input => { const type = input.type.toLowerCase(); input.addEventListener('blur', () => { if (type === 'text') { this.testText(input); } else if (type === 'tel') { this.testPhone(input); } else if (type === 'email') { this.testEmail(input); } else if (type === 'password') { this.testPassword(input); } }); }); }; getValues() { this.inputs.forEach(input => { const type = input.type.toLowerCase(); const isBoolen = (type == 'checkbox' || type == 'radio'); this.values[input.name] = (!isBoolen) ? input.value : input.checked; }); return this.values; }; baseTest(input, regExpBackup) { let inputIsValid = true; const pattern = input.getAttribute('pattern'); const reg = (pattern !== null) ? new RegExp(pattern, 'i') : regExpBackup; if (!reg.test(input.value)) inputIsValid = false; if (input.value === '') inputIsValid = false; this.changeClasses(input, inputIsValid); return inputIsValid; }; testText(input) { return this.baseTest(input, this.options.textReg); }; testEmail(input) { return this.baseTest(input, this.options.emailReg); }; testPassword(input) { return this.baseTest(input, this.options.passwordReg); }; testPhone(input) { return this.baseTest(input, this.options.phoneReg); }; changeClasses(input, inputIsValid) { const block = input.closest(`.${base.elStr.formBlock}`); if (inputIsValid) { block.classList.remove(this.options.errorClass); block.classList.add(this.options.validClass); } else { block.classList.add(this.options.errorClass); block.classList.remove(this.options.validClass); } }; validForm() { let formIsValid = true; this.inputs.forEach(input => { const type = input.type.toLowerCase(); switch (type) { case 'text': if (!this.testText(input)) formIsValid = false; break; case 'email': if (!this.testEmail(input)) formIsValid = false; break; case 'password': if (!this.testPassword(input)) formIsValid = false; break; case 'tel': if (!this.testPhone(input)) formIsValid = false; break; } }); return formIsValid; } }<file_sep>import * as base from '../views/base'; import * as loginView from '../views/login'; import Login from '../models/Login'; import Form from '../models/Form'; import state from '../models/state'; export default function () { base.clearContent(); base.hideHeader(); base.renderLoader(); base.removeLoader(); loginView.renderLogin(); addEvents(); } function addEvents() { const forms = document.querySelectorAll(`.${base.elStr.loginForm}`); forms.forEach(el => { const form = new Form(el); form.init(); el.addEventListener('submit', ev => { ev.preventDefault(); if (!form.validForm()) return; console.log('Trying to login...!') // afterSend(); }); }); }<file_sep>import axios from 'axios'; export default class Login { constructor() { } }<file_sep>export default { stateTest: 'testPassed' }<file_sep>const express = require('express'); const router = express.Router(); const companies = [ { id: 1, name: 'Company 1', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date(), location: 'Bogatynia', tags: ['remont', 'podłoga', 'pilne', 'wykończenie'], likes: 1223, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' }, { id: 2, name: 'Company 2', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date('2019-03-09'), location: 'Wrocław', tags: ['dach'], likes: 199, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' }, { id: 3, name: 'Company 3', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date('2019-03-08'), location: 'Zgorzelec', tags: ['remont', 'ściana'], likes: 1113, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' }, { id: 4, name: 'Company 4', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date('2019-03-07'), location: 'Warszawa', tags: ['remont', 'podłoga'], likes: 1883, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' }, { id: 5, name: 'Company 5', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date(), location: 'Bogatynia', tags: ['remont', 'podłoga', 'pilne', 'wykończenie'], likes: 1223, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' }, { id: 6, name: 'Company 6', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date('2019-03-09'), location: 'Wrocław', tags: ['dach'], likes: 200, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' }, { id: 7, name: 'Company 7', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date('2019-03-08'), location: 'Zgorzelec', tags: ['remont', 'ściana'], likes: 1113, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' }, { id: 8, name: 'Company 8', text: 'lorm ipsum sdasd ad asdasd asdf asdf asfasdf asfnask hfaksjhf jasb fkjasg fkasbdfakjhsgdfasjgf dasjhgdfaksjdf', date: new Date('2019-03-07'), location: 'Warszawa', tags: ['remont', 'podłoga'], likes: 1883, votes: 2000, details: { address: 'some street 12', zipCode: '59-920', country: 'Polska', nip: 123456789 }, services: ['Lorem 12', 'Lorem 232', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322', 'Lorem 14232', 'Lorem 12342', 'Lorem 14322','Lorem 1442'], reviews: [ { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusandae quisquam ullam,lendus ullam quaerat quasi.', date: new Date('2019-03-08'), rating: 3 }, { name: '<NAME>', text: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Recusaam,lendus ullam quaerat quasi.', date: new Date('2019-03-09'), rating: 5 } ], site: 'www.google.pl' } ]; router.get('/', (req, res) => { // Pretend database delay setTimeout(function() { res.send(companies) }, 1000); }); router.get('/:id', (req, res) => { // TODO - db query const index = companies.findIndex((el) => el.id === parseInt(req.params.id)); setTimeout(function() { res.send(companies[index]); }, 1000); }) module.exports = router;<file_sep>import './assets/assets'; import './routing/router'; import state from './models/state'; import companiesCtrl from './controllers/listCompaniesController'; import companyCtrl from './controllers/companyController'; import offersCtrl from './controllers/listOffersController'; import offerCtrl from './controllers/offerController'; import registrationCtrl from './controllers/registrationController'; import loginCtrl from './controllers/loginController'; window.onpopstate = (e) => { loadController(); console.log(e) }; window.addEventListener('locationChanged', function (e) { // TODO state.path = e.detail.path; state.param = e.detail.param; loadController(); // console.info('Location changed state', state); }, false); async function loadController() { // load each route controller later switch (state.path) { case '/company': companyCtrl(state.param); break; case '/companies': companiesCtrl() break; case '/offers': offersCtrl() break; case '/offer': offerCtrl(state.param); break; case '/registration': registrationCtrl(state.param); break; case '/login': loginCtrl(); break; default: offersCtrl(); break; } }; // offersCtrl(); // TODO // Poprawić router, bazujący na location / poprawne ścieżki<file_sep>import axios from 'axios'; export default class Registration { constructor() { } async createAccount( dataObj, type ) { const response = await axios.post(`/api/users/add/${type}`, { data: dataObj }); console.log(response); return response.data } }<file_sep>import * as base from '../views/base'; import * as listView from '../views/list'; import Companies from '../models/Companies'; import { navigate } from '../routing/router'; import state from '../models/state'; export default async function () { base.clearContent(); base.showHeader(); const companies = new Companies(); listView.renderWrapper(); try { base.renderLoader(); await companies.getCompanies(); state.companies = companies.list; base.removeLoader(); listView.renderCompanies(companies.list); addEvents(); console.log(state); } catch (error) { console.log(error); } }; function addEvents () { document.querySelector(`.${base.elStr.list}`).addEventListener('click', ev => { const target = ev.target; if(target.classList.contains(base.elStr.listCompanyLink)) { ev.preventDefault() navigate(`/company:${target.getAttribute('href').replace('#','')}`); } }) }<file_sep>import '../../style/main.scss'; import '../../assets/svgs/sprite.svg';
d0de4d0b3935089c6269ef74b610bc96276b678e
[ "JavaScript" ]
20
JavaScript
marcincyboran/workbook
a47c1485b6d857503511cbc3ccc0f4232a2c5891
311f6fd0adb2879a19b7c17c30c246365386e8fb
refs/heads/master
<file_sep>#!/bin/bash - #=============================================================================== # # FILE: mysql-backup.sh # # USAGE: ./mysql-backup.sh # # DESCRIPTION: Script for backup all databases using percona backup tool # # OPTIONS: --- # REQUIREMENTS: innobackupex-1.5.1 # BUGS: --- # NOTES: --- # AUTHOR: <NAME> (antonichuk), <EMAIL> # ORGANIZATION: Lviv, Ukraine # CREATED: 01.09.14 16:17 # REVISION: 1.0 #=============================================================================== set -o nounset # Treat unset variables as an error INNOBACKUPEX=innobackupex-1.5.1 INNOBACKUPEXFULL=/usr/bin/$INNOBACKUPEX USEROPTIONS="--user=root --password=moIj>Ob;bIm;wyiT%" TMPFILE="/tmp/backup.$$.tmp" MYCNF=/etc/my.cnf MYSQL=/usr/bin/mysql MYSQLADMIN=/usr/bin/mysqladmin BACKUPDIR=/data/db # Backups base directory DAILYBACKUPFULL=$BACKUPDIR/daily # Full daily backups directory HOURLYBACKUP=$BACKUPDIR/hourly # Hourly nncremental backups directory FULLBACKUPLIFE=86400 # Lifetime of the latest full daily backup in seconds KEEP=7 # Number of full backups and its incrementals to keep # Take start time STARTED_AT=`date +%s` # Display error message and exit # error() { echo "$1" 1>&2 exit 1 } # Check options before proceeding if [ ! -x $INNOBACKUPEXFULL ]; then error "$INNOBACKUPEXFULL does not exist." fi if [ ! -d $BACKUPDIR ]; then error "Backup destination folder: $BACKUPDIR does not exist." fi if [ -z "`$MYSQLADMIN $USEROPTIONS status | grep 'Uptime'`" ] ; then error "ERROR: MySQL does not appear to be running." fi if ! `echo 'exit' | $MYSQL -s $USEROPTIONS` ; then error "ERROR: Supplied mysql username or password appears to be incorrect." fi # Some info output echo "$0 started at: `date`" # Create full daily and hourly incr backup directories if they not exist. mkdir -p $DAILYBACKUPFULL mkdir -p $HOURLYBACKUP # Find latest full backup LATEST_FULL=`find $DAILYBACKUPFULL -mindepth 1 -maxdepth 1 -type d -printf "%P\n" | sort -nr | head -1` # Get latest backup last modification time LATEST_FULL_CREATED_AT=`stat -c %Y $DAILYBACKUPFULL/$LATEST_FULL` # Run an incremental backup if latest full is still valid. Otherwise, run a new full one. if [ "$LATEST_FULL" -a `expr $LATEST_FULL_CREATED_AT + $FULLBACKUPLIFE + 5` -ge $STARTED_AT ] ; then # Create incremental backups dir if not exists. TMPINCRDIR=$HOURLYBACKUP/$LATEST_FULL mkdir -p $TMPINCRDIR # Find latest incremental backup. LATEST_INCR=`find $TMPINCRDIR -mindepth 1 -maxdepth 1 -type d | sort -nr | head -1` # If this is the first incremental, use the full as base. Otherwise, use the latest incremental as base. if [ ! $LATEST_INCR ] ; then INCRBASEDIR=$DAILYBACKUPFULL/$LATEST_FULL else INCRBASEDIR=$LATEST_INCR fi echo "Running new incremental backup using $INCRBASEDIR as base." $INNOBACKUPEXFULL --defaults-file=$MYCNF $USEROPTIONS --incremental $TMPINCRDIR --incremental-basedir $INCRBASEDIR > $TMPFILE 2>&1 else echo "Running new full backup." $INNOBACKUPEXFULL --defaults-file=$MYCNF $USEROPTIONS $DAILYBACKUPFULL > $TMPFILE 2>&1 fi if [ -z "`tail -1 $TMPFILE | grep 'completed OK!'`" ] ; then echo "$INNOBACKUPEX failed:"; echo echo "---------- ERROR OUTPUT from $INNOBACKUPEX ----------" cat $TMPFILE rm -f $TMPFILE exit 1 fi THISBACKUP=`awk -- "/Backup created in directory/ { split( \\\$0, p, \"'\" ) ; print p[2] }" $TMPFILE` rm -f $TMPFILE echo "Databases backed up successfully to: $THISBACKUP" echo # Cleanup echo "Cleanup. Keeping $KEEP full daily backups and its incrementals." AGE=$(($FULLBACKUPLIFE * $KEEP / 60)) find $DAILYBACKUPFULL -maxdepth 1 -type d -mmin +$AGE -execdir echo "removing: "$DAILYBACKUPFULL/{} \; -execdir rm -rf $DAILYBACKUPFULL/{} \; -execdir echo "removing: "$HOURLYBACKUP/{} \; -execdir rm -rf $HOURLYBACKUP/{} \; echo echo "Completed at: `date`" exit 0 <file_sep>#!/bin/bash #=============================================================================== # # FILE: mysql-restore.sh # # USAGE: ./mysql-restore.sh -p <path to backup to restore> -d <database name to restore> -t <table name to restore> # # DESCRIPTION: This is script for restore databases from full or incremental backups # # OPTIONS: --- # REQUIREMENTS: Percona XtraBackup # BUGS: --- # NOTES: --- # AUTHOR: <NAME> (antonichuk), <EMAIL> # ORGANIZATION: Lviv, Ukraine # CREATED: 01.09.14 01:45 # REVISION: 1.0 #=============================================================================== set -o nounset # Treat unset variables as an error # Define variables #INNOBACKUPEX=innobackupex-1.5.1 INNOBACKUPEX=innobackupex INNOBACKUPEXFULL=/usr/bin/$INNOBACKUPEX TMPFILE="/tmp/mysql-restore.$$.tmp" MYCNF=/data/db/my.cnf # We must you another my.cnf file for restoring db's, where we provide path to datadir to - /data/db/restore BACKUPDIR=/data/db # Backups base directory DAILYBACKUP=$BACKUPDIR/full # Full backups directory HOURLYBACKUP=$BACKUPDIR/hour # Incremental backups directory MEMORY=1024M # Amount of memory to use when preparing the backup START=`date +%s` USEROPTIONS="--user=root --password=moIj>Ob;bIm;wyiT%" RESTOREDDIR=/data/db/restored RESTORE= DATABASE= TABLE= LAST_INCR_BACKUP= REALPATH= DEFAULTDB=binpress # Print usage info usage() { cat<<EOF >&2 How to use: $0 -p <path to backup to restore> -d <database name to restore> -t <table name to restore> When -d (database) not set, default db name for restore wiil be use Tou can change it in $DEFAULTDB variable When -t (table name) not set, all tables from database will be restored For restore some table, you must set database name from which it will be restored, and table name that will be restored. EOF } # Display error message and exit error() { echo "$@" exit 1 } # Check for errors in innobackupex output# check_innobackupex_error() { if [ -z "`tail -1 $TMPFILE | grep 'completed OK!'`" ] ; then echo "$INNOBACKUPEX failed:"; echo echo "---------- ERROR OUTPUT from $INNOBACKUPEX ----------" cat $TMPFILE rm -f $TMPFILE exit 1 fi } # Check options before proceeding if [ ! -x $INNOBACKUPEXFULL ]; then error "$INNOBACKUPEXFULL does not exist. You must install Percona XtraBackup" fi # Check for arguments, if no arguments, then show usage and exit if [ $# = 0 ]; then usage exit 1 fi while getopts ":lp:d:t:" OPTION; do case $OPTION in l ) LAST_INCR_BACKUP=latest ;; p ) RESTORE=$OPTARG ;; d ) DATABASE=$OPTARG ;; t ) TABLE=$OPTARG ;; ?) usage exit 1 ;; esac done #if [[ -z $RESTORE ]] #then # echo # echo "You must select path to direcotory with backups!!!" # echo "Or you can use --latest options to restore from latest incremenatlal backup" # echo "Please, read usage instuction!!!" # echo # usage # echo # exit 1 #fi # Ask user to continiue or not read -p "Are you sure that you want to restore databases? Press "Y" to continiue or any key to exit" -n 1 -r if [[ ! $REPLY =~ ^[Yy]$ ]] then echo echo "OK!" echo "Try next time when you will be ready" exit 1 fi # Check if used "-l" and "-p", we can't use -l and -p option if [[ ! -z $LAST_INCR_BACKUP ]] && [[ ! -z $RESTORE ]] then echo "We can't use both options -l and -p" usage exit 1 fi # Check folder with backups for existing if [ ! -d $RESTORE ]; then error "Backup to restore: $RESTORE does not exis." fi # Some info output echo "Script $0 started at: `date`" full_to_incr() { PARENT_DIR=`dirname $RESTORE` if [ $PARENT_DIR = $DAILYBACKUP ] then FULLBACKUP=$RESTORE echo "Restore `basename $FULLBACKUP`" echo else if [ `dirname $PARENT_DIR` = $HOURLYBACKUP ] then INCR=`basename $RESTORE` FULL=`basename $PARENT_DIR` FULLBACKUP=$DAILYBACKUP/$FULL if [ ! -d $FULLBACKUP ] then error "Full backup: $FULLBACKUP does not exist." fi echo "Restore $FULL up to incremental $INCR" echo "Replay committed transactions on full backup" $INNOBACKUPEXFULL --defaults-file=$MYCNF --apply-log --redo-only --use-memory=$MEMORY $FULLBACKUP > $TMPFILE 2>&1 check_innobackupex_error # Apply incrementals to base backup for i in `find $PARENT_DIR -mindepth 1 -maxdepth 1 -type d -printf "%P\n" | sort -n`; do echo "Applying $i to full ..." $INNOBACKUPEXFULL --defaults-file=$MYCNF --apply-log --redo-only --use-memory=$MEMORY $FULLBACKUP --incremental-dir=$PARENT_DIR/$i > $TMPFILE 2>&1 check_innobackupex_error if [ $INCR = $i ] then break # break. we are restoring up to this incremental. fi done else error "Unknown backup type" fi fi } # Preparing databse to restore prepare_databases() { echo "Preparing to restoring ..." $INNOBACKUPEXFULL --defaults-file=$MYCNF --apply-log --use-memory=$MEMORY $FULLBACKUP > $TMPFILE 2>&1 check_innobackupex_error } # Restoring all databases restore_all_db() { echo "Restoring all databases" $INNOBACKUPEXFULL --defaults-file=$MYCNF --copy-back $FULLBACKUP > $TMPFILE 2>&1 check_innobackupex_error rm -f $TMPFILE } # Restoring defined databse restore_db() { echo "Restoring only $DATABASE database" $INNOBACKUPEXFULL $USEROPTIONS --include=$DATABASE $FULLBACKUP > $TMPFILE 2>&1 check_innobackupex_error rm -f $TMPFILE } # Restoring default databse restore_default_db() { echo "Restoring default $DEFAULTDB database" $INNOBACKUPEXFULL $USEROPTIONS --include=$DEFAULTDB $FULLBACKUP > $TMPFILE 2>&1 check_innobackupex_error rm -f $TMPFILE } # Restoring table from database restore_table() { echo "Restoring only table $TABLE from $DATABASE database" $INNOBACKUPEXFULL $USEROPTIONS --include $DATABASE.$TABLE $FULLBACKUP > $TMPFILE 2>&1 check_innobackupex_error rm -f $TMPFILE } # Find last incremental backup last_incr () { echo "Finding last incremental backup" LATEST_INCR=`find $HOURLYBACKUP -mindepth 1 -maxdepth 2 -type d -printf "%P\n" | sort -nr | head -1` RESTORE=$HOURLYBACKUP/$LATEST_INCR } # If use key "-l" and no path to backup, no database name, no table to restore, will be restored default db from lates incr. if [[ ! -z $LAST_INCR_BACKUP ]] && [[ -z $DATABASE ]] && [[ -z $TABLE ]] then last_incr echo "Will be restored deault $DEFAULTDB database from last incremental backup from: $RESTORE" full_to_incr prepare_databases restore_default_db SPENT=$((`date +%s` - $START)) echo "Took $SPENT seconds" echo "Completed at: `date`" exit 0 else # If use key "-l" and Database "ALL", all db's from lates incremental backup will be restored. if [[ ! -z $LAST_INCR_BACKUP ]] && [[ $DATABASE="ALL" ]] && [[ -z $TABLE ]] then last_incr echo "All database will be restored..." full_to_incr prepare_databases restore_all_db SPENT=$((`date +%s` - $START)) echo "Took $SPENT seconds" echo "Completed at: `date`" echo echo "All db's has been restored from latest backup" echo "You can copy it to MySQL data dir, usualy it is in /var/lib/mysql" echo "Verify files ownership in mysql data dir." echo "You can fix permission by this command: chown -R mysql:mysql /var/lib/mysql" echo "You are able to start MySQL server now" exit 0 else # If use key "-l" and no path to backup, no table to restore, defined database with all tables will be restored from lates incr. if [[ ! -z $LAST_INCR_BACKUP ]] && [[ ! -z $DATABASE ]] && [[ -z $TABLE ]] then last_incr echo "Database $DATABASE from latest incremental backup will be restored" full_to_incr prepare_databases restore_db SPENT=$((`date +%s` - $START)) echo "Took $SPENT seconds" echo "Completed at: `date`" exit 0 else # If use key "-l" -d <database> -t <table>, then it will restore table from database from lates incr. if [[ ! -z $LAST_INCR_BACKUP ]] && [[ ! -z $DATABASE ]] && [[ ! -z $TABLE ]] then last_incr echo "Database $TABLE from database $DATABASE using latest incremental backup will be restored" full_to_incr prepare_databases restore_table SPENT=$((`date +%s` - $START)) echo "Took $SPENT seconds" echo "Completed at: `date`" exit 0 else # Restore default db from path if [[ ! -z $RESTORE ]] && [[ -z $DATABASE ]] && [[ -z $TABLE ]] then full_to_incr prepare_databases restore_db echo "Database $DATABASE has been restored" SPENT=$((`date +%s` - $START)) echo echo "Took $SPENT seconds" echo "Completed at: `date`" exit 0 else # Restore ALL db's from path if [[ ! -z $RESTORE ]] && [[ $DATABASE="ALL" ]] && [[ -z $TABLE ]] then full_to_incr prepare_databases restore_all_db echo "Table $TABLE from $DATABASE has been restored" SPENT=$((`date +%s` - $START)) echo echo "Took $SPENT seconds" echo "Completed at: `date`" exit 0 else # Restore database from path if [[ ! -z $RESTORE ]] && [[ ! -z $DATABASE ]] && [[ -z $TABLE ]] then full_to_incr prepare_databases restore__db echo "Table database $DATABASE from $RESTORE has been restored" SPENT=$((`date +%s` - $START)) echo echo "Took $SPENT seconds" echo "Completed at: `date`" exit 0 fi fi fi fi fi fi fi
e9581a49f8017680ba65f7897ad8dfae8d751dc6
[ "Shell" ]
2
Shell
antonichuk/mysql-scripts
62251c81bea65d36f520c5edeb412d98291686f0
24127c770cae85a091ac57ab05cdf2d750b6c037
refs/heads/master
<repo_name>nzznq/vue_frame<file_sep>/src/components/common/index.js import LwPanel from "./exampleFrame/panel.vue"; import LwWords from "./exampleFrame/words.vue"; import LwLink from "./exampleFrame/link.vue"; import LwPic from "./exampleFrame/picture.vue"; import LwCode from "./exampleFrame/code.vue"; import LwSubtitle from "./exampleFrame/subtitle.vue"; const components = [ LwPanel, LwWords, LwLink, LwPic, LwCode, LwSubtitle ]; export default components;<file_sep>/src/router/index.js import Vue from 'vue' import Router from 'vue-router' const _import = require('./_import_' + process.env.NODE_ENV); Vue.use(Router) //基础路由 export const baseRouter = [ { path: '/', name: 'example-main', component: _import('example/main/index'), children:[ { path:'/', redirect:'/common' }, { path: 'git', name: 'git', component: _import('example/git/git') }, { path: 'api', name: 'api', component: _import('example/api/api') }, { path: 'npm', name: 'npm', component: _import('example/npm/npm') }, { path: 'common', name: 'common', component: _import('example/common/common') }, { path: 'project', name: 'project', component: _import('example/project/project') } ] },{ path: '/test', name: 'test', component: _import('test/test') } ] //业务路由 export const businessRouter = [ ].concat(baseRouter); export default new Router({ linkActiveClass:"check", //路由激活类名 routes: businessRouter });
68c6593faa2dec9a85458ade0dfc5fba193c8182
[ "JavaScript" ]
2
JavaScript
nzznq/vue_frame
c0aa5bafb0c52a75c813443ab3e2eff9015de1bd
2fdbebcd6b8fddb5fcc1b13686adff3966142a60
refs/heads/master
<repo_name>etalanin/scenetext<file_sep>/test.php <?php function cmp($a, $b) { if ($a["box"] > $b["box"]) return 1; else if ($a["box"] < $b["box"]) return -1; else if ($a["area"] > $b["area"]) return 1; else if ($a["area"] < $b["area"]) return -1; else if ($a["perimeter"] > $b["perimeter"]) return 1; else if ($a["perimeter"] < $b["perimeter"]) return -1; else if ($a["euler"] > $b["euler"]) return 1; else if ($a["euler"] < $b["euler"]) return -1; else if ($a["crossings"] > $b["crossings"]) return 1; else if ($a["crossings"] < $b["crossings"]) return -1; return 0; } $files_dir = "/home/evgeny/argus/scenetext/testimages/"; $filenames = array("ontario_small.jpg", "vilnius.jpg", "lines.jpg", "painting.jpg", "road.jpg", "floor.jpg", "campaign.jpg", "incorrect640.jpg", "lettera.jpg", "abv.jpg"); $exename = "bin/scenetext"; $op = array(); $code = 0; $results = array(); $times = array(); $approach_idx = 0; $region_idx = 0; foreach($filenames as $fn) { echo "Testing {$fn}... "; $approach_idx = 0; $region_idx = 0; $op = array(); $results = array(); exec("{$exename} {$files_dir}{$fn}", $op, $code); if ($code != 0) { die("FAIL\n"); } foreach($op as $l) { if (strpos($l, "time") !== false) { $times[$approach_idx] = floatval(substr($l, strpos($l, "time: ") + 6)); $approach_idx++; $region_idx = 0; } else if (strpos($l, "New region") !== false) { $region_idx++; } else if (strpos($l, "Area") !== false) { $results[$approach_idx][$region_idx]["area"] = intval(substr($l, strpos($l, ": ") + 2)); } else if (strpos($l, "Bounding box") !== false) { $results[$approach_idx][$region_idx]["box"] = trim(substr($l, strpos($l, "("))); } else if (strpos($l, "Perimeter") !== false) { $results[$approach_idx][$region_idx]["perimeter"] = intval(substr($l, strpos($l, ": ") + 2)); } else if (strpos($l, "Euler number") !== false) { $results[$approach_idx][$region_idx]["euler"] = intval(substr($l, strpos($l, ": ") + 2)); } else if (strpos($l, "Crossings") !== false) { $results[$approach_idx][$region_idx]["crossings"] = trim(substr($l, strpos($l, ": ") + 2)); } else if (strpos($l, "fault") !== false) { die("FAIL"); } } usort($results[0], "cmp"); usort($results[1], "cmp"); if (count($results[0]) != count($results[1])) { echo "FAIL (number of elements)"; } else { for($i = 0; $i < count($results[0]); $i++) { if ( ($results[0][$i]["area"] != $results[1][$i]["area"]) || ($results[0][$i]["box"] != $results[1][$i]["box"]) || ($results[0][$i]["perimeter"] != $results[1][$i]["perimeter"]) || ($results[0][$i]["euler"] != $results[1][$i]["euler"]) || ($results[0][$i]["crossings"] != $results[1][$i]["crossings"]) ) { echo "FAIL (element #{$i})"; print_r($results[0][$i]); print_r($results[1][$i]); goto mark1; } } echo "SUCCESS ({$times[0]} vs. {$times[1]} ms): " . round($times[1] / $times[0], 2) . " times slower"; } mark1: echo "\n"; } ?> <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(opencv_sandbox) set(OpenCV_DIR "/home/evgeny/argus/git_trunk/build") find_package(OpenCV REQUIRED) add_executable(scenetext ./scenetext.cpp) set_target_properties(scenetext PROPERTIES LINKER_LANGUAGE CXX) target_link_libraries(scenetext ${OpenCV_LIBS}) <file_sep>/scenetext.cpp #include "opencv2/highgui/highgui.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "opencv2/contrib/contrib.hpp" #include <iostream> #include <fstream> #include <sstream> using namespace cv; using namespace std; int GroundTruth(Mat& _originalImage, bool showImage = false) { double t = (double)getTickCount(); Mat originalImage(_originalImage.rows + 2, _originalImage.cols + 2, _originalImage.type()); copyMakeBorder(_originalImage, originalImage, 1, 1, 1, 1, BORDER_CONSTANT, Scalar(255, 255, 255)); Mat bwImage(originalImage.size(), CV_8UC1); uchar thresholdValue = 100; uchar maxValue = 255; uchar middleValue = 192; uchar zeroValue = 0; Scalar middleScalar(middleValue); Scalar zeroScalar(zeroValue); static int neigborsCount = 4; static int dx[] = {-1, 0, 0, 1}; static int dy[] = { 0, -1, 1, 0}; int di, rx, ry; int perimeter; cvtColor(originalImage, bwImage, CV_RGB2GRAY); threshold(bwImage, bwImage, thresholdValue, maxValue, THRESH_BINARY_INV); int regionsCount = 0; int totalPixelCount = bwImage.rows * bwImage.cols; Point seedPoint; Rect rectFilled; int valuesSum, q1, q2, q3; bool p00, p10, p01, p11; for(int i = 0; i < totalPixelCount; i++) { if (bwImage.data[i] == maxValue) { seedPoint.x = i % bwImage.cols; seedPoint.y = i / bwImage.cols; if ((seedPoint.x == 0) || (seedPoint.y == 0) || (seedPoint.x == bwImage.cols - 1) || (seedPoint.y == bwImage.rows - 1)) { continue; } regionsCount++; size_t pixelsFilled = floodFill(bwImage, seedPoint, middleScalar, &rectFilled); printf("New region: %d\n", regionsCount); // We use -1 here since image was expanded by 1 pixel //printf("Start point: (%d; %d)\n", seedPoint.x - 1, seedPoint.y - 1); printf("Area: %d\n", (int)pixelsFilled); printf("Bounding box (%d; %d) + (%d; %d)\n", rectFilled.x - 1, rectFilled.y - 1, rectFilled.width, rectFilled.height); perimeter = 0; q1 = 0; q2 = 0; q3 = 0; int crossings[rectFilled.height]; for(int j = 0; j < rectFilled.height; j++) { crossings[j] = 0; } for(ry = rectFilled.y - 1; ry <= rectFilled.y + rectFilled.height; ry++) { for(rx = rectFilled.x - 1; rx <= rectFilled.x + rectFilled.width; rx++) { if ((bwImage.at<uint8_t>(ry, rx - 1) != bwImage.at<uint8_t>(ry, rx)) && (bwImage.at<uint8_t>(ry, rx - 1) + bwImage.at<uint8_t>(ry, rx) == middleValue + zeroValue)) { crossings[ry - rectFilled.y]++; } if (bwImage.at<uint8_t>(ry, rx) == middleValue) { for(di = 0; di < neigborsCount; di++) { int xNew = rx + dx[di]; int yNew = ry + dy[di]; if (bwImage.at<uint8_t>(yNew, xNew) == zeroValue) { perimeter++; } } } p00 = bwImage.at<uint8_t>(ry, rx) == middleValue; p01 = bwImage.at<uint8_t>(ry, rx + 1) == middleValue; p10 = bwImage.at<uint8_t>(ry + 1, rx) == middleValue; p11 = bwImage.at<uint8_t>(ry + 1, rx + 1) == middleValue; valuesSum = p00 + p01 + p10 + p11; if (valuesSum == 1) q1++; else if (valuesSum == 3) q2++; else if ((valuesSum == 2) && (p00 == p11)) q3++; } } q1 = q1 - q2 + 2 * q3; if (q1 % 4 != 0) { printf("Non-integer Euler number"); exit(0); } q1 /= 4; printf("Perimeter: %d\n", (int)perimeter); printf("Euler number: %d\n", q1); printf("Crossings: "); for(int j = 0; j < rectFilled.height; j++) { printf("%d ", crossings[j]); } printf("\n=====\n\n"); floodFill(bwImage, seedPoint, zeroScalar); rectangle(originalImage, rectFilled, zeroScalar); } } t = (double)getTickCount() - t; printf("Working time: %g ms\n", t * 1000. / getTickFrequency()); if (showImage) { imshow("Truth", originalImage); waitKey(); } } class Region { private: Point start; Rect bounds; int area; int perimeter; int euler; int imageh; int* crossings; public: Region() { } Region(Point _p, int h) { start = _p; bounds.x = _p.x; bounds.y = _p.y; bounds.width = 1; bounds.height = 1; area = 1; perimeter = 4; euler = 0; imageh = h; crossings = new int[imageh + 1]; memset(crossings, 0, imageh * 4); crossings[_p.y] = 2; } ~Region() { delete[] crossings; } void Attach(Region* _extra, int _borderLength, int _p0y, int _hn) { if (start != _extra->start) { bounds |= _extra->bounds; area += _extra->area; perimeter += _extra->perimeter - 2 * _borderLength; euler += _extra->euler; for(int i = bounds.y - 1; i < bounds.y + bounds.height + 2; i++) { crossings[i] += _extra->crossings[i]; } crossings[_p0y] -= 2 * _hn; } } void CorrectEuler(int _delta) { euler += _delta; } Rect Bounds() { return bounds; } Point Start() { return start; } int Area() { return area; } int Perimeter() { return perimeter; } int Euler() { return euler; } int* Crossings() { return crossings; } int BoundsArea() { return bounds.width * bounds.height; } }; Point uf_Find(Point _x, Point** _parents) { if (_parents[_x.x][_x.y].x == -1) { return Point(-1, -1); } while(_parents[_x.x][_x.y] != _x) { _x = _parents[_x.x][_x.y]; } return _x; } void MatasLike(Mat& _originalImage, bool showImage = false) { double t = (double)getTickCount(); Mat originalImage(_originalImage.rows + 2, _originalImage.cols + 2, _originalImage.type()); copyMakeBorder(_originalImage, originalImage, 1, 1, 1, 1, BORDER_CONSTANT, Scalar(255, 255, 255)); Mat bwImage(originalImage.size(), CV_8UC1); vector<Point> pointLevels[256]; Point pc; static int neighborsCount = 4; static int dx[] = {-1, 0, 0, 1}; static int dy[] = { 0, -1, 1, 0}; int di; int i, j, k; cvtColor(originalImage, bwImage, CV_RGB2GRAY); int** ranksArray; ranksArray = new int*[bwImage.cols]; for(i = 0; i < bwImage.cols; i++) { ranksArray[i] = new int[bwImage.rows]; } Point** parentsArray; parentsArray = new Point*[bwImage.cols]; for(i = 0; i < bwImage.cols; i++) { parentsArray[i] = new Point[bwImage.rows]; for(j = 0; j < bwImage.rows; j++) { parentsArray[i][j] = Point(-1, -1); } } Region*** regionsArray; regionsArray = new Region**[bwImage.cols]; for(i = 0; i < bwImage.cols; i++) { regionsArray[i] = new Region*[bwImage.rows]; for(j = 0; j < bwImage.rows; j++) { regionsArray[i][j] = NULL; } } // Filling pointLevels for(i = 0; i < bwImage.rows; i++) { const uchar* bwImageRow = bwImage.ptr<uchar>(i); for(j = 0; j < bwImage.cols; j++) { pc.x = j; pc.y = i; pointLevels[bwImageRow[j]].push_back(pc); } } static int thresh_start = 0; static int thresh_end = 101; static int thresh_step = 1; int thresh; bool changed = false; bool is_good_neighbor[3][3]; bool is_any_neighbor[3][3]; is_any_neighbor[1][1] = false; int neighborsInRegions = 0, horizontalNeighbors = 0; int q1 = 0, q2 = 0, q3 = 0; int q10 = 0, q20 = 0, q30 = 0; int qtemp = 0; Point p0, p1, proot, p1root; Region* point_region = NULL; int point_rank, neighbor_rank; int x_new, y_new; int ddx, ddy; int npx, npy; for(thresh = thresh_start; thresh < thresh_end; thresh += thresh_step) { for(k = 0; k < pointLevels[thresh].size(); k++) { p0 = pointLevels[thresh][k]; // Surely point when accessed for the first time is not in any region // Setting parent, rank, creating region (uf_makeset) parentsArray[p0.x][p0.y] = p0; ranksArray[p0.x][p0.y] = 0; regionsArray[p0.x][p0.y] = new Region(p0, originalImage.rows); // Surely find will be successful since region we are searching for was just created point_region = regionsArray[p0.x][p0.y]; proot = p0; changed = false; is_any_neighbor[1][1] = false; q1 = 0; q2 = 0; q3 = 0; q10 = 0; q20 = 0; q30 = 0; qtemp = 0; for(ddx = -1; ddx <= 1; ddx++) { for(ddy = -1; ddy <= 1; ddy++) { if ((ddx != 0) || (ddy != 0)) { is_any_neighbor[ddx+1][ddy+1] = uf_Find(Point(p0.x + ddx, p0.y + ddy), parentsArray) != Point(-1, -1); } if ((ddx >= 0) && (ddy >= 0)) { qtemp = is_any_neighbor[ddx+1][ddy+1] + is_any_neighbor[ddx+1][ddy] + is_any_neighbor[ddx][ddy+1] + is_any_neighbor[ddx][ddy]; if (qtemp == 0) { q1++; } else if (qtemp == 1) { q10++; npx = ddx == 0 ? 0 : 2; npy = ddy == 0 ? 0 : 2; if (is_any_neighbor[npx][npy]) { q3++; } } else if (qtemp == 2) { if (is_any_neighbor[ddx+1][ddy+1] == is_any_neighbor[ddx][ddy]) { q30++; } q2++; } else if (qtemp == 3) { q20++; } } } } qtemp = (q1 - q2 + 2 * q3) - (q10 - q20 + 2 * q30); if (qtemp % 4 != 0) { printf("Non-integer Euler number"); exit(0); } qtemp /= 4; for(di = 0; di < neighborsCount; di++) { x_new = p0.x + dx[di]; y_new = p0.y + dy[di]; // TODO: implement corresponding function? if ((x_new < 0) || (y_new < 0) || (x_new >= originalImage.cols) || (y_new >= originalImage.rows)) { continue; } if (changed) { proot = uf_Find(p0, parentsArray); point_region = regionsArray[proot.x][proot.y]; // point_region should exist! } // p1 is neighbor of point of interest p1.x = x_new; p1.y = y_new; if (parentsArray[p1.x][p1.y] != Point(-1, -1)) { // Entering here means that p1 belongs to some region since has a parent // Will now find root p1root = uf_Find(p1, parentsArray); // Need to union. Three cases: rank1>rank2, rank1<rank2, rank1=rank2 point_rank = ranksArray[p0.x][p0.y]; neighbor_rank = ranksArray[p1root.x][p1root.y]; is_good_neighbor[3][3]; neighborsInRegions = 0; horizontalNeighbors = 0; for(ddx = -1; ddx <= 1; ddx++) { for(ddy = -1; ddy <= 1; ddy++) { if ((ddx != 0) || (ddy != 0)) { is_good_neighbor[ddx+1][ddy+1] = uf_Find(Point(p0.x + ddx, p0.y + ddy), parentsArray) == p1root; if (is_good_neighbor[ddx+1][ddy+1]) { if (ddy == 0) { horizontalNeighbors++; } if ((ddy == 0) || (ddx == 0)) { neighborsInRegions++; } } } } } // uf_union if (point_rank < neighbor_rank) { parentsArray[proot.x][proot.y] = p1root; regionsArray[p1root.x][p1root.y]->Attach(regionsArray[proot.x][proot.y], neighborsInRegions, p0.y, horizontalNeighbors); if (proot != p1root) { // TODO: check if smth is really erased delete regionsArray[proot.x][proot.y]; regionsArray[proot.x][proot.y] = NULL; changed = true; } } else if (point_rank > neighbor_rank) { parentsArray[p1root.x][p1root.y] = proot; regionsArray[proot.x][proot.y]->Attach(regionsArray[p1root.x][p1root.y], neighborsInRegions, p0.y, horizontalNeighbors); if (proot != p1root) { // TODO: check if smth is really erased delete regionsArray[p1root.x][p1root.y]; regionsArray[p1root.x][p1root.y] = NULL; } } else { parentsArray[p1root.x][p1root.y] = proot; ranksArray[proot.x][proot.y]++; regionsArray[proot.x][proot.y]->Attach(regionsArray[p1root.x][p1root.y], neighborsInRegions, p0.y, horizontalNeighbors); if (proot != p1root) { // TODO: check if smth is really erased delete regionsArray[p1root.x][p1root.y]; regionsArray[p1root.x][p1root.y] = NULL; } } } else { // Neighbor not in region. Doing nothing } } Point p0r = uf_Find(p0, parentsArray); regionsArray[p0r.x][p0r.y]->CorrectEuler(qtemp); } /* printf("Threshold: %d. Regions count: %ld.\n", thresh, regions.size()); for(map<Point, Region, PointComp>::iterator it = regions.begin(); it != regions.end(); it++) { if (it->second.Area2() > 100) { //printf("Region bounds: %d %d %d %d\n", it->second.Bounds().x, it->second.Bounds().y, it->second.Bounds().width, it->second.Bounds().height); rectangle(bwImage, it->second.Bounds(), Scalar(0, 0, 0)); } } */ } t = (double)getTickCount() - t; int regionsCount = 0; for(i = 0; i < bwImage.cols; i++) { for(j = 0; j < bwImage.rows; j++) { if (regionsArray[i][j] != NULL) { regionsCount++; rectangle(originalImage, regionsArray[i][j]->Bounds(), Scalar(0, 0, 0)); printf("New region: %d\n", regionsCount); printf("Area: %d\n", regionsArray[i][j]->Area()); printf("Bounding box (%d; %d) + (%d; %d)\n", regionsArray[i][j]->Bounds().x - 1, regionsArray[i][j]->Bounds().y - 1, regionsArray[i][j]->Bounds().width, regionsArray[i][j]->Bounds().height); printf("Perimeter: %d\n", regionsArray[i][j]->Perimeter()); printf("Euler number: %d\n", regionsArray[i][j]->Euler()); printf("Crossings: "); for(int k = regionsArray[i][j]->Bounds().y; k < regionsArray[i][j]->Bounds().y + regionsArray[i][j]->Bounds().height; k++) { printf("%d ", regionsArray[i][j]->Crossings()[k]); } printf("\n"); printf("=====\n\n"); } } } printf("Working time: %g ms\n", t * 1000. / getTickFrequency()); if (showImage) { imshow("Approach", originalImage); waitKey(); } } int main(int argc, char** argv) { string filename; if (argc == 1) { //filename = "../testimages/ontario_small.jpg"; filename = "../testimages/vilnius.jpg"; //filename = "../testimages/lines.jpg"; //filename = "../testimages/painting.jpg"; //filename = "../testimages/road.jpg"; //filename = "../testimages/floor.jpg"; //filename = "../testimages/campaign.jpg"; //filename = "../testimages/incorrect640.jpg"; //filename = "../testimages/points4.jpg"; //filename = "../testimages/lettera.jpg"; //filename = "../testimages/abv.jpg"; } else { filename = argv[1]; } Mat originalImage = imread(filename); Mat originalImage2 = imread(filename); GroundTruth(originalImage); MatasLike(originalImage2); return 0; }
361398baeafbe99dd9ec730c263a67416ff9c96c
[ "CMake", "C++", "PHP" ]
3
PHP
etalanin/scenetext
2b3c07ae6272c3fee92d9dbfa388ace356f9833a
875b35bceda61db057f20cb6f1c2701c4ec0e2d0
refs/heads/main
<file_sep>package com.zack.springcloud.dao; import com.zack.springcloud.pojo.Dept; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; /** * com.zack.springcloud.dao * * @author zhangc * @version 1.0 * @create 2020/10/27 15:47 */ @Mapper @Repository public interface DeptDao { public boolean addDept(Dept dept); public Dept selectById(Long id); public List<Dept> selectAll(); } <file_sep>package com.zack.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * com.zack.springcloud * * @author zhangc * @version 1.0 * @create 2020/10/28 11:05 */ @SpringBootApplication @EnableEurekaServer public class EurekaServer { public static void main(String[] args) { SpringApplication.run(EurekaServer.class, args); } } <file_sep>package com.zack.springcloud.pojo; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; /** * com.zack.springcloud.pojo * * @author zhangc * @version 1.0 * @create 2020/10/27 10:27 */ @Data @NoArgsConstructor @Accessors(chain = true) public class Dept implements Serializable { private Long id; private String dName; private String dbSource; public Dept(String dName) { this.dName = dName; } /** * 链式写法 * Dept dept = new Dept(); * dept.setId().setDName(); */ } <file_sep>package com.zack.springcloud.service.impl; import com.zack.springcloud.dao.DeptDao; import com.zack.springcloud.pojo.Dept; import com.zack.springcloud.service.DeptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * com.zack.springcloud.service.impl * * @author zhangc * @version 1.0 * @create 2020/10/27 15:57 */ @Service public class DeptServiceImpl implements DeptService { @Autowired private DeptDao deptDao; public boolean addDept(Dept dept) { return deptDao.addDept(dept); } public Dept selectById(Long id) { return deptDao.selectById(id); } public List<Dept> selectAll() { return deptDao.selectAll(); } } <file_sep>package com.zack.springcloud.service; import com.zack.springcloud.pojo.Dept; import java.util.List; /** * com.zack.springcloud.service * * @author zhangc * @version 1.0 * @create 2020/10/27 15:57 */ public interface DeptService { public boolean addDept(Dept dept); public Dept selectById(Long id); public List<Dept> selectAll(); } <file_sep>package com.zack.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * com.zack.springcloud * * @author zhangc * @version 1.0 * @create 2020/10/27 16:35 */ @SpringBootApplication public class DeptProvider { public static void main(String[] args) { SpringApplication.run(DeptProvider.class, args); } }
7d4c9c580ba824b62d14f1a2d38d15177cf1b250
[ "Java" ]
6
Java
zc-zack/springcloud
9c2619c93e25052917bf78df85874297abfbf6ae
f10a0288f22e48d262b5e6fd918ca0e785079f06
refs/heads/master
<repo_name>Doko-Demo-Doa/ImageEffect<file_sep>/app/src/main/java/com/phamvanquan/imageeffect/MainInterface.java package com.phamvanquan.imageeffect; import android.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ViewGroup; import android.widget.LinearLayout; import com.phamvanquan.imageeffect.Views.CustomView; public class MainInterface extends AppCompatActivity { LinearLayout llContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_interface_layout); llContent =(LinearLayout) findViewById(R.id.llContent); ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); CustomView customView = new CustomView(MainInterface.this); customView.setLayoutParams(layoutParams); llContent.addView(customView); } }
2e850bd12001b8cc01193936108a06edd50798c3
[ "Java" ]
1
Java
Doko-Demo-Doa/ImageEffect
42b34918131e7ccec259146a7831079b5d03bd36
ac3e3a46f6ea17d3b7e9a09fa70492b7c14f2cea
refs/heads/master
<repo_name>yuttasakcom/go-sample<file_sep>/16.Built-in.Handlers/README.md # Built-in Handlers ## http.NotFoundHandler ``` func NotFoundHandler () Handler ``` ## http.StripPrefix ``` func StripPrefix(prefix string, h handler) Handler ``` ## http.fileServer ``` func FileServer(root FileSystem) Handle type FileSystem interface { Open(name stirng) (File, error) } type dir string func (d Dir Open(name string)) (File, error) ``` <file_sep>/04.for.go package main import "fmt" func main() { var n [5]int n[1] = 1 n[3] = 3 for i := 0; i < len(n); i++ { fmt.Println(n[i]) } fmt.Println("--------------") for _, v := range n { fmt.Println(v) } } <file_sep>/utils/hello.go package utils // Hello sample package func Hello() string { return "Hello!" } <file_sep>/utils/reverse_test.go package utils import "testing" func TestReverse(t *testing.T) { msg := Reverse("Hello World!") if msg != "!dlroW olleH" { t.Error("อยากได้ !dlroW olleH แต่ได้ ", msg) } } <file_sep>/07.slice.go package main import "fmt" func main() { a := make([]int, 5) a[1] = 1 a[3] = 3 fmt.Println(a) a = append(a, 5) fmt.Println(a) fmt.Println("-------------") b := []int{1, 2, 3, 4, 5} fmt.Println(b[1:]) // ตั้งแต่ index = 1 , เป็นต้นไป fmt.Println(b[:3]) // ตั้งแต่ index = 0 , ถึง index = 3 แต่ไม่เอา index = 3 fmt.Println(b[1:3]) // ตั้งแต่ index = 1 , ถึง index = 3 แต่ไม่เอา index = 3 fmt.Println(b[:]) // ทั้งหมด } <file_sep>/08.map.go package main import "fmt" func main() { a := make(map[string]string) a["name"] = "Gopher" a["age"] = "35" fmt.Println(a) x, ok := a["x"] // ok = false, x = fmt.Println(ok) fmt.Println(x) for k, v := range a { fmt.Println(k, ":", v) } fmt.Println("-----------") b := map[string]string{ "name": "Gopher", "age": "35", } fmt.Println(b) for k, v := range b { fmt.Println(k, ":", v) } } <file_sep>/01.package.go package main import ( "fmt" "github.com/yuttasakcom/go-sample/utils" ) func main() { fmt.Println(utils.Hello()) fmt.Println("Sum 1 + 2 = ", utils.Add(1, 2)) } <file_sep>/05.if-else.go package main import ( "fmt" ) func main() { fmt.Println("Input score: ") var score int fmt.Scan(&score) if score > 50 { fmt.Println("score มีค่ามากกว่า 50") } else { fmt.Println("score มีค่าน้อยกว่า หรือเท่ากับ 50") } } <file_sep>/06.switch.go package main import ( "fmt" ) func main() { fmt.Println("Input score: ") var score int fmt.Scanln(&score) switch { case score > 50: fmt.Println("score มีค่ามากกว่า 50") default: fmt.Println("score มีค่าน้อยกว่า หรือเท่ากับ 50") } } <file_sep>/utils/add_test.go package utils import "testing" func TestAddTwoNumber(t *testing.T) { res := Add(1, 2) if res != 3 { t.Error("คาดหวังว่าจะได้ 3 ผลลัพธ์คือ ", res) } } <file_sep>/02.variables.go package main import ( "fmt" "reflect" "strconv" "unicode/utf8" ) var Pi = 3.14 func main() { var name string name = "Gopher" fmt.Print(name) fmt.Printf(" type is %T\n", name) var age = 35 fmt.Print(age) fmt.Printf(" type is %T\n", age) fmt.Printf("Convert %d to string = %q\n", age, strconv.Itoa(age)) grade := 3.47 fmt.Print(grade) fmt.Printf(" type is %T\n", grade) // Convert sum := float64(age) * Pi fmt.Println("sum: ", sum) fmt.Println("type of sum =", reflect.TypeOf(sum)) greeting := "สวัสดี" fmt.Println("Len: ", len(greeting)) fmt.Println("RuneCount: ", utf8.RuneCountInString(greeting)) // ## Output // Gopher type is string // 35 type is int // Convert 35 to string = "35" // 3.47 type is float64 // sum: 109.9 // type of sum = float64 // Len: 18 // RuneCount: 6 } <file_sep>/utils/hello_test.go package utils import "testing" func TestHello(t *testing.T) { msg := Hello() if msg != "Hello!" { t.Error("คาดหวังว่าจะแสดง Hello! ผลลัพธ์คือ ", msg) } } <file_sep>/10.struct.go package main import "fmt" type person struct { Name string NickName string } func (p person) greet() { fmt.Println("Hello!") } func mutatePerson(p person) { p.Name = "Hacker" fmt.Println(p) } func mutatePersonPointer(p *person) { p.Name = "Cracker" } func main() { p := person{ Name: "Facker", NickName: "Gopher", } fmt.Println(p) fmt.Println("---------") mutatePerson(p) fmt.Println("----------") mutatePersonPointer(&p) fmt.Println(p) fmt.Println("---------") p.greet() }
3ff805a4e2ab46bfbecf8a911a105f9f31796990
[ "Markdown", "Go" ]
13
Markdown
yuttasakcom/go-sample
37d69d7fd2840e9c3309f5705019b3a481506675
4cf98fcbcf2be490d628afbeab66fb58a8424ed1
refs/heads/main
<repo_name>Elynemelo/Projeto-Spring-Boot-Academia<file_sep>/academiaSpringBoot/src/main/java/com/accenture/academiaSpringBoot/model/Professor.java package com.accenture.academiaSpringBoot.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.GroupSequence; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import org.hibernate.validator.constraints.Length; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString @Entity @Table @GroupSequence({Professor.class}) public class Professor { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @NotBlank(message = "O campo NOME é obrigatório, por favor, informe um nome!") @Length(min = 3, max = 35, message = "O nome deverá ter no máximo {35} caracteres") private String nome; @NotBlank(message = "O CPF é obrigatório!") @Max(11) private String cpf; @Min(18) private int idade; @NotBlank(message = "O campo SALÁRIO é obrigatório, por favor, informe o salário!") private double salario; } <file_sep>/academiaSpringBoot/src/main/java/com/accenture/academiaSpringBoot/repository/CursoRepository.java package com.accenture.academiaSpringBoot.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.accenture.academiaSpringBoot.model.Curso; public interface CursoRepository extends JpaRepository<Curso, Integer>{ }<file_sep>/academiaSpringBoot/src/main/java/com/accenture/academiaSpringBoot/controller/ProfessorController.java package com.accenture.academiaSpringBoot.controller; //import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.accenture.academiaSpringBoot.model.Professor; import com.accenture.academiaSpringBoot.repository.ProfessorRepository; @RestController @RequestMapping("/users") public class ProfessorController { // private List<Professor> professores = new ArrayList<Professor>(); @Autowired private ProfessorRepository professorRepository; @PostMapping("/createProfessor") public Professor criarProfessor(@Valid @RequestBody Professor professor) { return this.professorRepository.save(professor); //alunos.add(aluno); //return "ALUNO inserido na lista com sucesso"; } @GetMapping("/listProfessores") public List<Professor> listProfessores() { return this.professorRepository.findAll(); //return professores; } @GetMapping("/procuraProfessor/{id}") public Optional<Professor> procuraProfessor(@PathVariable("id") int id) { Optional<Professor> professorFinder = this.professorRepository.findById(id); if (professorFinder.isPresent()) { return professorFinder; }else { return Optional.empty(); } //Professor procurado = null; //for(Professor professor: professores) { // if (professor.getId() == id) { // procurado = professor; // } //} //return procurado; } @PutMapping("/updateProfessor/{id}") public String updateProfessor(@PathVariable("id")int id, @RequestBody Professor newProfessor) { Optional<Professor> oldProfessor = this.professorRepository.findById(id); if (oldProfessor.isPresent()) { Professor professor = oldProfessor.get(); professor.setNome(newProfessor.getNome()); professor.setCpf(newProfessor.getCpf()); professor.setIdade(newProfessor.getIdade()); professor.setSalario(newProfessor.getSalario()); professorRepository.save(professor); return "Dados do Professor alterado com sucesso!"; }else { return "Professor não existe no banco de dados!"; } //* // public List<Aluno> updateAluno(@PathVariable("id")int id, @RequestBody Aluno aluno) { // for(Aluno a: alunos) { // if (a.getId() == id) { // int i = alunos.indexOf(a); // alunos.set(i,aluno); // } // } // return alunos; } @DeleteMapping("/deleteProfessor/{id}") public String delete(@PathVariable("id") int id) { Optional<Professor> professorFinder = this.professorRepository.findById(id); if (professorFinder.isPresent()) { professorRepository.delete(professorFinder.get()); return "Professor excluído com sucesso!"; }else { return "Professor não existe no banco de dados!"; } } //Professor a = null; //boolean encontrou = false; //for (Professor professor : professores) { // if (professor.getId() == id) { // encontrou = true; // a = professor; // } // } // if (encontrou == true) { // professores.remove(a); //} //} }<file_sep>/academiaSpringBoot/src/main/java/com/accenture/academiaSpringBoot/repository/ProfessorRepository.java package com.accenture.academiaSpringBoot.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.accenture.academiaSpringBoot.model.Professor; public interface ProfessorRepository extends JpaRepository<Professor, Integer>{ } <file_sep>/academiaSpringBoot/src/main/java/com/accenture/academiaSpringBoot/controller/CursoController.java package com.accenture.academiaSpringBoot.controller; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.accenture.academiaSpringBoot.model.Curso; import com.accenture.academiaSpringBoot.repository.CursoRepository; @RestController @RequestMapping("/cursos") public class CursoController { @Autowired private CursoRepository cursoRepository; @PostMapping("/create") public Curso criarCurso(@Valid @RequestBody Curso curso) { return this.cursoRepository.save(curso); } @GetMapping("/list") public List<Curso> listCursos() { return this.cursoRepository.findAll(); } @GetMapping("/procura/{id}") public Optional<Curso> procuraCurso(@PathVariable("id") int id) { Optional<Curso> cursoFinder = this.cursoRepository.findById(id); if (cursoFinder.isPresent()) { return cursoFinder; }else { return Optional.empty(); } } @PutMapping("/update/{id}") public String updateCurso(@PathVariable("id")int id, @RequestBody Curso newCurso) { Optional<Curso> oldCurso = this.cursoRepository.findById(id); if (oldCurso.isPresent()) { Curso curso = oldCurso.get(); curso.setCod(newCurso.getCod()); curso.setNome(newCurso.getNome()); cursoRepository.save(curso); return "Dados do Curso alterado com sucesso!"; }else { return "Curso não existe no banco de dados!"; } } @DeleteMapping("/delete/{id}") public String delete(@PathVariable("id") int id) { Optional<Curso> cursoFinder = this.cursoRepository.findById(id); if (cursoFinder.isPresent()) { cursoRepository.delete(cursoFinder.get()); return "Curso excluído com sucesso!"; }else { return "Curso não existe no banco de dados!"; } } }
eddca34360988d6c3832d51232227742c608f4a6
[ "Java" ]
5
Java
Elynemelo/Projeto-Spring-Boot-Academia
67f8454e4f9125270930dceeb0dbc78385e85975
649b92e140d023b2802e7d95002587c606ecd94e
refs/heads/master
<file_sep>[Exercise 14.21](ex_21/) Consider the query ${\textbf{P}}({Rain}{{\,|\,}}{Sprinkler}{{\,=\,}}{true},{WetGrass}{{\,=\,}}{true})$ in Figure [rain-clustering-figure](#/)(a) (page [rain-clustering-figure](#/)) and how Gibbs sampling can answer it. 1. How many states does the Markov chain have? 2. Calculate the **transition matrix** ${\textbf{Q}}$ containing $q({\textbf{y}}$ $\rightarrow$ ${\textbf{y}}')$ for all ${\textbf{y}}$, ${\textbf{y}}'$. 3. What does ${\textbf{ Q}}^2$, the square of the transition matrix, represent? 4. What about ${\textbf{Q}}^n$ as $n\to \infty$? 5. Explain how to do probabilistic inference in Bayesian networks, assuming that ${\textbf{Q}}^n$ is available. Is this a practical way to do inference? <file_sep>[Exercise 13.14](ex_14/) We wish to transmit an $n$-bit message to a receiving agent. The bits in the message are independently corrupted (flipped) during transmission with $\epsilon$ probability each. With an extra parity bit sent along with the original information, a message can be corrected by the receiver if at most one bit in the entire message (including the parity bit) has been corrupted. Suppose we want to ensure that the correct message is received with probability at least $1-\delta$. What is the maximum feasible value of $n$? Calculate this value for the case $\epsilon{{\,=\,}}0.002$, $\delta{{\,=\,}}0.01$. <file_sep>[Exercise 17.23](ex_23/) A Dutch auction is similar in an English auction, but rather than starting the bidding at a low price and increasing, in a Dutch auction the seller starts at a high price and gradually lowers the price until some buyer is willing to accept that price. (If multiple bidders accept the price, one is arbitrarily chosen as the winner.) More formally, the seller begins with a price $p$ and gradually lowers $p$ by increments of $d$ until at least one buyer accepts the price. Assuming all bidders act rationally, is it true that for arbitrarily small $d$, a Dutch auction will always result in the bidder with the highest value for the item obtaining the item? If so, show mathematically why. If not, explain how it may be possible for the bidder with highest value for the item not to obtain it. <file_sep>[Exercise 25.8 \[confspace-exercise\]](ex_8/) This exercise explores the relationship between workspace and configuration space using the examples shown in Figure [FigEx2](#FigEx2). 1. Consider the robot configurations shown in Figure [FigEx2](#FigEx2)(a) through (c), ignoring the obstacle shown in each of the diagrams. Draw the corresponding arm configurations in configuration space. (*Hint:* Each arm configuration maps to a single point in configuration space, as illustrated in Figure [FigArm1](#FigEx2)(b).) 2. Draw the configuration space for each of the workspace diagrams in Figure [FigEx2](#FigEx2)(a)–(c). (*Hint:* The configuration spaces share with the one shown in Figure [FigEx2](#FigEx2)(a) the region that corresponds to self-collision, but differences arise from the lack of enclosing obstacles and the different locations of the obstacles in these individual figures.) 3. For each of the black dots in Figure [FigEx2](#/)(e)–(f), draw the corresponding configurations of the robot arm in workspace. Please ignore the shaded regions in this exercise. 4. The configuration spaces shown in Figure [FigEx2](#FigEx2)(e)–(f) have all been generated by a single workspace obstacle (dark shading), plus the constraints arising from the self-collision constraint (light shading). Draw, for each diagram, the workspace obstacle that corresponds to the darkly shaded area. 5. Figure [FigEx2](#FigEx2)(d) illustrates that a single planar obstacle can decompose the workspace into two disconnected regions. What is the maximum number of disconnected regions that can be created by inserting a planar obstacle into an obstacle-free, connected workspace, for a 2DOF robot? Give an example, and argue why no larger number of disconnected regions can be created. How about a non-planar obstacle? <center> <b id="FigEx2">Figure [FigEx2]</b> Diagrams for Exercise [confspace-exercise](#/). </center> $\quad\quad\quad\quad\quad\quad$ | $\quad\quad\quad\quad\quad\quad$ | $\quad\quad\quad\quad\quad\quad$ :-------------------------:|:-------------------------:|:-------------------------: ![exerciseRobot1](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/exerciseRobot1.svg) | ![exerciseRobot3](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/exerciseRobot3.svg) | ![exerciseRobot6](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/exerciseRobot6.svg) (a) | (b) | (c) ![exerciseConf2](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/exerciseConf2.svg) | ![exerciseConf4](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/exerciseConf4.svg) | ![exerciseConf5](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/exerciseConf5.svg) (d) | (e) | (f) <file_sep>[Exercise 18.9](ex_9/) Construct a data set (set of examples with attributes and classifications) that would cause the decision-tree learning algorithm to find a non-minimal-sized tree. Show the tree constructed by the algorithm and the minimal-sized tree that you can generate by hand. <file_sep>[Exercise 13.6 \[inclusion-exclusion-exercise\]](ex_6/) Prove Equation ([kolmogorov-disjunction-equation](#/)) from Equations ([basic-probability-axiom-equation](#/)) and ([proposition-probability-equation](#/)). <file_sep>[Exercise 25.4](ex_4/) Suppose that you are working with the robot in Exercise [AB-manipulator-ex](#/) and you are given the problem of finding a path from the starting configuration of figure [figRobot2](#figRobot2) to the ending configuration. Consider a potential function $$D(A, {Goal})^2 + D(B, {Goal})^2 + \frac{1}{D(A, B)^2}$$ where $D(A,B)$ is the distance between the closest points of A and B. 1. Show that hill climbing in this potential field will get stuck in a local minimum. 2. Describe a potential field where hill climbing will solve this particular problem. You need not work out the exact numerical coefficients needed, just the general form of the solution. (Hint: Add a term that “rewards" the hill climber for moving A out of B’s way, even in a case like this where this does not reduce the distance from A to B in the above sense.) <file_sep>[Exercise 14.3 \[cpt-equivalence-exercise\]](ex_3/) Equation ([parameter-joint-repn-equation](#/)) on page [parameter-joint-repn-equation](#/) defines the joint distribution represented by a Bayesian network in terms of the parameters $\theta(X_i{{\,|\,}}{Parents}(X_i))$. This exercise asks you to derive the equivalence between the parameters and the conditional probabilities ${\textbf{ P}}(X_i{{\,|\,}}{Parents}(X_i))$ from this definition. 1. Consider a simple network $X\rightarrow Y\rightarrow Z$ with three Boolean variables. Use Equations ([conditional-probability-equation](#/)) and ([marginalization-equation](#/)) (pages [conditional-probability-equation](#/) and [marginalization-equation](#/)) to express the conditional probability $P(z{{\,|\,}}y)$ as the ratio of two sums, each over entries in the joint distribution ${\textbf{P}}(X,Y,Z)$. 2. Now use Equation ([parameter-joint-repn-equation](#/)) to write this expression in terms of the network parameters $\theta(X)$, $\theta(Y{{\,|\,}}X)$, and $\theta(Z{{\,|\,}}Y)$. 3. Next, expand out the summations in your expression from part (b), writing out explicitly the terms for the true and false values of each summed variable. Assuming that all network parameters satisfy the constraint $\sum_{x_i} \theta(x_i{{\,|\,}}{parents}(X_i)){{\,=\,}}1$, show that the resulting expression reduces to $\theta(z{{\,|\,}}y)$. 4. Generalize this derivation to show that $\theta(X_i{{\,|\,}}{Parents}(X_i)) = {\textbf{P}}(X_i{{\,|\,}}{Parents}(X_i))$ for any Bayesian network. <file_sep>[Exercise 14.11 \[LG-exercise\]](ex_11/) Consider the family of linear Gaussian networks, as defined on page [LG-network-page](#/). 1. In a two-variable network, let $X_1$ be the parent of $X_2$, let $X_1$ have a Gaussian prior, and let ${\textbf{P}}(X_2{{\,|\,}}X_1)$ be a linear Gaussian distribution. Show that the joint distribution $P(X_1,X_2)$ is a multivariate Gaussian, and calculate its covariance matrix. 2. Prove by induction that the joint distribution for a general linear Gaussian network on $X_1,\ldots,X_n$ is also a multivariate Gaussian. <file_sep>[Exercise 10.1](ex_1/) Consider a robot whose operation is described by the following PDDL operators: $$ Op({Go(x,y)},{At(Robot,x)},{\lnot At(Robot,x) \land At(Robot,y)}) $$ $$ Op({Pick(o)},{At(Robot,x)\land At(o,x)},{\lnot At(o,x) \land Holding(o)}) $$ $$ Op({Drop(o)},{At(Robot,x)\land Holding(o)},{At(o,x) \land \lnot Holding(o)} $$ 1. The operators allow the robot to hold more than one object. Show how to modify them with an $EmptyHand$ predicate for a robot that can hold only one object. 2. Assuming that these are the only actions in the world, write a successor-state axiom for $EmptyHand$. <file_sep>[Exercise 13.25](ex_25/) Let $X$, $Y$, $Z$ be Boolean random variables. Label the eight entries in the joint distribution ${\textbf{P}}(X,Y,Z)$ as $a$ through $h$. Express the statement that $X$ and $Y$ are conditionally independent given $Z$, as a set of equations relating $a$ through $h$. How many *nonredundant* equations are there? <file_sep>[Exercise 17.24](ex_24/) Imagine an auction mechanism that is just like an ascending-bid auction, except that at the end, the winning bidder, the one who bid $b_{max}$, pays only $b_{max}/2$ rather than $b_{max}$. Assuming all agents are rational, what is the expected revenue to the auctioneer for this mechanism, compared with a standard ascending-bid auction? <file_sep>[Exercise 18.3](ex_3/) Draw a decision tree for the problem of deciding whether to move forward at a road intersection, given that the light has just turned green. <file_sep>[Exercise 15.6](ex_6/) Consider the vacuum worlds of Figure [vacuum-maze-ch4-figure](#/) (perfect sensing) and Figure [vacuum-maze-hmm2-figure](#/) (noisy sensing). Suppose that the robot receives an observation sequence such that, with perfect sensing, there is exactly one possible location it could be in. Is this location necessarily the most probable location under noisy sensing for sufficiently small noise probability $\epsilon$? Prove your claim or find a counterexample. <file_sep> Describe and implement a *real-time*, *multiplayer* game-playing environment, where time is part of the environment state and players are given fixed time allocations. <file_sep>[Exercise 16.20](ex_20/) Consider a student who has the choice to buy or not buy a textbook for a course. We’ll model this as a decision problem with one Boolean decision node, $B$, indicating whether the agent chooses to buy the book, and two Boolean chance nodes, $M$, indicating whether the student has mastered the material in the book, and $P$, indicating whether the student passes the course. Of course, there is also a utility node, $U$. A certain student, Sam, has an additive utility function: 0 for not buying the book and -\$100 for buying it; and \$2000 for passing the course and 0 for not passing. Sam’s conditional probability estimates are as follows: $$\begin{array}{ll} P(p|b,m) = 0.9 & P(m|b) = 0.9 \\ P(p|b, \lnot m) = 0.5 & P(m|\lnot b) = 0.7 \\ P(p|\lnot b, m) = 0.8 & \\ P(p|\lnot b, \lnot m) = 0.3 & \\ \end{array}$$ You might think that $P$ would be independent of $B$ given $M$, But this course has an open-book final—so having the book helps. 1. Draw the decision network for this problem. 2. Compute the expected utility of buying the book and of not buying it. 3. What should Sam do? <file_sep>[Exercise 16.8](ex_8/) Prove that the judgments $B \succ A$ and $C \succ D$ in the Allais paradox (page [allais-page](#/)) violate the axiom of substitutability. <file_sep> A sentence is in disjunctive normal form(DNF) if it is the disjunction of conjunctions of literals. For example, the sentence $(A \land B \land \lnot C) \lor (\lnot A \land C) \lor (B \land \lnot C)$ is in DNF.<br> 1. Any propositional logic sentence is logically equivalent to the assertion that some possible world in which it would be true is in fact the case. From this observation, prove that any sentence can be written in DNF.<br> 2. Construct an algorithm that converts any sentence in propositional logic into DNF. (*Hint*: The algorithm is similar to the algorithm for conversion to CNF iven in Sectio <a href="#">pl-resolution-section</a>.)<br> 3. Construct a simple algorithm that takes as input a sentence in DNF and returns a satisfying assignment if one exists, or reports that no satisfying assignment exists.<br> 4. Apply the algorithms in (b) and (c) to the following set of sentences:<br> $A {\Rightarrow} B$<bR> $B {\Rightarrow} C$<br> $C {\Rightarrow} A$<br> 5. Since the algorithm in (b) is very similar to the algorithm for conversion to CNF, and since the algorithm in (c) is much simpler than any algorithm for solving a set of sentences in CNF, why is this technique not used in automated reasoning? <file_sep>[Exercise 15.12 \[switching-kf-exercise\]](ex_12/) Often, we wish to monitor a continuous-state system whose behavior switches unpredictably among a set of $k$ distinct “modes.” For example, an aircraft trying to evade a missile can execute a series of distinct maneuvers that the missile may attempt to track. A Bayesian network representation of such a **switching Kalman filter** model is shown in Figure [switching-kf-figure](#switching-kf-figure). 1. Suppose that the discrete state $S_t$ has $k$ possible values and that the prior continuous state estimate $${\textbf{P}}(\textbf{X}_0)$$ is a multivariate Gaussian distribution. Show that the prediction $${\textbf{P}}(\textbf{X}_1)$$ is a **mixture of Gaussians**—that is, a weighted sum of Gaussians such that the weights sum to 1. 2. Show that if the current continuous state estimate $${\textbf{P}}(\textbf{X}_t|\textbf{e}_{1:t})$$ is a mixture of $m$ Gaussians, then in the general case the updated state estimate $${\textbf{P}}(\textbf{X}_{t+1}|\textbf{e}_{1:t+1})$$ will be a mixture of $km$ Gaussians. 3. What aspect of the temporal process do the weights in the Gaussian mixture represent? The results in (a) and (b) show that the representation of the posterior grows without limit even for switching Kalman filters, which are among the simplest hybrid dynamic models. <file_sep>--- layout: exercise title: Exercise 1.1 permalink: /intro-exercises/ex_1/ breadcrumb: 1-Introduction --- {% include mathjax_support %} <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1</a> <button type="button" class="btn btn-dark float-right" title="Solve this Exercise" onclick="solve('ex1.1');" href="#"><i id="ex1.1" class="fas fa-pen" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" title="Edit this Question" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.1');" href="#"><i id="ex1.1" class="far fa-edit" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative question.md %}</p> </div> </div> <br> <file_sep>--- layout: exercise title: Exercise 1.9 permalink: /intro-exercises/ex_9/ chapterLabel: 1-Introduction breadcrumb: Introduction --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="intro-exercises" data-exercise="ex_9" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 21.5](ex_5/) Write out the parameter update equations for TD learning with $$\hat{U}(x,y) = \theta_0 + \theta_1 x + \theta_2 y + \theta_3\,\sqrt{(x-x_g)^2 + (y-y_g)^2}\ .$$ <file_sep>[Exercise 18.15](ex_15/) Suppose that a learning algorithm is trying to find a consistent hypothesis when the classifications of examples are actually random. There are $n$ Boolean attributes, and examples are drawn uniformly from the set of $2^n$ possible examples. Calculate the number of examples required before the probability of finding a contradiction in the data reaches 0.5. <file_sep>[Exercise 10.6](ex_6/) A finite Turing machine has a finite one-dimensional tape of cells, each cell containing one of a finite number of symbols. One cell has a read and write head above it. There is a finite set of states the machine can be in, one of which is the accept state. At each time step, depending on the symbol on the cell under the head and the machine’s current state, there are a set of actions we can choose from. Each action involves writing a symbol to the cell under the head, transitioning the machine to a state, and optionally moving the head left or right. The mapping that determines which actions are allowed is the Turing machine’s program. Your goal is to control the machine into the accept state. Represent the Turing machine acceptance problem as a planning problem. If you can do this, it demonstrates that determining whether a planning problem has a solution is at least as hard as the Turing acceptance problem, which is PSPACE-hard. <file_sep>[Exercise 14.5](ex_5/) Consider the Bayesian network in Figure [burglary-figure](#/). 1. If no evidence is observed, are ${Burglary}$ and ${Earthquake}$ independent? Prove this from the numerical semantics and from the topological semantics. 2. If we observe ${Alarm}{{\,=\,}}{true}$, are ${Burglary}$ and ${Earthquake}$ independent? Justify your answer by calculating whether the probabilities involved satisfy the definition of conditional independence. <file_sep>[Exercise 21.1](ex_1/) Implement a passive learning agent in a simple environment, such as the $4\times 3$ world. For the case of an initially unknown environment model, compare the learning performance of the direct utility estimation, TD, and ADP algorithms. Do the comparison for the optimal policy and for several random policies. For which do the utility estimates converge faster? What happens when the size of the environment is increased? (Try environments with and without obstacles.) <file_sep>[Exercise 13.16](ex_16/) Consider two medical tests, A and B, for a virus. Test A is 95% effective at recognizing the virus when it is present, but has a 10% false positive rate (indicating that the virus is present, when it is not). Test B is 90% effective at recognizing the virus, but has a 5% false positive rate. The two tests use independent methods of identifying the virus. The virus is carried by 1% of all people. Say that a person is tested for the virus using only one of the tests, and that test comes back positive for carrying the virus. Which test returning positive is more indicative of someone really carrying the virus? Justify your answer mathematically. <file_sep>[Exercise 15.10](ex_10/) This exercise is concerned with filtering in an environment with no landmarks. Consider a vacuum robot in an empty room, represented by an $n \times m$ rectangular grid. The robot’s location is hidden; the only evidence available to the observer is a noisy location sensor that gives an approximation to the robot’s location. If the robot is at location $(x, y)$ then with probability .1 the sensor gives the correct location, with probability .05 each it reports one of the 8 locations immediately surrounding $(x, y)$, with probability .025 each it reports one of the 16 locations that surround those 8, and with the remaining probability of .1 it reports “no reading.” The robot’s policy is to pick a direction and follow it with probability .8 on each step; the robot switches to a randomly selected new heading with probability .2 (or with probability 1 if it encounters a wall). Implement this as an HMM and do filtering to track the robot. How accurately can we track the robot’s path? <file_sep>[Exercise 18.14](ex_14/) Suppose you are running a learning experiment on a new algorithm for Boolean classification. You have a data set consisting of 100 positive and 100 negative examples. You plan to use leave-one-out cross-validation and compare your algorithm to a baseline function, a simple majority classifier. (A majority classifier is given a set of training data and then always outputs the class that is in the majority in the training set, regardless of the input.) You expect the majority classifier to score about 50% on leave-one-out cross-validation, but to your surprise, it scores zero every time. Can you explain why? <file_sep>[Exercise 21.9](ex_9/) Extend the standard game-playing environment (Chapter [game-playing-chapter](#/)) to incorporate a reward signal. Put two reinforcement learning agents into the environment (they may, of course, share the agent program) and have them play against each other. Apply the generalized TD update rule (Equation ([generalized-td-equation](#/))) to update the evaluation function. You might wish to start with a simple linear weighted evaluation function and a simple game, such as tic-tac-toe. <file_sep>[Exercise 16.22 \[car-vpi-exercise\]](ex_22/) (Adapted from Pearl [@Pearl:1988].) A used-car buyer can decide to carry out various tests with various costs (e.g., kick the tires, take the car to a qualified mechanic) and then, depending on the outcome of the tests, decide which car to buy. We will assume that the buyer is deciding whether to buy car $c_1$, that there is time to carry out at most one test, and that $t_1$ is the test of $c_1$ and costs \$50. A car can be in good shape (quality $$q^+$$) or bad shape (quality $q^-$), and the tests might help indicate what shape the car is in. Car $c_1$ costs \$1,500, and its market value is $$\$2,000$$ if it is in good shape; if not, $$\$700$$ in repairs will be needed to make it in good shape. The buyer’s estimate is that $c_1$ has a 70% chance of being in good shape. 1. Draw the decision network that represents this problem. 2. Calculate the expected net gain from buying $c_1$, given no test. 3. Tests can be described by the probability that the car will pass or fail the test given that the car is in good or bad shape. We have the following information: $$P({pass}(c_1,t_1) | q^+(c_1)) = {0.8}$$ $$P({pass}(c_1,t_1) | q^-(c_1)) = {0.35}$$ Use Bayes’ theorem to calculate the probability that the car will pass (or fail) its test and hence the probability that it is in good (or bad) shape given each possible test outcome. 4. Calculate the optimal decisions given either a pass or a fail, and their expected utilities. 5. Calculate the value of information of the test, and derive an optimal conditional plan for the buyer. <file_sep>[Exercise 12.12](ex_12/) Write a set of sentences that allows one to calculate the price of an individual tomato (or other object), given the price per pound. Extend the theory to allow the price of a bag of tomatoes to be calculated. <file_sep>[Exercise 16.12](ex_12/) How much is a micromort worth to you? Devise a protocol to determine this. Ask questions based both on paying to avoid risk and being paid to accept risk. <file_sep>[Exercise 18.27](ex_27/) Consider the following set of examples, each with six inputs and one target output: | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | | $\textbf{x}_1$ | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | $\textbf{x}_2$ | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | | $\textbf{x}_3$ | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 1 | 1 | | $\textbf{x}_4$ | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | | $\textbf{x}_5$ | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | | $\textbf{x}_6$ | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | | $\textbf{T}$ | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1. Run the perceptron learning rule on these data and show the final weights. 2. Run the decision tree learning rule, and show the resulting decision tree. 3. Comment on your results. <file_sep>[Exercise 12.26](ex_26/) Recall that inheritance information in semantic networks can be captured logically by suitable implication sentences. This exercise investigates the efficiency of using such sentences for inheritance. 1. Consider the information in a used-car catalog such as Kelly’s Blue Book—for example, that 1973 Dodge vans are (or perhaps were once) worth 575. Suppose all this information (for 11,000 models) is encoded as logical sentences, as suggested in the chapter. Write down three such sentences, including that for 1973 Dodge vans. How would you use the sentences to find the value of a *particular* car, given a backward-chaining theorem prover such as Prolog? 2. Compare the time efficiency of the backward-chaining method for solving this problem with the inheritance method used in semantic nets. 3. Explain how forward chaining allows a logic-based system to solve the same problem efficiently, assuming that the KB contains only the 11,000 sentences about prices. 4. Describe a situation in which neither forward nor backward chaining on the sentences will allow the price query for an individual car to be handled efficiently. 5. Can you suggest a solution enabling this type of query to be solved efficiently in all cases in logic systems? (*Hint:* Remember that two cars of the same year and model have the same price.) <file_sep>[Exercise 16.23 \[nonnegative-VPI-exercise\]](ex_23/) Recall the definition of *value of information* in Section [VPI-section](#/). 1. Prove that the value of information is nonnegative and order independent. 2. Explain why it is that some people would prefer not to get some information—for example, not wanting to know the sex of their baby when an ultrasound is done. 3. A function $f$ on sets is **submodular** if, for any element $x$ and any sets $A$ and $B$ such that $A\subseteq B$, adding $x$ to $A$ gives a greater increase in $f$ than adding $x$ to $B$: $$A\subseteq B \Rightarrow (f(A \cup \{x\}) - f(A)) \geq (f(B\cup \{x\}) - f(B))\ .$$ Submodularity captures the intuitive notion of *diminishing returns*. Is the value of information, viewed as a function $f$ on sets of possible observations, submodular? Prove this or find a counterexample. <file_sep>[Exercise 14.16](ex_16/) Consider the Bayes net shown in Figure [politics-figure](#politics-figure). 1. Which of the following are asserted by the network *structure*? 1. ${\textbf{P}}(B,I,M) = {\textbf{P}}(B){\textbf{P}}(I){\textbf{P}}(M)$. 2. ${\textbf{P}}(J{{\,|\,}}G) = {\textbf{P}}(J{{\,|\,}}G,I)$. 3. ${\textbf{P}}(M{{\,|\,}}G,B,I) = {\textbf{P}}(M{{\,|\,}}G,B,I,J)$. 2. Calculate the value of $P(b,i,\lnot m,g,j)$. 3. Calculate the probability that someone goes to jail given that they broke the law, have been indicted, and face a politically motivated prosecutor. 4. A **context-specific independence** (see page [CSI-page](#/)) allows a variable to be independent of some of its parents given certain values of others. In addition to the usual conditional independences given by the graph structure, what context-specific independences exist in the Bayes net in Figure [politics-figure](#politics-figure)? 5. Suppose we want to add the variable $P{{\,=\,}}{PresidentialPardon}$ to the network; draw the new network and briefly explain any links you add. <file_sep>[Exercise 23.16](ex_16/) Consider the following sentence (from *The New York Times,* July 28, 2008): > Banks struggling to recover from multibillion-dollar loans on real > estate are curtailing loans to American businesses, depriving even > healthy companies of money for expansion and hiring. 1. Which of the words in this sentence are lexically ambiguous? 2. Find two cases of syntactic ambiguity in this sentence (there are more than two.) 3. Give an instance of metaphor in this sentence. 4. Can you find semantic ambiguity? <file_sep>[Exercise 17.5](ex_5/) Can any finite search problem be translated exactly into a Markov decision problem such that an optimal solution of the latter is also an optimal solution of the former? If so, explain *precisely* how to translate the problem and how to translate the solution back; if not, explain *precisely* why not (i.e., give a counterexample). <file_sep>[Exercise 18.4](ex_4/) We never test the same attribute twice along one path in a decision tree. Why not? <file_sep>[Exercise 11.11 \[alt-vacuum-exercise\]](ex_11/) Conditional effects were illustrated for the ${Suck}$ action in the vacuum world—which square becomes clean depends on which square the robot is in. Can you think of a new set of propositional variables to define states of the vacuum world, such that ${Suck}$ has an *unconditional* description? Write out the descriptions of ${Suck}$, ${Left}$, and ${Right}$, using your propositions, and demonstrate that they suffice to describe all possible states of the world. <file_sep>[Exercise 18.31](ex_31/) Suppose that a training set contains only a single example, repeated 100 times. In 80 of the 100 cases, the single output value is 1; in the other 20, it is 0. What will a back-propagation network predict for this example, assuming that it has been trained and reaches a global optimum? (*Hint:* to find the global optimum, differentiate the error function and set it to zero.) <file_sep>[Exercise 12.27 \[natural-stupidity-exercise\]](ex_27/) One might suppose that the syntactic distinction between unboxed links and singly boxed links in semantic networks is unnecessary, because singly boxed links are always attached to categories; an inheritance algorithm could simply assume that an unboxed link attached to a category is intended to apply to all members of that category. Show that this argument is fallacious, giving examples of errors that would arise. <file_sep>[Exercise 12.5](ex_5/) State the following in the language you developed for the previous exercise: 1. In situation $S_0$, window $W_1$ is behind $W_2$ but sticks out on the left and right. Do *not* state exact coordinates for these; describe the *general* situation. 2. If a window is displayed, then its top edge is higher than its bottom edge. 3. After you create a window $w$, it is displayed. 4. A window can be minimized if it is displayed. <file_sep>[Exercise 13.23 \[normalization-exercise\]](ex_23/) In this exercise, you will complete the normalization calculation for the meningitis example. First, make up a suitable value for $P(s{{\,|\,}}\lnot m)$, and use it to calculate unnormalized values for $P(m{{\,|\,}}s)$ and $P(\lnot m {{\,|\,}}s)$ (i.e., ignoring the $P(s)$ term in the Bayes’ rule expression, Equation ([meningitis-bayes-equation](#/))). Now normalize these values so that they add to 1. <file_sep>[Exercise 16.17 \[airport-au-id-exercise\]](ex_17/) Repeat Exercise [airport-id-exercise](#/), using the action-utility representation shown in Figure [airport-au-id-figure](#/). <file_sep>[Exercise 17.25](ex_25/) Teams in the National Hockey League historically received 2 points for winning a game and 0 for losing. If the game is tied, an overtime period is played; if nobody wins in overtime, the game is a tie and each team gets 1 point. But league officials felt that teams were playing too conservatively in overtime (to avoid a loss), and it would be more exciting if overtime produced a winner. So in 1999 the officials experimented in mechanism design: the rules were changed, giving a team that loses in overtime 1 point, not 0. It is still 2 points for a win and 1 for a tie. 1. Was hockey a zero-sum game before the rule change? After? 2. Suppose that at a certain time $t$ in a game, the home team has probability $p$ of winning in regulation time, probability $0.78-p$ of losing, and probability 0.22 of going into overtime, where they have probability $q$ of winning, $.9-q$ of losing, and .1 of tying. Give equations for the expected value for the home and visiting teams. 3. Imagine that it were legal and ethical for the two teams to enter into a pact where they agree that they will skate to a tie in regulation time, and then both try in earnest to win in overtime. Under what conditions, in terms of $p$ and $q$, would it be rational for both teams to agree to this pact? 4. @Longley+Sankaran:2005 report that since the rule change, the percentage of games with a winner in overtime went up 18.2%, as desired, but the percentage of overtime games also went up 3.6%. What does that suggest about possible collusion or conservative play after the rule change? <file_sep>--- layout: chapter title: Introduction permalink: /intro-exercises/ chapterLabel: 1-Introduction breadcrumb: Introduction --- {% include mathjax_support %} # 1. Introduction These exercises are intended to stimulate discussion, and some might be set as term projects. Alternatively, preliminary attempts can be made now, and these attempts can be reviewed after the completion of the book. <br> <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.1');" href="#"><i id="ex1.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.1');" href="#"><i id="ex1.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.2');" href="#"><i id="ex1.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.2');" href="#"><i id="ex1.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.3');" href="#"><i id="ex1.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.3');" href="#"><i id="ex1.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.1');" href="#"><i id="ex1.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.4');" href="#"><i id="ex1.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.5');" href="#"><i id="ex1.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.5');" href="#"><i id="ex1.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.6');" href="#"><i id="ex1.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.6');" href="#"><i id="ex1.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.7');" href="#"><i id="ex1.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.7');" href="#"><i id="ex1.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.8');" href="#"><i id="ex1.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.8');" href="#"><i id="ex1.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.1');" href="#"><i id="ex1.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.9');" href="#"><i id="ex1.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.10');" href="#"><i id="ex1.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.10');" href="#"><i id="ex1.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.11');" href="#"><i id="ex1.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.11');" href="#"><i id="ex1.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.12');" href="#"><i id="ex1.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.12');" href="#"><i id="ex1.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.13');" href="#"><i id="ex1.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.13');" href="#"><i id="ex1.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.14');" href="#"><i id="ex1.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.14');" href="#"><i id="ex1.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.1');" href="#"><i id="ex1.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.15');" href="#"><i id="ex1.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_16/' class="p-2">Exercise 16</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.16');" href="#"><i id="ex1.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.16');" href="#"><i id="ex1.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_17/' class="p-2">Exercise 17</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.17');" href="#"><i id="ex1.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.17');" href="#"><i id="ex1.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_18/' class="p-2">Exercise 18</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.18');" href="#"><i id="ex1.18" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.18');" href="#"><i id="ex1.18" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_18/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_19/' class="p-2">Exercise 19</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.19');" href="#"><i id="ex1.19" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.19');" href="#"><i id="ex1.19" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_19/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_20/' class="p-2">Exercise 20</a> <button type="button" class="btn btn-dark float-right" title="Bookmark Exercise" onclick="bookmark('ex1.20');" href="#"><i id="ex1.20" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex1.20');" href="#"><i id="ex1.20" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_20/question.md %}</p> </div> </div> <br> <!-- {% include disqus.html %} --> <file_sep>[Exercise 17.3](ex_3/) Select a specific member of the set of policies that are optimal for $R(s)>0$ as shown in Figure [sequential-decision-policies-figure](#/)(b), and calculate the fraction of time the agent spends in each state, in the limit, if the policy is executed forever. (*Hint*: Construct the state-to-state transition probability matrix corresponding to the policy and see Exercise [markov-convergence-exercise](#/).) <file_sep>[Exercise 14.10](ex_10/) Consider a simple Bayesian network with root variables ${Cold}$, ${Flu}$, and ${Malaria}$ and child variable ${Fever}$, with a noisy-OR conditional distribution for ${Fever}$ as described in Section [canonical-distribution-section](#/). By adding appropriate auxiliary variables for inhibition events and fever-inducing events, construct an equivalent Bayesian network whose CPTs (except for root variables) are deterministic. Define the CPTs and prove equivalence. <file_sep>[Exercise 19.4](ex_4/) Would a probabilistic version of determinations be useful? Suggest a definition. <file_sep>[Exercise 7.28 \[minesweeper-exercise\]](ex_28/) Minesweeper, the well-known computer game, is closely related to the wumpus world. A minesweeper world is a rectangular grid of $N$ squares with $M$ invisible mines scattered among them. Any square may be probed by the agent; instant death follows if a mine is probed. Minesweeper indicates the presence of mines by revealing, in each probed square, the *number* of mines that are directly or diagonally adjacent. The goal is to probe every unmined square. 1. Let $X_{i,j}$ be true iff square $[i,j]$ contains a mine. Write down the assertion that exactly two mines are adjacent to \[1,1\] as a sentence involving some logical combination of $X_{i,j}$ propositions. 2. Generalize your assertion from (a) by explaining how to construct a CNF sentence asserting that $k$ of $n$ neighbors contain mines. 3. Explain precisely how an agent can use {DPLL} to prove that a given square does (or does not) contain a mine, ignoring the global constraint that there are exactly $M$ mines in all. 4. Suppose that the global constraint is constructed from your method from part (b). How does the number of clauses depend on $M$ and $N$? Suggest a way to modify {DPLL} so that the global constraint does not need to be represented explicitly. 5. Are any conclusions derived by the method in part (c) invalidated when the global constraint is taken into account? 6. Give examples of configurations of probe values that induce *long-range dependencies* such that the contents of a given unprobed square would give information about the contents of a far-distant square. (*Hint*: consider an $N\times 1$ board.) <file_sep>[Exercise 15.20 \[dbn-elimination-exercise\]](ex_20/) Consider applying the variable elimination algorithm to the umbrella DBN unrolled for three slices, where the query is ${\textbf{P}}(R_3|u_1,u_2,u_3)$. Show that the space complexity of the algorithm—the size of the largest factor—is the same, regardless of whether the rain variables are eliminated in forward or backward order. <file_sep> A basic wooden railway set contains the pieces shown in . The task is to connect these pieces into a railway that has no overlapping tracks and no loose ends where a train could run off onto the floor.<br> 1. Suppose that the pieces fit together *exactly* with no slack. Give a precise formulation of the task as a search problem.<br> 2. Identify a suitable uninformed search algorithm for this task and explain your choice.<br> 3. Explain why removing any one of the “fork” pieces makes the problem unsolvable. <br> 4. Give an upper bound on the total size of the state space defined by your formulation. (*Hint*: think about the maximum branching factor for the construction process and the maximum depth, ignoring the problem of overlapping pieces and loose ends. Begin by pretending that every piece is unique.) <file_sep>[Exercise 14.8 \[markov-blanket-exercise\]](ex_8/) The **Markov blanket** of a variable is defined on page [markov-blanket-page](#/). Prove that a variable is independent of all other variables in the network, given its Markov blanket and derive Equation ([markov-blanket-equation](#/)) (page [markov-blanket-equation](#/)). <center> <b id="car-starts-figure">Figure [car-starts-figure]</b> A Bayesian network describing some features of a car's electrical system and engine. Each variable is Boolean, and the *true* value indicates that the corresponding aspect of the vehicle is in working order. </center> ![car-starts-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/car-starts.svg) <file_sep>[Exercise 13.7](ex_7/) Consider the set of all possible five-card poker hands dealt fairly from a standard deck of fifty-two cards. 1. How many atomic events are there in the joint probability distribution (i.e., how many five-card hands are there)? 2. What is the probability of each atomic event? 3. What is the probability of being dealt a royal straight flush? Four of a kind? <file_sep>[Exercise 12.30 \[buying-exercise\]](ex_30/) Our description of Internet shopping omitted the all-important step of actually *buying* the product. Provide a formal logical description of buying, using event calculus. That is, define the sequence of events that occurs when a buyer submits a credit-card purchase and then eventually gets billed and receives the product. <file_sep>[Exercise 13.19](ex_19/) After your yearly checkup, the doctor has bad news and good news. The bad news is that you tested positive for a serious disease and that the test is 99% accurate (i.e., the probability of testing positive when you do have the disease is 0.99, as is the probability of testing negative when you don’t have the disease). The good news is that this is a rare disease, striking only 1 in 100,000 people of your age. Why is it good news that the disease is rare? What are the chances that you actually have the disease? <file_sep>[Exercise 17.1 \[mdp-model-exercise\]](ex_1/) For the $4\times 3$ world shown in Figure [sequential-decision-world-figure](#/), calculate which squares can be reached from (1,1) by the action sequence $[{Up},{Up},{Right},{Right},{Right}]$ and with what probabilities. Explain how this computation is related to the prediction task (see Section [general-filtering-section](#/)) for a hidden Markov model. <file_sep>--- layout: chapter title: Main permalink: /philosophy-exercises/ --- {% include mathjax_support %} # 26. Philosophical Foundations <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.1');" href="#"><i id="ex26.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.1');" href="#"><i id="ex26.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.2');" href="#"><i id="ex26.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.2');" href="#"><i id="ex26.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.3');" href="#"><i id="ex26.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.3');" href="#"><i id="ex26.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.4');" href="#"><i id="ex26.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.4');" href="#"><i id="ex26.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 (brain-prosthesis-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.5');" href="#"><i id="ex26.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.5');" href="#"><i id="ex26.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.6');" href="#"><i id="ex26.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.6');" href="#"><i id="ex26.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.7');" href="#"><i id="ex26.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.7');" href="#"><i id="ex26.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.8');" href="#"><i id="ex26.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.8');" href="#"><i id="ex26.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.9');" href="#"><i id="ex26.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.9');" href="#"><i id="ex26.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 10</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.10');" href="#"><i id="ex26.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.10');" href="#"><i id="ex26.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.11');" href="#"><i id="ex26.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.11');" href="#"><i id="ex26.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex26.12');" href="#"><i id="ex26.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex26.12');" href="#"><i id="ex26.1 2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <file_sep>[Exercise 24.3](ex_3/) Consider an infinitely long cylinder of radius $r$ oriented with its axis along the $y$-axis. The cylinder has a Lambertian surface and is viewed by a camera along the positive $z$-axis. What will you expect to see in the image if the cylinder is illuminated by a point source at infinity located on the positive $x$-axis? Draw the contours of constant brightness in the projected image. Are the contours of equal brightness uniformly spaced? <file_sep>[Exercise 14.2](ex_2/) We have a bag of three biased coins $a$, $b$, and $c$ with probabilities of coming up heads of 30%, 60%, and 75%, respectively. One coin is drawn randomly from the bag (with equal likelihood of drawing each of the three coins), and then the coin is flipped three times to generate the outcomes $X_1$, $X_2$, and $X_3$. 1. Draw the Bayesian network corresponding to this setup and define the necessary CPTs. 2. Calculate which coin was most likely to have been drawn from the bag if the observed flips come out heads twice and tails once. <file_sep>--- layout: exercise title: Exercise 22.9 permalink: /nlp-communicating-exercises/ex_9/ breadcrumb: 22-Natural-Language-Processing --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="nlp-communicating-exercises" data-exercise="ex_9" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 14.12 \[multivalued-probit-exercise\]](ex_12/) The probit distribution defined on page [probit-page](#/) describes the probability distribution for a Boolean child, given a single continuous parent. 1. How might the definition be extended to cover multiple continuous parents? 2. How might it be extended to handle a *multivalued* child variable? Consider both cases where the child’s values are ordered (as in selecting a gear while driving, depending on speed, slope, desired acceleration, etc.) and cases where they are unordered (as in selecting bus, train, or car to get to work). (*Hint*: Consider ways to divide the possible values into two sets, to mimic a Boolean variable.) <file_sep>[Exercise 20.6 \[linear-regression-exercise\]](ex_6/) Consider $N$ data points $(x_j,y_j)$, where the $y_j$s are generated from the $x_j$s according to the linear Gaussian model in Equation ([linear-gaussian-likelihood-equation](#/)). Find the values of $\theta_1$, $\theta_2$, and $\sigma$ that maximize the conditional log likelihood of the data. <file_sep>[Exercise 14.23 \[MH-exercise\]](ex_23/) The **Metropolis--Hastings** algorithm is a member of the MCMC family; as such, it is designed to generate samples $\textbf{x}$ (eventually) according to target probabilities $\pi(\textbf{x})$. (Typically we are interested in sampling from $\pi(\textbf{x}){{\,=\,}}P(\textbf{x}{{\,|\,}}\textbf{e})$.) Like simulated annealing, Metropolis–Hastings operates in two stages. First, it samples a new state $\textbf{x'}$ from a **proposal distribution** $q(\textbf{x'}{{\,|\,}}\textbf{x})$, given the current state $\textbf{x}$. Then, it probabilistically accepts or rejects $\textbf{x'}$ according to the **acceptance probability** $$\alpha(\textbf{x'}{{\,|\,}}\textbf{x}) = \min\ \left(1,\frac{\pi(\textbf{x'})q(\textbf{x}{{\,|\,}}\textbf{x'})}{\pi(\textbf{x})q(\textbf{x'}{{\,|\,}}\textbf{x})} \right)\ .$$ If the proposal is rejected, the state remains at $\textbf{x}$. 1. Consider an ordinary Gibbs sampling step for a specific variable $X_i$. Show that this step, considered as a proposal, is guaranteed to be accepted by Metropolis–Hastings. (Hence, Gibbs sampling is a special case of Metropolis–Hastings.) 2. Show that the two-step process above, viewed as a transition probability distribution, is in detailed balance with $\pi$. <file_sep>[Exercise 19.6 \[prolog-ir-exercise\]](ex_6/) Suppose one writes a logic program that carries out a resolution inference step. That is, let ${Resolve}(c_1,c_2,c)$ succeed if $c$ is the result of resolving $c_1$ and $c_2$. Normally, ${Resolve}$ would be used as part of a theorem prover by calling it with $c_1$ and $c_2$ instantiated to particular clauses, thereby generating the resolvent $c$. Now suppose instead that we call it with $c$ instantiated and $c_1$ and $c_2$ uninstantiated. Will this succeed in generating the appropriate results of an inverse resolution step? Would you need any special modifications to the logic programming system for this to work? <file_sep>--- layout: exercise title: Exercise 12.2 permalink: /kr-exercises/ex_2/ breadcrumb: 12-Knowledge-Representation --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="kr-exercises" data-exercise="ex_2" data-rating="0"></i></div> {% include_relative question.md %} <file_sep> One might suppose that we can avoid the problem of variable conflict in unification during backward chaining by standardizing apart all of the sentences in the knowledge base once and for all. Show that, for some sentences, this approach cannot work. (*Hint*: Consider a sentence in which one part unifies with another.) <file_sep>[Exercise 20.9 \[ML-parents-exercise\]](ex_9/) Consider an arbitrary Bayesian network, a complete data set for that network, and the likelihood for the data set according to the network. Give a simple proof that the likelihood of the data cannot decrease if we add a new link to the network and recompute the maximum-likelihood parameter values. <file_sep> Prove that satisfies the graph separation property illustrated in . (*Hint*: Begin by showing that the property holds at the start, then show that if it holds before an iteration of the algorithm, it holds afterwards.) Describe a search algorithm that violates the property. <file_sep>[Exercise 15.16 \[sleep1-exercise\]](ex_16/) A professor wants to know if students are getting enough sleep. Each day, the professor observes whether the students sleep in class, and whether they have red eyes. The professor has the following domain theory: - The prior probability of getting enough sleep, with no observations, is 0.6. - The probability of getting enough sleep on night $t$ is 0.8 given that the student got enough sleep the previous night, and 0.2 if not. - The probability of having red eyes is 0.2 if the student got enough sleep, and 0.7 if not. - The probability of sleeping in class is 0.1 if the student got enough sleep, and 0.3 if not. Formulate this information as a dynamic Bayesian network that the professor could use to filter or predict from a sequence of observations. Then reformulate it as a hidden Markov model that has only a single observation variable. Give the complete probability tables for the model. <file_sep>[Exercise 16.13 \[kmax-exercise\]](ex_13/) Let continuous variables $X_1,\ldots,X_k$ be independently distributed according to the same probability density function $f(x)$. Prove that the density function for $\max\{X_1,\ldots,X_k\}$ is given by $kf(x)(F(x))^{k-1}$, where $F$ is the cumulative distribution for $f$. <file_sep>[Exercise 18.12 \[missing-value-DTL-exercise\]](ex_12/) The standard DECISION-TREE-LEARNING algorithm described in the chapter does not handle cases in which some examples have missing attribute values. 1. First, we need to find a way to classify such examples, given a decision tree that includes tests on the attributes for which values can be missing. Suppose that an example $\textbf{x}$ has a missing value for attribute $A$ and that the decision tree tests for $A$ at a node that $\textbf{x}$ reaches. One way to handle this case is to pretend that the example has *all* possible values for the attribute, but to weight each value according to its frequency among all of the examples that reach that node in the decision tree. The classification algorithm should follow all branches at any node for which a value is missing and should multiply the weights along each path. Write a modified classification algorithm for decision trees that has this behavior. 2. Now modify the information-gain calculation so that in any given collection of examples $C$ at a given node in the tree during the construction process, the examples with missing values for any of the remaining attributes are given “as-if” values according to the frequencies of those values in the set $C$. <file_sep> This exercise looks at the recursive application of rewrite rules, using logic programming. A rewrite rule (or **demodulator** in terminology) is an equation with a specified direction. For example, the rewrite rule $x+0 \rightarrow x$ suggests replacing any expression that matches $x+0$ with the expression $x$. Rewrite rules are a key component of equational reasoning systems. Use the predicate rewrite(X,Y) to represent rewrite rules. For example, the earlier rewrite rule is written as rewrite(X+0,X). Some terms are *primitive* and cannot be further simplified; thus, we write primitive(0) to say that 0 is a primitive term.<br> 1. Write a definition of a predicate simplify(X,Y), that is true when Y is a simplified version of X—that is, when no further rewrite rules apply to any subexpression of Y.<br> 2. Write a collection of rules for the simplification of expressions involving arithmetic operators, and apply your simplification algorithm to some sample expressions.<br> 3. Write a collection of rewrite rules for symbolic differentiation, and use them along with your simplification rules to differentiate and simplify expressions involving arithmetic expressions, including exponentiation.<br> <file_sep> How long does it take to prove ${KB}{\models}\alpha$ using {DPLL} when $\alpha$ is a literal *already contained in* ${KB}$? Explain. <file_sep>[Exercise 21.7 \[approx-LMS-exercise\]](ex_7/) Implement an exploring reinforcement learning agent that uses direct utility estimation. Make two versions—one with a tabular representation and one using the function approximator in Equation ([4x3-linear-approx-equation](#/)). Compare their performance in three environments: 1. The $4\times 3$ world described in the chapter. 2. A ${10}\times {10}$ world with no obstacles and a +1 reward at (10,10). 3. A ${10}\times {10}$ world with no obstacles and a +1 reward at (5,5). <file_sep> Discuss what is meant by *optimal* behavior in the wumpus world. Show that the {Hybrid-Wumpus-Agent} is not optimal, and suggest ways to improve it. <file_sep>[Exercise 23.5](ex_5/) Outline the major differences between Java (or any other computer language with which you are familiar) and English, commenting on the “understanding” problem in each case. Think about such things as grammar, syntax, semantics, pragmatics, compositionality, context-dependence, lexical ambiguity, syntactic ambiguity, reference finding (including pronouns), background knowledge, and what it means to “understand” in the first place. <file_sep>[Exercise 12.11 \[alt-measure-exercise\]](ex_11/) An alternative scheme for representing measures involves applying the units function to an abstract length object. In such a scheme, one would write ${Inches}({Length}(L_1)) = {1.5}$. How does this scheme compare with the one in the chapter? Issues include conversion axioms, names for abstract quantities (such as “50 dollars”), and comparisons of abstract measures in different units (50 inches is more than 50 centimeters). <file_sep>[Exercise 13.21 \[pv-xyz-exercise\]](ex_21/) Show that the statement of conditional independence $${\textbf{P}}(X,Y {{\,|\,}}Z) = {\textbf{P}}(X{{\,|\,}}Z) {\textbf{P}}(Y{{\,|\,}}Z)$$ is equivalent to each of the statements $${\textbf{P}}(X{{\,|\,}}Y,Z) = {\textbf{P}}(X{{\,|\,}}Z) \quad\mbox{and}\quad {\textbf{P}}(Y{{\,|\,}}X,Z) = {\textbf{P}}(Y{{\,|\,}}Z)\ .$$ <file_sep>[Exercise 18.18 \[DL-expressivity-exercise\]](ex_18/) This exercise concerns the expressiveness of decision lists (Section [learning-theory-section](#/)). 1. Show that decision lists can represent any Boolean function, if the size of the tests is not limited. 2. Show that if the tests can contain at most $k$ literals each, then decision lists can represent any function that can be represented by a decision tree of depth $k$. <file_sep>[Exercise 23.7](ex_7/) Consider the sentence “Someone walked slowly to the supermarket” and a lexicon consisting of the following words: $Pronoun \rightarrow \textbf{someone} \quad Verb \rightarrow \textbf{walked}$ $Adv \rightarrow \textbf{slowly} \quad Prep \rightarrow \textbf{to}$ $Article \rightarrow \textbf{the} \quad Noun \rightarrow \textbf{supermarket}$ Which of the following three grammars, combined with the lexicon, generates the given sentence? Show the corresponding parse tree(s). | $\quad\quad\quad\quad (A):\quad\quad\quad\quad$ | $\quad\quad\quad\quad(B):\quad\quad\quad\quad$ | $\quad\quad\quad\quad(C):\quad\quad\quad\quad$ | | --- | --- | --- | | $S\rightarrow NP\space VP$ | $S\rightarrow NP\space VP$ | $S\rightarrow NP\space VP$ | | $NP\rightarrow Pronoun$ | $NP\rightarrow Pronoun$ | $NP\rightarrow Pronoun$ | | $NP\rightarrow Article\space Noun $ | $NP\rightarrow Noun$ | $NP\rightarrow Article\space NP$ | | $VP\rightarrow VP\space PP$ | $NP\rightarrow Article\space NP$ | $VP\rightarrow Verb\space Adv$ | | $VP\rightarrow VP\space Adv\space Adv$ | $VP\rightarrow Verb\space Vmod$ | $Adv\rightarrow Adv\space Adv$ | | $VP\rightarrow Verb$ | $Vmod\rightarrow Adv\space Vmod$ | $Adv\rightarrow PP$ | | $PP\rightarrow Prep\space NP$ | $Vmod\rightarrow Adv$ | $PP\rightarrow Prep\space NP$ | | $NP\rightarrow Noun$ | $Adv\rightarrow PP$ | $NP\rightarrow Noun$ | | $\quad$ | $PP\rightarrow Prep\space NP$ | $\quad$ | For each of the preceding three grammars, write down three sentences of English and three sentences of non-English generated by the grammar. Each sentence should be significantly different, should be at least six words long, and should include some new lexical entries (which you should define). Suggest ways to improve each grammar to avoid generating the non-English sentences. <file_sep>[Exercise 12.7](ex_7/) (Adapted from an example by <NAME>.) Your mission is to capture, in logical form, enough knowledge to answer a series of questions about the following simple scenario: > Yesterday John went to the North Berkeley Safeway supermarket and > bought two pounds of tomatoes and a pound of ground beef. Start by trying to represent the content of the sentence as a series of assertions. You should write sentences that have straightforward logical structure (e.g., statements that objects have certain properties, that objects are related in certain ways, that all objects satisfying one property satisfy another). The following might help you get started: - Which classes, objects, and relations would you need? What are their parents, siblings and so on? (You will need events and temporal ordering, among other things.) - Where would they fit in a more general hierarchy? - What are the constraints and interrelationships among them? - How detailed must you be about each of the various concepts? To answer the questions below, your knowledge base must include background knowledge. You’ll have to deal with what kind of things are at a supermarket, what is involved with purchasing the things one selects, what the purchases will be used for, and so on. Try to make your representation as general as possible. To give a trivial example: don’t say “People buy food from Safeway,” because that won’t help you with those who shop at another supermarket. Also, don’t turn the questions into answers; for example, question (c) asks “Did John buy any meat?”—not “Did John buy a pound of ground beef?” Sketch the chains of reasoning that would answer the questions. If possible, use a logical reasoning system to demonstrate the sufficiency of your knowledge base. Many of the things you write might be only approximately correct in reality, but don’t worry too much; the idea is to extract the common sense that lets you answer these questions at all. A truly complete answer to this question is *extremely* difficult, probably beyond the state of the art of current knowledge representation. But you should be able to put together a consistent set of axioms for the limited questions posed here. 1. Is John a child or an adult? \[Adult\] 2. Does John now have at least two tomatoes? \[Yes\] 3. Did John buy any meat? \[Yes\] 4. If Mary was buying tomatoes at the same time as John, did he see her? \[Yes\] 5. Are the tomatoes made in the supermarket? \[No\] 6. What is John going to do with the tomatoes? \[Eat them\] 7. Does Safeway sell deodorant? \[Yes\] 8. Did John bring some money or a credit card to the supermarket? \[Yes\] 9. Does John have less money after going to the supermarket? \[Yes\] <file_sep>[Exercise 18.23 \[ensemble-error-exercise\]](ex_23/) Consider an ensemble learning algorithm that uses simple majority voting among $K$ learned hypotheses. Suppose that each hypothesis has error $\epsilon$ and that the errors made by each hypothesis are independent of the others’. Calculate a formula for the error of the ensemble algorithm in terms of $K$ and $\epsilon$, and evaluate it for the cases where $K=5$, 10, and 20 and $\epsilon={0.1}$, 0.2, and 0.4. If the independence assumption is removed, is it possible for the ensemble error to be *worse* than $\epsilon$? <file_sep>[Exercise 19.5 \[ir-step-exercise\]](ex_5/) Fill in the missing values for the clauses $C_1$ or $C_2$ (or both) in the following sets of clauses, given that $C$ is the resolvent of $C_1$ and $C_2$: 1. $C = {True} \Rightarrow P(A,B)$, $C_1 = P(x,y) \Rightarrow Q(x,y)$, $C_2 = ??$. 2. $C = {True} \Rightarrow P(A,B)$, $C_1 = ??$, $C_2 = ??$. 3. $C = P(x,y) \Rightarrow P(x,f(y))$, $C_1 = ??$, $C_2 = ??$. If there is more than one possible solution, provide one example of each different kind. <file_sep>[Exercise 17.14 \[policy-loss-exercise\]](ex_14/) How can the value determination algorithm be used to calculate the expected loss experienced by an agent using a given set of utility estimates ${U}$ and an estimated model ${P}$, compared with an agent using correct values? <file_sep>[Exercise 18.2](ex_2/) Repeat Exercise [infant-language-exercise](#/) for the case of learning to play tennis (or some other sport with which you are familiar). Is this supervised learning or reinforcement learning? <file_sep>[Exercise 21.4](ex_4/) The direct utility estimation method in Section [passive-rl-section](#/) uses distinguished terminal states to indicate the end of a trial. How could it be modified for environments with discounted rewards and no terminal states? <file_sep>[Exercise 17.7 \[threshold-cost-exercise\]](ex_7/) For the environment shown in Figure [sequential-decision-world-figure](#/), find all the threshold values for $R(s)$ such that the optimal policy changes when the threshold is crossed. You will need a way to calculate the optimal policy and its value for fixed $R(s)$. (*Hint*: Prove that the value of any fixed policy varies linearly with $R(s)$.) <file_sep>[Exercise 12.14](ex_14/) Write event calculus axioms to describe the actions in the wumpus world. <file_sep>[Exercise 13.3](ex_3/) For each of the following statements, either prove it is true or give a counterexample. 1. If $P(a {{\,|\,}}b, c) = P(b {{\,|\,}}a, c)$, then $P(a {{\,|\,}}c) = P(b {{\,|\,}}c)$ 2. If $P(a {{\,|\,}}b, c) = P(a)$, then $P(b {{\,|\,}}c) = P(b)$ 3. If $P(a {{\,|\,}}b) = P(a)$, then $P(a {{\,|\,}}b, c) = P(a {{\,|\,}}c)$ <file_sep> On page <a href="#">iterative-lengthening-page</a>, we mentioned **iterative lengthening search**, an iterative analog of uniform cost search. The idea is to use increasing limits on path cost. If a node is generated whose path cost exceeds the current limit, it is immediately discarded. For each new iteration, the limit is set to the lowest path cost of any node discarded in the previous iteration.<br> 1. Show that this algorithm is optimal for general path costs.<br> 2. Consider a uniform tree with branching factor $b$, solution depth $d$, and unit step costs. How many iterations will iterative lengthening require?<br> 3. Now consider step costs drawn from the continuous range $[\epsilon,1]$, where $0 < \epsilon < 1$. How many iterations are required in the worst case? <br> 4. Implement the algorithm and apply it to instances of the 8-puzzle and traveling salesperson problems. Compare the algorithm’s performance to that of uniform-cost search, and comment on your results. <br> <file_sep>[Exercise 14.22 \[gibbs-proof-exercise\]](ex_22/) This exercise explores the stationary distribution for Gibbs sampling methods. 1. The convex composition $[\alpha, q_1; 1-\alpha, q_2]$ of $q_1$ and $q_2$ is a transition probability distribution that first chooses one of $q_1$ and $q_2$ with probabilities $\alpha$ and $1-\alpha$, respectively, and then applies whichever is chosen. Prove that if $q_1$ and $q_2$ are in detailed balance with $\pi$, then their convex composition is also in detailed balance with $\pi$. (*Note*: this result justifies a variant of GIBBS-ASK in which variables are chosen at random rather than sampled in a fixed sequence.) 2. Prove that if each of $q_1$ and $q_2$ has $\pi$ as its stationary distribution, then the sequential composition $q {{\,=\,}}q_1 \circ q_2$ also has $\pi$ as its stationary distribution. <file_sep>[Exercise 10.17 \[strips-translation-exercise\]](ex_17/) Consider how to translate a set of action schemas into the successor-state axioms of situation calculus. 1. Consider the schema for ${Fly}(p,{from},{to})$. Write a logical definition for the predicate ${Poss}({Fly}(p,{from},{to}),s)$, which is true if the preconditions for ${Fly}(p,{from},{to})$ are satisfied in situation $s$. 2. Next, assuming that ${Fly}(p,{from},{to})$ is the only action schema available to the agent, write down a successor-state axiom for ${At}(p,x,s)$ that captures the same information as the action schema. 3. Now suppose there is an additional method of travel: ${Teleport}(p,{from},{to})$. It has the additional precondition $\lnot {Warped}(p)$ and the additional effect ${Warped}(p)$. Explain how the situation calculus knowledge base must be modified. 4. Finally, develop a general and precisely specified procedure for carrying out the translation from a set of action schemas to a set of successor-state axioms. <file_sep>[Exercise 13.8](ex_8/) Given the full joint distribution shown in Figure [dentist-joint-table](#/), calculate the following: 1. $\textbf{P}({toothache})$. 2. $\textbf{P}({Cavity})$. 3. $\textbf{P}({Toothache}{{\,|\,}}{cavity})$. 4. $\textbf{P}({Cavity}{{\,|\,}}{toothache}\lor {catch})$. <file_sep>[Exercise 23.15](ex_15/) Augment the $\large \varepsilon_1$ grammar so that it handles article–noun agreement. That is, make sure that “agents” and “an agent” are ${\it NP}$s, but “agent” and “an agents” are not. <file_sep>[Exercise 16.19](ex_19/) Modify and extend the Bayesian network code in the code repository to provide for creation and evaluation of decision networks and the calculation of information value. <file_sep>[Exercise 13.12](ex_12/) Deciding to put our knowledge of probability to good use, we encounter a slot machine with three independently turning reels, each producing one of the four symbols bar, bell, lemon, or cherry with equal probability. The slot machine has the following payout scheme for a bet of 1 coin (where “?” denotes that we don’t care what comes up for that wheel): > bar/bar/bar pays 21 coins > bell/bell/bell pays 16 coins > lemon/lemon/lemon pays 5 coins > cherry/cherry/cherry pays 3 coins > cherry/cherry/? pays 2 coins > cherry/?/? pays 1 coin 1. Compute the expected “payback” percentage of the machine. In other words, for each coin played, what is the expected coin return? 2. Compute the probability that playing the slot machine once will result in a win. 3. Estimate the mean and median number of plays you can expect to make until you go broke, if you start with 8 coins. You can run a simulation to estimate this, rather than trying to compute an exact answer. <file_sep>[Exercise 15.18](ex_18/) Suppose that a particular student shows up with red eyes and sleeps in class every day. Given the model described in Exercise [sleep1-exercise](#/), explain why the probability that the student had enough sleep the previous night converges to a fixed point rather than continuing to go down as we gather more days of evidence. What is the fixed point? Answer this both numerically (by computation) and analytically. <file_sep>[Exercise 12.23](ex_23/) The assumption of *logical omniscience,* discussed on page [logical-omniscience](#/), is of course not true of any actual reasoners. Rather, it is an *idealization* of the reasoning process that may be more or less acceptable depending on the applications. Discuss the reasonableness of the assumption for each of the following applications of reasoning about knowledge: 1. Partial knowledge adversary games, such as card games. Here one player wants to reason about what his opponent knows about the state of the game. 2. Chess with a clock. Here the player may wish to reason about the limits of his opponent’s or his own ability to find the best move in the time available. For instance, if player A has much more time left than player B, then A will sometimes make a move that greatly complicates the situation, in the hopes of gaining an advantage because he has more time to work out the proper strategy. 3. A shopping agent in an environment in which there are costs of gathering information. 4. Reasoning about public key cryptography, which rests on the intractability of certain computational problems. <file_sep>[Exercise 14.20 \[primitive-sampling-exercise\]](ex_20/) Consider the problem of generating a random sample from a specified distribution on a single variable. Assume you have a random number generator that returns a random number uniformly distributed between 0 and 1. 1. Let $X$ be a discrete variable with $P(X{{\,=\,}}x_i){{\,=\,}}p_i$ for $i{{\,\in\\,}}\{1,\ldots,k\}$. The **cumulative distribution** of $X$ gives the probability that $X{{\,\in\\,}}\{x_1,\ldots,x_j\}$ for each possible $j$. (See also Appendix [math-appendix].) Explain how to calculate the cumulative distribution in $O(k)$ time and how to generate a single sample of $X$ from it. Can the latter be done in less than $O(k)$ time? 2. Now suppose we want to generate $N$ samples of $X$, where $N\gg k$. Explain how to do this with an expected run time per sample that is *constant* (i.e., independent of $k$). 3. Now consider a continuous-valued variable with a parameterized distribution (e.g., Gaussian). How can samples be generated from such a distribution? 4. Suppose you want to query a continuous-valued variable and you are using a sampling algorithm such as LIKELIHOODWEIGHTING to do the inference. How would you have to modify the query-answering process? <file_sep>[Exercise 11.2](ex_2/) You have a number of trucks with which to deliver a set of packages. Each package starts at some location on a grid map, and has a destination somewhere else. Each truck is directly controlled by moving forward and turning. Construct a hierarchy of high-level actions for this problem. What knowledge about the solution does your hierarchy encode? <file_sep>[Exercise 14.24 \[soccer-rpm-exercise\]](ex_24/) Three soccer teams $A$, $B$, and $C$, play each other once. Each match is between two teams, and can be won, drawn, or lost. Each team has a fixed, unknown degree of quality—an integer ranging from 0 to 3—and the outcome of a match depends probabilistically on the difference in quality between the two teams. 1. Construct a relational probability model to describe this domain, and suggest numerical values for all the necessary probability distributions. 2. Construct the equivalent Bayesian network for the three matches. 3. Suppose that in the first two matches $A$ beats $B$ and draws with $C$. Using an exact inference algorithm of your choice, compute the posterior distribution for the outcome of the third match. 4. Suppose there are $n$ teams in the league and we have the results for all but the last match. How does the complexity of predicting the last game vary with $n$? 5. Investigate the application of MCMC to this problem. How quickly does it converge in practice and how well does it scale? <file_sep>[Exercise 17.19](ex_19/) In the children’s game of rock–paper–scissors each player reveals at the same time a choice of rock, paper, or scissors. Paper wraps rock, rock blunts scissors, and scissors cut paper. In the extended version rock–paper–scissors–fire–water, fire beats rock, paper, and scissors; rock, paper, and scissors beat water; and water beats fire. Write out the payoff matrix and find a mixed-strategy solution to this game. <file_sep>[Exercise 22.3](ex_3/) *Zipf’s law* of word distribution states the following: Take a large corpus of text, count the frequency of every word in the corpus, and then rank these frequencies in decreasing order. Let $f_{I}$ be the $I$th largest frequency in this list; that is, $f_{1}$ is the frequency of the most common word (usually “the”), $f_{2}$ is the frequency of the second most common word, and so on. Zipf’s law states that $f_{I}$ is approximately equal to $\alpha / I$ for some constant $\alpha$. The law tends to be highly accurate except for very small and very large values of $I$. <file_sep>[Exercise 21.8](ex_8/) Devise suitable features for reinforcement learning in stochastic grid worlds (generalizations of the $4\times 3$ world) that contain multiple obstacles and multiple terminal states with rewards of $+1$ or $-1$. <file_sep>[Exercise 12.17](ex_17/) Investigate ways to extend the event calculus to handle *simultaneous* events. Is it possible to avoid a combinatorial explosion of axioms? <file_sep>[Exercise 12.8](ex_8/) Make the necessary additions or changes to your knowledge base from the previous exercise so that the questions that follow can be answered. Include in your report a discussion of your changes, explaining why they were needed, whether they were minor or major, and what kinds of questions would necessitate further changes. 1. Are there other people in Safeway while John is there? \[Yes—staff!\] 2. Is John a vegetarian? \[No\] 3. Who owns the deodorant in Safeway? \[Safeway Corporation\] 4. Did John have an ounce of ground beef? \[Yes\] 5. Does the Shell station next door have any gas? \[Yes\] 6. Do the tomatoes fit in John’s car trunk? \[Yes\] <file_sep>[Exercise 13.30](ex_30/) Redo the probability calculation for pits in \[1,3\] and \[2,2\], assuming that each square contains a pit with probability 0.01, independent of the other squares. What can you say about the relative performance of a logical versus a probabilistic agent in this case? <file_sep>[Exercise 20.5 \[BNB-exercise\]](ex_5/) Explain how to apply the boosting method of Chapter [concept-learning-chapter](#/) to naive Bayes learning. Test the performance of the resulting algorithm on the restaurant learning problem. <file_sep>[Exercise 10.15](ex_15/) We contrasted forward and backward state-space searchers with partial-order planners, saying that the latter is a plan-space searcher. Explain how forward and backward state-space search can also be considered plan-space searchers, and say what the plan refinement operators are. <file_sep>[Exercise 23.18](ex_18/) Select five sentences and submit them to an online translation service. Translate them from English to another language and back to English. Rate the resulting sentences for grammaticality and preservation of meaning. Repeat the process; does the second round of iteration give worse results or the same results? Does the choice of intermediate language make a difference to the quality of the results? If you know a foreign language, look at the translation of one paragraph into that language. Count and describe the errors made, and conjecture why these errors were made. <file_sep>[Exercise 10.14](ex_14/) Examine the definition of **bidirectional search** in Chapter [search-chapter](#/). 1. Would bidirectional state-space search be a good idea for planning? 2. What about bidirectional search in the space of partial-order plans? 3. Devise a version of partial-order planning in which an action can be added to a plan if its preconditions can be achieved by the effects of actions already in the plan. Explain how to deal with conflicts and ordering constraints. Is the algorithm essentially identical to forward state-space search? <file_sep>[Exercise 12.4 \[windows-exercise\]](ex_4/) Develop a representational system for reasoning about windows in a window-based computer interface. In particular, your representation should be able to describe: - The state of a window: minimized, displayed, or nonexistent. - Which window (if any) is the active window. - The position of every window at a given time. - The order (front to back) of overlapping windows. - The actions of creating, destroying, resizing, and moving windows; changing the state of a window; and bringing a window to the front. Treat these actions as atomic; that is, do not deal with the issue of relating them to mouse actions. Give axioms describing the effects of actions on fluents. You may use either event or situation calculus. Assume an ontology containing *situations,* *actions,* *integers* (for $x$ and $y$ coordinates) and *windows*. Define a language over this ontology; that is, a list of constants, function symbols, and predicates with an English description of each. If you need to add more categories to the ontology (e.g., pixels), you may do so, but be sure to specify these in your write-up. You may (and should) use symbols defined in the text, but be sure to list these explicitly. <file_sep>[Exercise 19.1 \[dbsig-exercise\]](ex_1/) Show, by translating into conjunctive normal form and applying resolution, that the conclusion drawn on page [dbsig-page](#/) concerning Brazilians is sound. <file_sep>[Exercise 16.18](ex_18/) For either of the airport-siting diagrams from Exercises [airport-id-exercise] and [airport-au-id-exercise], to which conditional probability table entry is the utility most sensitive, given the available evidence? <file_sep>[Exercise 14.15](ex_15/) Consider the network shown in Figure [telescope-nets-figure](#telescope-nets-figure)(ii), and assume that the two telescopes work identically. $N{{\,\in\\,}}\{1,2,3\}$ and $M_1,M_2{{\,\in\\,}}\{0,1,2,3,4\}$, with the symbolic CPTs as described in Exercise [telescope-exercise](#/). Using the enumeration algorithm (Figure [enumeration-algorithm](#/) on page [enumeration-algorithm](#/)), calculate the probability distribution ${\textbf{P}}(N{{\,|\,}}M_1{{\,=\,}}2,M_2{{\,=\,}}2)$. <center> <b id="telescope-nets-figure">Figure [telescope-nets-figure]</b> Three possible networks for the telescope problem. </center> ![telescope-nets-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/telescope-nets.svg) <center> <b id="politics-figure">Figure [politics-figure]</b> A simple Bayes net with Boolean variables B = {BrokeElectionLaw}, I = {Indicted}, M = {PoliticallyMotivatedProsecutor}, G= {FoundGuilty}, J = {Jailed}. </center> ![politics-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/politics.svg) <file_sep>--- layout: exercise title: Exercise 5.1 permalink: /game-playing-exercises/ex_1/ breadcrumb: 5-Adversarial-Search --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="game-playing-exercises" data-exercise="ex_1" data-rating="0"></i></div> {% include_relative question.md %} <file_sep> Prove the following assertion: For every game tree, the utility obtained by max using minimax decisions against a suboptimal min will never be lower than the utility obtained playing against an optimal min. Can you come up with a game tree in which max can do still better using a *suboptimal* strategy against a suboptimal min? <figure> <img src="http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/line-game4.svg" alt="line-game4-figure" id="line-game4-figure" style="width:100%"> <figcaption><center><b>The starting position of a simple game.</b></center></figcaption> </figure> Player $A$ moves first. The two players take turns moving, and each player must move his token to an open adjacent space in either direction. If the opponent occupies an adjacent space, then a player may jump over the opponent to the next open space if any. (For example, if $A$ is on 3 and $B$ is on 2, then $A$ may move back to 1.) The game ends when one player reaches the opposite end of the board. If player $A$ reaches space 4 first, then the value of the game to $A$ is $+1$; if player $B$ reaches space 1 first, then the value of the game to $A$ is $-1$. <file_sep>[Exercise 20.8 \[beta-integration-exercise\]](ex_8/) This exercise investigates properties of the Beta distribution defined in Equation ([beta-equation](#/)). 1. By integrating over the range $[0,1]$, show that the normalization constant for the distribution ${{\rm beta}}[a,b]$ is given by $\alpha = \Gamma(a+b)/\Gamma(a)\Gamma(b)$ where $\Gamma(x)$ is the **Gamma function**, defined by $\Gamma(x+1){{\,=\,}}x\cdot\Gamma(x)$ and $\Gamma(1){{\,=\,}}1$. (For integer $x$, $\Gamma(x+1){{\,=\,}}x!$.) 2. Show that the mean is $a/(a+b)$. 3. Find the mode(s) (the most likely value(s) of $\theta$). 4. Describe the distribution ${{\rm beta}}[\epsilon,\epsilon]$ for very small $\epsilon$. What happens as such a distribution is updated? <file_sep>[Exercise 24.8](ex_8/) (Courtesy of <NAME>.) Figure [bottle-figure](#bottle-figure) shows two cameras at X and Y observing a scene. Draw the image seen at each camera, assuming that all named points are in the same horizontal plane. What can be concluded from these two images about the relative distances of points A, B, C, D, and E from the camera baseline, and on what basis? <file_sep>[Exercise 13.4](ex_4/) Would it be rational for an agent to hold the three beliefs $P(A) {{\,=\,}}{0.4}$, $P(B) {{\,=\,}}{0.3}$, and $P(A \lor B) {{\,=\,}}{0.5}$? If so, what range of probabilities would be rational for the agent to hold for $A \land B$? Make up a table like the one in Figure [de-finetti-table](#/), and show how it supports your argument about rationality. Then draw another version of the table where $P(A \lor B) {{\,=\,}}{0.7}$. Explain why it is rational to have this probability, even though the table shows one case that is a loss and three that just break even. (*Hint:* what is Agent 1 committed to about the probability of each of the four cases, especially the case that is a loss?) <file_sep>[Exercise 25.11 \[subsumption-exercise\]](ex_11/) In Figure [Fig5](#/)(b) on page [Fig5](#/), we encountered an augmented finite state machine for the control of a single leg of a hexapod robot. In this exercise, the aim is to design an AFSM that, when combined with six copies of the individual leg controllers, results in efficient, stable locomotion. For this purpose, you have to augment the individual leg controller to pass messages to your new AFSM and to wait until other messages arrive. Argue why your controller is efficient, in that it does not unnecessarily waste energy (e.g., by sliding legs), and in that it propels the robot at reasonably high speeds. Prove that your controller satisfies the dynamic stability condition given on page [polygon-stability-condition-page](#/). <file_sep> Consider the $n$-queens problem using the “efficient” incremental formulation given on page <a href="#">nqueens-page</a>. Explain why the state space has at least $\sqrt[3]{n!}$ states and estimate the largest $n$ for which exhaustive exploration is feasible. (*Hint*: Derive a lower bound on the branching factor by considering the maximum number of squares that a queen can attack in any column.) <file_sep>[Exercise 22.10](ex_10/) Write a regular expression or a short program to extract company names. Test it on a corpus of business news articles. Report your recall and precision. <file_sep>[Exercise 23.11](ex_11/) Consider the following toy grammar: > $S \rightarrow NP\space VP$ > $NP \rightarrow Noun$ > $NP \rightarrow NP\space and\space NP$ > $NP \rightarrow NP\space PP$ > $VP \rightarrow Verb$ > $VP \rightarrow VP\space and \space VP$ > $VP \rightarrow VP\space PP$ > $PP \rightarrow Prep\space NP$ > $Noun \rightarrow Sally\space; pools\space; streams\space; swims$ > $Prep \rightarrow in$ > $Verb \rightarrow pools\space; streams\space; swims$ 1. Show all the parse trees in this grammar for the sentence “Sally swims in streams and pools.” 2. Show all the table entries that would be made by a (non-probabalistic) CYK parser on this sentence. <file_sep>[Exercise 15.2 \[markov-convergence-exercise\]](ex_2/) In this exercise, we examine what happens to the probabilities in the umbrella world in the limit of long time sequences. 1. Suppose we observe an unending sequence of days on which the umbrella appears. Show that, as the days go by, the probability of rain on the current day increases monotonically toward a fixed point. Calculate this fixed point. 2. Now consider *forecasting* further and further into the future, given just the first two umbrella observations. First, compute the probability $P(r_{2+k}|u_1,u_2)$ for $k=1 \ldots 20$ and plot the results. You should see that the probability converges towards a fixed point. Prove that the exact value of this fixed point is 0.5. <file_sep>--- layout: exercise title: Exercise 12.6 permalink: /kr-exercises/ex_6/ breadcrumb: 12-Knowledge-Representation --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="kr-exercises" data-exercise="ex_6" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 17.20](ex_20/) Solve the game of *three*-finger Morra. <file_sep>[Exercise 11.3 \[HLA-unique-exercise\]](ex_3/) Suppose that a high-level action has exactly one implementation as a sequence of primitive actions. Give an algorithm for computing its preconditions and effects, given the complete refinement hierarchy and schemas for the primitive actions. <file_sep>[Exercise 12.9](ex_9/) Represent the following seven sentences using and extending the representations developed in the chapter: 1. Water is a liquid between 0 and 100 degrees. 2. Water boils at 100 degrees. 3. The water in John’s water bottle is frozen. 4. Perrier is a kind of water. 5. John has Perrier in his water bottle. 6. All liquids have a freezing point. 7. A liter of water weighs more than a liter of alcohol. <file_sep>[Exercise 23.4](ex_4/) Consider the following simple PCFG for noun phrases: > 0.6: NP $\rightarrow$ Det\ AdjString\ Noun > 0.4: NP $\rightarrow$ Det\ NounNounCompound > 0.5: AdjString $\rightarrow$ Adj\ AdjString > 0.5: AdjString $\rightarrow$ $\Lambda$ > 1.0: NounNounCompound $\rightarrow$ Noun > 0.8: Det $\rightarrow$ **the** > 0.2: Det $\rightarrow$ **a** > 0.5: Adj $\rightarrow$ **small** > 0.5: Adj $\rightarrow$ **green** > 0.6: Noun $\rightarrow$ **village** > 0.4: Noun $\rightarrow$ **green** where $\Lambda$ denotes the empty string. 1. What is the longest NP that can be generated by this grammar? (i) three words(ii) four words(iii) infinitely many words 2. Which of the following have a nonzero probability of being generated as complete NPs? (i) a small green village(ii) a green green green(iii) a small village green 3. What is the probability of generating “the green green”? 4. What types of ambiguity are exhibited by the phrase in (c)? 5. Given any PCFG and any finite word sequence, is it possible to calculate the probability that the sequence was generated by the PCFG? <file_sep>[Exercise 17.17 \[2state-pomdp-exercise\]](ex_17/) Consider a version of the two-state POMDP on page [2state-pomdp-page](#/) in which the sensor is 90% reliable in state 0 but provides no information in state 1 (that is, it reports 0 or 1 with equal probability). Analyze, either qualitatively or quantitatively, the utility function and the optimal policy for this problem. <file_sep>[Exercise 22.8](ex_8/) Try to ascertain which of the search engines from the previous exercise are using case folding, stemming, synonyms, and spelling correction. <file_sep> In the following, a “max” tree consists only of max nodes, whereas an “expectimax” tree consists of a max node at the root with alternating layers of chance and max nodes. At chance nodes, all outcome probabilities are nonzero. The goal is to *find the value of the root* with a bounded-depth search. For each of (a)–(f), either give an example or explain why this is impossible.<br> 1. Assuming that leaf values are finite but unbounded, is pruning (as in alpha–beta) ever possible in a max tree?<br> 2. Is pruning ever possible in an expectimax tree under the same conditions?<br> 3. If leaf values are all nonnegative, is pruning ever possible in a max tree? Give an example, or explain why not.<br> 4. If leaf values are all nonnegative, is pruning ever possible in an expectimax tree? Give an example, or explain why not.<br> 5. If leaf values are all in the range $[0,1]$, is pruning ever possible in a max tree? Give an example, or explain why not.<br> 6. If leaf values are all in the range $[0,1]$, is pruning ever possible in an expectimax tree?1<br> 7. Consider the outcomes of a chance node in an expectimax tree. Which of the following evaluation orders is most likely to yield pruning opportunities?<br> i. Lowest probability first<br> ii. Highest probability first<br> iii. Doesn’t make any difference<br> <file_sep>[Exercise 14.9](ex_9/) Consider the network for car diagnosis shown in Figure [car-starts-figure](#car-starts-figure). 1. Extend the network with the Boolean variables ${IcyWeather}$ and ${StarterMotor}$. 2. Give reasonable conditional probability tables for all the nodes. 3. How many independent values are contained in the joint probability distribution for eight Boolean nodes, assuming that no conditional independence relations are known to hold among them? 4. How many independent probability values do your network tables contain? 5. The conditional distribution for ${Starts}$ could be described as a **noisy-AND** distribution. Define this family in general and relate it to the noisy-OR distribution. <file_sep>[Exercise 21.3 \[prioritized-sweeping-exercise\]](ex_3/) Starting with the passive ADP agent, modify it to use an approximate ADP algorithm as discussed in the text. Do this in two steps: 1. Implement a priority queue for adjustments to the utility estimates. Whenever a state is adjusted, all of its predecessors also become candidates for adjustment and should be added to the queue. The queue is initialized with the state from which the most recent transition took place. Allow only a fixed number of adjustments. 2. Experiment with various heuristics for ordering the priority queue, examining their effect on learning rates and computation time. <file_sep>[Exercise 10.10](ex_10/) Construct levels 0, 1, and 2 of the planning graph for the problem in Figure [airport-pddl-algorithm](#/). <file_sep>[Exercise 10.16 \[satplan-preconditions-exercise\]](ex_16/) Up to now we have assumed that the plans we create always make sure that an action’s preconditions are satisfied. Let us now investigate what propositional successor-state axioms such as ${HaveArrow}^{t+1} {\;\;{\Leftrightarrow}\;\;}{}$ $({HaveArrow}^t \land \lnot {Shoot}^t)$ have to say about actions whose preconditions are not satisfied. 1. Show that the axioms predict that nothing will happen when an action is executed in a state where its preconditions are not satisfied. 2. Consider a plan $p$ that contains the actions required to achieve a goal but also includes illegal actions. Is it the case that $$ initial state \land successor-state axioms \land p {\models} goal ? $$ 3. With first-order successor-state axioms in situation calculus, is it possible to prove that a plan containing illegal actions will achieve the goal? <file_sep>[Exercise 10.13](ex_13/) The set-level heuristic (see page [set-level-page](#/)) uses a planning graph to estimate the cost of achieving a conjunctive goal from the current state. What relaxed problem is the set-level heuristic the solution to? <file_sep>[Exercise 11.8](ex_8/) Consider the following argument: In a framework that allows uncertain initial states, **nondeterministic effects** are just a notational convenience, not a source of additional representational power. For any action schema $a$ with nondeterministic effect $P \lor Q$, we could always replace it with the conditional effects ${~R{:}~P} \land {~\lnot R{:}~Q}$, which in turn can be reduced to two regular actions. The proposition $R$ stands for a random proposition that is unknown in the initial state and for which there are no sensing actions. Is this argument correct? Consider separately two cases, one in which only one instance of action schema $a$ is in the plan, the other in which more than one instance is. <file_sep>[Exercise 18.10](ex_10/) A decision *graph* is a generalization of a decision tree that allows nodes (i.e., attributes used for splits) to have multiple parents, rather than just a single parent. The resulting graph must still be acyclic. Now, consider the XOR function of *three* binary input attributes, which produces the value 1 if and only if an odd number of the three input attributes has value 1. 1. Draw a minimal-sized decision *tree* for the three-input XOR function. 2. Draw a minimal-sized decision *graph* for the three-input XOR function. <file_sep>[Exercise 25.7 \[voronoi-exercise\]](ex_7/) Implement an algorithm for calculating the Voronoi diagram of an arbitrary 2D environment, described by an $n\times n$ Boolean array. Illustrate your algorithm by plotting the Voronoi diagram for 10 interesting maps. What is the complexity of your algorithm? <file_sep>--- layout: exercise title: Exercise 21.5 permalink: /reinforcement-learning-exercises/ex_5/ breadcrumb: 21-Reinforcement-Learning --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="reinforcement-learning-exercises" data-exercise="ex_5" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 22.11](ex_11/) Consider the problem of trying to evaluate the quality of an IR system that returns a ranked list of answers (like most Web search engines). The appropriate measure of quality depends on the presumed model of what the searcher is trying to achieve, and what strategy she employs. For each of the following models, propose a corresponding numeric measure. 1. The searcher will look at the first twenty answers returned, with the objective of getting as much relevant information as possible. 2. The searcher needs only one relevant document, and will go down the list until she finds the first one. 3. The searcher has a fairly narrow query and is able to examine all the answers retrieved. She wants to be sure that she has seen everything in the document collection that is relevant to her query. (E.g., a lawyer wants to be sure that she has found *all* relevant precedents, and is willing to spend considerable resources on that.) 4. The searcher needs just one document relevant to the query, and can afford to pay a research assistant for an hour’s work looking through the results. The assistant can look through 100 retrieved documents in an hour. The assistant will charge the searcher for the full hour regardless of whether he finds it immediately or at the end of the hour. 5. The searcher will look through all the answers. Examining a document has cost \\$ A; finding a relevant document has value \\$ B; failing to find a relevant document has cost \\$ C for each relevant document not found. 6. The searcher wants to collect as many relevant documents as possible, but needs steady encouragement. She looks through the documents in order. If the documents she has looked at so far are mostly good, she will continue; otherwise, she will stop. <file_sep>[Exercise 23.1 \[washing-clothes-exercise\]](ex_1/) Read the following text once for understanding, and remember as much of it as you can. There will be a test later. > The procedure is actually quite simple. First you arrange things into different groups. Of course, one pile may be sufficient depending on how much there is to do. If you have to go somewhere else due to lack of facilities that is the next step, otherwise you are pretty well set. It is important not to overdo things. That is, it is better to do too few things at once than too many. In the short run this may not seem important but complications can easily arise. A mistake is expensive as well. At first the whole procedure will seem complicated. Soon, however, it will become just another facet of life. It is difficult to foresee any end to the necessity for this task in the immediate future, but then one can never tell. After the procedure is completed one arranges the material into different groups again. Then they can be put into their appropriate places. Eventually they will be used once more and the whole cycle will have to be repeated. However, this is part of life. <file_sep>[Exercise 14.6](ex_6/) Suppose that in a Bayesian network containing an unobserved variable $Y$, all the variables in the Markov blanket ${MB}(Y)$ have been observed. 1. Prove that removing the node $Y$ from the network will not affect the posterior distribution for any other unobserved variable in the network. 2. Discuss whether we can remove $Y$ if we are planning to use (i) rejection sampling and (ii) likelihood weighting. <center> <b id="handedness-figure">Figure [handedness-figure]</b> Three possible structures for a Bayesian network describing genetic inheritance of handedness. </center> ![handedness-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/handedness1.svg) <file_sep>[Exercise 23.20](ex_20/) (Adapted from [@Knight:1999].) Our translation model assumes that, after the phrase translation model selects phrases and the distortion model permutes them, the language model can unscramble the permutation. This exercise investigates how sensible that assumption is. Try to unscramble these proposed lists of phrases into the correct order: 1. have, programming, a, seen, never, I, language, better 2. loves, john, mary 3. is the, communication, exchange of, intentional, information brought, by, about, the production, perception of, and signs, from, drawn, a, of, system, signs, conventional, shared 4. created, that, we hold these, to be, all men, truths, are, equal, self-evident Which ones could you do? What type of knowledge did you draw upon? Train a bigram model from a training corpus, and use it to find the highest-probability permutation of some sentences from a test corpus. Report on the accuracy of this model. <file_sep> In this exercise, use the sentences you wrote in Exercise <a href="#>fol-horses-exercise</a> to answer a question by using a backward-chaining algorithm.<br> 1. Draw the proof tree generated by an exhaustive backward-chaining algorithm for the query ${\exists\,h\;\;}{Horse}(h)$, where clauses are matched in the order given.<br> 2. What do you notice about this domain?<br> 3. How many solutions for $h$ actually follow from your sentences?<br> 4. Can you think of a way to find all of them? (*Hint*: See @Smith+al:1986.)<br> <file_sep>[Exercise 15.14 \[kalman-variance-exercise\]](ex_14/) Let us examine the behavior of the variance update in Equation ([kalman-univariate-equation](#/)) (page [kalman-univariate-equation](#/)). 1. Plot the value of $\sigma_t^2$ as a function of $t$, given various values for $\sigma_x^2$ and $\sigma_z^2$. 2. Show that the update has a fixed point $\sigma^2$ such that $\sigma_t^2 \rightarrow \sigma^2$ as $t \rightarrow \infty$, and calculate the value of $\sigma^2$. 3. Give a qualitative explanation for what happens as $\sigma_x^2\rightarrow 0$ and as $\sigma_z^2\rightarrow 0$. <file_sep>--- layout: exercise title: Exercise 12.29 permalink: /kr-exercises/ex_29/ breadcrumb: 12-Knowledge-Representation --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="kr-exercises" data-exercise="ex_29" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 10.3](ex_3/) \[strips-airport-exercise\]Given the action schemas and initial state from Figure [airport-pddl-algorithm](#/), what are all the applicable concrete instances of ${Fly}(p,{from},{to})$ in the state described by $$ At(P_1,JFK) \land At(P_2,SFO) \land Plane(P_1) \land Plane(P_2) \land Airport(JFK) \land Airport(SFO)? $$ <file_sep>[Exercise 19.2](ex_2/) For each of the following determinations, write down the logical representation and explain why the determination is true (if it is): 1. Design and denomination determine the mass of a coin. 2. For a given program, input determines output. 3. Climate, food intake, exercise, and metabolism determine weight gain and loss. 4. Baldness is determined by the baldness (or lack thereof) of one’s maternal grandfather. <file_sep> Show that the 8-puzzle states are divided into two disjoint sets, such that any state is reachable from any other state in the same set, while no state is reachable from any state in the other set. (*Hint:* See @Berlekamp+al:1982.) Devise a procedure to decide which set a given state is in, and explain why this is useful for generating random states. <file_sep>[Exercise 22.4](ex_4/) Choose a corpus of at least 20,000 words of online text, and verify Zipf’s law experimentally. Define an error measure and find the value of $\alpha$ where Zipf’s law best matches your experimental data. Create a log–log graph plotting $f_{I}$ vs. $I$ and $\alpha/I$ vs. $I$. (On a log–log graph, the function $\alpha/I$ is a straight line.) In carrying out the experiment, be sure to eliminate any formatting tokens (e.g., HTML tags) and normalize upper and lower case. <file_sep>[Exercise 18.22 \[svm-exercise\]](ex_22/) Construct a support vector machine that computes the xor function. Use values of +1 and –1 (instead of 1 and 0) for both inputs and outputs, so that an example looks like $([-1, 1], 1)$ or $([-1, -1], -1)$. Map the input $[x_1,x_2]$ into a space consisting of $x_1$ and $x_1\,x_2$. Draw the four input points in this space, and the maximal margin separator. What is the margin? Now draw the separating line back in the original Euclidean input space. <file_sep>[Exercise 11.12](ex_12/) Find a suitably dirty carpet, free of obstacles, and vacuum it. Draw the path taken by the vacuum cleaner as accurately as you can. Explain it, with reference to the forms of planning discussed in this chapter. <file_sep>[Exercise 20.10](ex_10/) Consider a single Boolean random variable $Y$ (the “classification”). Let the prior probability $P(Y=true)$ be $\pi$. Let’s try to find $\pi$, given a training set $D=(y_1,\ldots,y_N)$ with $N$ independent samples of $Y$. Furthermore, suppose $p$ of the $N$ are positive and $n$ of the $N$ are negative. 1. Write down an expression for the likelihood of $D$ (i.e., the probability of seeing this particular sequence of examples, given a fixed value of $\pi$) in terms of $\pi$, $p$, and $n$. 2. By differentiating the log likelihood $L$, find the value of $\pi$ that maximizes the likelihood. 3. Now suppose we add in $k$ Boolean random variables $X_1, X_2,\ldots,X_k$ (the “attributes”) that describe each sample, and suppose we assume that the attributes are conditionally independent of each other given the goal $Y$. Draw the Bayes net corresponding to this assumption. 4. Write down the likelihood for the data including the attributes, using the following additional notation: - $\alpha_i$ is $P(X_i=true \| Y=true)$. - $\beta_i$ is $P(X_i=true \| Y=false)$. - $p_i^+$ is the count of samples for which $X_i=true$ and $Y=true$. - $n_i^+$ is the count of samples for which $X_i=false$ and $Y=true$. - $p_i^-$ is the count of samples for which $X_i=true$ and $Y=false$. - $n_i^-$ is the count of samples for which $X_i=false$ and $Y=false$. \[*Hint*: consider first the probability of seeing a single example with specified values for $X_1, X_2,\ldots,X_k$ and $Y$.\] 5. By differentiating the log likelihood $L$, find the values of $\alpha_i$ and $\beta_i$ (in terms of the various counts) that maximize the likelihood and say in words what these values represent. 6. Let $k = 2$, and consider a data set with 4 all four possible examples of thexor function. Compute the maximum likelihood estimates of $\pi$, $\alpha_1$, $\alpha_2$, $\beta_1$, and $\beta_2$. 7. Given these estimates of $\pi$, $\alpha_1$, $\alpha_2$, $\beta_1$, and $\beta_2$, what are the posterior probabilities $P(Y=true | x_1,x_2)$ for each example? <file_sep>[Exercise 18.1 \[infant-language-exercise\]](ex_1/) Consider the problem faced by an infant learning to speak and understand a language. Explain how this process fits into the general learning model. Describe the percepts and actions of the infant, and the types of learning the infant must do. Describe the subfunctions the infant is trying to learn in terms of inputs and outputs, and available example data. <file_sep>[Exercise 13.5 \[exclusive-exhaustive-exercise\]](ex_5/) This question deals with the properties of possible worlds, defined on page [possible-worlds-page](#/) as assignments to all random variables. We will work with propositions that correspond to exactly one possible world because they pin down the assignments of all the variables. In probability theory, such propositions are called **atomic event**. For example, with Boolean variables $X_1$, $X_2$, $X_3$, the proposition $x_1\land \lnot x_2 \land \lnot x_3$ fixes the assignment of the variables; in the language of propositional logic, we would say it has exactly one model. 1. Prove, for the case of $n$ Boolean variables, that any two distinct atomic events are mutually exclusive; that is, their conjunction is equivalent to ${false}$. 2. Prove that the disjunction of all possible atomic events is logically equivalent to ${true}$. 3. Prove that any proposition is logically equivalent to the disjunction of the atomic events that entail its truth. <file_sep>[Exercise 15.1 \[state-augmentation-exercise\]](ex_1/) Show that any second-order Markov process can be rewritten as a first-order Markov process with an augmented set of state variables. Can this always be done *parsimoniously*, i.e., without increasing the number of parameters needed to specify the transition model? <file_sep>[Exercise 18.11 \[pruning-DTL-exercise\]](ex_11/) This exercise considers $\chi^2$ pruning of decision trees (Section [chi-squared-section](#/)). 1. Create a data set with two input attributes, such that the information gain at the root of the tree for both attributes is zero, but there is a decision tree of depth 2 that is consistent with all the data. What would $\chi^2$ pruning do on this data set if applied bottom up? If applied top down? 2. Modify DECISION-TREE-LEARNING to include $\chi^2$-pruning. You might wish to consult Quinlan [@Quinlan:1986] or [@Kearns+Mansour:1998] for details. <file_sep>[Exercise 12.21](ex_21/) The two preceding exercises assume a fairly primitive notion of ownership. For example, the buyer starts by *owning* the dollar bills. This picture begins to break down when, for example, one’s money is in the bank, because there is no longer any specific collection of dollar bills that one owns. The picture is complicated still further by borrowing, leasing, renting, and bailment. Investigate the various commonsense and legal concepts of ownership, and propose a scheme by which they can be represented formally. <file_sep>[Exercise 18.30](ex_30/) Implement a data structure for layered, feed-forward neural networks, remembering to provide the information needed for both forward evaluation and backward propagation. Using this data structure, write a function NEURAL-NETWORK-OUTPUT that takes an example and a network and computes the appropriate output values. <file_sep>[Exercise 17.6 \[reward-equivalence-exercise\]](ex_6/) Sometimes MDPs are formulated with a reward function $R(s,a)$ that depends on the action taken or with a reward function $R(s,a,s')$ that also depends on the outcome state. 1. Write the Bellman equations for these formulations. 2. Show how an MDP with reward function $R(s,a,s')$ can be transformed into a different MDP with reward function $R(s,a)$, such that optimal policies in the new MDP correspond exactly to optimal policies in the original MDP. 3. Now do the same to convert MDPs with $R(s,a)$ into MDPs with $R(s)$. <file_sep>[Exercise 12.29 \[shopping-grammar-exercise\]](ex_29/) A complete solution to the problem of inexact matches to the buyer’s description in shopping is very difficult and requires a full array of natural language processing and information retrieval techniques. (See Chapters [nlp1-chapter](#/) and [nlp-english-chapter](#/).) One small step is to allow the user to specify minimum and maximum values for various attributes. The buyer must use the following grammar for product descriptions: $$ Description \rightarrow Category \space [Connector \space Modifier]* $$ $$ Connector \rightarrow "with" \space | "and" | "," $$ $$ Modifier \rightarrow Attribute \space |\space Attribute \space Op \space Value $$ $$ Op \rightarrow "=" | "\gt" | "\lt" $$ Here, ${Category}$ names a product category, ${Attribute}$ is some feature such as “CPU” or “price,” and ${Value}$ is the target value for the attribute. So the query “computer with at least a 2.5 GHz CPU for under 500” must be re-expressed as “computer with CPU $>$ 2.5 GHz and price $<$ 500.” Implement a shopping agent that accepts descriptions in this language. <file_sep>[Exercise 17.22](ex_22/) The following payoff matrix, from @Blinder:1983 by way of @Bernstein:1996, shows a game between politicians and the Federal Reserve. | | Fed: contract | Fed: do nothing | Fed: expand | | --- | --- | --- | --- | | **Pol: contract** | $F=7, P=1$ | $F=9,P=4$ | $F=6,P=6$ | | **Pol: do nothing** | $F=8, P=2$ | $F=5,P=5$ | $F=4,P=9$ | | **Pol: expand** | $F=3, P=3$ | $F=2,P=7$ | $F=1,P=8$ | Politicians can expand or contract fiscal policy, while the Fed can expand or contract monetary policy. (And of course either side can choose to do nothing.) Each side also has preferences for who should do what—neither side wants to look like the bad guys. The payoffs shown are simply the rank orderings: 9 for first choice through 1 for last choice. Find the Nash equilibrium of the game in pure strategies. Is this a Pareto-optimal solution? You might wish to analyze the policies of recent administrations in this light. <file_sep>[Exercise 13.10 \[unfinished-game-exercise\]](ex_10/) In his letter of August 24, 1654, Pascal was trying to show how a pot of money should be allocated when a gambling game must end prematurely. Imagine a game where each turn consists of the roll of a die, player *E* gets a point when the die is even, and player *O* gets a point when the die is odd. The first player to get 7 points wins the pot. Suppose the game is interrupted with *E* leading 4–2. How should the money be fairly split in this case? What is the general formula? (Fermat and Pascal made several errors before solving the problem, but you should be able to get it right the first time.) <file_sep>[Exercise 13.29](ex_29/) In our analysis of the wumpus world, we used the fact that each square contains a pit with probability 0.2, independently of the contents of the other squares. Suppose instead that exactly $N/5$ pits are scattered at random among the $N$ squares other than \[1,1\]. Are the variables $P_{i,j}$ and $P_{k,l}$ still independent? What is the joint distribution ${\textbf{P}}(P_{1,1},\ldots,P_{4,4})$ now? Redo the calculation for the probabilities of pits in \[1,3\] and \[2,2\]. <file_sep>[Exercise 18.21 \[svm-ellipse-exercise\]](ex_21/) Figure [kernel-machine-figure](#/) showed how a circle at the origin can be linearly separated by mapping from the features $(x_1, x_2)$ to the two dimensions $(x_1^2, x_2^2)$. But what if the circle is not located at the origin? What if it is an ellipse, not a circle? The general equation for a circle (and hence the decision boundary) is $(x_1-a)^2 + (x_2-b)^2 - r^2{{\,=\,}}0$, and the general equation for an ellipse is $c(x_1-a)^2 + d(x_2-b)^2 - 1 {{\,=\,}}0$. 1. Expand out the equation for the circle and show what the weights $w_i$ would be for the decision boundary in the four-dimensional feature space $(x_1, x_2, x_1^2, x_2^2)$. Explain why this means that any circle is linearly separable in this space. 2. Do the same for ellipses in the five-dimensional feature space $(x_1, x_2, x_1^2, x_2^2, x_1 x_2)$. <file_sep>[Exercise 21.12](ex_12/) Investigate the application of reinforcement learning ideas to the modeling of human and animal behavior. <file_sep>[Exercise 14.14 \[telescope-exercise\]](ex_14/) Two astronomers in different parts of the world make measurements $M_1$ and $M_2$ of the number of stars $N$ in some small region of the sky, using their telescopes. Normally, there is a small possibility $e$ of error by up to one star in each direction. Each telescope can also (with a much smaller probability $f$) be badly out of focus (events $F_1$ and $F_2$), in which case the scientist will undercount by three or more stars (or if $N$ is less than 3, fail to detect any stars at all). Consider the three networks shown in Figure [telescope-nets-figure](#telescope-nets-figure). 1. Which of these Bayesian networks are correct (but not necessarily efficient) representations of the preceding information? 2. Which is the best network? Explain. 3. Write out a conditional distribution for ${\textbf{P}}(M_1{{\,|\,}}N)$, for the case where $N{{\,\in\\,}}\{1,2,3\}$ and $M_1{{\,\in\\,}}\{0,1,2,3,4\}$. Each entry in the conditional distribution should be expressed as a function of the parameters $e$ and/or $f$. 4. Suppose $M_1{{\,=\,}}1$ and $M_2{{\,=\,}}3$. What are the *possible* numbers of stars if you assume no prior constraint on the values of $N$? 5. What is the *most likely* number of stars, given these observations? Explain how to compute this, or if it is not possible to compute, explain what additional information is needed and how it would affect the result. <file_sep>[Exercise 17.12](ex_12/) Consider an undiscounted MDP having three states, (1, 2, 3), with rewards $-1$, $-2$, $0$, respectively. State 3 is a terminal state. In states 1 and 2 there are two possible actions: $a$ and $b$. The transition model is as follows: - In state 1, action $a$ moves the agent to state 2 with probability 0.8 and makes the agent stay put with probability 0.2. - In state 2, action $a$ moves the agent to state 1 with probability 0.8 and makes the agent stay put with probability 0.2. - In either state 1 or state 2, action $b$ moves the agent to state 3 with probability 0.1 and makes the agent stay put with probability 0.9. Answer the following questions: 1. What can be determined *qualitatively* about the optimal policy in states 1 and 2? 2. Apply policy iteration, showing each step in full, to determine the optimal policy and the values of states 1 and 2. Assume that the initial policy has action $b$ in both states. 3. What happens to policy iteration if the initial policy has action $a$ in both states? Does discounting help? Does the optimal policy depend on the discount factor? <file_sep>[Exercise 16.10](ex_10/) Tickets to a lottery cost 1. There are two possible prizes: a 10 payoff with probability 1/50, and a 1,000,000 payoff with probability 1/2,000,000. What is the expected monetary value of a lottery ticket? When (if ever) is it rational to buy a ticket? Be precise—show an equation involving utilities. You may assume current wealth of $k$ and that $U(S_k)=0$. You may also assume that $U(S_{k+{10}}) = {10}\times U(S_{k+1})$, but you may not make any assumptions about $U(S_{k+1,{000},{000}})$. Sociological studies show that people with lower income buy a disproportionate number of lottery tickets. Do you think this is because they are worse decision makers or because they have a different utility function? Consider the value of contemplating the possibility of winning the lottery versus the value of contemplating becoming an action hero while watching an adventure movie. <file_sep>[Exercise 14.4](ex_4/) The **arc reversal** operation of in a Bayesian network allows us to change the direction of an arc $X\rightarrow Y$ while preserving the joint probability distribution that the network represents @Shachter:1986. Arc reversal may require introducing new arcs: all the parents of $X$ also become parents of $Y$, and all parents of $Y$ also become parents of $X$. 1. Assume that $X$ and $Y$ start with $m$ and $n$ parents, respectively, and that all variables have $k$ values. By calculating the change in size for the CPTs of $X$ and $Y$, show that the total number of parameters in the network cannot decrease during arc reversal. (*Hint*: the parents of $X$ and $Y$ need not be disjoint.) 2. Under what circumstances can the total number remain constant? 3. Let the parents of $X$ be $\textbf{U} \cup \textbf{V}$ and the parents of $Y$ be $\textbf{V} \cup \textbf{W}$, where $\textbf{U}$ and $\textbf{W}$ are disjoint. The formulas for the new CPTs after arc reversal are as follows: $$\begin{aligned} {\textbf{P}}(Y{{\,|\,}}\textbf{U},\textbf{V},\textbf{W}) &=& \sum_x {\textbf{P}}(Y{{\,|\,}}\textbf{V},\textbf{W}, x) {\textbf{P}}(x{{\,|\,}}\textbf{U}, \textbf{V}) \\ {\textbf{P}}(X{{\,|\,}}\textbf{U},\textbf{V},\textbf{W}, Y) &=& {\textbf{P}}(Y{{\,|\,}}X, \textbf{V}, \textbf{W}) {\textbf{P}}(X{{\,|\,}}\textbf{U}, \textbf{V}) / {\textbf{P}}(Y{{\,|\,}}\textbf{U},\textbf{V},\textbf{W})\ .\end{aligned}$$ Prove that the new network expresses the same joint distribution over all variables as the original network. <file_sep>[Exercise 16.15](ex_15/) Economists often make use of an exponential utility function for money: $U(x) = -e^{-x/R}$, where $R$ is a positive constant representing an individual’s risk tolerance. Risk tolerance reflects how likely an individual is to accept a lottery with a particular expected monetary value (EMV) versus some certain payoff. As $R$ (which is measured in the same units as $x$) becomes larger, the individual becomes less risk-averse. 1. Assume Mary has an exponential utility function with $R = \$400$. Mary is given the choice between receiving $$\$400$$ with certainty (probability 1) or participating in a lottery which has a 60% probability of winning \$5000 and a 40% probability of winning nothing. Assuming Marry acts rationally, which option would she choose? Show how you derived your answer. 2. Consider the choice between receiving $$\$100$$ with certainty (probability 1) or participating in a lottery which has a 50% probability of winning \$500 and a 50% probability of winning nothing. Approximate the value of R (to 3 significant digits) in an exponential utility function that would cause an individual to be indifferent to these two alternatives. (You might find it helpful to write a short program to help you solve this problem.) <file_sep>[Exercise 13.31](ex_31/) Implement a hybrid probabilistic agent for the wumpus world, based on the hybrid agent in Figure [hybrid-wumpus-agent-algorithm](#/) and the probabilistic inference procedure outlined in this chapter. <file_sep>--- layout: chapter title: Main permalink: /fol-exercises/ --- {% include mathjax_support %} # 8. First Order Logic <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.1');" href="#"><i id="ex8.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.1');" href="#"><i id="ex8.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.2');" href="#"><i id="ex8.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.2');" href="#"><i id="ex8.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.3');" href="#"><i id="ex8.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.3');" href="#"><i id="ex8.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.4');" href="#"><i id="ex8.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.4');" href="#"><i id="ex8.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 (two-friends-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.5');" href="#"><i id="ex8.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.5');" href="#"><i id="ex8.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6 (8puzzle-parity-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.6');" href="#"><i id="ex8.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.6');" href="#"><i id="ex8.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7 (nqueens-size-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.7');" href="#"><i id="ex8.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.7');" href="#"><i id="ex8.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8 (empty-universe-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.8');" href="#"><i id="ex8.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.8');" href="#"><i id="ex8.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9 (hillary-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.9');" href="#"><i id="ex8.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.9');" href="#"><i id="ex8.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.10');" href="#"><i id="ex8.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.10');" href="#"><i id="ex8.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.11');" href="#"><i id="ex8.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.11');" href="#"><i id="ex8.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.12');" href="#"><i id="ex8.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.12');" href="#"><i id="ex8.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13 (language-determination-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.13');" href="#"><i id="ex8.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.13');" href="#"><i id="ex8.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.14');" href="#"><i id="ex8.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.14');" href="#"><i id="ex8.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15 (Peano-completion-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.15');" href="#"><i id="ex8.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.15');" href="#"><i id="ex8.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_16/' class="p-2">Exercise 16 (wumpus-diagnostic-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.16');" href="#"><i id="ex8.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.16');" href="#"><i id="ex8.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_17/' class="p-2">Exercise 17 (kinship-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.17');" href="#"><i id="ex8.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.17');" href="#"><i id="ex8.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_18/' class="p-2">Exercise 18 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.18');" href="#"><i id="ex8.18" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.18');" href="#"><i id="ex8.18" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_18/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_19/' class="p-2">Exercise 19 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.19');" href="#"><i id="ex8.19" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.19');" href="#"><i id="ex8.19" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_19/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_20/' class="p-2">Exercise 20 (list-representation-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.20');" href="#"><i id="ex8.20" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.20');" href="#"><i id="ex8.20" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_20/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_21/' class="p-2">Exercise 21 (adjacency-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.21');" href="#"><i id="ex8.21" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.21');" href="#"><i id="ex8.21" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_21/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_22/' class="p-2">Exercise 22 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.22');" href="#"><i id="ex8.22" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.22');" href="#"><i id="ex8.22" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_22/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_23/' class="p-2">Exercise 23 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.23');" href="#"><i id="ex8.23" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.23');" href="#"><i id="ex8.23" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_23/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_24/' class="p-2">Exercise 24 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.24');" href="#"><i id="ex8.24" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.24');" href="#"><i id="ex8.24" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_24/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_25/' class="p-2">Exercise 25 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.25');" href="#"><i id="ex8.25" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.25');" href="#"><i id="ex8.25" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_25/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_26/' class="p-2">Exercise 26 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.26');" href="#"><i id="ex8.26" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.26');" href="#"><i id="ex8.26" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_26/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_27/' class="p-2">Exercise 27 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.27');" href="#"><i id="ex8.27" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.27');" href="#"><i id="ex8.27" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_27/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_28/' class="p-2">Exercise 28 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.28');" href="#"><i id="ex8.28" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.28');" href="#"><i id="ex8.28" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_28/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_29/' class="p-2">Exercise 29 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.29');" href="#"><i id="ex8.29" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.29');" href="#"><i id="ex8.29" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_29/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_30/' class="p-2">Exercise 30 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.30');" href="#"><i id="ex8.30" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.30');" href="#"><i id="ex8.30" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_30/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_31/' class="p-2">Exercise 31 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.31');" href="#"><i id="ex8.31" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.31');" href="#"><i id="ex8.31" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_31/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_32/' class="p-2">Exercise 32 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.32');" href="#"><i id="ex8.32" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.32');" href="#"><i id="ex8.32" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_32/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_33/' class="p-2">Exercise 33 (4bit-adder-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.33');" href="#"><i id="ex8.33" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.33');" href="#"><i id="ex8.33" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_33/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_34/' class="p-2">Exercise 34 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.34');" href="#"><i id="ex8.34" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.34');" href="#"><i id="ex8.34" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_34/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_35/' class="p-2">Exercise 35 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.35');" href="#"><i id="ex8.35" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.35');" href="#"><i id="ex8.35" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_35/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_36/' class="p-2">Exercise 36 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex8.36');" href="#"><i id="ex8.36" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex8.36');" href="#"><i id="ex8.36" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_36/question.md %}</p> </div> </div> <br> <file_sep>--- layout: exercise title: Exercise 3.34 permalink: /search-exercises/ex_34/ breadcrumb: 3-Solving-Problems-By-Searching --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="search-exercises" data-exercise="ex_34" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 14.7 \[handedness-exercise\]](ex_7/) Let $H_x$ be a random variable denoting the handedness of an individual $x$, with possible values $l$ or $r$. A common hypothesis is that left- or right-handedness is inherited by a simple mechanism; that is, perhaps there is a gene $G_x$, also with values $l$ or $r$, and perhaps actual handedness turns out mostly the same (with some probability $s$) as the gene an individual possesses. Furthermore, perhaps the gene itself is equally likely to be inherited from either of an individual’s parents, with a small nonzero probability $m$ of a random mutation flipping the handedness. 1. Which of the three networks in Figure [handedness-figure](#handedness-figure) claim that $ {\textbf{P}}(G_{father},G_{mother},G_{child}) = {\textbf{P}}(G_{father}){\textbf{P}}(G_{mother}){\textbf{P}}(G_{child})$? 2. Which of the three networks make independence claims that are consistent with the hypothesis about the inheritance of handedness? 3. Which of the three networks is the best description of the hypothesis? 4. Write down the CPT for the $G_{child}$ node in network (a), in terms of $s$ and $m$. 5. Suppose that $P(G_{father}{{\,=\,}}l)=P(G_{mother}{{\,=\,}}l)=q$. In network (a), derive an expression for $P(G_{child}{{\,=\,}}l)$ in terms of $m$ and $q$ only, by conditioning on its parent nodes. 6. Under conditions of genetic equilibrium, we expect the distribution of genes to be the same across generations. Use this to calculate the value of $q$, and, given what you know about handedness in humans, explain why the hypothesis described at the beginning of this question must be wrong. <file_sep> Suppose we extend Evans’s *SYSTEM* program so that it can score 200 on a standard IQ test. Would we then have a program more intelligent than a human? Explain. <file_sep>[Exercise 16.4 \[St-Petersburg-exercise\]](ex_4/) In 1713, <NAME> stated a puzzle, now called the St. Petersburg paradox, which works as follows. You have the opportunity to play a game in which a fair coin is tossed repeatedly until it comes up heads. If the first heads appears on the $n$th toss, you win $2^n$ dollars. 1. Show that the expected monetary value of this game is infinite. 2. How much would you, personally, pay to play the game? 3. Nicolas’s cousin <NAME> resolved the apparent paradox in 1738 by suggesting that the utility of money is measured on a logarithmic scale (i.e., $U(S_{n}) = a\log_2 n +b$, where $S_n$ is the state of having $n$). What is the expected utility of the game under this assumption? 4. What is the maximum amount that it would be rational to pay to play the game, assuming that one’s initial wealth is $k$? <file_sep>[Exercise 18.29 \[linear-nn-exercise\]](ex_29/) Suppose you had a neural network with linear activation functions. That is, for each unit the output is some constant $c$ times the weighted sum of the inputs. 1. Assume that the network has one hidden layer. For a given assignment to the weights $\textbf{w}$, write down equations for the value of the units in the output layer as a function of $\textbf{w}$ and the input layer $\textbf{x}$, without any explicit mention of the output of the hidden layer. Show that there is a network with no hidden units that computes the same function. 2. Repeat the calculation in part (a), but this time do it for a network with any number of hidden layers. 3. Suppose a network with one hidden layer and linear activation functions has $n$ input and output nodes and $h$ hidden nodes. What effect does the transformation in part (a) to a network with no hidden layers have on the total number of weights? Discuss in particular the case $h \ll n$. <file_sep>--- layout: chapter title: Main permalink: /logical-inference-exercises/ --- {% include mathjax_support %} # 9. Inference in First-Order Logic <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.1');" href="#"><i id="ex9.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.1');" href="#"><i id="ex9.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.2');" href="#"><i id="ex9.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.2');" href="#"><i id="ex9.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.3');" href="#"><i id="ex9.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.3');" href="#"><i id="ex9.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.4');" href="#"><i id="ex9.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.4');" href="#"><i id="ex9.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.5');" href="#"><i id="ex9.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.5');" href="#"><i id="ex9.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6 (subsumption-lattice-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.6');" href="#"><i id="ex9.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.6');" href="#"><i id="ex9.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7 (fol-horses-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.7');" href="#"><i id="ex9.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.7');" href="#"><i id="ex9.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.8');" href="#"><i id="ex9.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.8');" href="#"><i id="ex9.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.9');" href="#"><i id="ex9.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.9');" href="#"><i id="ex9.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10 (csp-clause-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.10');" href="#"><i id="ex9.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.10');" href="#"><i id="ex9.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.11');" href="#"><i id="ex9.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.11');" href="#"><i id="ex9.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.12');" href="#"><i id="ex9.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.12');" href="#"><i id="ex9.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.13');" href="#"><i id="ex9.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.13');" href="#"><i id="ex9.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.14');" href="#"><i id="ex9.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.14');" href="#"><i id="ex9.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15 (standardize-failure-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.15');" href="#"><i id="ex9.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.15');" href="#"><i id="ex9.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_16/' class="p-2">Exercise 16 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.16');" href="#"><i id="ex9.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.16');" href="#"><i id="ex9.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_17/' class="p-2">Exercise 17 (bc-trace-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.17');" href="#"><i id="ex9.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.17');" href="#"><i id="ex9.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_18/' class="p-2">Exercise 18 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.18');" href="#"><i id="ex9.18" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.18');" href="#"><i id="ex9.18" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_18/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_19/' class="p-2">Exercise 19 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.19');" href="#"><i id="ex9.19" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.19');" href="#"><i id="ex9.19" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_19/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_20/' class="p-2">Exercise 20 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.20');" href="#"><i id="ex9.20" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.20');" href="#"><i id="ex9.20" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_20/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_21/' class="p-2">Exercise 21 (diff-simplify-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.21');" href="#"><i id="ex9.21" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.21');" href="#"><i id="ex9.21" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_21/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_22/' class="p-2">Exercise 22 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.22');" href="#"><i id="ex9.22" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.22');" href="#"><i id="ex9.22" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_22/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_23/' class="p-2">Exercise 23 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.23');" href="#"><i id="ex9.23" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.23');" href="#"><i id="ex9.23" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_23/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_24/' class="p-2">Exercise 24 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.24');" href="#"><i id="ex9.24" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.24');" href="#"><i id="ex9.24" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_24/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_25/' class="p-2">Exercise 25 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.25');" href="#"><i id="ex9.25" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.25');" href="#"><i id="ex9.25" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_25/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_26/' class="p-2">Exercise 26 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.26');" href="#"><i id="ex9.26" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.26');" href="#"><i id="ex9.26" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_26/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_27/' class="p-2">Exercise 27 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.27');" href="#"><i id="ex9.27" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.27');" href="#"><i id="ex9.27" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_27/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_28/' class="p-2">Exercise 28 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.28');" href="#"><i id="ex9.28" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.28');" href="#"><i id="ex9.28" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_28/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_29/' class="p-2">Exercise 29 (quantifier-order-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.29');" href="#"><i id="ex9.29" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.29');" href="#"><i id="ex9.29" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_29/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_30/' class="p-2">Exercise 30 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.30');" href="#"><i id="ex9.30" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.30');" href="#"><i id="ex9.30" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_30/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_31/' class="p-2">Exercise 31 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex9.31');" href="#"><i id="ex9.31" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex9.31');" href="#"><i id="ex9.31" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_31/question.md %}</p> </div> </div> <br> <file_sep>[Exercise 10.4](ex_4/) The monkey-and-bananas problem is faced by a monkey in a laboratory with some bananas hanging out of reach from the ceiling. A box is available that will enable the monkey to reach the bananas if he climbs on it. Initially, the monkey is at $A$, the bananas at $B$, and the box at $C$. The monkey and box have height ${Low}$, but if the monkey climbs onto the box he will have height ${High}$, the same as the bananas. The actions available to the monkey include ${Go}$ from one place to another, ${Push}$ an object from one place to another, ${ClimbUp}$ onto or ${ClimbDown}$ from an object, and ${Grasp}$ or ${Ungrasp}$ an object. The result of a ${Grasp}$ is that the monkey holds the object if the monkey and object are in the same place at the same height. 1. Write down the initial state description. 2. Write the six action schemas. 3. Suppose the monkey wants to fool the scientists, who are off to tea, by grabbing the bananas, but leaving the box in its original place. Write this as a general goal (i.e., not assuming that the box is necessarily at C) in the language of situation calculus. Can this goal be solved by a classical planning system? 4. Your schema for pushing is probably incorrect, because if the object is too heavy, its position will remain the same when the ${Push}$ schema is applied. Fix your action schema to account for heavy objects. <file_sep>[Exercise 25.6 \[inverse-kinematics-exercise\]](ex_6/) Consider the robot arm shown in Figure [FigArm1](#/). Assume that the robot’s base element is 70cm long and that its upper arm and forearm are each 50cm long. As argued on page [inverse-kinematics-not-unique](#/), the inverse kinematics of a robot is often not unique. State an explicit closed-form solution of the inverse kinematics for this arm. Under what exact conditions is the solution unique? <file_sep> The neural structure of the sea slug *Aplysia* has been widely studied (first by <NAME> <NAME>) because it has only about 20,000 neurons, most of them large and easily manipulated. Assuming that the cycle time for an *Aplysia* neuron is roughly the same as for a human neuron, how does the computational power, in terms of memory updates per second, compare with the high-end computer described in (Figure [computer-brain-table](#/))? <file_sep>[Exercise 22.1](ex_1/) This exercise explores the quality of the $n$-gram model of language. Find or create a monolingual corpus of 100,000 words or more. Segment it into words, and compute the frequency of each word. How many distinct words are there? Also count frequencies of bigrams (two consecutive words) and trigrams (three consecutive words). Now use those frequencies to generate language: from the unigram, bigram, and trigram models, in turn, generate a 100-word text by making random choices according to the frequency counts. Compare the three generated texts with actual language. Finally, calculate the perplexity of each model. <file_sep>[Exercise 22.2](ex_2/) Write a program to do **segmentation** of words without spaces. Given a string, such as the URL “thelongestlistofthelongeststuffatthelongestdomainnameatlonglast.com,” return a list of component words: \[“the,” “longest,” “list,” $\ldots$\]. This task is useful for parsing URLs, for spelling correction when words runtogether, and for languages such as Chinese that do not have spaces between words. It can be solved with a unigram or bigram word model and a dynamic programming algorithm similar to the Viterbi algorithm. <file_sep> The **heuristic path algorithm** @Pohl:1977 is a best-first search in which the evaluation function is $f(n) = (2-w)g(n) + wh(n)$. For what values of $w$ is this complete? For what values is it optimal, assuming that $h$ is admissible? What kind of search does this perform for $w=0$, $w=1$, and $w=2$? <file_sep>[Exercise 11.14](ex_14/) Consider the following problem: A patient arrives at the doctor’s office with symptoms that could have been caused either by dehydration or by disease $D$ (but not both). There are two possible actions: ${Drink}$, which unconditionally cures dehydration, and ${Medicate}$, which cures disease $D$ but has an undesirable side effect if taken when the patient is dehydrated. Write the problem description, and diagram a sensorless plan that solves the problem, enumerating all relevant possible worlds. <file_sep>[Exercise 16.21 \[airport-id-exercise\]](ex_21/) This exercise completes the analysis of the airport-siting problem in Figure [airport-id-figure](#/). 1. Provide reasonable variable domains, probabilities, and utilities for the network, assuming that there are three possible sites. 2. Solve the decision problem. 3. What happens if changes in technology mean that each aircraft generates half the noise? 4. What if noise avoidance becomes three times more important? 5. Calculate the VPI for ${AirTraffic}$, ${Litigation}$, and ${Construction}$ in your model. <file_sep>[Exercise 18.28 \[perceptron-ML-gradient-exercise\]](ex_28/) Section [logistic-regression-section](#/) (page [logistic-regression-section](#/)) noted that the output of the logistic function could be interpreted as a *probability* $p$ assigned by the model to the proposition that $f(\textbf{x}){{\,=\,}}1$; the probability that $f(\textbf{x}){{\,=\,}}0$ is therefore $1-p$. Write down the probability $p$ as a function of $\textbf{x}$ and calculate the derivative of $\log p$ with respect to each weight $w_i$. Repeat the process for $\log (1-p)$. These calculations give a learning rule for minimizing the negative-log-likelihood loss function for a probabilistic hypothesis. Comment on any resemblance to other learning rules in the chapter. <file_sep>[Exercise 21.11](ex_11/) Implement the REINFORCE and PEGASUS algorithms and apply them to the $4\times 3$ world, using a policy family of your own choosing. Comment on the results. <file_sep>[Exercise 25.2 \[mcl-implement-exercise\]](ex_2/) Implement Monte Carlo localization for a simulated robot with range sensors. A grid map and range data are available from the code repository at [aima.cs.berkeley.edu](http://aima.cs.berkeley.edu). You should demonstrate successful global localization of the robot. <center> <b id="figRobot2">Figure [figRobot2]</b> A Robot manipulator in two of its possible configurations. </center> ![figRobot2](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/figRobot2.svg) <file_sep>[Exercise 16.5](ex_5/) Write a computer program to automate the process in Exercise [assessment-exercise](#/). Try your program out on several people of different net worth and political outlook. Comment on the consistency of your results, both for an individual and across individuals. <file_sep>[Exercise 21.10 \[10x10-exercise\]](ex_10/) Compute the true utility function and the best linear approximation in $x$ and $y$ (as in Equation ([4x3-linear-approx-equation](#/))) for the following environments: 1. A ${10}\times {10}$ world with a single $+1$ terminal state at (10,10). 2. As in (a), but add a $-1$ terminal state at (10,1). 3. As in (b), but add obstacles in 10 randomly selected squares. 4. As in (b), but place a wall stretching from (5,2) to (5,9). 5. As in (a), but with the terminal state at (5,5). The actions are deterministic moves in the four directions. In each case, compare the results using three-dimensional plots. For each environment, propose additional features (besides $x$ and $y$) that would improve the approximation and show the results. <file_sep>[Exercise 20.1 \[bayes-candy-exercise\]](ex_1/) The data used for Figure [bayes-candy-figure](#/) on page [bayes-candy-figure](#/) can be viewed as being generated by $h_5$. For each of the other four hypotheses, generate a data set of length 100 and plot the corresponding graphs for $P(h_i|d_1,\ldots,d_N)$ and $P(D_{N+1}=lime|d_1,\ldots,d_N)$. Comment on your results. <file_sep>[Exercise 20.2](ex_2/) Repeat Exercise [bayes-candy-exercise](#/), this time plotting the values of $P(D_{N+1}=lime|h_{MAP})$ and $P(D_{N+1}=lime|h_{ML})$. <file_sep>[Exercise 13.20 \[conditional-bayes-exercise\]](ex_20/) It is quite often useful to consider the effect of some specific propositions in the context of some general background evidence that remains fixed, rather than in the complete absence of information. The following questions ask you to prove more general versions of the product rule and Bayes’ rule, with respect to some background evidence $\textbf{e}$: 1. Prove the conditionalized version of the general product rule: $${\textbf{P}}(X,Y {{\,|\,}}\textbf{e}) = {\textbf{P}}(X{{\,|\,}}Y,\textbf{e}) {\textbf{P}}(Y{{\,|\,}}\textbf{e})\ .$$ 2. Prove the conditionalized version of Bayes’ rule in Equation ([conditional-bayes-equation](#/)). <file_sep>[Exercise 15.4 \[flawed-viterbi-exercise\]](ex_4/) On page [flawed-viterbi-page](#/), we outlined a flawed procedure for finding the most likely state sequence, given an observation sequence. The procedure involves finding the most likely state at each time step, using smoothing, and returning the sequence composed of these states. Show that, for some temporal probability models and observation sequences, this procedure returns an impossible state sequence (i.e., the posterior probability of the sequence is zero). <file_sep>[Exercise 17.4 \[nonseparable-exercise\]](ex_4/) Suppose that we define the utility of a state sequence to be the *maximum* reward obtained in any state in the sequence. Show that this utility function does not result in stationary preferences between state sequences. Is it still possible to define a utility function on states such that MEU decision making gives optimal behavior? <file_sep>[Exercise 12.25](ex_25/) Translate the following description logic expression (from page [description-logic-ex](#/)) into first-order logic, and comment on the result: $$ And(Man, AtLeast(3,Son), AtMost(2,Daughter), All(Son,And(Unemployed,Married, All(Spouse,Doctor ))), All(Daughter,And(Professor, Fills(Department ,Physics,Math)))) $$ <file_sep>[Exercise 11.10](ex_10/) In the blocks world we were forced to introduce two action schemas, ${Move}$ and ${MoveToTable}$, in order to maintain the ${Clear}$ predicate properly. Show how conditional effects can be used to represent both of these cases with a single action. <file_sep>[Exercise 10.8 \[sussman-anomaly-exercise\]](ex_8/) Figure [sussman-anomaly-figure](#/) (page [sussman-anomaly-figure](#/)) shows a blocks-world problem that is known as the {Sussman anomaly}. The problem was considered anomalous because the noninterleaved planners of the early 1970s could not solve it. Write a definition of the problem and solve it, either by hand or with a planning program. A noninterleaved planner is a planner that, when given two subgoals $G_{1}$ and $G_{2}$, produces either a plan for $G_{1}$ concatenated with a plan for $G_{2}$, or vice versa. Can a noninterleaved planner solve this problem? How, or why not? <file_sep>[Exercise 16.2](ex_2/) Chris considers four used cars before buying the one with maximum expected utility. Pat considers ten cars and does the same. All other things being equal, which one is more likely to have the better car? Which is more likely to be disappointed with their car’s quality? By how much (in terms of standard deviations of expected quality)? <file_sep>--- layout: chapter title: Beyond Classical Search permalink: /advanced-search-exercises/ --- {% include mathjax_support %} # 4. Beyond Classical Search <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.1');" href="#"><i id="ex4.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.1');" href="#"><i id="ex4.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.2');" href="#"><i id="ex4.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.2');" href="#"><i id="ex4.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.3');" href="#"><i id="ex4.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.3');" href="#"><i id="ex4.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4 (hill-climbing-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.4');" href="#"><i id="ex4.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.4');" href="#"><i id="ex4.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 (cond-plan-repeated-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.5');" href="#"><i id="ex4.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.5');" href="#"><i id="ex4.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6 (cond-loop-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.6');" href="#"><i id="ex4.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.6');" href="#"><i id="ex4.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.7');" href="#"><i id="ex4.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.7');" href="#"><i id="ex4.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8 (belief-state-superset-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.8');" href="#"><i id="ex4.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.8');" href="#"><i id="ex4.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9 (multivalued-sensorless-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.9');" href="#"><i id="ex4.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.9');" href="#"><i id="ex4.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10 (vacuum-solvable-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.10');" href="#"><i id="ex4.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.10');" href="#"><i id="ex4.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11 (vacuum-solvable-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.11');" href="#"><i id="ex4.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.11');" href="#"><i id="ex4.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 12 (path-planning-agent-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.12');" href="#"><i id="ex4.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.12');" href="#"><i id="ex4.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 13 (online-offline-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.13');" href="#"><i id="ex4.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.13');" href="#"><i id="ex4.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14 (online-offline-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.14');" href="#"><i id="ex4.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.14');" href="#"><i id="ex4.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15 (path-planning-hc-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.15');" href="#"><i id="ex4.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.15');" href="#"><i id="ex4.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_16/' class="p-2">Exercise 16</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.16');" href="#"><i id="ex4.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.16');" href="#"><i id="ex4.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_17/' class="p-2">Exercise 17</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex4.17');" href="#"><i id="ex4.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex4.17');" href="#"><i id="ex4.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <file_sep>[Exercise 10.12](ex_12/) We saw that planning graphs can handle only propositional actions. What if we want to use planning graphs for a problem with variables in the goal, such as ${At}(P_{1}, x) \land {At}(P_{2}, x)$, where $x$ is assumed to be bound by an existential quantifier that ranges over a finite domain of locations? How could you encode such a problem to work with planning graphs? <file_sep>[Exercise 12.6](ex_6/) State the following in the language you developed for the previous exercise: 1. In situation $S_0$, window $W_1$ is behind $W_2$ but sticks out on the top and bottom. Do *not* state exact coordinates for these; describe the *general* situation. 2. If a window is displayed, then its top edge is higher than its bottom edge. 3. After you create a window $w$, it is displayed. 4. A window can be minimized only if it is displayed. <file_sep>[Exercise 23.10 \[chomsky-form-exercise\]](ex_10/) In this exercise you will transform $\large \varepsilon_0$ into Chomsky Normal Form (CNF). There are five steps: (a) Add a new start symbol, (b) Eliminate $\epsilon$ rules, (c) Eliminate multiple words on right-hand sides, (d) Eliminate rules of the form (${\it X}$ ${{\;}}\rightarrow{{\;}}$${\it Y}$), (e) Convert long right-hand sides into binary rules. 1. The start symbol, $S$, can occur only on the left-hand side in CNF. Replace ${\it S}$ everywhere by a new symbol ${\it S'}$ and add a rule of the form ${\it S}$ ${{\;}}\rightarrow{{\;}}$${\it S'}$. 2. The empty string, $\epsilon$ cannot appear on the right-hand side in CNF. $\large \varepsilon_0$ does not have any rules with $\epsilon$, so this is not an issue. 3. A word can appear on the right-hand side in a rule only of the form (${\it X}$ ${{\;}}\rightarrow{{\;}}$*word*). Replace each rule of the form (${\it X}$ ${{\;}}\rightarrow{{\;}}$…*word* …) with (${\it X}$ ${{\;}}\rightarrow{{\;}}$…${\it W'}$ …) and (${\it W'}$ ${{\;}}\rightarrow{{\;}}$*word*), using a new symbol ${\it W'}$. 4. A rule (${\it X}$ ${{\;}}\rightarrow{{\;}}$${\it Y}$) is not allowed in CNF; it must be (${\it X}$ ${{\;}}\rightarrow{{\;}}$${\it Y}$ ${\it Z}$) or (${\it X}$ ${{\;}}\rightarrow{{\;}}$*word*). Replace each rule of the form (${\it X}$ ${{\;}}\rightarrow{{\;}}$${\it Y}$) with a set of rules of the form (${\it X}$ ${{\;}}\rightarrow{{\;}}$…), one for each rule (${\it Y}$ ${{\;}}\rightarrow{{\;}}$…), where (…) indicates one or more symbols. 5. Replace each rule of the form (${\it X}$ ${{\;}}\rightarrow{{\;}}$${\it Y}$ ${\it Z}$ …) with two rules, (${\it X}$ ${{\;}}\rightarrow{{\;}}$${\it Y}$ ${\it Z'}$) and (${\it Z'}$ ${{\;}}\rightarrow{{\;}}$${\it Z}$ …), where ${\it Z'}$ is a new symbol. Show each step of the process and the final set of rules. <file_sep> Consider the family of generalized tic-tac-toe games, defined as follows. Each particular game is specified by a set $\mathcal S$ of *squares* and a collection $\mathcal W$ of *winning positions.* Each winning position is a subset of $\mathcal S$. For example, in standard tic-tac-toe, $\mathcal S$ is a set of 9 squares and $\mathcal W$ is a collection of 8 subsets of $\cal W$: the three rows, the three columns, and the two diagonals. In other respects, the game is identical to standard tic-tac-toe. Starting from an empty board, players alternate placing their marks on an empty square. A player who marks every square in a winning position wins the game. It is a tie if all squares are marked and neither player has won.<br> 1. Let $N= |{\mathcal S}|$, the number of squares. Give an upper bound on the number of nodes in the complete game tree for generalized tic-tac-toe as a function of $N$.<br> 2. Give a lower bound on the size of the game tree for the worst case, where ${\mathcal W} = {\{\,\}}$.<br> 3. Propose a plausible evaluation function that can be used for any instance of generalized tic-tac-toe. The function may depend on $\mathcal S$ and $\mathcal W$.<br> 4. Assume that it is possible to generate a new board and check whether it is a winning position in 100$N$ machine instructions and assume a 2 gigahertz processor. Ignore memory limitations. Using your estimate in (a), roughly how large a game tree can be completely solved by alpha–beta in a second of CPU time? a minute? an hour? <file_sep> This question considers representing satisfiability (SAT) problems as CSPs.<br> 1. Draw the constraint graph corresponding to the SAT problem $$(\lnot X_1 \lor X_2) \land (\lnot X_2 \lor X_3) \land \ldots \land (\lnot X_{n-1} \lor X_n)$$ for the particular case $n{{\,=\,}}5$.<br> 2. How many solutions are there for this general SAT problem as a function of $n$?<br> 3. Suppose we apply {Backtracking-Search} (page <a href="#">backtracking-search-algorithm</a>) to find *all* solutions to a SAT CSP of the type given in (a). (To find *all* solutions to a CSP, we simply modify the basic algorithm so it continues searching after each solution is found.) Assume that variables are ordered $X_1,\ldots,X_n$ and ${false}$ is ordered before ${true}$. How much time will the algorithm take to terminate? (Write an $O(\cdot)$ expression as a function of $n$.)<br> 4. We know that SAT problems in Horn form can be solved in linear time by forward chaining (unit propagation). We also know that every tree-structured binary CSP with discrete, finite domains can be solved in time linear in the number of variables (Section <a href="#">csp-structure-section</a>). Are these two facts connected? Discuss.<br> <file_sep>[Exercise 10.11 \[graphplan-proof-exercise\]](ex_11/) Prove the following assertions about planning graphs: 1. A literal that does not appear in the final level of the graph cannot be achieved. 2. The level cost of a literal in a serial graph is no greater than the actual cost of an optimal plan for achieving it. <file_sep>[Exercise 14.19 \[bn-complexity-exercise\]](ex_19/) Investigate the complexity of exact inference in general Bayesian networks: 1. Prove that any 3-SAT problem can be reduced to exact inference in a Bayesian network constructed to represent the particular problem and hence that exact inference is NP-hard. (*Hint*: Consider a network with one variable for each proposition symbol, one for each clause, and one for the conjunction of clauses.) 2. The problem of counting the number of satisfying assignments for a 3-SAT problem is \#P-complete. Show that exact inference is at least as hard as this. <file_sep>[Exercise 12.10 \[part-decomposition-exercise\]](ex_10/) Write definitions for the following: 1. ${ExhaustivePartDecomposition}$ 2. ${PartPartition}$ 3. ${PartwiseDisjoint}$ These should be analogous to the definitions for ${ExhaustiveDecomposition}$, ${Partition}$, and ${Disjoint}$. Is it the case that ${PartPartition}(s,{BunchOf}(s))$? If so, prove it; if not, give a counterexample and define sufficient conditions under which it does hold. <file_sep>[Exercise 25.12 \[human-robot-exercise\]](ex_12/) (This exercise was first devised by <NAME> and <NAME>. It works for first graders through graduate students.) Humans are so adept at basic household tasks that they often forget how complex these tasks are. In this exercise you will discover the complexity and recapitulate the last 30 years of developments in robotics. Consider the task of building an arch out of three blocks. Simulate a robot with four humans as follows: **Brain.** The Brain direct the hands in the execution of a plan to achieve the goal. The Brain receives input from the Eyes, but *cannot see the scene directly*. The brain is the only one who knows what the goal is. **Eyes.** The Eyes report a brief description of the scene to the Brain: “There is a red box standing on top of a green box, which is on its side” Eyes can also answer questions from the Brain such as, “Is there a gap between the Left Hand and the red box?” If you have a video camera, point it at the scene and allow the eyes to look at the viewfinder of the video camera, but not directly at the scene. **Left hand** and **right hand.** One person plays each Hand. The two Hands stand next to each other, each wearing an oven mitt on one hand, Hands execute only simple commands from the Brain—for example, “Left Hand, move two inches forward.” They cannot execute commands other than motions; for example, they cannot be commanded to “Pick up the box.” The Hands must be *blindfolded*. The only sensory capability they have is the ability to tell when their path is blocked by an immovable obstacle such as a table or the other Hand. In such cases, they can beep to inform the Brain of the difficulty. <file_sep>[Exercise 15.5 \[hmm-likelihood-exercise\]](ex_5/) Equation ([matrix-filtering-equation](#/)) describes the filtering process for the matrix formulation of HMMs. Give a similar equation for the calculation of likelihoods, which was described generically in Equation ([forward-likelihood-equation](#/)). <file_sep>[Exercise 23.19](ex_19/) The $D_i$ values for the sentence in Figure [mt-alignment-figure](#/) sum to 0. Will that be true of every translation pair? Prove it or give a counterexample. <file_sep>[Exercise 15.11](ex_11/) This exercise is concerned with filtering in an environment with no landmarks. Consider a vacuum robot in an empty room, represented by an $n \times m$ rectangular grid. The robot’s location is hidden; the only evidence available to the observer is a noisy location sensor that gives an approximation to the robot’s location. If the robot is at location $(x, y)$ then with probability .1 the sensor gives the correct location, with probability .05 each it reports one of the 8 locations immediately surrounding $(x, y)$, with probability .025 each it reports one of the 16 locations that surround those 8, and with the remaining probability of .1 it reports “no reading.” The robot’s policy is to pick a direction and follow it with probability .7 on each step; the robot switches to a randomly selected new heading with probability .3 (or with probability 1 if it encounters a wall). Implement this as an HMM and do filtering to track the robot. How accurately can we track the robot’s path? <center> <b id="switching-kf-figure">Figure [switching-kf-figure]</b> A Bayesian network representation of a switching Kalman filter. The switching variable $S_t$ is a discrete state variable whose value determines the transition model for the continuous state variables $\textbf{X}_t$. For any discrete state $\textit{i}$, the transition model $\textbf{P}(\textbf{X}_{t+1}|\textbf{X}_t,S_t= i)$ is a linear Gaussian model, just as in a regular Kalman filter. The transition model for the discrete state, $\textbf{P}(S_{t+1}|S_t)$, can be thought of as a matrix, as in a hidden Markov model. </center> ![switching-kf-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/switching-kf.svg) <file_sep>[Exercise 10.9](ex_9/) Prove that backward search with PDDL problems is complete. <file_sep>[Exercise 17.16](ex_16/) What is the time complexity of $d$ steps of POMDP value iteration for a sensorless environment? <file_sep>[Exercise 18.32](ex_32/) The neural network whose learning performance is measured in Figure [restaurant-back-prop-figure](#/) has four hidden nodes. This number was chosen somewhat arbitrarily. Use a cross-validation method to find the best number of hidden nodes. <file_sep>[Exercise 13.17](ex_17/) Suppose you are given a coin that lands ${heads}$ with probability $x$ and ${tails}$ with probability $1 - x$. Are the outcomes of successive flips of the coin independent of each other given that you know the value of $x$? Are the outcomes of successive flips of the coin independent of each other if you do *not* know the value of $x$? Justify your answer. <file_sep>[Exercise 25.5 \[inverse-kinematics-exercise\]](ex_5/) Consider the robot arm shown in Figure [FigArm1](#/). Assume that the robot’s base element is 60cm long and that its upper arm and forearm are each 40cm long. As argued on page [inverse-kinematics-not-unique](#/), the inverse kinematics of a robot is often not unique. State an explicit closed-form solution of the inverse kinematics for this arm. Under what exact conditions is the solution unique? <file_sep>[Exercise 24.7](ex_7/) Which of the following are true, and which are false? 1. Finding corresponding points in stereo images is the easiest phase of the stereo depth-finding process. 2. In stereo views of the same scene, greater accuracy is obtained in the depth calculations if the two camera positions are farther apart. 3. Lines with equal lengths in the scene always project to equal lengths in the image. 4. Straight lines in the image necessarily correspond to straight lines in the scene. <center> <b id="bottle-figure">Figure [bottle-figure]</b> Top view of a two-camera vision system observing a bottle with a wall behind it. </center> ![bottle-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/bottle-stereo.svg) <file_sep>[Exercise 12.16](ex_16/) This exercise concerns the problem of planning a route for a robot to take from one city to another. The basic action taken by the robot is ${Go}(x,y)$, which takes it from city $x$ to city $y$ if there is a route between those cities. ${Road}(x, y)$ is true if and only if there is a road connecting cities $x$ and $y$; if there is, then ${Distance}(x, y)$ gives the length of the road. See the map on page [romania-distances-figure](#/) for an example. The robot begins in Arad and must reach Bucharest. 1. Write a suitable logical description of the initial situation of the robot. 2. Write a suitable logical query whose solutions provide possible paths to the goal. 3. Write a sentence describing the ${Go}$ action. 4. Now suppose that the robot consumes fuel at the rate of .02 gallons per mile. The robot starts with 20 gallons of fuel. Augment your representation to include these considerations. 5. Now suppose some of the cities have gas stations at which the robot can fill its tank. Extend your representation and write all the rules needed to describe gas stations, including the ${Fillup}$ action. <file_sep>[Exercise 18.8](ex_8/) Consider the following data set comprised of three binary input attributes ($A_1, A_2$, and $A_3$) and one binary output: | $\quad \textbf{Example}$ | $\quad A_1\quad$ | $\quad A_2\quad$ | $\quad A_3\quad$ | $\quad Output\space y$ | | --- | --- | --- | --- | --- | | $\textbf{x}_1$ | 1 | 0 | 0 | 0 | | $\textbf{x}_2$ | 1 | 0 | 1 | 0 | | $\textbf{x}_3$ | 0 | 1 | 0 | 0 | | $\textbf{x}_4$ | 1 | 1 | 1 | 1 | | $\textbf{x}_5$ | 1 | 1 | 0 | 1 | Use the algorithm in Figure [DTL-algorithm](#/) (page [DTL-algorithm](#/)) to learn a decision tree for these data. Show the computations made to determine the attribute to split at each node. <file_sep>[Exercise 23.22](ex_22/) We forgot to mention that the text in Exercise [washing-clothes-exercise](#/) is entitled “Washing Clothes.” Reread the text and answer the questions in Exercise [washing-clothes2-exercise](#/). Did you do better this time? Bransford and Johnson [@Bransford+Johnson:1973] used this text in a controlled experiment and found that the title helped significantly. What does this tell you about how language and memory works? <file_sep>[Exercise 16.1 \[almanac-game\]](ex_1/) (Adapted from <NAME>.) This exercise concerns the **Almanac Game**, which is used by decision analysts to calibrate numeric estimation. For each of the questions that follow, give your best guess of the answer, that is, a number that you think is as likely to be too high as it is to be too low. Also give your guess at a 25th percentile estimate, that is, a number that you think has a 25% chance of being too high, and a 75% chance of being too low. Do the same for the 75th percentile. (Thus, you should give three estimates in all—low, median, and high—for each question.) 1. Number of passengers who flew between New York and Los Angeles in 1989. 2. Population of Warsaw in 1992. 3. Year in which Coronado discovered the Mississippi River. 4. Number of votes received by <NAME> in the 1976 presidential election. 5. Age of the oldest living tree, as of 2002. 6. Height of the Hoover Dam in feet. 7. Number of eggs produced in Oregon in 1985. 8. Number of Buddhists in the world in 1992. 9. Number of deaths due to AIDS in the United States in 1981. 10. Number of U.S. patents granted in 1901. The correct answers appear after the last exercise of this chapter. From the point of view of decision analysis, the interesting thing is not how close your median guesses came to the real answers, but rather how often the real answer came within your 25% and 75% bounds. If it was about half the time, then your bounds are accurate. But if you’re like most people, you will be more sure of yourself than you should be, and fewer than half the answers will fall within the bounds. With practice, you can calibrate yourself to give realistic bounds, and thus be more useful in supplying information for decision making. Try this second set of questions and see if there is any improvement: 1. Year of birth of Zsa Zsa Gabor. 2. Maximum distance from Mars to the sun in miles. 3. Value in dollars of exports of wheat from the United States in 1992. 4. Tons handled by the port of Honolulu in 1991. 5. Annual salary in dollars of the governor of California in 1993. 6. Population of San Diego in 1990. 7. Year in which <NAME> founded Providence, Rhode Island. 8. Height of Mt. Kilimanjaro in feet. 9. Length of the Brooklyn Bridge in feet. 10. Number of deaths due to automobile accidents in the United States in 1992. <file_sep>[Exercise 10.2](ex_2/) Describe the differences and similarities between problem solving and planning. <file_sep>[Exercise 23.8](ex_8/) Collect some examples of time expressions, such as “two o’clock,” “midnight,” and “12:46.” Also think up some examples that are ungrammatical, such as “thirteen o’clock” or “half past two fifteen.” Write a grammar for the time language. <file_sep>[Exercise 16.9](ex_9/) Consider the Allais paradox described on page [allais-page](#/): an agent who prefers $B$ over $A$ (taking the sure thing), and $C$ over $D$ (taking the higher EMV) is not acting rationally, according to utility theory. Do you think this indicates a problem for the agent, a problem for the theory, or no problem at all? Explain. <file_sep> Imagine that, in Exercise \[two-friends-exercise\], one of the friends wants to avoid the other. The problem then becomes a two-player game. We assume now that the players take turns moving. The game ends only when the players are on the same node; the terminal payoff to the pursuer is minus the total time taken. (The evader “wins” by never losing.) An example is shown in Figure. <a href="#pursuit-evasion-game-figure">pursuit-evasion-game-figure</a><br> 1. Copy the game tree and mark the values of the terminal nodes.<br> 2. Next to each internal node, write the strongest fact you can infer about its value (a number, one or more inequalities such as “$\geq 14$”, or a “?”).<br> 3. Beneath each question mark, write the name of the node reached by that branch.<br> 4. Explain how a bound on the value of the nodes in (c) can be derived from consideration of shortest-path lengths on the map, and derive such bounds for these nodes. Remember the cost to get to each leaf as well as the cost to solve it.<br> 5. Now suppose that the tree as given, with the leaf bounds from (d), is evaluated from left to right. Circle those “?” nodes that would *not* need to be expanded further, given the bounds from part (d), and cross out those that need not be considered at all.<br> 6. Can you prove anything in general about who wins the game on a map that is a tree?<br> <file_sep>[Exercise 11.7](ex_7/) Some of the operations in standard programming languages can be modeled as actions that change the state of the world. For example, the assignment operation changes the contents of a memory location, and the print operation changes the state of the output stream. A program consisting of these operations can also be considered as a plan, whose goal is given by the specification of the program. Therefore, planning algorithms can be used to construct programs that achieve a given specification. 1. Write an action schema for the assignment operator (assigning the value of one variable to another). Remember that the original value will be overwritten! 2. Show how object creation can be used by a planner to produce a plan for exchanging the values of two variables by using a temporary variable. <file_sep>[Exercise 20.3 \[candy-trade-exercise\]](ex_3/) Suppose that Ann’s utilities for cherry and lime candies are $c_A$ and $\ell_A$, whereas Bob’s utilities are $c_B$ and $\ell_B$. (But once Ann has unwrapped a piece of candy, Bob won’t buy it.) Presumably, if Bob likes lime candies much more than Ann, it would be wise for Ann to sell her bag of candies once she is sufficiently sure of its lime content. On the other hand, if Ann unwraps too many candies in the process, the bag will be worth less. Discuss the problem of determining the optimal point at which to sell the bag. Determine the expected utility of the optimal procedure, given the prior distribution from Section [statistical-learning-section](#/). <file_sep>[Exercise 18.25](ex_25/) A simple perceptron cannot represent xor (or, generally, the parity function of its inputs). Describe what happens to the weights of a four-input, hard-threshold perceptron, beginning with all weights set to 0.1, as examples of the parity function arrive. <file_sep>[Exercise 18.17](ex_17/) Prove that a decision list can represent the same function as a decision tree while using at most as many rules as there are leaves in the decision tree for that function. Give an example of a function represented by a decision list using strictly fewer rules than the number of leaves in a minimal-sized decision tree for that same function. <file_sep>[Exercise 19.7 \[foil-literals-exercise\]](ex_7/) Suppose that is considering adding a literal to a clause using a binary predicate $P$ and that previous literals (including the head of the clause) contain five different variables. 1. How many functionally different literals can be generated? Two literals are functionally identical if they differ only in the names of the *new* variables that they contain. 2. Can you find a general formula for the number of different literals with a predicate of arity $r$ when there are $n$ variables previously used? 3. Why does not allow literals that contain no previously used variables? <file_sep>[Exercise 13.22](ex_22/) Suppose you are given a bag containing $n$ unbiased coins. You are told that $n-1$ of these coins are normal, with heads on one side and tails on the other, whereas one coin is a fake, with heads on both sides. 1. Suppose you reach into the bag, pick out a coin at random, flip it, and get a head. What is the (conditional) probability that the coin you chose is the fake coin? 2. Suppose you continue flipping the coin for a total of $k$ times after picking it and see $k$ heads. Now what is the conditional probability that you picked the fake coin? 3. Suppose you wanted to decide whether the chosen coin was fake by flipping it $k$ times. The decision procedure returns ${fake}$ if all $k$ flips come up heads; otherwise it returns ${normal}$. What is the (unconditional) probability that this procedure makes an error? <file_sep>[Exercise 14.13](ex_13/) In your local nuclear power station, there is an alarm that senses when a temperature gauge exceeds a given threshold. The gauge measures the temperature of the core. Consider the Boolean variables $A$ (alarm sounds), $F_A$ (alarm is faulty), and $F_G$ (gauge is faulty) and the multivalued nodes $G$ (gauge reading) and $T$ (actual core temperature). 1. Draw a Bayesian network for this domain, given that the gauge is more likely to fail when the core temperature gets too high. 2. Is your network a polytree? Why or why not? 3. Suppose there are just two possible actual and measured temperatures, normal and high; the probability that the gauge gives the correct temperature is $x$ when it is working, but $y$ when it is faulty. Give the conditional probability table associated with $G$. 4. Suppose the alarm works correctly unless it is faulty, in which case it never sounds. Give the conditional probability table associated with $A$. 5. Suppose the alarm and gauge are working and the alarm sounds. Calculate an expression for the probability that the temperature of the core is too high, in terms of the various conditional probabilities in the network. <file_sep>[Exercise 11.4](ex_4/) Suppose that the optimistic reachable set of a high-level plan is a superset of the goal set; can anything be concluded about whether the plan achieves the goal? What if the pessimistic reachable set doesn’t intersect the goal set? Explain. <file_sep>[Exercise 13.24](ex_24/) This exercise investigates the way in which conditional independence relationships affect the amount of information needed for probabilistic calculations. 1. Suppose we wish to calculate $P(h{{\,|\,}}e_1,e_2)$ and we have no conditional independence information. Which of the following sets of numbers are sufficient for the calculation? 1. ${\textbf{P}}(E_1,E_2)$, ${\textbf{P}}(H)$, ${\textbf{P}}(E_1{{\,|\,}}H)$, ${\textbf{P}}(E_2{{\,|\,}}H)$ 2. ${\textbf{P}}(E_1,E_2)$, ${\textbf{P}}(H)$, ${\textbf{P}}(E_1,E_2{{\,|\,}}H)$ 3. ${\textbf{P}}(H)$, ${\textbf{P}}(E_1{{\,|\,}}H)$, ${\textbf{P}}(E_2{{\,|\,}}H)$ 2. Suppose we know that ${\textbf{P}}(E_1{{\,|\,}}H,E_2)={\textbf{P}}(E_1{{\,|\,}}H)$ for all values of $H$, $E_1$, $E_2$. Now which of the three sets are sufficient? <file_sep>[Exercise 15.13 \[kalman-update-exercise\]](ex_13/) Complete the missing step in the derivation of Equation ([kalman-one-step-equation](#/)) on page [kalman-one-step-equation](#/), the first update step for the one-dimensional Kalman filter. <file_sep>[Exercise 14.18 \[VE-exercise\]](ex_18/) Consider the variable elimination algorithm in Figure [elimination-ask-algorithm](#/) (page [elimination-ask-algorithm](#/)). 1. Section [exact-inference-section](#/) applies variable elimination to the query $${\textbf{P}}({Burglary}{{\,|\,}}{JohnCalls}{{\,=\,}}{true},{MaryCalls}{{\,=\,}}{true})\ .$$ Perform the calculations indicated and check that the answer is correct. 2. Count the number of arithmetic operations performed, and compare it with the number performed by the enumeration algorithm. 3. Suppose a network has the form of a *chain*: a sequence of Boolean variables $X_1,\ldots, X_n$ where ${Parents}(X_i){{\,=\,}}\{X_{i-1}\}$ for $i{{\,=\,}}2,\ldots,n$. What is the complexity of computing ${\textbf{P}}(X_1{{\,|\,}}X_n{{\,=\,}}{true})$ using enumeration? Using variable elimination? 4. Prove that the complexity of running variable elimination on a polytree network is linear in the size of the tree for any variable ordering consistent with the network structure. <file_sep>[Exercise 13.27](ex_27/) Write out a general algorithm for answering queries of the form ${\textbf{P}}({Cause}{{\,|\,}}\textbf{e})$, using a naive Bayes distribution. Assume that the evidence $\textbf{e}$ may assign values to *any subset* of the effect variables. <file_sep> Consider the problem of moving $k$ knights from $k$ starting squares $s_1,\ldots,s_k$ to $k$ goal squares $g_1,\ldots,g_k$, on an unbounded chessboard, subject to the rule that no two knights can land on the same square at the same time. Each action consists of moving *up to* $k$ knights simultaneously. We would like to complete the maneuver in the smallest number of actions.<br> 1. What is the maximum branching factor in this state space, expressed as a function of $k$?<br> 2. Suppose $h_i$ is an admissible heuristic for the problem of moving knight $i$ to goal $g_i$ by itself. Which of the following heuristics are admissible for the $k$-knight problem? Of those, which is the best?<br> 1. $\min\{h_1,\ldots,h_k\}$.<br> 2. $\max\{h_1,\ldots,h_k\}$.<br> 3. $\sum_{i= 1}^{k} h_i$.<br> 3. Repeat (b) for the case where you are allowed to move only one knight at a time. <file_sep>[Exercise 15.19 \[battery-sequence-exercise\]](ex_19/) This exercise analyzes in more detail the persistent-failure model for the battery sensor in Figure [battery-persistence-figure](#/)(a) (page [battery-persistence-figure](#/)). 1. Figure [battery-persistence-figure](#/)(b) stops at $t=32$. Describe qualitatively what should happen as $t\to\infty$ if the sensor continues to read 0. 2. Suppose that the external temperature affects the battery sensor in such a way that transient failures become more likely as temperature increases. Show how to augment the DBN structure in Figure [battery-persistence-figure](#/)(a), and explain any required changes to the CPTs. 3. Given the new network structure, can battery readings be used by the robot to infer the current temperature? <file_sep> In the following, a “max” tree consists only of max nodes, whereas an “expectimax” tree consists of a max node at the root with alternating layers of chance and max nodes. At chance nodes, all outcome probabilities are nonzero. The goal is to *find the value of the root* with a bounded-depth search.<br> 1. Assuming that leaf values are finite but unbounded, is pruning (as in alpha–beta) ever possible in a max tree? Give an example, or explain why not.<br> 2. Is pruning ever possible in an expectimax tree under the same conditions? Give an example, or explain why not.<br> 3. If leaf values are constrained to be in the range $[0,1]$, is pruning ever possible in a max tree? Give an example, or explain why not.<br> 4. If leaf values are constrained to be in the range $[0,1]$, is pruning ever possible in an expectimax tree? Give an example (qualitatively different from your example in (e), if any), or explain why not.<br> 5. If leaf values are constrained to be nonnegative, is pruning ever possible in a max tree? Give an example, or explain why not.<br> 6. If leaf values are constrained to be nonnegative, is pruning ever possible in an expectimax tree? Give an example, or explain why not.<br> 7. Consider the outcomes of a chance node in an expectimax tree. Which of the following evaluation orders is most likely to yield pruning opportunities: (i) Lowest probability first; (ii) Highest probability first; (iii) Doesn’t make any difference? <file_sep>--- layout: exercise title: Exercise 13.25 permalink: /probability-exercises/ex_25/ breadcrumb: 13-Quantifying-Uncertainity --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="probability-exercises" data-exercise="ex_25" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 23.2](ex_2/) An *HMM grammar* is essentially a standard HMM whose state variable is $N$ (nonterminal, with values such as $Det$, $Adjective$, $Noun$ and so on) and whose evidence variable is $W$ (word, with values such as $is$, $duck$, and so on). The HMM model includes a prior ${\textbf{P}}(N_0)$, a transition model ${\textbf{P}}(N_{t+1}|N_t)$, and a sensor model ${\textbf{P}}(W_t|N_t)$. Show that every HMM grammar can be written as a PCFG. \[Hint: start by thinking about how the HMM prior can be represented by PCFG rules for the sentence symbol. You may find it helpful to illustrate for the particular HMM with values $A$, $B$ for $N$ and values $x$, $y$ for $W$.\] <file_sep>[Exercise 12.15](ex_15/) State the interval-algebra relation that holds between every pair of the following real-world events: > $LK$: The life of President Kennedy. > $IK$: The infancy of President Kennedy. > $PK$: The presidency of President Kennedy. > $LJ$: The life of President Johnson. > $PJ$: The presidency of President Johnson. > $LO$: The life of President Obama. <file_sep>[Exercise 15.17](ex_17/) For the DBN specified in Exercise [sleep1-exercise](#/) and for the evidence values $$ \textbf{e}_1 = not\space red\space eyes,\space not\space sleeping\space in\space class $$ $$ \textbf{e}_2 = red\space eyes,\space not\space sleeping\space in\space class $$ $$ \textbf{e}_3 = red\space eyes,\space sleeping\space in\space class $$ perform the following computations: 1. State estimation: Compute $$P({EnoughSleep}_t | \textbf{e}_{1:t})$$ for each of $t = 1,2,3$. 2. Smoothing: Compute $$P({EnoughSleep}_t | \textbf{e}_{1:3})$$ for each of $t = 1,2,3$. 3. Compare the filtered and smoothed probabilities for $t=1$ and $t=2$. <file_sep>[Exercise 24.2](ex_2/) Consider a picture of a white sphere floating in front of a black backdrop. The image curve separating white pixels from black pixels is sometimes called the “outline” of the sphere. Show that the outline of a sphere, viewed in a perspective camera, can be an ellipse. Why do spheres not look like ellipses to you? <file_sep>[Exercise 25.10 \[robot-exploration-exercise\]](ex_10/) Consider the simplified robot shown in Figure [FigEx3](#FigEx3). Suppose the robot’s Cartesian coordinates are known at all times, as are those of its goal location. However, the locations of the obstacles are unknown. The robot can sense obstacles in its immediate proximity, as illustrated in this figure. For simplicity, let us assume the robot’s motion is noise-free, and the state space is discrete. Figure [FigEx3](#FigEx3) is only one example; in this exercise you are required to address all possible grid worlds with a valid path from the start to the goal location. 1. Design a deliberate controller that guarantees that the robot always reaches its goal location if at all possible. The deliberate controller can memorize measurements in the form of a map that is being acquired as the robot moves. Between individual moves, it may spend arbitrary time deliberating. 2. Now design a *reactive* controller for the same task. This controller may not memorize past sensor measurements. (It may not build a map!) Instead, it has to make all decisions based on the current measurement, which includes knowledge of its own location and that of the goal. The time to make a decision must be independent of the environment size or the number of past time steps. What is the maximum number of steps that it may take for your robot to arrive at the goal? 3. How will your controllers from (a) and (b) perform if any of the following six conditions apply: continuous state space, noise in perception, noise in motion, noise in both perception and motion, unknown location of the goal (the goal can be detected only when within sensor range), or moving obstacles. For each condition and each controller, give an example of a situation where the robot fails (or explain why it cannot fail). <file_sep>[Exercise 23.13](ex_13/) Consider the following PCFG: > $S \rightarrow NP \space VP[1.0] $ > $NP \rightarrow \textit{Noun}[0.6] \space|\space \textit{Pronoun}[0.4] $ > $VP \rightarrow \textit{Verb} \space NP[0.8] \space|\space \textit{Modal}\space \textit{Verb}[0.2]$ > $\textit{Noun} \rightarrow \textbf{can}[0.1] \space|\space \textbf{fish}[0.3] \space|\space ...$ > $\textit{Pronoun} \rightarrow \textbf{I}[0.4] \space|\space ...$ > $\textit{Verb} \rightarrow \textbf{can}[0.01] \space|\space \textbf{fish}[0.1] \space|\space ...$ > $\textit{Modal} \rightarrow \textbf{can}[0.3] \space|\space ...$ The sentence “I can fish” has two parse trees with this grammar. Show the two trees, their prior probabilities, and their conditional probabilities, given the sentence. <file_sep>[Exercise 16.11 \[assessment-exercise\]](ex_11/) Assess your own utility for different incremental amounts of money by running a series of preference tests between some definite amount $M_1$ and a lottery $[p,M_2; (1-p), 0]$. Choose different values of $M_1$ and $M_2$, and vary $p$ until you are indifferent between the two choices. Plot the resulting utility function. <file_sep>--- layout: exercise title: Exercise 7.2 permalink: /knowledge-logic-exercises/ex_2/ breadcrumb: 7-Logical-Agents --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="knowledge-logic-exercises" data-exercise="ex_2" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 18.16](ex_16/) Construct a *decision list* to classify the data below. Select tests to be as small as possible (in terms of attributes), breaking ties among tests with the same number of attributes by selecting the one that classifies the greatest number of examples correctly. If multiple tests have the same number of attributes and classify the same number of examples, then break the tie using attributes with lower index numbers (e.g., select $A_1$ over $A_2$). | | $\quad A_1\quad$ | $\quad A_2\quad$ | $\quad A_3\quad$ | $\quad A_y\quad$ | $\quad y\quad$ | | --- | --- | --- | --- | --- | --- | | $\textbf{x}_1$ | 1 | 0 | 0 | 0 | 1 | | $\textbf{x}_2$ | 1 | 0 | 1 | 1 | 1 | | $\textbf{x}_3$ | 0 | 1 | 0 | 0 | 1 | | $\textbf{x}_4$ | 0 | 1 | 1 | 0 | 0 | | $\textbf{x}_5$ | 1 | 1 | 0 | 1 | 1 | | $\textbf{x}_6$ | 0 | 1 | 0 | 1 | 0 | | $\textbf{x}_7$ | 0 | 0 | 1 | 1 | 1 | | $\textbf{x}_8$ | 0 | 0 | 1 | 0 | 0 | <file_sep>[Exercise 10.5](ex_5/) The original {Strips} planner was designed to control Shakey the robot. Figure [shakey-figure](#shakey-figure) shows a version of Shakey’s world consisting of four rooms lined up along a corridor, where each room has a door and a light switch. The actions in Shakey’s world include moving from place to place, pushing movable objects (such as boxes), climbing onto and down from rigid objects (such as boxes), and turning light switches on and off. The robot itself could not climb on a box or toggle a switch, but the planner was capable of finding and printing out plans that were beyond the robot’s abilities. Shakey’s six actions are the following: - ${Go}(x,y,r)$, which requires that Shakey be ${At}$ $x$ and that $x$ and $y$ are locations ${In}$ the same room $r$. By convention a door between two rooms is in both of them. - Push a box $b$ from location $x$ to location $y$ within the same room: ${Push}(b,x,y,r)$. You will need the predicate ${Box}$ and constants for the boxes. - Climb onto a box from position $x$: ${ClimbUp}(x, b)$; climb down from a box to position $x$: ${ClimbDown}(b, x)$. We will need the predicate ${On}$ and the constant ${Floor}$. - Turn a light switch on or off: ${TurnOn}(s,b)$; ${TurnOff}(s,b)$. To turn a light on or off, Shakey must be on top of a box at the light switch’s location. Write PDDL sentences for Shakey’s six actions and the initial state from Figure [shakey-figure](#shakey-figure). Construct a plan for Shakey to get ${Box}{}_2$ into ${Room}{}_2$. <center> <b id="shakey-figure">Figure [shakey-figure]</b> Shakey's world. Shakey can move between landmarks within a room, can pass through the door between rooms, can climb climbable objects and push pushable objects, and can flip light switches. </center> ![shakey-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/shakey2.svg) <file_sep>--- layout: chapter title: Constraint Satisfaction Problems permalink: /csp-exercises/ --- {% include mathjax_support %} # 6. Constraint Satisfaction Problems <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.1');" href="#"><i id="ex6.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.1');" href="#"><i id="ex6.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.2');" href="#"><i id="ex6.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.2');" href="#"><i id="ex6.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3 (crossword-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.3');" href="#"><i id="ex6.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.3');" href="#"><i id="ex6.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4 (csp-definition-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.4');" href="#"><i id="ex6.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.4');" href="#"><i id="ex6.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.5');" href="#"><i id="ex6.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.5');" href="#"><i id="ex6.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6 (nary-csp-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.6');" href="#"><i id="ex6.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.6');" href="#"><i id="ex6.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7 (zebra-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.7');" href="#"><i id="ex6.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.7');" href="#"><i id="ex6.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.8');" href="#"><i id="ex6.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.8');" href="#"><i id="ex6.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.9');" href="#"><i id="ex6.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.9');" href="#"><i id="ex6.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.10');" href="#"><i id="ex6.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.10');" href="#"><i id="ex6.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.11');" href="#"><i id="ex6.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.11');" href="#"><i id="ex6.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.12');" href="#"><i id="ex6.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.12');" href="#"><i id="ex6.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.13');" href="#"><i id="ex6.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.13');" href="#"><i id="ex6.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex14/' class="p-2">Exercise 14 (ac4-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.14');" href="#"><i id="ex6.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.14');" href="#"><i id="ex6.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex15/' class="p-2">Exercise 15 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.15');" href="#"><i id="ex6.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.15');" href="#"><i id="ex6.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex16/' class="p-2">Exercise 16 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.16');" href="#"><i id="ex6.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.14');" href="#"><i id="ex6.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex17/' class="p-2">Exercise 17 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.17');" href="#"><i id="ex6.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.17');" href="#"><i id="ex6.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex18/' class="p-2">Exercise 18 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.18');" href="#"><i id="ex6.18" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.18');" href="#"><i id="ex6.18" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_18/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex19/' class="p-2">Exercise 19 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.19');" href="#"><i id="ex6.19" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.19');" href="#"><i id="ex6.19" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_19/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex20/' class="p-2">Exercise 20 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex6.20');" href="#"><i id="ex6.20" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex6.20');" href="#"><i id="ex6.20" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_20/question.md %}</p> </div> </div> <br> <file_sep>[Exercise 25.3 \[AB-manipulator-ex\]](ex_3/) Consider a robot with two simple manipulators, as shown in figure [figRobot2](#figRobot2). Manipulator A is a square block of side 2 which can slide back and on a rod that runs along the x-axis from x=$-$10 to x=10. Manipulator B is a square block of side 2 which can slide back and on a rod that runs along the y-axis from y=-10 to y=10. The rods lie outside the plane of manipulation, so the rods do not interfere with the movement of the blocks. A configuration is then a pair ${\langle}x,y{\rangle}$ where $x$ is the x-coordinate of the center of manipulator A and where $y$ is the y-coordinate of the center of manipulator B. Draw the configuration space for this robot, indicating the permitted and excluded zones. <file_sep>[Exercise 22.6](ex_6/) This exercise concerns the classification of spam email. Create a corpus of spam email and one of non-spam mail. Examine each corpus and decide what features appear to be useful for classification: unigram words? bigrams? message length, sender, time of arrival? Then train a classification algorithm (decision tree, naive Bayes, SVM, logistic regression, or some other algorithm of your choosing) on a training set and report its accuracy on a test set. <file_sep>[Exercise 11.9 \[conformant-flip-literal-exercise\]](ex_9/) Suppose the ${Flip}$ action always changes the truth value of variable $L$. Show how to define its effects by using an action schema with conditional effects. Show that, despite the use of conditional effects, a 1-CNF belief state representation remains in 1-CNF after a ${Flip}$. <file_sep>[Exercise 11.13](ex_13/) The following quotes are from the backs of shampoo bottles. Identify each as an unconditional, conditional, or execution-monitoring plan. (a) “Lather. Rinse. Repeat.” (b) “Apply shampoo to scalp and let it remain for several minutes. Rinse and repeat if necessary.” (c) “See a doctor if problems persist.” <file_sep>[Exercise 13.1](ex_1/) Show from first principles that $P(a{{\,|\,}}b\land a) = 1$. <file_sep> This exercise looks into the relationship between clauses and implication sentences.<br> 1. Show that the clause $(\lnot P_1 \lor \cdots \lor \lnot P_m \lor Q)$ is logically equivalent to the implication sentence $(P_1 \land \cdots \land P_m) {\;{\Rightarrow}\;}Q$.<br> 2. Show that every clause (regardless of the number of positive literals) can be written in the form $(P_1 \land \cdots \land P_m) {\;{\Rightarrow}\;}(Q_1 \lor \cdots \lor Q_n)$, where the $P$s and $Q$s are proposition symbols. A knowledge base consisting of such sentences is in implicative normal form or **Kowalski form** @Kowalski:1979.<br> 3. Write down the full resolution rule for sentences in implicative normal form.<br> <file_sep>--- layout: exercise title: Exercise 17.7 permalink: /complex-decisions-exercises/ex_7/ breadcrumb: 17-Making-Complex-Decision --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="complex-decisions-exercises" data-exercise="ex_7" data-rating="0"></i></div> {% include_relative question.md %} <file_sep> Here are two sentences in the language of first-order logic:<br> - **(A)** ${\forall\,x\;\;} {\exists\,y\;\;} ( x \geq y )$ - **(B)** ${\exists\,y\;\;} {\forall\,x\;\;} ( x \geq y )$ 1. Assume that the variables range over all the natural numbers $0,1,2,\ldots, \infty$ and that the “$\geq$” predicate means “is greater than or equal to.” Under this interpretation, translate (A) and (B) into English.<br> 2. Is (A) true under this interpretation?<br> 3. Is (B) true under this interpretation?<br> 4. Does (A) logically entail (B)?<br> 5. Does (B) logically entail (A)?<br> 6. Using resolution, try to prove that (A) follows from (B). Do this even if you think that (B) does not logically entail (A); continue until the proof breaks down and you cannot proceed (if it does break down). Show the unifying substitution for each resolution step. If the proof fails, explain exactly where, how, and why it breaks down.<br> 7. Now try to prove that (B) follows from (A).<br> <file_sep>[Exercise 13.28 \[naive-bayes-retrieval-exercise\]](ex_28/) Text categorization is the task of assigning a given document to one of a fixed set of categories on the basis of the text it contains. Naive Bayes models are often used for this task. In these models, the query variable is the document category, and the “effect” variables are the presence or absence of each word in the language; the assumption is that words occur independently in documents, with frequencies determined by the document category. 1. Explain precisely how such a model can be constructed, given as “training data” a set of documents that have been assigned to categories. 2. Explain precisely how to categorize a new document. 3. Is the conditional independence assumption reasonable? Discuss. <file_sep>[Exercise 10.18 \[disjunctive-satplan-exercise\]](ex_18/) In the $SATPlan$ algorithm in Figure [satplan-agent-algorithm](#/) (page [satplan-agent-algorithm](#/)), each call to the satisfiability algorithm asserts a goal $g^T$, where $T$ ranges from 0 to $T_{max}$. Suppose instead that the satisfiability algorithm is called only once, with the goal $g^0 \vee g^1 \vee \cdots \vee g^{T_{max}}$. 1. Will this always return a plan if one exists with length less than or equal to $T_{max}$? 2. Does this approach introduce any new spurious “solutions”? 3. Discuss how one might modify a satisfiability algorithm such as $WalkSAT$ so that it finds short solutions (if they exist) when given a disjunctive goal of this form. <file_sep>[Exercise 12.18 \[exchange-rates-exercise\]](ex_18/) Construct a representation for exchange rates between currencies that allows for daily fluctuations. <file_sep>--- layout: exercise title: Exercise 15.17 permalink: /dbn-exercises/ex_17/ breadcrumb: 15-Probabilistic-Reasoning-Over-Time --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="dbn-exercises" data-exercise="ex_17" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 23.3](ex_3/) Consider the following PCFG for simple verb phrases: > 0.1: VP $\rightarrow$ Verb > 0.2: VP $\rightarrow$ Copula Adjective > 0.5: VP $\rightarrow$ Verb the Noun > 0.2: VP $\rightarrow$ VP Adverb > 0.5: Verb $\rightarrow$ is > 0.5: Verb $\rightarrow$ shoots > 0.8: Copula $\rightarrow$ is > 0.2: Copula $\rightarrow$ seems > 0.5: Adjective $\rightarrow$ **unwell** > 0.5: Adjective $\rightarrow$ **well** > 0.5: Adverb $\rightarrow$ **well** > 0.5: Adverb $\rightarrow$ **badly** > 0.6: Noun $\rightarrow$ **duck** > 0.4: Noun $\rightarrow$ **well** 1. Which of the following have a nonzero probability as a VP? (i) shoots the duck well well well(ii) seems the well well(iii) shoots the unwell well badly 2. What is the probability of generating “is well well”? 3. What types of ambiguity are exhibited by the phrase in (b)? 4. Given any PCFG, is it possible to calculate the probability that the PCFG generates a string of exactly 10 words? <file_sep>[Exercise 12.13 \[namematch-exercise\]](ex_13/) Add sentences to extend the definition of the predicate ${Name}(s, c)$ so that a string such as “laptop computer” matches the appropriate category names from a variety of stores. Try to make your definition general. Test it by looking at ten online stores, and at the category names they give for three different categories. For example, for the category of laptops, we found the names “Notebooks,” “Laptops,” “Notebook Computers,” “Notebook,” “Laptops and Notebooks,” and “Notebook PCs.” Some of these can be covered by explicit ${Name}$ facts, while others could be covered by sentences for handling plurals, conjunctions, etc. <file_sep>[Exercise 23.14](ex_14/) An augmented context-free grammar can represent languages that a regular context-free grammar cannot. Show an augmented context-free grammar for the language $a^nb^nc^n$. The allowable values for augmentation variables are 1 and $SUCCESSOR(n)$, where $n$ is a value. The rule for a sentence in this language is $$S(n) {{{{\;}}\rightarrow{{\;}}}}A(n) {{\;}}B(n) {{\;}}C(n) \ .$$ Show the rule(s) for each of ${\it A}$, ${\it B}$, and ${\it C}$. <file_sep> Suppose we put into a logical knowledge base a segment of the U.S. census data listing the age, city of residence, date of birth, and mother of every person, using social security numbers as identifying constants for each person. Thus, George’s age is given by ${Age}(\mbox{{443}}-{65}-{1282}}, {56})$. Which of the following indexing schemes S1–S5 enable an efficient solution for which of the queries Q1–Q4 (assuming normal backward chaining)?<br> <br> - **S1**: an index for each atom in each position.<br> - **S2**: an index for each first argument.<br> - **S3**: an index for each predicate atom.<br> - **S4**: an index for each *combination* of predicate and first argument.<br> - **S5**: an index for each *combination* of predicate and second argument and an index for each first argument.<br> - **Q1**: ${Age}(\mbox 443-44-4321,x)$<br> - **Q2**: ${ResidesIn}(x,{Houston})$<br> - **Q3**: ${Mother}(x,y)$<br> - **Q4**: ${Age}(x,{34}) \land {ResidesIn}(x,{TinyTownUSA})$<br> <file_sep>[Exercise 17.13](ex_13/) Consider the $4\times 3$ world shown in Figure [sequential-decision-world-figure](#/). 1. Implement an environment simulator for this environment, such that the specific geography of the environment is easily altered. Some code for doing this is already in the online code repository. 2. Create an agent that uses policy iteration, and measure its performance in the environment simulator from various starting states. Perform several experiments from each starting state, and compare the average total reward received per run with the utility of the state, as determined by your algorithm. 3. Experiment with increasing the size of the environment. How does the run time for policy iteration vary with the size of the environment? <file_sep>[Exercise 21.6](ex_6/) Adapt the vacuum world (Chapter [agents-chapter](#/)) for reinforcement learning by including rewards for squares being clean. Make the world observable by providing suitable percepts. Now experiment with different reinforcement learning agents. Is function approximation necessary for success? What sort of approximator works for this application? <file_sep>--- layout: chapter title: Intelligent Agent permalink: /agents-exercises/ breadcrumb: 2-Intelligent-Agent --- {% include mathjax_support %} # 2. Intelligent Agents <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.1');" href="#"><i id="ex2.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.1');" href="#"><i id="ex2.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2 (vacuum-rationality-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.2');" href="#"><i id="ex2.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.2');" href="#"><i id="ex2.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.3');" href="#"><i id="ex2.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.3');" href="#"><i id="ex2.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.4');" href="#"><i id="ex2.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.4');" href="#"><i id="ex2.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 (PEAS-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.5');" href="#"><i id="ex2.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.5');" href="#"><i id="ex2.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.6');" href="#"><i id="ex2.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.6');" href="#"><i id="ex2.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7 (agent-fn-prog-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.7');" href="#"><i id="ex2.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.7');" href="#"><i id="ex2.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.8');" href="#"><i id="ex2.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.8');" href="#"><i id="ex2.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.9');" href="#"><i id="ex2.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.9');" href="#"><i id="ex2.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> --- <div>The following exercises all concern the implementation of environments and agents for the vacuum-cleaner world. </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10 (vacuum-start-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.10');" href="#"><i id="ex2.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.10');" href="#"><i id="ex2.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.11');" href="#"><i id="ex2.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.11');" href="#"><i id="ex2.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12 (vacuum-motion-penalty-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.12');" href="#"><i id="ex2.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.12');" href="#"><i id="ex2.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13 (vacuum-unknown-geog-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.13');" href="#"><i id="ex2.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.13');" href="#"><i id="ex2.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14 (vacuum-bump-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.14');" href="#"><i id="ex2.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.14');" href="#"><i id="ex2.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15 (vacuum-finish-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex2.15');" href="#"><i id="ex2.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex2.15');" href="#"><i id="ex2.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <file_sep>[Exercise 23.9](ex_9/) Some linguists have argued as follows: > Children learning a language hear only *positive > examples* of the language and no *negative > examples*. Therefore, the hypothesis that “every possible > sentence is in the language” is consistent with all the observed > examples. Moreover, this is the simplest consistent hypothesis. > Furthermore, all grammars for languages that are supersets of the true > language are also consistent with the observed data. Yet children do > induce (more or less) the right grammar. It follows that they begin > with very strong innate grammatical constraints that rule out all of > these more general hypotheses *a priori*. Comment on the weak point(s) in this argument from a statistical learning viewpoint. <file_sep>[Exercise 12.3](ex_3/) Figure [ontology-figure](#/) shows the top levels of a hierarchy for everything. Extend it to include as many real categories as possible. A good way to do this is to cover all the things in your everyday life. This includes objects and events. Start with waking up, and proceed in an orderly fashion noting everything that you see, touch, do, and think about. For example, a random sampling produces music, news, milk, walking, driving, gas, Soda Hall, carpet, talking, Professor Fateman, chicken curry, tongue, \$ 7, sun, the daily newspaper, and so on. You should produce both a single hierarchy chart (on a large sheet of paper) and a listing of objects and categories with the relations satisfied by members of each category. Every object should be in a category, and every category should be in the hierarchy. <file_sep>[Exercise 13.15 \[independence-exercise\]](ex_15/) Show that the three forms of independence in Equation ([independence-equation](#/)) are equivalent. <file_sep>[Exercise 17.11 \[101x3-mdp-exercise\]](ex_11/) Consider the $101 \times 3$ world shown in Figure [grid-mdp-figure](#grid-mdp-figure)(b). In the start state the agent has a choice of two deterministic actions, *Up* or *Down*, but in the other states the agent has one deterministic action, *Right*. Assuming a discounted reward function, for what values of the discount $\gamma$ should the agent choose *Up* and for which *Down*? Compute the utility of each action as a function of $\gamma$. (Note that this simple example actually reflects many real-world situations in which one must weigh the value of an immediate action versus the potential continual long-term consequences, such as choosing to dump pollutants into a lake.) <file_sep>[Exercise 13.2 \[sum-to-1-exercise\]](ex_2/) Using the axioms of probability, prove that any probability distribution on a discrete random variable must sum to 1. <file_sep>[Exercise 16.16](ex_16/) Alex is given the choice between two games. In Game 1, a fair coin is flipped and if it comes up heads, Alex receives $$\$100$$. If the coin comes up tails, Alex receives nothing. In Game 2, a fair coin is flipped twice. Each time the coin comes up heads, Alex receives $$\$50$$, and Alex receives nothing for each coin flip that comes up tails. Assuming that Alex has a monotonically increasing utility function for money in the range \[\$0, \$100\], show mathematically that if Alex prefers Game 2 to Game 1, then Alex is risk averse (at least with respect to this range of monetary amounts). Show that if $X_1$ and $X_2$ are preferentially independent of $X_3$, and $X_2$ and $X_3$ are preferentially independent of $X_1$, then $X_3$ and $X_1$ are preferentially independent of $X_2$. <file_sep> A logical knowledge base represents the world using a set of sentences with no explicit structure. An **analogical** representation, on the other hand, has physical structure that corresponds directly to the structure of the thing represented. Consider a road map of your country as an analogical representation of facts about the country—it represents facts with a map language. The two-dimensional structure of the map corresponds to the two-dimensional surface of the area.<br> 1. Give five examples of *symbols* in the map language.<br> 2. An *explicit* sentence is a sentence that the creator of the representation actually writes down. An *implicit* sentence is a sentence that results from explicit sentences because of properties of the analogical representation. Give three examples each of *implicit* and *explicit* sentences in the map language.<br> 3. Give three examples of facts about the physical structure of your country that cannot be represented in the map language.<br> 4. Give two examples of facts that are much easier to express in the map language than in first-order logic.<br> 5. Give two other examples of useful analogical representations. What are the advantages and disadvantages of each of these languages? <file_sep>--- layout: chapter title: Logical Agents permalink: /knowledge-logic-exercises/ --- {% include mathjax_support %} # 7. Logical Agents <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.1');" href="#"><i id="ex7.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.1');" href="#"><i id="ex7.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.2');" href="#"><i id="ex7.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.2');" href="#"><i id="ex7.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3 (truth-value-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.3');" href="#"><i id="ex7.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.3');" href="#"><i id="ex7.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.4');" href="#"><i id="ex7.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.4');" href="#"><i id="ex7.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.5');" href="#"><i id="ex7.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.5');" href="#"><i id="ex7.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6 (deduction-theorem-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.6');" href="#"><i id="ex7.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.6');" href="#"><i id="ex7.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.7');" href="#"><i id="ex7.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.7');" href="#"><i id="ex7.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.8');" href="#"><i id="ex7.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.8');" href="#"><i id="ex7.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.9');" href="#"><i id="ex7.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.9');" href="#"><i id="ex7.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.10');" href="#"><i id="ex7.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.10');" href="#"><i id="ex7.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11 (logical-equivalence-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.11');" href="#"><i id="ex7.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.11');" href="#"><i id="ex7.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12 (propositional-validity-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.12');" href="#"><i id="ex7.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.12');" href="#"><i id="ex7.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13 (propositional-validity-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.13');" href="#"><i id="ex7.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.13');" href="#"><i id="ex7.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14 (cnf-proof-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.14');" href="#"><i id="ex7.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.14');" href="#"><i id="ex7.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.15');" href="#"><i id="ex7.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.15');" href="#"><i id="ex7.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_16/' class="p-2">Exercise 16 (inf-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.16');" href="#"><i id="ex7.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.16');" href="#"><i id="ex7.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_17/' class="p-2">Exercise 17 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.17');" href="#"><i id="ex7.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.17');" href="#"><i id="ex7.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_18/' class="p-2">Exercise 18 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.18');" href="#"><i id="ex7.18" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.18');" href="#"><i id="ex7.18" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_18/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_19/' class="p-2">Exercise 19 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.19');" href="#"><i id="ex7.19" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.19');" href="#"><i id="ex7.19" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_19/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_20/' class="p-2">Exercise 20 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.20');" href="#"><i id="ex7.20" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.20');" href="#"><i id="ex7.20" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_20/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_21/' class="p-2">Exercise 21 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.21');" href="#"><i id="ex7.21" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.21');" href="#"><i id="ex7.21" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_21/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_22/' class="p-2">Exercise 22 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.22');" href="#"><i id="ex7.22" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.2');" href="#"><i id="ex7.22" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_22/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_23/' class="p-2">Exercise 23 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.23');" href="#"><i id="ex7.23" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.23');" href="#"><i id="ex7.23" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_23/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_24/' class="p-2">Exercise 24 (dnf-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.24');" href="#"><i id="ex7.24" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.24');" href="#"><i id="ex7.24" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_24/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_25/' class="p-2">Exercise 25 (convert-clausal-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.25');" href="#"><i id="ex7.25" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.25');" href="#"><i id="ex7.25" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_25/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 26 (convert-clausal-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.26');" href="#"><i id="ex7.26" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.26');" href="#"><i id="ex7.26" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_26/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_27/' class="p-2">Exercise 27 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.27');" href="#"><i id="ex7.27" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.27');" href="#"><i id="ex7.27" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_27/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_28/' class="p-2">Exercise 28 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.28');" href="#"><i id="ex7.28" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.28');" href="#"><i id="ex7.28" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_28/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_29/' class="p-2">Exercise 29 (known-literal-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.29');" href="#"><i id="ex7.29" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.29');" href="#"><i id="ex7.29" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_29/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_30/' class="p-2">Exercise 30 (dpll-fc-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.30');" href="#"><i id="ex7.30" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.30');" href="#"><i id="ex7.30" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_30/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_31/' class="p-2">Exercise 31 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.31');" href="#"><i id="ex7.31" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.31');" href="#"><i id="ex7.31" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_31/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_32/' class="p-2">Exercise 32 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.32');" href="#"><i id="ex7.32" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.32');" href="#"><i id="ex7.32" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_32/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 33 </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.33');" href="#"><i id="ex7.33" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.33');" href="#"><i id="ex7.33" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_33/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_34/' class="p-2">Exercise 34 (ss-axiom-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.34');" href="#"><i id="ex7.34" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.34');" href="#"><i id="ex7.34" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_34/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_35/' class="p-2">Exercise 35 (hybrid-wumpus-exercise) </a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex7.35');" href="#"><i id="ex7.35" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex7.35');" href="#"><i id="ex7.35" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_35/question.md %}</p> </div> </div> <br> <file_sep>[Exercise 17.18 \[dominant-equilibrium-exercise\]](ex_18/) Show that a dominant strategy equilibrium is a Nash equilibrium, but not vice versa. <file_sep>[Exercise 25.9](ex_9/) Consider a mobile robot moving on a horizontal surface. Suppose that the robot can execute two kinds of motions: - Rolling forward a specified distance. - Rotating in place through a specified angle. The state of such a robot can be characterized in terms of three parameters ${\langle}x,y,\phi$, the x-coordinate and y-coordinate of the robot (more precisely, of its center of rotation) and the robot’s orientation expressed as the angle from the positive x direction. The action “$Roll(D)$” has the effect of changing state ${\langle}x,y,\phi$ to ${\langle}x+D \cos(\phi), y+D \sin(\phi), \phi {\rangle}$, and the action $Rotate(\theta)$ has the effect of changing state ${\langle}x,y,\phi {\rangle}$ to ${\langle}x,y, \phi + \theta {\rangle}$. 1. Suppose that the robot is initially at ${\langle}0,0,0 {\rangle}$ and then executes the actions $Rotate(60^{\circ})$, $Roll(1)$, $Rotate(25^{\circ})$, $Roll(2)$. What is the final state of the robot? 2. Now suppose that the robot has imperfect control of its own rotation, and that, if it attempts to rotate by $\theta$, it may actually rotate by any angle between $\theta-10^{\circ}$ and $\theta+10^{\circ}$. In that case, if the robot attempts to carry out the sequence of actions in (A), there is a range of possible ending states. What are the minimal and maximal values of the x-coordinate, the y-coordinate and the orientation in the final state? 3. Let us modify the model in (B) to a probabilistic model in which, when the robot attempts to rotate by $\theta$, its actual angle of rotation follows a Gaussian distribution with mean $\theta$ and standard deviation $10^{\circ}$. Suppose that the robot executes the actions $Rotate(90^{\circ})$, $Roll(1)$. Give a simple argument that (a) the expected value of the location at the end is not equal to the result of rotating exactly $90^{\circ}$ and then rolling forward 1 unit, and (b) that the distribution of locations at the end does not follow a Gaussian. (Do not attempt to calculate the true mean or the true distribution.) The point of this exercise is that rotational uncertainty quickly gives rise to a lot of positional uncertainty and that dealing with rotational uncertainty is painful, whether uncertainty is treated in terms of hard intervals or probabilistically, due to the fact that the relation between orientation and position is both non-linear and non-monotonic. <center> <b id="FigEx3">Figure [FigEx3]</b> Simplified robot in a maze. See Exercise [robot-exploration-exercise](#/)</center> ![FigEx3](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/robotics-pic7.svg) <file_sep>--- layout: exercise title: Exercise 5.25 permalink: /game-playing-exercises/ex_25/ breadcrumb: 5-Adversarial-Search --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="game-playing-exercises" data-exercise="ex_25" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 21.2](ex_2/) Chapter [complex-decisions-chapter](#/) defined a **proper policy** for an MDP as one that is guaranteed to reach a terminal state. Show that it is possible for a passive ADP agent to learn a transition model for which its policy $\pi$ is improper even if $\pi$ is proper for the true MDP; with such models, the POLICY-EVALUATION step may fail if $\gamma{{\,=\,}}1$. Show that this problem cannot arise if POLICY-EVALUATION is applied to the learned model only at the end of a trial. <file_sep>// bookmark.js window.onload = function(){ console.log("Bookmarks"); for (var i = 0, len = localStorage.length; i < len; ++i) { var key = localStorage.key(i); var value = localStorage.getItem(key); bookmark(key); console.log(key); } }; function bookmark(exercise){ var btn = document.getElementById(exercise); var btnColor = btn.style.color; if(btnColor == 'white'){ localStorage.setItem(exercise, 'gold'); btn.style.color=localStorage.getItem(exercise); }else{ localStorage.removeItem(exercise); btn.style.color= 'white'; } } <file_sep>[Exercise 20.7 \[noisy-OR-ML-exercise\]](ex_7/) Consider the noisy-OR model for fever described in Section [canonical-distribution-section](#/). Explain how to apply maximum-likelihood learning to fit the parameters of such a model to a set of complete data. (*Hint*: use the chain rule for partial derivatives.) <file_sep>[Exercise 24.1](ex_1/) In the shadow of a tree with a dense, leafy canopy, one sees a number of light spots. Surprisingly, they all appear to be circular. Why? After all, the gaps between the leaves through which the sun shines are not likely to be circular. <file_sep>[Exercise 18.13 \[gain-ratio-DTL-exercise\]](ex_13/) In Section [broadening-decision-tree-section](#/), we noted that attributes with many different possible values can cause problems with the gain measure. Such attributes tend to split the examples into numerous small classes or even singleton classes, thereby appearing to be highly relevant according to the gain measure. The **gain-ratio** criterion selects attributes according to the ratio between their gain and their intrinsic information content—that is, the amount of information contained in the answer to the question, “What is the value of this attribute?” The gain-ratio criterion therefore tries to measure how efficiently an attribute provides information on the correct classification of an example. Write a mathematical expression for the information content of an attribute, and implement the gain ratio criterion in DECISION-TREE-LEARNING. <file_sep>[Exercise 16.6 \[surprise-candy-exercise\]](ex_6/) The Surprise Candy Company makes candy in two flavors: 75% are strawberry flavor and 25% are anchovy flavor. Each new piece of candy starts out with a round shape; as it moves along the production line, a machine randomly selects a certain percentage to be trimmed into a square; then, each piece is wrapped in a wrapper whose color is chosen randomly to be red or brown. 70% of the strawberry candies are round and 70% have a red wrapper, while 90% of the anchovy candies are square and 90% have a brown wrapper. All candies are sold individually in sealed, identical, black boxes. Now you, the customer, have just bought a Surprise candy at the store but have not yet opened the box. Consider the three Bayes nets in Figure [3candy-figure](#3candy-figure). 1. Which network(s) can correctly represent ${\textbf{P}}(Flavor,Wrapper,Shape)$? 2. Which network is the best representation for this problem? 3. Does network (i) assert that ${\textbf{P}}(Wrapper|Shape){{\,=\,}}{\textbf{P}}(Wrapper)$? 4. What is the probability that your candy has a red wrapper? 5. In the box is a round candy with a red wrapper. What is the probability that its flavor is strawberry? 6. A unwrapped strawberry candy is worth $s$ on the open market and an unwrapped anchovy candy is worth $a$. Write an expression for the value of an unopened candy box. 7. A new law prohibits trading of unwrapped candies, but it is still legal to trade wrapped candies (out of the box). Is an unopened candy box now worth more than less than, or the same as before? <center> <b id="3candy-figure">Figure [3candy-figure]</b> Three proposed Bayes nets for the Surprise Candy problem </center> ![3candy-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/3candy.svg) <file_sep>[Exercise 11.15](ex_15/) To the medication problem in the previous exercise, add a ${Test}$ action that has the conditional effect ${CultureGrowth}$ when ${Disease}$ is true and in any case has the perceptual effect ${Known}({CultureGrowth})$. Diagram a conditional plan that solves the problem and minimizes the use of the ${Medicate}$ action. <file_sep>[Exercise 20.4](ex_4/) Two statisticians go to the doctor and are both given the same prognosis: A 40% chance that the problem is the deadly disease $A$, and a 60% chance of the fatal disease $B$. Fortunately, there are anti-$A$ and anti-$B$ drugs that are inexpensive, 100% effective, and free of side-effects. The statisticians have the choice of taking one drug, both, or neither. What will the first statistician (an avid Bayesian) do? How about the second statistician, who always uses the maximum likelihood hypothesis? The doctor does some research and discovers that disease $B$ actually comes in two versions, dextro-$B$ and levo-$B$, which are equally likely and equally treatable by the anti-$B$ drug. Now that there are three hypotheses, what will the two statisticians do? <file_sep>[Exercise 11.6](ex_6/) In Figure [jobshop-cpm-figure](#/) we showed how to describe actions in a scheduling problem by using separate fields for , , and . Now suppose we wanted to combine scheduling with nondeterministic planning, which requires nondeterministic and conditional effects. Consider each of the three fields and explain if they should remain separate fields, or if they should become effects of the action. Give an example for each of the three. <file_sep>[Exercise 13.26](ex_26/) (Adapted from Pearl [-@Pearl:1988].) Suppose you are a witness to a nighttime hit-and-run accident involving a taxi in Athens. All taxis in Athens are blue or green. You swear, under oath, that the taxi was blue. Extensive testing shows that, under the dim lighting conditions, discrimination between blue and green is 75% reliable. 1. Is it possible to calculate the most likely color for the taxi? (*Hint:* distinguish carefully between the proposition that the taxi *is* blue and the proposition that it *appears* blue.) 2. What if you know that 9 out of 10 Athenian taxis are green? <file_sep>[Exercise 23.12 \[exercise-subj-verb-agree\]](ex_12/) Using DCG notation, write a grammar for a language that is just like $\large \varepsilon_1$, except that it enforces agreement between the subject and verb of a sentence and thus does not generate ungrammatical sentences such as “I smells the wumpus.” <file_sep>--- layout: exercise title: Exercise 26.4 permalink: /philosophy-exercises/ex_4/ breadcrumb: 26-Philosophical-Foundations --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="philosophy-exercises" data-exercise="ex_4" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>--- layout: exercise title: Exercise 12.16 permalink: /kr-exercises/ex_16/ breadcrumb: 12-Knowledge-Representation --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="kr-exercises" data-exercise="ex_16" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 18.33 \[embedding-separability-exercise\]](ex_33/) Consider the problem of separating $N$ data points into positive and negative examples using a linear separator. Clearly, this can always be done for $N{{\,=\,}}2$ points on a line of dimension $d{{\,=\,}}1$, regardless of how the points are labeled or where they are located (unless the points are in the same place). 1. Show that it can always be done for $N{{\,=\,}}3$ points on a plane of dimension $d{{\,=\,}}2$, unless they are collinear. 2. Show that it cannot always be done for $N{{\,=\,}}4$ points on a plane of dimension $d{{\,=\,}}2$. 3. Show that it can always be done for $N{{\,=\,}}4$ points in a space of dimension $d{{\,=\,}}3$, unless they are coplanar. 4. Show that it cannot always be done for $N{{\,=\,}}5$ points in a space of dimension $d{{\,=\,}}3$. 5. The ambitious student may wish to prove that $N$ points in general position (but not $N+1$) are linearly separable in a space of dimension $N-1$. <file_sep>--- layout: chapter title: Adversarial Search permalink: /game-playing-exercises/ --- {% include mathjax_support %} # 5. Adversarial Search <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.1');" href="#"><i id="ex5.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.1');" href="#"><i id="ex5.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.2');" href="#"><i id="ex5.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.2');" href="#"><i id="ex5.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.3');" href="#"><i id="ex5.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.3');" href="#"><i id="ex5.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4 (game-playing-chance-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.4');" href="#"><i id="ex5.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.4');" href="#"><i id="ex5.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.5');" href="#"><i id="ex5.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.5');" href="#"><i id="ex5.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.6');" href="#"><i id="ex5.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.6');" href="#"><i id="ex5.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7 (minimax-optimality-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.7');" href="#"><i id="ex5.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.7');" href="#"><i id="ex5.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.8');" href="#"><i id="ex5.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.8');" href="#"><i id="ex5.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.9');" href="#"><i id="ex5.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.9');" href="#"><i id="ex5.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.10');" href="#"><i id="ex5.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.10');" href="#"><i id="ex5.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.11');" href="#"><i id="ex5.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.11');" href="#"><i id="ex5.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_12/' class="p-2">Exercise 12</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.12');" href="#"><i id="ex5.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.12');" href="#"><i id="ex5.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.13');" href="#"><i id="ex5.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.13');" href="#"><i id="ex5.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.14');" href="#"><i id="ex5.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.14');" href="#"><i id="ex5.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.15');" href="#"><i id="ex5.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.15');" href="#"><i id="ex5.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_16/' class="p-2">Exercise 16</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.16');" href="#"><i id="ex5.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.16');" href="#"><i id="ex5.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_17/' class="p-2">Exercise 17</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.17');" href="#"><i id="ex5.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.17');" href="#"><i id="ex5.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_18/' class="p-2">Exercise 18</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.18');" href="#"><i id="ex5.18" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.18');" href="#"><i id="ex5.18" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_18/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_19/' class="p-2">Exercise 19</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.19');" href="#"><i id="ex5.19" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.19');" href="#"><i id="ex5.19" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_19/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_20/' class="p-2">Exercise 20 (game-linear-transform)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.20');" href="#"><i id="ex5.20" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.20');" href="#"><i id="ex5.20" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_20/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_21/' class="p-2">Exercise 21 (game-playing-monte-carlo-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.21');" href="#"><i id="ex5.21" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.21');" href="#"><i id="ex5.21" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_21/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_22/' class="p-2">Exercise 22</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.22');" href="#"><i id="ex5.22" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.22');" href="#"><i id="ex5.22" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_22/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_23/' class="p-2">Exercise 23</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.23');" href="#"><i id="ex5.23" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.23');" href="#"><i id="ex5.23" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_23/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_24/' class="p-2">Exercise 24</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.24');" href="#"><i id="ex5.24" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.1');" href="#"><i id="ex5.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_25/' class="p-2">Exercise 25</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex5.25');" href="#"><i id="ex5.25" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex5.25');" href="#"><i id="ex5.25" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_25/question.md %}</p> </div> </div> <br> <file_sep>[Exercise 15.7 \[hmm-robust-exercise\]](ex_7/) In Section [hmm-localization-section](#/), the prior distribution over locations is uniform and the transition model assumes an equal probability of moving to any neighboring square. What if those assumptions are wrong? Suppose that the initial location is actually chosen uniformly from the northwest quadrant of the room and the action actually tends to move southeast\[hmm-robot-southeast-page\]. Keeping the HMM model fixed, explore the effect on localization and path accuracy as the southeasterly tendency increases, for different values of $\epsilon$. <file_sep>[Exercise 12.2](ex_2/) You are to create a system for advising computer science undergraduates on what courses to take over an extended period in order to satisfy the program requirements. (Use whatever requirements are appropriate for your institution.) First, decide on a vocabulary for representing all the information, and then represent it; then formulate a query to the system that will return a legal program of study as a solution. You should allow for some tailoring to individual students, in that your system should ask what courses or equivalents the student has already taken, and not generate programs that repeat those courses. Suggest ways in which your system could be improved—for example to take into account knowledge about student preferences, the workload, good and bad instructors, and so on. For each kind of knowledge, explain how it could be expressed logically. Could your system easily incorporate this information to find all feasible programs of study for a student? Could it find the *best* program? <file_sep>[Exercise 24.5](ex_5/) A stereoscopic system is being contemplated for terrain mapping. It will consist of two CCD cameras, each having ${512}\times {512}$ pixels on a 10 cm $\times$ 10 cm square sensor. The lenses to be used have a focal length of 16 cm, with the focus fixed at infinity. For corresponding points ($u_1,v_1$) in the left image and ($u_2,v_2$) in the right image, $v_1=v_2$ because the $x$-axes in the two image planes are parallel to the epipolar lines—the lines from the object to the camera. The optical axes of the two cameras are parallel. The baseline between the cameras is 1 meter. 1. If the nearest distance to be measured is 16 meters, what is the largest disparity that will occur (in pixels)? 2. What is the distance resolution at 16 meters, due to the pixel spacing? 3. What distance corresponds to a disparity of one pixel? <file_sep>[Exercise 12.28](ex_28/) One part of the shopping process that was not covered in this chapter is checking for compatibility between items. For example, if a digital camera is ordered, what accessory batteries, memory cards, and cases are compatible with the camera? Write a knowledge base that can determine the compatibility of a set of items and suggest replacements or additional items if the shopper makes a choice that is not compatible. The knowledge base should works with at least one line of products and extend easily to other lines. <file_sep>[Exercise 12.19 \[fixed-definition-exercise\]](ex_19/) Define the predicate ${Fixed}$, where ${Fixed}({Location}(x))$ means that the location of object $x$ is fixed over time. <file_sep>[Exercise 22.7](ex_7/) Create a test set of ten queries, and pose them to three major Web search engines. Evaluate each one for precision at 1, 3, and 10 documents. Can you explain the differences between engines? <file_sep>[Exercise 15.9](ex_9/) We have described three policies for the vacuum robot: (1) a uniform random walk, (2) a bias for wandering southeast, as described in Exercise [hmm-robust-exercise](#/), and (3) the policy described in Exercise [roomba-viterbi-exercise](#/). Suppose an observer is given the observation sequence from a vacuum robot, but is not sure which of the three policies the robot is following. What approach should the observer use to find the most likely path, given the observations? Implement the approach and test it. How much does the localization accuracy suffer, compared to the case in which the observer knows which policy the robot is following? <file_sep> On page <a href="#">Gaschnig-h-page</a> , we defined the relaxation of the 8-puzzle in which a tile can move from square A to square B if B is blank. The exact solution of this problem defines **Gaschnig's heuristic** @Gaschnig:1979. Explain why Gaschnig’s heuristic is at least as accurate as $h_1$ (misplaced tiles), and show cases where it is more accurate than both $h_1$ and $h_2$ (Manhattan distance). Explain how to calculate Gaschnig’s heuristic efficiently. <file_sep> This problem exercises the basic concepts of game playing, using tic-tac-toe (noughts and crosses) as an example. We define $X_n$ as the number of rows, columns, or diagonals with exactly $n$ $X$’s and no $O$’s. Similarly, $O_n$ is the number of rows, columns, or diagonals with just $n$ $O$’s. The utility function assigns $+1$ to any position with $X_3=1$ and $-1$ to any position with $O_3 = 1$. All other terminal positions have utility 0. For nonterminal positions, we use a linear evaluation function defined as ${Eval}(s) = 3X_2(s) + X_1(s) - (3O_2(s) + O_1(s))$. <br> 1. Approximately how many possible games of tic-tac-toe are there?<br> 2. Show the whole game tree starting from an empty board down to depth 2 (i.e., one $X$ and one $O$ on the board), taking symmetry into account.<br> 3. Mark on your tree the evaluations of all the positions at depth 2.<br> 4. Using the minimax algorithm, mark on your tree the backed-up values for the positions at depths 1 and 0, and use those values to choose the best starting move.<br> 5. Circle the nodes at depth 2 that would *not* be evaluated if alpha–beta pruning were applied, assuming the nodes are generated in the optimal order for alpha–beta pruning.<br> <file_sep>[Exercise 22.9](ex_9/) Estimate how much storage space is necessary for the index to a 100 billion-page corpus of Web pages. Show the assumptions you made. <file_sep> Consider the problem of deciding whether a propositional logic sentence is true in a given model.<br> 1. Write a recursive algorithm PL-True?$ (s, m )$ that returns ${true}$ if and only if the sentence $s$ is true in the model $m$ (where $m$ assigns a truth value for every symbol in $s$). The algorithm should run in time linear in the size of the sentence. (Alternatively, use a version of this function from the online code repository.)<br> 2. Give three examples of sentences that can be determined to be true or false in a *partial* model that does not specify a truth value for some of the symbols.<br> 3. Show that the truth value (if any) of a sentence in a partial model cannot be determined efficiently in general.<br> 4. Modify your algorithm so that it can sometimes judge truth from partial models, while retaining its recursive structure and linear run time. Give three examples of sentences whose truth in a partial model is *not* detected by your algorithm.<br> 5. Investigate whether the modified algorithm makes $TT-Entails?$ more efficient. <file_sep>[Exercise 17.15 \[4x3-pomdp-exercise\]](ex_15/) Let the initial belief state $b_0$ for the $4\times 3$ POMDP on page [4x3-pomdp-page](#/) be the uniform distribution over the nonterminal states, i.e., $< \frac{1}{9},\frac{1}{9},\frac{1}{9},\frac{1}{9},\frac{1}{9},\frac{1}{9},\frac{1}{9},\frac{1}{9},\frac{1}{9},0,0 >$. Calculate the exact belief state $b_1$ after the agent moves and its sensor reports 1 adjacent wall. Also calculate $b_2$ assuming that the same thing happens again. <file_sep>[Exercise 18.7 \[nonnegative-gain-exercise\]](ex_7/) \[nonnegative-gain-exercise\]Suppose that an attribute splits the set of examples $E$ into subsets $E_k$ and that each subset has $p_k$ positive examples and $n_k$ negative examples. Show that the attribute has strictly positive information gain unless the ratio $p_k/(p_k+n_k)$ is the same for all $k$. <file_sep>[Exercise 18.26 \[linear-separability-exercise\]](ex_26/) Recall from Chapter [concept-learning-chapter](#/) that there are $2^{2^n}$ distinct Boolean functions of $n$ inputs. How many of these are representable by a threshold perceptron? <file_sep>[Exercise 17.8 \[vi-contraction-exercise\]](ex_8/) Equation ([vi-contraction-equation](#/)) on page [vi-contraction-equation](#/) states that the Bellman operator is a contraction. 1. Show that, for any functions $f$ and $g$, $$|\max_a f(a) - \max_a g(a)| \leq \max_a |f(a) - g(a)|\ .$$ 2. Write out an expression for $$|(B\,U_i - B\,U'_i)(s)|$$ and then apply the result from (1) to complete the proof that the Bellman operator is a contraction. <file_sep>[Exercise 25.1 \[mcl-biasdness-exercise\]](ex_1/) Monte Carlo localization is *biased* for any finite sample size—i.e., the expected value of the location computed by the algorithm differs from the true expected value—because of the way particle filtering works. In this question, you are asked to quantify this bias. To simplify, consider a world with four possible robot locations: $X=\{x_{{\rm 1}},x_{{\rm 2}},x_{{\rm 3}},x_{{\rm 4}}\}$. Initially, we draw $N\geq {{\rm 1}}$ samples uniformly from among those locations. As usual, it is perfectly acceptable if more than one sample is generated for any of the locations $X$. Let $Z$ be a Boolean sensor variable characterized by the following conditional probabilities: $$\begin{aligned} P(z\mid x_{{\rm 1}}) &=& {{\rm {0.8}}} \qquad\qquad P(\lnot z\mid x_{{\rm 1}})\;\;=\;\;{{\rm {0.2}}} \\ P(z\mid x_{{\rm 2}}) &=& {{\rm {0.4}}} \qquad\qquad P(\lnot z\mid x_{{\rm 2}})\;\;=\;\;{{\rm {0.6}}} \\ P(z\mid x_{{\rm 3}}) &=& {{\rm {0.1}}} \qquad\qquad P(\lnot z\mid x_{{\rm 3}})\;\;=\;\;{{\rm {0.9}}} \\ P(z\mid x_{{\rm 4}}) &=& {{\rm {0.1}}} \qquad\qquad P(\lnot z\mid x_{{\rm 4}})\;\;=\;\;{{\rm {0.9}}}\ .\end{aligned}$$ MCL uses these probabilities to generate particle weights, which are subsequently normalized and used in the resampling process. For simplicity, let us assume we generate only one new sample in the resampling process, regardless of $N$. This sample might correspond to any of the four locations in $X$. Thus, the sampling process defines a probability distribution over $X$. 1. What is the resulting probability distribution over $X$ for this new sample? Answer this question separately for $N={{\rm 1}},\ldots,{{\rm {10}}}$, and for $N=\infty$. 2. The difference between two probability distributions $P$ and $Q$ can be measured by the KL divergence, which is defined as $${KL}(P,Q) = \sum_i P(x_i)\log\frac{P(x_i)}{Q(x_i)}\ .$$ What are the KL divergences between the distributions in (a) and the true posterior? 3. What modification of the problem formulation (not the algorithm!) would guarantee that the specific estimator above is unbiased even for finite values of $N$? Provide at least two such modifications (each of which should be sufficient). <file_sep>[Exercise 18.6 \[leaf-classification-exercise\]](ex_6/) In the recursive construction of decision trees, it sometimes happens that a mixed set of positive and negative examples remains at a leaf node, even after all the attributes have been used. Suppose that we have $p$ positive examples and $n$ negative examples. 1. Show that the solution used by DECISION-TREE-LEARNING, which picks the majority classification, minimizes the absolute error over the set of examples at the leaf. 2. Show that the **class probability** $p/(p+n)$ minimizes the sum of squared errors. <file_sep>[Exercise 15.3 \[island-exercise\]](ex_3/) This exercise develops a space-efficient variant of the forward–backward algorithm described in Figure [forward-backward-algorithm](#/) (page [forward-backward-algorithm](#/)). We wish to compute $$\textbf{P} (\textbf{X}_k|\textbf{e}_{1:t})$$ for $$k=1,\ldots ,t$$. This will be done with a divide-and-conquer approach. 1. Suppose, for simplicity, that $t$ is odd, and let the halfway point be $h=(t+1)/2$. Show that $$\textbf{P} (\textbf{X}_k|\textbf{e}_{1:t}) $$ can be computed for $k=1,\ldots ,h$ given just the initial forward message $$\textbf{f}_{1:0}$$, the backward message $$\textbf{b}_{h+1:t}$$, and the evidence $$\textbf{e}_{1:h}$$. 2. Show a similar result for the second half of the sequence. 3. Given the results of (a) and (b), a recursive divide-and-conquer algorithm can be constructed by first running forward along the sequence and then backward from the end, storing just the required messages at the middle and the ends. Then the algorithm is called on each half. Write out the algorithm in detail. 4. Compute the time and space complexity of the algorithm as a function of $t$, the length of the sequence. How does this change if we divide the input into more than two pieces? <file_sep>--- layout: chapter title: Search Exercises permalink: /search-exercises/ --- {% include mathjax_support %} # 3. Solving Problems By Searching <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 1</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.1');" href="#"><i id="ex3.1" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.1');" href="#"><i id="ex3.1" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_1/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_2/' class="p-2">Exercise 2</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.2');" href="#"><i id="ex3.2" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.2');" href="#"><i id="ex3.2" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_2/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_3/' class="p-2">Exercise 3</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.3');" href="#"><i id="ex3.3" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.3');" href="#"><i id="ex3.3" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_3/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_4/' class="p-2">Exercise 4</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.4');" href="#"><i id="ex3.4" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.4');" href="#"><i id="ex3.4" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_4/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_5/' class="p-2">Exercise 5 (two-friends-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.5');" href="#"><i id="ex3.5" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.5');" href="#"><i id="ex3.5" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_5/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_6/' class="p-2">Exercise 6 (8puzzle-parity-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.6');" href="#"><i id="ex3.6" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.6');" href="#"><i id="ex3.6" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_6/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_7/' class="p-2">Exercise 7 (nqueens-size-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.7');" href="#"><i id="ex3.7" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.7');" href="#"><i id="ex3.7" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_7/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_8/' class="p-2">Exercise 8</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.8');" href="#"><i id="ex3.8" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.8');" href="#"><i id="ex3.8" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_8/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_9/' class="p-2">Exercise 9 (path-planning-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.1');" href="#"><i id="ex3.9" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.9');" href="#"><i id="ex3.9" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_9/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_10/' class="p-2">Exercise 10 (negative-g-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.10');" href="#"><i id="ex3.10" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.10');" href="#"><i id="ex3.10" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_10/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_11/' class="p-2">Exercise 11 (mc-problem)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.11');" href="#"><i id="ex3.11" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.11');" href="#"><i id="ex3.11" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_11/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 12</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.12');" href="#"><i id="ex3.12" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.12');" href="#"><i id="ex3.12" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_12/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_13/' class="p-2">Exercise 13</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.13');" href="#"><i id="ex3.13" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.13');" href="#"><i id="ex3.13" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_13/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_14/' class="p-2">Exercise 14</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.14');" href="#"><i id="ex3.14" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.14');" href="#"><i id="ex3.14" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_14/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_15/' class="p-2">Exercise 15</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.15');" href="#"><i id="ex3.15" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.15');" href="#"><i id="ex3.15" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_15/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_16/' class="p-2">Exercise 16 (graph-separation-property-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.16');" href="#"><i id="ex3.16" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.16');" href="#"><i id="ex3.16" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_16/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_17/' class="p-2">Exercise 17</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.17');" href="#"><i id="ex3.17" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.17');" href="#"><i id="ex3.17" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_17/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_18/' class="p-2">Exercise 18</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.18');" href="#"><i id="ex3.18" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.18');" href="#"><i id="ex3.18" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_18/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_19/' class="p-2">Exercise 19 (brio-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.19');" href="#"><i id="ex3.19" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.19');" href="#"><i id="ex3.19" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_19/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_20/' class="p-2">Exercise 20</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.20');" href="#"><i id="ex3.20" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.20');" href="#"><i id="ex3.20" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_20/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_21/' class="p-2">Exercise 21 (iterative-lengthening-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.21');" href="#"><i id="ex3.21" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.21');" href="#"><i id="ex3.21" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_21/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_22/' class="p-2">Exercise 22</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.22');" href="#"><i id="ex3.22" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.22');" href="#"><i id="ex3.22" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_22/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_23/' class="p-2">Exercise 23</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.23');" href="#"><i id="ex3.23" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.23');" href="#"><i id="ex3.23" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_23/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_24/' class="p-2">Exercise 24 (vacuum-search-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.24');" href="#"><i id="ex3.24" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.24');" href="#"><i id="ex3.24" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_24/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_25/' class="p-2">Exercise 25 (search-special-case-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.25');" href="#"><i id="ex3.25" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.25');" href="#"><i id="ex3.25" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_25/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_26/' class="p-2">Exercise 26</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.26');" href="#"><i id="ex3.26" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.26');" href="#"><i id="ex3.26" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_26/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_27/' class="p-2">Exercise 27</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.27');" href="#"><i id="ex3.27" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.27');" href="#"><i id="ex3.27" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_27/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_28/' class="p-2">Exercise 28</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.28');" href="#"><i id="ex3.28" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.28');" href="#"><i id="ex3.28" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_28/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_29/' class="p-2">Exercise 29 (failure-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.29');" href="#"><i id="ex3.29" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.29');" href="#"><i id="ex3.29" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_29/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_30/' class="p-2">Exercise 30</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.30');" href="#"><i id="ex3.30" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.30');" href="#"><i id="ex3.30" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_30/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_31/' class="p-2">Exercise 31</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.31');" href="#"><i id="ex3.31" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.31');" href="#"><i id="ex3.31" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_31/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_1/' class="p-2">Exercise 32</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.32');" href="#"><i id="ex3.32" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.32');" href="#"><i id="ex3.32" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_32/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_33/' class="p-2">Exercise 33</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.33');" href="#"><i id="ex3.33" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.33');" href="#"><i id="ex3.33" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_33/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_34/' class="p-2">Exercise 34</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.34');" href="#"><i id="ex3.34" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.34');" href="#"><i id="ex3.34" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_34/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_35/' class="p-2">Exercise 35</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.35');" href="#"><i id="ex3.35" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.35');" href="#"><i id="ex3.35" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_35/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_36/' class="p-2">Exercise 36</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.36');" href="#"><i id="ex3.36" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.36');" href="#"><i id="ex3.36" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_36/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_37/' class="p-2">Exercise 37</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.37');" href="#"><i id="ex3.37" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.37');" href="#"><i id="ex3.37" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_37/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_38/' class="p-2">Exercise 38</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.38');" href="#"><i id="ex3.38" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.38');" href="#"><i id="ex3.38" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_38/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_39/' class="p-2">Exercise 39 (Gaschnig-h-exercise)</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.39');" href="#"><i id="ex3.39" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.39');" href="#"><i id="ex3.39" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_39/question.md %}</p> </div> </div> <br> <div class="card"> <div class="card-header p-2"> <a href='ex_40/' class="p-2">Exercise 40</a> <button type="button" class="btn btn-dark float-right" onclick="bookmark('ex3.40');" href="#"><i id="ex3.40" class="fas fa-bookmark" style="color:white"></i></button> <button type="button" class="btn btn-dark float-right" style="margin-left:10px; margin-right:10px;" onclick="upvote('ex3.40');" href="#"><i id="ex3.40" class="fas fa-thumbs-up" style="color:white"></i></button> </div> <div class="card-body"> <p class="card-text">{% include_relative exercises/ex_40/question.md %}</p> </div> </div> <br> <file_sep> Develop a formal proof of correctness for alpha–beta pruning. To do this, consider the situation shown in Figure <a href="#alpha-beta-proof-figure">alpha-beta-proof-figure</a>. The question is whether to prune node $n_j$, which is a max-node and a descendant of node $n_1$. The basic idea is to prune it if and only if the minimax value of $n_1$ can be shown to be independent of the value of $n_j$.<br> 1. Mode $n_1$ takes on the minimum value among its children: $n_1 = \min(n_2,n_{{21}},\ldots,n_{2b_2})$. Find a similar expression for $n_2$ and hence an expression for $n_1$ in terms of $n_j$.<br> 2. Let $l_i$ be the minimum (or maximum) value of the nodes to the *left* of node $n_i$ at depth $i$, whose minimax value is already known. Similarly, let $r_i$ be the minimum (or maximum) value of the unexplored nodes to the right of $n_i$ at depth $i$. Rewrite your expression for $n_1$ in terms of the $l_i$ and $r_i$ values.<br> 3. Now reformulate the expression to show that in order to affect $n_1$, $n_j$ must not exceed a certain bound derived from the $l_i$ values.<br> 4. Repeat the process for the case where $n_j$ is a min-node.<br> <figure> <img src="http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/alpha-beta-proof.svg" alt="alpha-beta-proof-figure" id="alpha-beta-proof-figure" style="width:100%"> <figcaption><center><b>Situation when considering whether to prune node $n_j$.</b></center></figcaption> </figure> <file_sep>[Exercise 17.9](ex_9/) This exercise considers two-player MDPs that correspond to zero-sum, turn-taking games like those in Chapter [game-playing-chapter](#/). Let the players be $A$ and $B$, and let $R(s)$ be the reward for player $A$ in state $s$. (The reward for $B$ is always equal and opposite.) 1. Let $U_A(s)$ be the utility of state $s$ when it is $A$’s turn to move in $s$, and let $U_B(s)$ be the utility of state $s$ when it is $B$’s turn to move in $s$. All rewards and utilities are calculated from $A$’s point of view (just as in a minimax game tree). Write down Bellman equations defining $U_A(s)$ and $U_B(s)$. 2. Explain how to do two-player value iteration with these equations, and define a suitable termination criterion. 3. Consider the game described in Figure [line-game4-figure](#/) on page [line-game4-figure](#/). Draw the state space (rather than the game tree), showing the moves by $A$ as solid lines and moves by $B$ as dashed lines. Mark each state with $R(s)$. You will find it helpful to arrange the states $(s_A,s_B)$ on a two-dimensional grid, using $s_A$ and $s_B$ as “coordinates.” 4. Now apply two-player value iteration to solve this game, and derive the optimal policy. <center> <b id="grid-mdp-figure">Figure [grid-mdp-figure]</b> (a) $3 \times 3$ world for Exercise [3x3-mdp-exercise](#/). The reward for each state is indicated. The upper right square is a terminal state. (b) $101 \times 3$ world for Exercise [101x3-mdp-exercise](#/) (omitting 93 identical columns in the middle). The start state has reward 0. </center> ![grid-mdp-figure](http://nalinc.github.io/aima-exercises/Jupyter%20notebook/figures/grid-mdp-figure.svg) <file_sep>[Exercise 12.1](ex_1/) Define an ontology in first-order logic for tic-tac-toe. The ontology should contain situations, actions, squares, players, marks (X, O, or blank), and the notion of winning, losing, or drawing a game. Also define the notion of a forced win (or draw): a position from which a player can force a win (or draw) with the right sequence of actions. Write axioms for the domain. (Note: The axioms that enumerate the different squares and that characterize the winning positions are rather long. You need not write these out in full, but indicate clearly what they look like.) <file_sep>--- layout: exercise title: Exercise 1.5 permalink: /intro-exercises/ex_5/ breadcrumb: 1-Introduction --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="intro-exercises" data-exercise="ex_5" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 18.5](ex_5/) Suppose we generate a training set from a decision tree and then apply decision-tree learning to that training set. Is it the case that the learning algorithm will eventually return the correct tree as the training-set size goes to infinity? Why or why not? <file_sep> Consider the two-player game described in Figure <a href="#line-game4-figure">line-game4-figure</a><br> 1. Draw the complete game tree, using the following conventions:<br> - Write each state as $(s_A,s_B)$, where $s_A$ and $s_B$ denote the token locations.<br> - Put each terminal state in a square box and write its game value in a circle.<br> - Put *loop states* (states that already appear on the path to the root) in double square boxes. Since their value is unclear, annotate each with a “?” in a circle.<br> 2. Now mark each node with its backed-up minimax value (also in a circle). Explain how you handled the “?” values and why.<br> 3. Explain why the standard minimax algorithm would fail on this game tree and briefly sketch how you might fix it, drawing on your answer to (b). Does your modified algorithm give optimal decisions for all games with loops?<br> 4. This 4-square game can be generalized to $n$ squares for any $n > 2$. Prove that $A$ wins if $n$ is even and loses if $n$ is odd. <file_sep>[Exercise 12.22 \[card-on-forehead-exercise\]](ex_22/) (Adapted from @Fagin+al:1995.) Consider a game played with a deck of just 8 cards, 4 aces and 4 kings. The three players, Alice, Bob, and Carlos, are dealt two cards each. Without looking at them, they place the cards on their foreheads so that the other players can see them. Then the players take turns either announcing that they know what cards are on their own forehead, thereby winning the game, or saying “I don’t know.” Everyone knows the players are truthful and are perfect at reasoning about beliefs. 1. Game 1. Alice and Bob have both said “I don’t know.” Carlos sees that Alice has two aces (A-A) and Bob has two kings (K-K). What should Carlos say? (*Hint*: consider all three possible cases for Carlos: A-A, K-K, A-K.) 2. Describe each step of Game 1 using the notation of modal logic. 3. Game 2. Carlos, Alice, and Bob all said “I don’t know” on their first turn. Alice holds K-K and Bob holds A-K. What should Carlos say on his second turn? 4. Game 3. Alice, Carlos, and Bob all say “I don’t know” on their first turn, as does Alice on her second turn. Alice and Bob both hold A-K. What should Carlos say? 5. Prove that there will always be a winner to this game. <file_sep>[Exercise 18.20 \[knn-mean-mode\]](ex_20/) Suppose a $7$-nearest-neighbors regression search returns $ \{4, 2, 8, 4, 9, 11, 100\} $ as the 7 nearest $y$ values for a given $x$ value. What is the value of $\hat{y}$ that minimizes the $L_1$ loss function on this data? There is a common name in statistics for this value as a function of the $y$ values; what is it? Answer the same two questions for the $L_2$ loss function. <file_sep>[Exercise 18.24](ex_24/) Construct by hand a neural network that computes the xor function of two inputs. Make sure to specify what sort of units you are using. <file_sep> A propositional *2-CNF* expression is a conjunction of clauses, each containing *exactly 2* literals, e.g., $$(A\lor B) \land (\lnot A \lor C) \land (\lnot B \lor D) \land (\lnot C \lor G) \land (\lnot D \lor G)\ .$$<br> 1. Prove using resolution that the above sentence entails $G$.<br> 2. Two clauses are *semantically distinct* if they are not logically equivalent. How many semantically distinct 2-CNF clauses can be constructed from $n$ proposition symbols?<br> 3. Using your answer to (b), prove that propositional resolution always terminates in time polynomial in $n$ given a 2-CNF sentence containing no more than $n$ distinct symbols.<br> 4. Explain why your argument in (c) does not apply to 3-CNF.<br> <file_sep>[Exercise 24.6](ex_6/) Which of the following are true, and which are false? 1. Finding corresponding points in stereo images is the easiest phase of the stereo depth-finding process. 2. Shape-from-texture can be done by projecting a grid of light-stripes onto the scene. 3. Lines with equal lengths in the scene always project to equal lengths in the image. 4. Straight lines in the image necessarily correspond to straight lines in the scene. <file_sep>[Exercise 12.20](ex_20/) Describe the event of trading something for something else. Describe buying as a kind of trading in which one of the objects traded is a sum of money. <file_sep>[Exercise 23.17 \[washing-clothes2-exercise\]](ex_17/) Without looking back at Exercise [washing-clothes-exercise](#/), answer the following questions: 1. What are the four steps that are mentioned? 2. What step is left out? 3. What is “the material” that is mentioned in the text? 4. What kind of mistake would be expensive? 5. Is it better to do too few things or too many? Why? <file_sep>--- layout: chapter title: Main permalink: /bayes-nets-exercises/ --- {% include mathjax_support %} # 14. Probabilistic Reasoning <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_1" data-rating="0"></i></div> {% include_relative exercises/ex_1/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_2" data-rating="0"></i></div> {% include_relative exercises/ex_2/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_3" data-rating="0"></i></div> {% include_relative exercises/ex_3/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_4" data-rating="0"></i></div> {% include_relative exercises/ex_4/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_5" data-rating="0"></i></div> {% include_relative exercises/ex_5/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_6" data-rating="0"></i></div> {% include_relative exercises/ex_6/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_7" data-rating="0"></i></div> {% include_relative exercises/ex_7/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_8" data-rating="0"></i></div> {% include_relative exercises/ex_8/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_9" data-rating="0"></i></div> {% include_relative exercises/ex_9/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_10" data-rating="0"></i></div> {% include_relative exercises/ex_10/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_11" data-rating="0"></i></div> {% include_relative exercises/ex_11/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_12" data-rating="0"></i></div> {% include_relative exercises/ex_12/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_13" data-rating="0"></i></div> {% include_relative exercises/ex_13/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_14" data-rating="0"></i></div> {% include_relative exercises/ex_14/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_15" data-rating="0"></i></div> {% include_relative exercises/ex_15/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_16" data-rating="0"></i></div> {% include_relative exercises/ex_16/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_17" data-rating="0"></i></div> {% include_relative exercises/ex_17/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_18" data-rating="0"></i></div> {% include_relative exercises/ex_18/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_19" data-rating="0"></i></div> {% include_relative exercises/ex_19/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_20" data-rating="0"></i></div> {% include_relative exercises/ex_20/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_21" data-rating="0"></i></div> {% include_relative exercises/ex_21/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_22" data-rating="0"></i></div> {% include_relative exercises/ex_22/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_23" data-rating="0"></i></div> {% include_relative exercises/ex_23/question.md %} <div><i class="arrow-up loader" data-chapter="bayes-nets-exercises" data-exercise="ex_24" data-rating="0"></i></div> {% include_relative exercises/ex_24/question.md %} <file_sep>[Exercise 23.21](ex_21/) Calculate the most probable path through the HMM in Figure [sr-hmm-figure](#/) for the output sequence $[C_1,C_2,C_3,C_4,C_4,C_6,C_7]$. Also give its probability. <file_sep>[Exercise 11.1](ex_1/) The goals we have considered so far all ask the planner to make the world satisfy the goal at just one time step. Not all goals can be expressed this way: you do not achieve the goal of suspending a chandelier above the ground by throwing it in the air. More seriously, you wouldn’t want your spacecraft life-support system to supply oxygen one day but not the next. A *maintenance goal* is achieved when the agent’s plan causes a condition to hold continuously from a given state onward. Describe how to extend the formalism of this chapter to support maintenance goals. <file_sep>[Exercise 17.10 \[3x3-mdp-exercise\]](ex_10/) Consider the $3 \times 3$ world shown in Figure [grid-mdp-figure](#grid-mdp-figure)(a). The transition model is the same as in the $4\times 3$ Figure [sequential-decision-world-figure](#/): 80% of the time the agent goes in the direction it selects; the rest of the time it moves at right angles to the intended direction. Implement value iteration for this world for each value of $r$ below. Use discounted rewards with a discount factor of 0.99. Show the policy obtained in each case. Explain intuitively why the value of $r$ leads to each policy. 1. $r = -100$ 2. $r = -3$ 3. $r = 0$ 4. $r = +3$ <file_sep>[Exercise 10.7 \[negative-effects-exercise\]](ex_7/) Explain why dropping negative effects from every action schema results in a relaxed problem, provided that preconditions and goals contain only positive literals. <file_sep>[Exercise 24.4](ex_4/) Edges in an image can correspond to a variety of events in a scene. Consider Figure [illuminationfigure](#/) (page [illuminationfigure](#/)), and assume that it is a picture of a real three-dimensional scene. Identify ten different brightness edges in the image, and for each, state whether it corresponds to a discontinuity in (a) depth, (b) surface orientation, (c) reflectance, or (d) illumination. <file_sep>--- layout: exercise title: Exercise 8.22 permalink: /fol-exercises/ex_22/ breadcrumb: 8-First-Order-Logic --- {% include mathjax_support %} <div><i class="arrow-up loader" data-chapter="fol-exercises" data-exercise="ex_22" data-rating="0"></i></div> {% include_relative question.md %} <file_sep>[Exercise 20.11](ex_11/) Consider the application of EM to learn the parameters for the network in Figure [mixture-networks-figure](#/)(a), given the true parameters in Equation ([candy-true-equation](#/)). 1. Explain why the EM algorithm would not work if there were just two attributes in the model rather than three. 2. Show the calculations for the first iteration of EM starting from Equation ([candy-64-equation](#/)). 3. What happens if we start with all the parameters set to the same value $p$? (*Hint*: you may find it helpful to investigate this empirically before deriving the general result.) 4. Write out an expression for the log likelihood of the tabulated candy data on page [candy-counts-page](#/) in terms of the parameters, calculate the partial derivatives with respect to each parameter, and investigate the nature of the fixed point reached in part (c). <file_sep>[Exercise 21.13](ex_13/) Is reinforcement learning an appropriate abstract model for evolution? What connection exists, if any, between hardwired reward signals and evolutionary fitness? <file_sep>[Exercise 19.8](ex_8/) Using the data from the family tree in Figure [family2-figure](#/), or a subset thereof, apply the algorithm to learn a definition for the ${Ancestor}$ predicate. <file_sep>[Exercise 23.6](ex_6/) This exercise concerns grammars for very simple languages. 1. Write a context-free grammar for the language $a^n b^n$. 2. Write a context-free grammar for the palindrome language: the set of all strings whose second half is the reverse of the first half. 3. Write a context-sensitive grammar for the duplicate language: the set of all strings whose second half is the same as the first half. <file_sep>[Exercise 15.8 \[roomba-viterbi-exercise\]](ex_8/) Consider a version of the vacuum robot (page [vacuum-maze-hmm2-figure](#/)) that has the policy of going straight for as long as it can; only when it encounters an obstacle does it change to a new (randomly selected) heading. To model this robot, each state in the model consists of a *(location, heading)* pair. Implement this model and see how well the Viterbi algorithm can track a robot with this model. The robot’s policy is more constrained than the random-walk robot; does that mean that predictions of the most likely path are more accurate? <file_sep>[Exercise 17.21](ex_21/) In the *Prisoner’s Dilemma*, consider the case where after each round, Alice and Bob have probability $X$ meeting again. Suppose both players choose the perpetual punishment strategy (where each will choose ${refuse}$ unless the other player has ever played ${testify}$). Assume neither player has played ${testify}$ thus far. What is the expected future total payoff for choosing to ${testify}$ versus ${refuse}$ when $X = .2$? How about when $X = .05$? For what value of $X$ is the expected future total payoff the same whether one chooses to ${testify}$ or ${refuse}$ in the current round? <file_sep>[Exercise 22.5](ex_5/) (Adapted from @Jurafsky+Martin:2000.) In this exercise you will develop a classifier for authorship: given a text, the classifier predicts which of two candidate authors wrote the text. Obtain samples of text from two different authors. Separate them into training and test sets. Now train a language model on the training set. You can choose what features to use; $n$-grams of words or letters are the easiest, but you can add additional features that you think may help. Then compute the probability of the text under each language model and chose the most probable model. Assess the accuracy of this technique. How does accuracy change as you alter the set of features? This subfield of linguistics is called **stylometry**; its successes include the identification of the author of the disputed *Federalist Papers* @Mosteller+Wallace:1964 and some disputed works of Shakespeare @Hope:1994. @Khmelev+Tweedie:2001 produce good results with a simple letter bigram model.
3b56266df5a50b8001bf0dddfeca30579fdd828a
[ "Markdown", "JavaScript" ]
352
Markdown
Nalinc/sachinAIMA.github.io
b7d3d67bbf01830ee7883b6c287b767233d3df13
673e87c4ced83c137c915ef3ac46a8754f71162b
refs/heads/master
<repo_name>ci-wdi-900/boolean-basics-exercise<file_sep>/main.js /******************** * YOUR CODE BELOW! * ********************/ /******************************************************************************************** * CODE BELOW IS FOR EXPORTING THE VARIABLES AND FUNCTIONS YOU WROTE ABOVE TO MAIN.TEST.JS. * * THIS IS FOR INTERNAL USE ONLY * * DON'T ADD TO OR CHANGE ANYTHING BELOW! * ********************************************************************************************/ if (typeof iGetTheJoke === 'undefined') { iGetTheJoke = undefined; } if (typeof havingFun === 'undefined') { havingFun = undefined; } if (typeof learning === 'undefined') { learning = undefined; } if (typeof killingIt === 'undefined') { killingIt = undefined; } if (typeof isOpposite === 'undefined') { isOpposite = undefined; } if (typeof returnFalse === 'undefined') { returnFalse = undefined; } if (typeof both === 'undefined') { both = undefined; } if (typeof either === 'undefined') { either = undefined; } if (typeof firstOnly === 'undefined') { firstOnly = undefined; } if (typeof secondOnly === 'undefined') { secondOnly = undefined; } if (typeof neither === 'undefined') { neither = undefined; } if (typeof itsComplicated === 'undefined') { itsComplicated = undefined; } module.exports = { iGetTheJoke, havingFun, learning, killingIt, returnFalse, isOpposite, both, either, firstOnly, secondOnly, neither, itsComplicated, }<file_sep>/README.md # Foolin' With Booleans ### Introduction ```javascript divingIntoBooleans = true; ``` ### What You'll Learn * You'll be flexing your value-returning `function` muscles. * And you'll be trying your hand at: * Literal `boolean` values. * The unary `not` operator (`!`). * The binary `boolean` operators (`&&` and `||`). ### Tasks ![programmer joke: !false (it's funny because it's true)](https://storage.googleapis.com/replit/images/1569512326719_407dad6e2667dc94c76a8c0bcc18e25d.jpeg) Let's make some `booleans`! * Create a variable named `iGetTheJoke` and set it equal to a boolean value that corresponds to whether or not the above joke is awesome. * Create a variable called `havingFun` that holds the boolean value that corresponds to whether or not you are. In general, if not in this exercise. * Create a variable called `learning` that holds the boolean value that corresponds to whether or not you are. * Create a variable called `killingIt` and define it **in terms of the previous two variables** such that it is true if and only if both are. What this means is that if we changed the value of `learning` and `havingFun`, `killingIt` would automatically change to reflect it! Now let's make some functions! * Create a function named `returnFalse` that takes one parameter and _always_ returns `false` _no matter what the parameter is_! * Create a function named `isOpposite` that takes one parameter that is a boolean and returns the opposite of it! * Create a function named `both` that takes two parameters that are `booleans` and returns `true` if they're both `true`, and `false` otherwise. * Create a function named `either` that takes in two parameters that are `booleans` and returns `true` if either is `true`, and `false` otherwise. * Create a function named `firstOnly` that takes in two parameters and returns `true` only if the first parameter is `true` and the second parameter is `false`, otherwise returning `false`. * Create a function named `secondOnly` that takes in two parameters and returns `true` only if the second parameter is `true` and the first parameter is `false`, otherwise returning `false`. * Create a function named `neither` that takes in two parameters that are `booleans` and returns `true` if they're both `false`, and otherwise returns `false`. * Create a function named `itsComplicated` that returns `true` if the first parameter is `false` **OR** if both the second and third are `true`. Otherwise it returns `false`.
8e7201ca10a1057e8ece874e4b011cacea7162fa
[ "JavaScript", "Markdown" ]
2
JavaScript
ci-wdi-900/boolean-basics-exercise
ac5294ec0be35608d7b9844a8fc678bf82b497f2
5fa508f2997fd6859930d3c20aae578aebd2de81
refs/heads/master
<repo_name>SravyaBurugala/Project<file_sep>/StringEx.java package com.test.thread; public class StringEx { public static void main(String[] args) { String s1="abc"; String s2="abc"; System.out.println(s1==s2); String s3=s1.concat("hai"); System.out.println("s3 is "+s3); String s4=new String("abc"); String s5=new String("abc"); System.out.println("s4 is equal to s5"+(s4==s5)); System.out.println("s4 is equal to s5"+(s4==s1)); s4.concat("How r u"); //System.out.println("s4 is "+s4); } }
fc8f683766c2025092e1856f3a210c16b0092038
[ "Java" ]
1
Java
SravyaBurugala/Project
62d06de82f85a9dad7fd78ba6c4710cdac1871da
1bfff88f80bf2e4660d537ac3492daad35c0bc1c
refs/heads/master
<repo_name>busyrat/sensitive-code<file_sep>/bin/main.js #! /usr/bin/env node const execSync = require("child_process").execSync; const fs = require("fs"); const path = require("path"); const USER_HOME = process.env.HOME || process.env.USERPROFILE; const cfgPath = path.join(USER_HOME, ".sensicode/config.js"); let words = []; if (fs.existsSync(cfgPath)) { words = require(cfgPath).words || []; } const sensiWords = `(${words.join('|')})`; let results; try { results = execSync(`git grep -n -P "${sensiWords}"`, { encoding: "utf-8" }); } catch (e) { process.exit(0); } if (results) { console.error("发现敏感词:"); console.error(results.trim()); process.exit(1); } process.exit(0); <file_sep>/README.md # sensitive-code > 检查代码里面是否包含敏感代码,避免上传一些敏感的代码 默认读取用户根目录的 .sensicode/config.js ```js module.exports = { words: ['xxx'] } ``` ## 安装 ```shell npm install -g sensitive-code ``` ### 配合 husky 使用 - 安装依赖 `yarn add husky -D` - 在 package.json 中添加 ```js "husky": { "hooks": { "pre-commit": "sensicode" } } ``` ### 零依赖 把 bin 目录下的执行文件 直接复制到项目的 .git/hooks/pre-commit
df171eb3283b06fa66a6e84b18a12d6c2ac5ecd2
[ "JavaScript", "Markdown" ]
2
JavaScript
busyrat/sensitive-code
9b091c83fed2f1021cf84673d671909ff3a493b1
a5221c571053776b3da5554fa666ecf4e392a07a
refs/heads/master
<file_sep>{% load tag_shop %} {% if messages %} <div class="container"> {% for message in messages %} <div class="alert {{message.tags|get_class}} alert-dismissible fade show" role="alert"> <strong>{{message}}</strong> {% comment "For test" %} <p>{{message.tags}} ----- {{message.tags|capfirst}}</p> {% endcomment %} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} </div> {% endif %} <file_sep>from django.db import models from django.core.mail import send_mail from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.validators import UnicodeUsernameValidator from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Not email')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=<PASSWORD>, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def __str__(self): return self.email def get_short_name(self): return self.email def get_full_name(self): return " ".join(('author',self.first_name,self.last_name)) def send_email_user(self, subject, message, from_email=None, **kwargs): pass <file_sep># Generated by Django 2.2 on 2019-04-06 14:06 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('path', django.contrib.postgres.fields.ArrayField(base_field=models.IntegerField(), size=None)), ('text', models.CharField(max_length=200)), ('pud_date', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='LikePost', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('vote', models.SmallIntegerField(choices=[(-1, 'Не нравится'), (1, 'Нравится')], verbose_name='Голос')), ('object_id', models.SmallIntegerField()), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=120)), ('text', models.TextField()), ('created_date', models.DateTimeField(auto_now_add=True)), ('pub_date', models.DateTimeField(blank=True, null=True)), ('status', models.BooleanField(default=False)), ], ), ] <file_sep>{% load bootstrap4 %} <div class="container"> <div class="mt-3"> <p class="text-center">{{title}}</p> </div> <div class="mt-3"> <form action="" method='post' enctype="multipart/form-data" > {% csrf_token %} {% bootstrap_form form layout='horizontal'%} <input type="submit" value="Сохранить" class="btn btn-primary"> </form> </div> </div> <file_sep>from django.shortcuts import render, HttpResponse, redirect from django.contrib.auth.decorators import login_required from .models import Comment,Post,LikePost from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType User = get_user_model() @login_required def home(request): posts = Post.objects.filter(status=True).order_by('-pub_date') return render(request, 'post/post_all.html', {'posts':posts}) @login_required def post(request, id): post = Post.objects.select_related().get(id=id) return render(request, 'post/post.html', {'post':post}) @login_required def add_comment(request, id): return HttpResponse('add comment') @login_required def my_like(request,id): post = Post.objects.get(id=id) obj_type = ContentType.objects.get_for_model(post) like, is_created = LikePost.objects.get_or_create( content_type=obj_type, object_id=id, user=request.user) print('AAAAA',is_created) like.like_() like.save() print(like) return redirect('home') @login_required def dislike(reques,id): pass <file_sep>Django==2.2 django-bootstrap4==0.0.8 psycopg2==2.7.7 pytz==2018.9 sqlparse==0.3.0 <file_sep>from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from django.core.mail import EmailMessage from .tokens import account_activation_token from .forms import SignUpForm from .models import User def register(request): form = SignUpForm() if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): # user = form.save(commit=False) # user.is_active = False # user.save() user = form.save() current_site = get_current_site(request) mail_title = 'Activate your blog account.' message = render_to_string('user_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_title, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') return render(request, 'user/register.html', {'form': form}) def activate(request,uidb64,token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('home') # return HttpResponse('Thank you for your email confirmation. Now you can login your account.') return HttpResponse('Activation link is invalid!') def reactivate(request, uidb64): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): return HttpResponse('Activation link is invalid!') current_site = get_current_site(request) mail_title = 'Re-Activate your blog account.' message = render_to_string('user_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = user.email email = EmailMessage( mail_title, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') <file_sep>import re def func(text): if text.isalpha(): result = ''.join([i for i in text if not i.isdigit()]) print('Букв -> ', len(''.join(c for c in result if c not in '?:!/; '))) elif text.isdigit(): x = re.findall('(\d+)', text) print('Цифр -> ', len(x[0])) elif text.isalnum(): result = ''.join([i for i in text if not i.isdigit()]) print('Букв -> ', len(''.join(c for c in result if c not in '?:!/; '))) x = re.findall('(\d+)', text) print('Цифр -> ', len(x[0])) if __name__ == '__main__': func(input('Введите предложение -> ')) <file_sep>from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns=[ path('register', views.register, name='register'), path('activate/<str:uidb64>/<str:token>', views.activate, name='activate'), path('login', auth_views.LoginView.as_view(template_name='user/login.html'), name='login'), path('logout', auth_views.LogoutView.as_view(next_page='register'), name='logout'), path('reactivate/<str:uidb64>', views.reactivate, name='reactivate'), ] <file_sep>{% extends 'base.html'%} {% block content %} <div class="container"> <div class="card"> <div class="card-body"> <div class="card-title"> {{post.title}} </div> <div class="card-body"> {{post.text}} </div> <div class="add-comment"> <a href="{% url 'add_comment' id=post.id %}">Добавить комментарий</a> </div> <div class="comment"> {% for comment in post.set__post_id%} {% endfor %} </div> <div class="card-footer"> <p> {{post.auhtor}}</p> {{post.pub_date}} </div> </div> </div> </div> {% endblock %} <file_sep>from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('post/<str:id>', views.post, name='post'), path('post/<str:id>/add_comment', views.add_comment, name='add_comment'), path('like/<str:id>', views.my_like, name='my_like'), ] <file_sep>from django.db import models from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation from django.db.models import Sum from django.contrib.postgres.fields import ArrayField from django.utils import timezone class LikeManager(models.Manager): use_for_related_fields = True # def likes(self): # return self.get_queryset().filter(vote__gt=0) # # def dislikes(self): # return self.get_queryset().filter(vote__lt=0) def sum_rating(self): return self.get_queryset().aggregate(Sum('vote')).get('vote__sum') or 0 def posts(self): return self.get_queryset().filter(content_type__model='post').order_by('-posts__pub_date') def comments(self): return self.get_queryset().filter(content_type__model='comment').order_by('-comments__pub_date') class LikePost(models.Model): # LIKE = 1 # DISLIKE = -1 # # VOTES = ((DISLIKE, 'Не нравится'),(LIKE, 'Нравится')) # vote = models.SmallIntegerField(verbose_name=("Голос"), choices=VOTES) like = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='likepost', on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.SmallIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return str(self.like) # objects = LikeManager() def like_(self): self.like = not (self.like) class Post(models.Model): title = models.CharField(max_length=120) text = models.TextField() like = GenericRelation(LikePost, related_query_name='posts') auhtor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) pub_date = models.DateTimeField(blank=True, null=True) status = models.BooleanField(default=False) def publish(self): self.pub_date = timezone.now() self.save() def __str__(self): return self.title def total_like(self): return self.like.filter(like=True).count() class Comment(models.Model): path = ArrayField(models.IntegerField()) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) author_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.CharField(max_length=200) pud_date = models.DateTimeField(auto_now_add=True) like = GenericRelation(LikePost, related_query_name='comments') def __str__(self): return self.text def get_offset(self): level = len(self.path) - 1 if level > 5:level = 5 return level def get_col(self): level = len(self.path) - 1 if level > 5:level = 5 return 12 - level <file_sep>def func(): for i in range(a, b+1): if i % c == 0: X.append(i) if __name__ == '__main__': X = [] a = int(input('Введите первое число -> ')) b = int(input('Введите второе число -> ')) c = int(input('Введите третье число -> ')) func() val = ','.join(map(str, X)) print(f"{len(X)} потому что {val} делятся на {c}.") <file_sep>list = [ ("Tom", "19", "167", "54"), ("Jony", "24", "180", "69"), ("Json", "21", "185", "75"), ("John", "27", "190", "87"), ("Jony", "24", "191", "98"), ] def func(): list.sort(key=lambda i: i[n], reverse=True) print(list) if __name__ == '__main__': n = input('Отсортировать по имени нажмите [1], по возрасту [2], по росту [3], по весу [4]\n' '---> ') n = int(n) - 1 func()
dc8269d88540d1a2c25b8254c61dfc8048b9985b
[ "Python", "Text", "HTML" ]
14
HTML
DmitriyPosypaiko/DB2limited
b657507dd3b5aeb0dad2a92b86d82756b67a7198
de587bc5a6abbef23cab58d6d86fe5232a7f0d15
refs/heads/master
<repo_name>objectobject-hr/sdc-service-aaron<file_sep>/client/src/components/calendar-display-booking.jsx // jshint esversion:6 import React from 'react'; import Calendar from './calendar.jsx'; import SVG from 'react-inlinesvg'; import CheckIcon from '../../dist/icons/tick.svg'; import MinusIcon from '../../dist/icons/negative.svg'; import InfoIcon from '../../dist/icons/Info_Simple.svg'; import { connect } from 'react-redux'; import {setCheckInDate, setCheckOutDate, setTotal, startLoading, stopLoading, makeValid, makeInvalid, setDays, toggleCalendar} from '../redux/booking/booking.action.js'; import { selectCheckInDate, selectCheckOutDate, selectRate, selectCleaningFee, selectFee, selectGuests} from '../redux/booking/booking.selectors.js'; class CalendarDisplayBooking extends React.Component { constructor() { super(); let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; let monthNumbers = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']; let datesInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let daysInWeek = ['S', 'M', 'T', 'W', 'T', 'F', 'S']; let startDates = { '2019': [2, 5, 5, 1, 3, 6, 1, 4, 0, 2, 5, 0], '2020': [3, 6, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2] }; let years = [2019, 2020]; let dates = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']; this.state = { check_in: '', check_out: '', check_in_number: '', check_out_number: '', year: 2019, month: 'December', message: true, valid: false, error: false }; this.openMessage = this.openMessage.bind(this); this.closeMessage = this.closeMessage.bind(this); this.handleLeftClick = this.handleLeftClick.bind(this); this.handleRightClick = this.handleRightClick.bind(this); this.handleCheckInClick = this.handleCheckInClick.bind(this); this.handleCheckInClick2 = this.handleCheckInClick2.bind(this); this.selectSecondMonth = this.selectSecondMonth.bind(this); this.clearDates = this.clearDates.bind(this); this.endLoading = this.endLoading.bind(this); this.calculateTotal = this.calculateTotal.bind(this); this.closeCalendarForm = this.closeCalendarForm.bind(this); } closeCalendarForm(e) { this.props.toggleCalendar(); } calculateTotal() { let date1 = new Date(this.props.selectCheckInDate); let date2 = new Date(this.props.selectCheckOutDate); let Difference_In_Time = date2.getTime() - date1.getTime(); let Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24); this.props.setDays(Difference_In_Days); let subTotal = Difference_In_Days * this.props.selectRate + this.props.selectFee + this.props.selectCleaningFee * Math.pow(this.props.selectGuests, 0.5); let total = subTotal * 1.1; this.props.setTotal(total); } clearDates(e) { this.setState({check_in_number: '', check_in: '', check_out_number: '', check_out: ''}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }); } endLoading() { this.props.stopLoading(); } handleCheckInClick(e) { let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; let monthNumbers = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']; let dates2 = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']; if (!this.state.check_in_number) { if (e.target.childNodes[0].childNodes.length) { this.setState({check_in_number: e.target.childNodes[0].innerHTML, check_out_number: ''}, () => this.setState({check_in: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); })); } else { this.setState({check_in_number: e.target.innerHTML, check_out_number: ''}, () => this.setState({check_in: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); })); } } else if (this.state.check_in_number && !this.state.check_out_number) { if (e.target.childNodes[0].childNodes.length) { if (this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(e.target.childNodes[0].innerHTML) - 1] <= this.state.check_in) { this.setState({check_in_number: e.target.childNodes[0].innerHTML, check_out_number: ''}, () => this.setState({check_in: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => this.setState({valid: false, error: true, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } else { this.setState({check_out_number: e.target.childNodes[0].innerHTML}, () => this.setState({check_out: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_out_number) - 1]}, () => this.setState({valid: true, error: false, message: true}, () => { this.props.setCheckOutDate(this.state.check_out); this.props.makeValid(); this.props.startLoading(); setTimeout(() => { this.calculateTotal(); this.endLoading(); }, 3000); }))); } } else { if (this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(e.target.innerHTML) - 1] <= this.state.check_in) { this.setState({check_in_number: e.target.innerHTML, check_out_number: ''}, () => this.setState({check_in: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => this.setState({valid: false, error: true, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } else { this.setState({check_out_number: e.target.innerHTML}, () => this.setState({check_out: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_out_number) - 1]}, () => this.setState({valid: true, error: false, message: true}, () => { this.props.setCheckOutDate(this.state.check_out); this.props.makeValid(); this.props.startLoading(); setTimeout(() => { this.calculateTotal(); this.endLoading(); }, 3000); }))); } } } else { e.persist(); this.setState({check_in: '', check_out: '', check_in_number: '', check_out_number: ''}, () => { if (e.target.childNodes[0].childNodes.length) { this.setState({check_in_number: e.target.childNodes[0].innerHTML}, () => this.setState({check_in: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_in_number) - 1]}, () => this.setState({valid: false, error: false, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } else { this.setState({check_in_number: e.target.innerHTML}, () => this.setState({check_in: this.state.year + '-' + monthNumbers[months.indexOf(this.state.month)] + '-' + dates2[Number(this.state.check_in_number) - 1]}, () => this.setState({valid: false, error: false, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } }); } } selectSecondMonth(month, year) { let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; if (month === 'December' && year === 2019) { return 'January'; } else if (month === 'December' && year === 2020) { return null; } else { return months[months.indexOf(month) + 1]; } } handleCheckInClick2(e) { let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; let monthNumbers = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']; let dates2 = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']; let year2 = (this.state.month === 'December' && this.state.year === 2019) ? 2020 : this.state.year; let month2 = this.selectSecondMonth(this.state.month, this.state.year); let month2Number = monthNumbers[months.indexOf(month2)]; if (!this.state.check_in_number) { if (e.target.childNodes[0].childNodes.length) { this.setState({check_in_number: e.target.childNodes[0].innerHTML, check_out_number: ''}, () => this.setState({check_in: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); })); } else { this.setState({check_in_number: e.target.innerHTML, check_out_number: ''}, () => this.setState({check_in: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); })); } } else if (this.state.check_in_number && !this.state.check_out_number) { if (e.target.childNodes[0].childNodes.length) { if (year2 + '-' + month2Number + '-' + dates2[Number(e.target.childNodes[0].innerHTML) - 1] <= this.state.check_in) { this.setState({check_in_number: e.target.childNodes[0].innerHTML, check_out_number: ''}, () => this.setState({check_in: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => this.setState({valid: false, error: true, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } else { this.setState({check_out_number: e.target.childNodes[0].innerHTML}, () => this.setState({check_out: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_out_number) - 1]}, () => this.setState({valid: true, error: false, message: true}, () => { this.props.setCheckOutDate(this.state.check_out); this.props.makeValid(); this.props.startLoading(); setTimeout(() => { this.calculateTotal(); this.endLoading(); }, 3000); }))); } } else { if (year2 + '-' + month2Number + '-' + dates2[Number(e.target.innerHTML) - 1] <= this.state.check_in) { this.setState({check_in_number: e.target.innerHTML, check_out_number: ''}, () => this.setState({check_in: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_in_number) - 1], check_out: ''}, () => this.setState({valid: false, error: true, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } else { this.setState({check_out_number: e.target.innerHTML}, () => this.setState({check_out: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_out_number) - 1]}, () => this.setState({valid: true, error: false, message: true}, () => { this.props.setCheckOutDate(this.state.check_out); this.props.makeValid(); this.props.startLoading(); setTimeout(() => { this.calculateTotal(); this.endLoading(); }, 3000); }))); } } } else { e.persist(); this.setState({check_in: '', check_out: '', check_in_number: '', check_out_number: ''}, () => { if (e.target.childNodes[0].childNodes.length) { this.setState({check_in_number: e.target.childNodes[0].innerHTML}, () => this.setState({check_in: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_in_number) - 1]}, () => this.setState({valid: false, error: false, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } else { this.setState({check_in_number: e.target.innerHTML}, () => this.setState({check_in: year2 + '-' + monthNumbers[months.indexOf(month2)] + '-' + dates2[Number(this.state.check_in_number) - 1]}, () => this.setState({valid: false, error: false, message: true}, () => { this.props.setCheckInDate(this.state.check_in); this.props.setCheckOutDate(this.state.check_out); this.props.makeInvalid(); }))); } }); } } openMessage(e) { this.setState({message: true}); } closeMessage(e) { this.setState({message: false}); } componentDidMount() { } handleLeftClick(e) { let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; if (this.state.month === 'January' && this.state.year === 2019) { } else if (this.state.month === 'January' && this.state.year === 2020) { this.setState({month: 'December', year: 2019}); } else { this.setState({month: months[months.indexOf(this.state.month) - 1]}); } } handleRightClick() { let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; if (this.state.month === 'December' && this.state.year === 2019) { this.setState({month: 'January', year: 2020}); } else if (this.state.month === 'November' && this.state.year === 2020) { } else { this.setState({month: months[months.indexOf(this.state.month) + 1]}); } } render() { let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; let icon; let text; let containerClass; if (this.state.valid) { icon = CheckIcon; text = 'Your dates are available'; containerClass = 'al-green-container'; } else if (this.state.error) { icon = MinusIcon; text = 'Check out date must be after check in date'; containerClass = 'al-red-container'; } else { icon = InfoIcon; text = '1 night minimum stay'; containerClass = 'al-blue-container'; } return ( <div className={`${this.state.message ? 'al-calendar-display-large' : 'al-calendar-display'}`}> <div className='al-calendars-container'> <div className='al-calendar-container1'> <Calendar year={this.state.year} month={this.state.month} check_in={this.state.check_in} check_out={this.state.check_out} check_in_number={this.state.check_in_number} check_out_number={this.state.check_out_number} handleCheckInClick={this.handleCheckInClick}/> </div> <div className='al-calendar-container2'> <Calendar year={`${(this.state.month === 'December' && this.state.year === 2019) ? 2020 : this.state.year}`} month={this.selectSecondMonth(this.state.month, this.state.year)} check_in={this.state.check_in} check_out={this.state.check_out} check_in_number={this.state.check_in_number} check_out_number={this.state.check_out_number} handleCheckInClick={this.handleCheckInClick2}/> </div> </div> <div className={`${containerClass} 'al-calendar-message-area'`}> { this.state.message ? ( <div> <div className='al-calendar-message-close-button-container'> <button className='al-calendar-message-close-button' onClick={this.closeMessage}> <span className='al-calendar-message-close-button-text'>X</span> </button> </div> <div className={`${this.state.error ? 'al-calendar-message-text-adjust' : null} al-calendar-message-container`}> <div className='al-calendar-message-icon-container'> <SVG className='al-calendar-message-icon' src={icon}/> </div> <div className='al-calendar-message-text-container'> <span className='al-calendar-message-text'>{text}</span> </div> </div> </div> ) : ( null ) } </div> <div className={`${this.state.message ? 'al-calendar-left-button-container-booking' : 'al-calendar-left-button-container-booking-flat'}`}> <button className='al-calendar-button' onClick={this.handleLeftClick}> <span className='al-calendar-button-text'>{`<`}</span> </button> </div> <div className={`${this.state.message ? 'al-calendar-right-button-container-booking' : 'al-calendar-right-button-container-booking-flat'}`}> <button className='al-calendar-button' onClick={this.handleRightClick}> <span className='al-calendar-button-text'>{`>`}</span> </button> </div> <div className={`${this.state.message ? 'al-calendar-clear-dates-container-booking' : 'al-calendar-clear-dates-container-booking-flat'}`} onClick={this.clearDates}> <span className='al-calendar-clear-dates-text'>Clear dates </span> </div> <div className={`${this.state.message ? 'al-calendar-close-container-large' : 'al-calendar-close-container-flat'}`} onClick={this.closeCalendarForm}> <div className='al-calendar-close-text-container-booking'> <span className='al-calendar-close-text'>Close</span> </div> </div> </div> ); } }; const mapDispatchToProps = (dispatch) => { return ({ setCheckInDate: (date) => dispatch(setCheckInDate(date)), setCheckOutDate: (date) => dispatch(setCheckOutDate(date)), makeValid: () => dispatch(makeValid()), makeInvalid: () => dispatch(makeInvalid()), startLoading: () => dispatch(startLoading()), stopLoading: () => dispatch(stopLoading()), setTotal: (total) => dispatch(setTotal(total)), setDays: (days) => dispatch(setDays(days)), toggleCalendar: () => dispatch(toggleCalendar()) }); } const mapStateToProps = (state) => { return ({ selectCheckInDate: selectCheckInDate(state), selectCheckOutDate: selectCheckOutDate(state), selectRate: selectRate(state), selectFee: selectFee(state), selectCleaningFee: selectCleaningFee(state), selectGuests: selectGuests(state) }); }; export default connect(mapStateToProps, mapDispatchToProps)(CalendarDisplayBooking);<file_sep>/client/src/components/search-button.jsx // jshint esversion:6 import React from 'react'; const SearchButton = (props) => { return ( <button onClick={props.handleSubmit} className='al-search-button'><span className='al-search-button-text'>Search</span></button> ); }; export default SearchButton;<file_sep>/client/src/components/guests-input.jsx // jshint esversion:6 import React from 'react'; import GuestsForm from './guests-form.jsx'; import { connect } from 'react-redux'; import { selectGuests, selectGuestsForm } from '../redux/booking/booking.selectors.js'; import { toggleGuestsForm } from '../redux/booking/booking.action.js'; class GuestsInput extends React.Component { constructor(props) { super(props); this.state = { guests: 1, selected: false }; this.getGuests = this.getGuests.bind(this); this.toggleForm = this.toggleForm.bind(this); } getGuests(n) { this.setState({guests: n}); } toggleForm(e) { this.props.toggleGuestsForm(); } componentDidMount() { } render() { return ( <div className='al-guests-input'> <div className='al-guests-input-label-container'> <span className='al-guests-input-label-text-bottom'>Guests</span> </div> <div className='al-guests-input-number-container' onClick={this.toggleForm}> <span className='al-guests-input-number-text'>{`${this.props.selectGuests} ${this.props.selectGuests === 1 ? 'guest' : 'guests'}`}</span> </div> <div className='al-guests-form-container'> { this.props.selectGuestsForm ? ( <GuestsForm handleCloseGuestsForm={this.props.handleCloseGuestsForm} getGuests={this.getGuests}/> ) : ( null ) } </div> </div> ); } }; const mapDispatchToProps = (dispatch) => { return ({ toggleGuestsForm: () => dispatch(toggleGuestsForm()) }); } const mapStateToProps = (state) => { return ({ selectGuests: selectGuests(state), selectGuestsForm: selectGuestsForm(state) }); }; export default connect(mapStateToProps, mapDispatchToProps)(GuestsInput);<file_sep>/server/postgres/index.js // jshint esversion:6 const express = require("express"); const bodyParser = require("body-parser"); const morgan = require("morgan"); const path = require("path"); const db = require("../../dbhelpers/postgres/index.js"); // const pool = require("./pool.js"); const app = express(); const PORT = process.env.PORT || 3009; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(morgan("dev")); app.use(express.static(path.join(__dirname, "../../client/dist"))); app.get("/dates/:id", (req, res) => { const id = parseInt(req.params.id); db.query("SELECT * FROM bookingdates WHERE id = $1", [id], (err, results) => { if (err) { res.status(404).send(err); } res.status(200).send(results.rows); }); }); app.get("/listings/search", (req, res) => { let results = []; db.query( `SELECT * FROM listings WHERE title SIMILAR TO '(${req.query.query}%|%${ req.query.query }%|${req.query.query.slice(0, 1).toUpperCase() + req.query.query.slice(1)}%)' LIMIT 10;`, (err, titles) => { if (err) { res.status(404).send(err); } results.push(titles.rows); db.query( `SELECT * FROM listings WHERE city SIMILAR TO '(${req.query.query}%|%${ req.query.query }%|${req.query.query.slice(0, 1).toUpperCase() + req.query.query.slice(1)}%)' LIMIT 10;`, (err, cities) => { if (err) { res.status(404).send(err); } results.push(cities.rows.slice(0, 10 - results.length)); db.query( `SELECT * FROM listings WHERE states SIMILAR TO '(${ req.query.query }%|%${req.query.query}%|${req.query.query .slice(0, 1) .toUpperCase() + req.query.query.slice(1)}%)' LIMIT 10;`, (err, states) => { if (err) { res.status(404).send(err); } results.push(states.rows); res .status(200) .send(results[0].concat(results[1].concat(results[2]))); } ); } ); } ); }); app.get("/mlistings/:id", (req, res) => { console.log(`made it to get mlistings/:id get`); const id = parseInt(req.params.id); db.query("SELECT * FROM listings WHERE id = $1", [id], (err, results) => { if (err) { res.status(404).send(err); } res.status(200).send(results.rows); }); }); app.post("/mlistings", (req, res) => { const { title, venuetype, bedrooms, bathrooms, sleepcapacity, squarefeet, reviewoverview, rating, reviewnumber, owners, cleaningfee, states, city, pic } = req.body; db.query( "INSERT INTO listings (title, venuetype, bedrooms, bathrooms, sleepcapacity, squarefeet, reviewoverview, rating, reviewnumber, owners, cleaningfee, states, city, pic) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING *;", [ title, venuetype, bedrooms, bathrooms, sleepcapacity, squarefeet, reviewoverview, rating, reviewnumber, owners, cleaningfee, states, city, pic ], (err, results) => { if (err) { res.status(404).send(err); } res.status(200).send(results.rows); } ); }); app.put("/mlistings/:id", (req, res) => { console.log(req.body); const id = parseInt(req.params.id); const { title, venuetype, bedrooms, bathrooms, sleepcapacity, squarefeet, reviewoverview, rating, reviewnumber, owners, cleaningfee, states, city, pic } = req.body; db.query( "UPDATE listings SET title = $1, venuetype = $2, bedrooms = $3, bathrooms = $4, sleepcapacity = $5, squarefeet = $6, reviewoverview = $7, rating = $8, reviewnumber = $9, owners = $10, cleaningfee = $11, states = $12, city = $13, pic = $14 WHERE id = $15 RETURNING *;", [ title, venuetype, bedrooms, bathrooms, sleepcapacity, squarefeet, reviewoverview, rating, reviewnumber, owners, cleaningfee, states, city, pic, id ], (err, results) => { if (err) { res.status(404).send(err); } res.status(200).send(results.rows); } ); }); app.delete("/mlistings/:id", (req, res) => { console.log(`made it to mlistings/:id delete`); const id = parseInt(req.params.id); db.query("DELETE FROM listings WHERE id = $1", [id], (err, results) => { if (err) { res.status(404).send(err); } res.status(200).send(results.rows); }); }); app.listen(PORT, () => { console.log("we are listening to port", PORT + ", m o s t l y k e y s"); }); <file_sep>/client/src/components/booking-header.jsx // jshint esversion:6 import React from 'react'; import SVG from 'react-inlinesvg'; import LightningIcon from '../../dist/icons/flash.svg'; import UploadIcon from '../../dist/icons/upload.svg'; import HeartIcon from '../../dist/icons/heart.svg'; import SharedDropdown from './shared-dropdown.jsx'; import SelectedDropdown from './selected-dropdown.jsx'; import Overlay from './overlay.jsx'; import {LoadingDots} from './loading-dots.jsx'; import { connect } from 'react-redux'; import {selectLoading, selectRate} from '../redux/booking/booking.selectors.js'; class BookingHeader extends React.Component { constructor(props) { super(props); this.state = { shared: false, selected: false, loading: false }; this.handleClickShared = this.handleClickShared.bind(this); this.handleClickSelected = this.handleClickSelected.bind(this); this.handleCloseShared = this.handleCloseShared.bind(this); this.handleCloseSelected = this.handleCloseSelected.bind(this); } handleClickShared(e) { this.setState({shared: true, selected: false}); } handleClickSelected(e) { this.setState({selected: true, shared: false}); } handleCloseShared(e) { this.setState({shared: false}); } handleCloseSelected(e) { this.setState({selected: false}); } componentDidMount() { } render() { return ( <div className='al-booking-header'> { this.props.selectLoading ? ( <div className='al-loading-dots-container'> <LoadingDots /> </div> ) : ( <div className='al-booking-subcontainer'> <div className='al-booking-header-flash-container'> <SVG className='al-booking-header-flash' src={LightningIcon} /> </div> <div className='al-booking-header-rate-container'> <h1 className='al-booking-header-rate-text'>{`$${this.props.selectRate}`}</h1> </div> <div className='al-booking-header-nightly-container'> <span className='al-booking-header-nightly-text'>per night</span> </div> <div className='al-booking-header-icons-container'> <div onClick={this.handleClickShared} className='al-booking-header-icon-container'> <SVG className='al-booking-header-icon' src={UploadIcon} /> </div> <div onClick={this.handleClickSelected} className='al-booking-header-icon-container'> <SVG className='al-booking-header-icon' src={HeartIcon} /> </div> </div> <div className='al-shared-dropdown-container'> { this.state.shared ? ( <SharedDropdown handleCloseShared={this.handleCloseShared}/> ) : ( null ) } </div> <div className='al-selected-dropdown-container'> { this.state.selected ? ( <div> <SelectedDropdown handleCloseSelected={this.handleCloseSelected}/> <Overlay /> </div> ) : ( null ) } </div> </div> ) } </div> ); } }; const mapStateToProps = (state) => { return ({ selectLoading: selectLoading(state), selectRate: selectRate(state) }); }; export default connect(mapStateToProps, null)(BookingHeader); <file_sep>/client/src/components/sidebar.jsx // jshint esversion:6 import React from 'react'; import BookingTool from './booking-tool.jsx'; import BookingFooter from './booking-footer.jsx'; class Sidebar extends React.Component { constructor(props) { super(props); this.state = { }; } componentDidMount() { } render() { return ( <div className='al-sidebar'> <div className='al-booking-tool-container al-nav'> <BookingTool /> <div className='al-booking-footer-container'> <BookingFooter /> </div> </div> </div> ); } }; export default Sidebar;<file_sep>/client/src/components/valid-dates-display.jsx // jshint esversion:6 import React from 'react'; import SVG from 'react-inlinesvg'; import CheckIcon from '../../dist/icons/tick.svg'; import { connect } from 'react-redux'; import {selectValid} from '../redux/booking/booking.selectors.js'; class ValidDatesDisplay extends React.Component { constructor(props) { super(props); this.state = { valid: false }; this.toggleValid = this.toggleValid.bind(this); } toggleValid(e) { this.setState({valid: !this.state.valid}); } componentDidMount() { } render() { return ( <div className='al-valid-dates-display'> { this.props.selectValid ? ( <div className='al-valid-dates-display-valid-container'> <div className='al-valid-dates-display-icon-container'> <SVG className='al-valid-dates-display-icon' src={CheckIcon}/> </div> <div className='al-valid-dates-display-text-container'> <span className='al-valid-dates-display-text-valid'>Your dates are available</span> </div> </div> ) : ( <div> <div className='al-valid-dates-display-rectangle'> <div className='al-valid-dates-display-message-container'> <span className='al-valid-dates-display-text'>Enter dates for accurate pricing</span> </div> </div> <div className='al-valid-dates-display-triangle-container'> <div className='al-valid-dates-display-triangle'></div> </div> </div> ) } </div> ); } }; const mapStateToProps = (state) => { return ({ selectValid: selectValid(state) }); }; export default connect(mapStateToProps, null)(ValidDatesDisplay);<file_sep>/client/src/components/guests-form.jsx // jshint esversion:6 import React from 'react'; import SVG from 'react-inlinesvg'; import PeopleIcon from '../../dist/icons/people.svg'; import { connect } from 'react-redux'; import {toggleGuestsForm, setGuests, setCheckInDate, setCheckOutDate, setTotal, startLoading, stopLoading, makeValid, makeInvalid} from '../redux/booking/booking.action.js'; import { selectSleepCapacity, selectCheckInDate, selectCheckOutDate, selectRate, selectCleaningFee, selectFee, selectGuests} from '../redux/booking/booking.selectors.js'; class GuestsForm extends React.Component { constructor(props) { super(props); this.state = { adults: 1, children: 0 }; this.incrementAdults = this.incrementAdults.bind(this); this.incrementChildren = this.incrementChildren.bind(this); this.decrementAdults = this.decrementAdults.bind(this); this.decrementChildren = this.decrementChildren.bind(this); this.handleApply = this.handleApply.bind(this); this.calculateTotal = this.calculateTotal.bind(this); this.setLoading = this.setLoading.bind(this); } calculateTotal() { let date1 = new Date(this.props.selectCheckInDate); let date2 = new Date(this.props.selectCheckOutDate); let Difference_In_Time = date2.getTime() - date1.getTime(); let Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24); console.log(Difference_In_Days); let subTotal = Difference_In_Days * this.props.selectRate + this.props.selectFee + this.props.selectCleaningFee * Math.pow(this.state.adults + this.state.children, 0.5); let total = subTotal * 1.1; this.props.setTotal(total); this.props.stopLoading(); } setLoading() { if (this.props.selectCheckInDate && this.props.selectCheckOutDate) { this.props.startLoading(); setTimeout(() => { this.calculateTotal(); }, 3000); } } incrementAdults() { if (this.state.children + this.state.adults < this.props.selectSleepCapacity) { this.setState({adults: this.state.adults + 1}, () => { }); } } incrementChildren() { if (this.state.children + this.state.adults < this.props.selectSleepCapacity) { this.setState({children: this.state.children + 1}, () => { }); } } decrementAdults() { if (this.state.adults > 1) { this.setState({adults: this.state.adults - 1}, () => { }); } } decrementChildren() { if (this.state.children > 0) { this.setState({children: this.state.children - 1}, () => { }); } } handleApply() { this.props.setGuests(this.state.children + this.state.adults); this.props.toggleGuestsForm(); this.setLoading(); } componentDidMount() { } render() { return ( <div className='al-guests-form'> <div className='al-guests-form-title-container'> <div className='al-guests-form-icon-container'> <SVG className='al-guests-form-icon' src={PeopleIcon}/> </div> <div className='al-guests-form-text-container'> <span className='al-guests-form-text'>{`Maximum number of guests is ${this.props.selectSleepCapacity}`}</span> </div> </div> <div className='al-guests-form-adults-row-container'> <div className='al-guests-form-adults-amount-container'> <span className='al-guests-form-row-text'>{`${this.state.adults} ${this.state.adults === 1 ? 'adult' : 'adults'}`}</span> </div> <div className='al-guests-form-change-amount-form-container'> <div className='al-guests-form-subtract-button-container'> <button className={`${this.state.adults === 1 ? 'al-guests-form-button-invalid' : 'al-guests-form-button-valid'} 'al-guests-form-subtract-button'`} onClick={this.decrementAdults}> <span className='al-guests-form-subtract-text'>-</span> </button> </div> <div className='al-guests-form-add-button-container'> <button className={`${this.state.adults + this.state.children === this.props.selectSleepCapacity ? 'al-guests-form-button-invalid' : 'al-guests-form-button-valid'} 'al-guests-form-add-button'`} onClick={this.incrementAdults}> <span className='al-guests-form-add-text'>+</span> </button> </div> </div> </div> <div className='al-guests-form-childrens-row-container'> <div className='al-guests-form-childrens-amount-container'> <span className='al-guests-form-row-text'>{`${this.state.children} ${this.state.children === 1 ? 'child' : 'children'}`}</span> </div> <div className='al-guests-form-change-amount-form-container'> <div className='al-guests-form-subtract-button-container'> <button className={`${this.state.children === 0 ? 'al-guests-form-button-invalid' : 'al-guests-form-button-valid'} 'al-guests-form-subtract-button'`} onClick={this.decrementChildren}> <span className='al-guests-form-subtract-text'>-</span> </button> </div> <div className='al-guests-form-add-button-container'> <button className={`${this.state.adults + this.state.children === this.props.selectSleepCapacity ? 'al-guests-form-button-invalid' : 'al-guests-form-button-valid'} 'al-guests-form-add-button'`} onClick={this.incrementChildren}> <span className='al-guests-form-add-text'>+</span> </button> </div> </div> </div> <div className='al-guests-form-submit-button-container'> <button className='al-guests-form-submit-button' onClick={this.handleApply}> <span className='al-guests-form-submit-button-text'>Apply</span> </button> </div> </div> ); } }; const mapDispatchToProps = (dispatch) => { return ({ setGuests: (guests) => dispatch(setGuests(guests)), setCheckInDate: (date) => dispatch(setCheckInDate(date)), setCheckOutDate: (date) => dispatch(setCheckOutDate(date)), makeValid: () => dispatch(makeValid()), makeInvalid: () => dispatch(makeInvalid()), startLoading: () => dispatch(startLoading()), stopLoading: () => dispatch(stopLoading()), setTotal: (total) => dispatch(setTotal(total)), toggleGuestsForm: () => dispatch(toggleGuestsForm()) }); } const mapStateToProps = (state) => { return ({ selectSleepCapacity: selectSleepCapacity(state), selectCheckInDate: selectCheckInDate(state), selectCheckOutDate: selectCheckOutDate(state), selectRate: selectRate(state), selectFee: selectFee(state), selectCleaningFee: selectCleaningFee(state), selectGuests: selectGuests(state) }); }; export default connect(mapStateToProps, mapDispatchToProps)(GuestsForm); <file_sep>/client/src/components/booking-submit-form.jsx // jshint esversion:6 import React from 'react'; class BookingSubmitForm extends React.Component { constructor(props) { super(props); this.state = { } } componentDidMount() { } render() { return ( <div className='al-booking-submit-form'> <div className='al-booking-button-container'> <button className='al-booking-button'> <div className='al-booking-button-text-container'> <span className='al-booking-button-text'>Book Now</span> </div> </button> </div> </div> ); } }; export default BookingSubmitForm;<file_sep>/client/src/components/booking-reviews.jsx // jshint esversion:6 import React from 'react'; import StarRatings from 'react-star-ratings'; import { connect } from 'react-redux'; import {selectRating, selectReviewNumber} from '../redux/booking/booking.selectors.js'; class BookingReviews extends React.Component { constructor(props) { super(props); this.state = { }; } componentDidMount() { } render() { return ( <div className='al-booking-reviews'> <div className='al-star-rating-container'> <StarRatings rating={this.props.selectRating} starRatedColor='black' numberOfStars={5} name='rating' starDimension='15px' starSpacing='1.5px'/> </div> <div className='al-reviews-number-container'> <span className='al-reviews-number-text'>{`${this.props.selectReviewNumber} ${this.props.selectReviewNumber === 1 ? 'review' : 'reviews'}`}</span> </div> </div> ); } }; const mapStateToProps = (state) => { return ({ selectRating: selectRating(state), selectReviewNumber: selectReviewNumber(state) }); }; export default connect(mapStateToProps, null)(BookingReviews); <file_sep>/client/src/components/list-property-button.jsx // jshint esversion:6 import React from 'react'; const ListPropertyButton = () => { return ( <button className='al-list-property-button'><span className='al-list-property-button-text'>List your Property</span></button> ); }; export default ListPropertyButton;<file_sep>/README.md # Home Away System Design This project was my personal attempt at creating a more efficient back-end system. At the time of inheriting the legacy code base, base line traffic metrics were at roughly 500 requests per second. Through much testing, I have effectively scaled the back-end system to handle a 400% increase in traffic at roughly 100ms to a single endpoint, given restrictions and other various constraints. ## Table of Contents 1. [Usage](#Usage) 2. [Requirements](#requirements) 3. [Development](#development) ## Usage This project aimed to improve an existing back-end architecture, in an attempt to increase the amount traffic it can handle. To run locally: 1. Install dependencies 2. Inside of ```dbhelpers/postgres/``` open index.js and change - user to your postgres user/password settings - password to your <PASSWORD> user/password settings - host to "localhost" - database to "sdc_pg" - port to "5432" 3. From within the root directory, run ```node pgListingsSeed``` 4. From within the root directory, run ```npm run pgstart``` 5. Test the local api with [artillery.io](https://artillery.io/) ## Requirements - Node 6.13.0 - etc ## Development To test locally, I've used [artillery.io](https://artillery.io/) ### Installing Dependencies From within the root directory: ```sh npm install -g webpack npm install ``` # search-form-booking-tool # search-bar-booking-tool <file_sep>/client/src/components/feedback-form.jsx // jshint esversion:6 import React from 'react'; const FeedbackForm = () => { const options = ['I would like to leave a review for a property', 'I have an issue or question and would like some help', 'I want to leave a comment for this web site']; return ( <div className='al-feedback-form'> <div className='al-feedback-form-top-row'> <div className='al-feedback-form-title-container'> <h3 className='al-feedback-form-title-text'>Site Feedback</h3> <button className='al-feedback-form-button'><span className='al-feedback-form-button-text'>X</span></button> </div> </div> <div className='al-feedback-form-options-container'> { options.length ? ( options.map((option, i) => { return ( <div key={i} className='al-feedback-form-option-container'> <span className='al-feedback-form-option-text'>{option}</span> </div> ); }) ) : ( null ) } </div> </div> ); }; export default FeedbackForm;<file_sep>/client/src/components/booking-tool.jsx // jshint esversion:6 import React from 'react'; import BookingHeader from './booking-header.jsx'; import BookingReviews from './booking-reviews.jsx'; import BookingRating from './booking-rating.jsx'; import ValidDatesDisplay from './valid-dates-display.jsx'; import DatesInput from './dates-input.jsx'; import GuestsInput from './guests-input.jsx'; import BookingSubmitForm from './booking-submit-form.jsx'; import OwnerInfo from './owner-info.jsx'; import CalendarDisplayBooking from './calendar-display-booking.jsx'; import BookingTotal from './booking-total.jsx'; import { connect } from 'react-redux'; import {selectValid, selectCalendar} from '../redux/booking/booking.selectors.js'; import {toggleCalendar} from '../redux/booking/booking.action.js'; class BookingTool extends React.Component { constructor(props) { super(props); this.state = { check_in: '', check_out: '', guests: false, calendar: false, total: true, header_loading: false, total_loading: false, valid_dates: false }; this.handleCheckInSelect = this.handleCheckInSelect.bind(this); this.handleCheckOutSelect = this.handleCheckOutSelect.bind(this); this.handleGuestsForm = this.handleGuestsForm.bind(this); this.handleCloseGuestsForm = this.handleCloseGuestsForm.bind(this); this.openCalendar = this.openCalendar.bind(this); this.closeCalendar = this.closeCalendar.bind(this); this.handleTotal = this.handleTotal.bind(this); } handleTotal(e) { this.setState({total: !this.state.total}); } handleCheckInSelect(e) { this.setState({check_in: e.target.value}); } handleCheckOutSelect(e) { this.setState({check_out: e.target.value}); } openCalendar(e) { this.setState({calendar: true}); } closeCalendar(e) { this.setState({calendar: false}); } componentDidMount() { } handleGuestsForm(e) { this.setState({guests: true}); } handleCloseGuestsForm(e) { this.setState({guests: false}); } render() { let style = this.state.total ? 'al-booking-tool-total' : 'al-booking-tool'; return ( <div className={style}> <div className='al-booking-header-container'> <BookingHeader header_loading={this.state.header_loading}/> </div> <div className='al-booking-reviews-container'> <BookingReviews /> </div> <div className='al-booking-rating-container'> <BookingRating/> </div> <div className='al-valid-dates-display-container'> <ValidDatesDisplay valid_dates={this.state.valid_dates}/> </div> <div className='al-dates-input-container'> <DatesInput openCalendar={this.openCalendar} handleCheckInSelect={this.handleCheckInSelect} handleCheckOutSelect={this.handleCheckOutSelect} check_in={this.state.check_in} check_out={this.state.check_out}/> </div> <div className='al-guests-input-container'> <GuestsInput guests={this.state.guests} handleGuestsForm={this.handleGuestsForm} handleCloseGuestsForm={this.handleCloseGuestsForm}/> </div> <div className='al-booking-total-container'> { this.props.selectValid ? ( <BookingTotal total_loading={this.state.total_loading}/> ) : ( null ) } </div> <div className='al-booking-submit-form-container'> <BookingSubmitForm /> </div> <div className='al-owner-info-container'> <OwnerInfo /> </div> <div className='al-booking-calendar-container'> { this.props.selectCalendar ? ( <CalendarDisplayBooking closeCalendar={this.closeCalendar}/> ) : ( null ) } </div> </div> ); } } const mapStateToProps = (state) => { return ({ selectValid: selectValid(state), selectCalendar: selectCalendar(state) }); }; const mapDispatchToProps = (dispatch) => { return ({ toggleCalendar: () => dispatch(toggleCalendar()) }); } export default connect(mapStateToProps, mapDispatchToProps)(BookingTool);<file_sep>/dbhelpers/sqlfiles/createtable.sql DROP TABLE IF EXISTS listings; DROP TABLE IF EXISTS dates; CREATE TABLE listings ( id serial primary key, title varchar(355), venuetype varchar(355), bedrooms int, bathrooms int, sleepcapacity int, squarefeet int, reviewoverview varchar(355), rating varchar(355), reviewnumber int, owners varchar(355), cleaningfee varchar(355), states varchar(355), city varchar(355), pic varchar(355) ); CREATE TABLE dates ( id serial primary key, dates varchar(355), available BOOLEAN not null, checkin BOOLEAN not null, rate varchar(355), checkout BOOLEAN not null, listingid int );<file_sep>/client/src/components/search-dropdown.jsx // jshint esversion:6 import React from 'react'; import SearchResult from './search-result.jsx'; const SearchDropdown = (props) => { return ( <div className='al-search-dropdown'> { props.searchlistings.length ? ( props.searchlistings.map((searchlisting, i) => { return ( <SearchResult selectSearchResult={props.selectSearchResult} searchlisting={searchlisting} key={i}/> ); }) ) : ( null ) } </div> ); }; export default SearchDropdown;<file_sep>/dbhelpers/sqlfiles/dates.sql DROP TABLE IF EXISTS dates; CREATE TABLE dates( id serial primary key, dates varchar(200), available BOOLEAN not null, check_in BOOLEAN not null, rate float, check_out BOOLEAN not null, listing_id int )<file_sep>/client/src/components/flag-dropdown.jsx // jshint esversion:6 import React from 'react'; import SVG from 'react-inlinesvg'; import USAFlag from '../../dist/icons/united-states-of-america.svg'; import AustraliaFlag from '../../dist/icons/australia.svg'; import BrazilFlag from '../../dist/icons/brazil.svg'; import DenmarkFlag from '../../dist/icons/denmark.svg'; import GermanyFlag from '../../dist/icons/germany.svg'; import SpainFlag from '../../dist/icons/spain.svg'; import FranceFlag from '../../dist/icons/france.svg'; import ItalyFlag from '../../dist/icons/italy.svg'; import MexicoFlag from '../../dist/icons/mexico.svg'; import NewZealandFlag from '../../dist/icons/new-zealand.svg'; import NorwayFlag from '../../dist/icons/norway.svg'; import SwitzerlandFlag from '../../dist/icons/switzerland.svg'; import IrelandFlag from '../../dist/icons/ireland.svg'; import SingaporeFlag from '../../dist/icons/singapore.svg'; import SriLankaFlag from '../../dist/icons/sri-lanka.svg'; import FinlandFlag from '../../dist/icons/finland.svg'; import SwedenFlag from '../../dist/icons/sweden.svg'; import UnitedKingdomsFlag from '../../dist/icons/united-kingdom.svg'; import CanadaFlag from '../../dist/icons/canada.svg'; import GreeceFlag from '../../dist/icons/greece.svg'; import JapanFlag from '../../dist/icons/japan.svg'; const FlagDropdown = () => { return ( <div className='al-flag-dropdown'> <table className='al-flag-table'> <tbody className='al-flag-table-body'> <tr className='al-flag-table-row'> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={USAFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>United States</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={AustraliaFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Australia</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={BrazilFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Brasil</span> </div> </td> </tr> <tr className='al-flag-table-row'> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={DenmarkFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Danmark</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={GermanyFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Deutschland</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={SpainFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>España</span> </div> </td> </tr> <tr className='al-flag-table-row'> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={FranceFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>France</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={ItalyFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Italia</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={MexicoFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>México</span> </div> </td> </tr> <tr className='al-flag-table-row'> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={NewZealandFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>New Zealand</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={NorwayFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Norge</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={SwitzerlandFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Switzerland</span> </div> </td> </tr> <tr className='al-flag-table-row'> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={IrelandFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Ireland</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={SingaporeFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Singapore</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={SriLankaFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Sri Lanka</span> </div> </td> </tr> <tr className='al-flag-table-row'> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={FinlandFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Suomi</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={SwedenFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Sverige</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={UnitedKingdomsFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>United Kingdoms</span> </div> </td> </tr> <tr className='al-flag-table-row'> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={CanadaFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Canada</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={GreeceFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Greece</span> </div> </td> <td className='al-flag-table-entry'> <div className='al-flag-language-container'> <SVG src={JapanFlag} className='al-flag-icon'/> <span className='al-flag-language-text'>Japan</span> </div> </td> </tr> </tbody> </table> </div> ); }; export default FlagDropdown;<file_sep>/client/src/components/App.1.jsx // jshint esversion:6 import React from 'react'; import Header from './header.jsx'; import Sidebar from './sidebar.jsx'; import axios from 'axios'; import {setRate, setTotal, setTitle, setSleepCapacity, setReviewOverview, setRating, setReviewNumber, setOwner, setCleaningFee, setUSState, setCity, setPic} from '../redux/booking/booking.action.js'; import { connect } from 'react-redux'; class App1 extends React.Component { constructor() { super(); this.state = { check_in_date: '', check_out_date: '', adults: null, children: null, reviews: null, cleaning_fee: null, owner: '', rating: null, total: null }; } componentDidMount() { // let randomNumber = Math.floor(Math.random() * 104) + 1; // axios.get(`/mlistings/${randomNumber}`) // .then((results) => results.data[0]).catch(err => console.log(err)) // .then(data => { // this.props.setTitle(data.title); // this.props.setSleepCapacity(data.sleep_capacity); // this.props.setUSState(data.state); // this.props.setReviewOverview(data.review_overview); // this.props.setRating(data.rating); // this.props.setReviewNumber(data.review_number); // this.props.setOwner(data.owner); // this.props.setCleaningFee(data.cleaning_fee); // this.props.setCity(data.city); // this.props.setPic(data.pic); // return data.id; // }) // .then(id => axios.get(`/dates/${id}`)) // .then(dates => this.props.setRate(dates.data[0].rate)) // .catch(error => console.log(error)); // ; } render() { return ( <div className='al-test-container'> <div className='al-sidebar-container'> <Sidebar /> </div> </div> ); } } const mapDispatchToProps = (dispatch) => { return ({ setRate: (rate) => dispatch(setRate(rate)), setTotal: (total) => dispatch(setTotal(total)), setTitle: (title) => dispatch(setTitle(title)), setSleepCapacity: (sleep_capacity) => dispatch(setSleepCapacity(sleep_capacity)), setReviewOverview: (review_overview) => dispatch(setReviewOverview(review_overview)), setRating: (rating) => dispatch(setRating(rating)), setReviewNumber: (review_number) => dispatch(setReviewNumber(review_number)), setOwner: (owner) => dispatch(setOwner(owner)), setCleaningFee: (cleaning_fee) => dispatch(setCleaningFee(cleaning_fee)), setUSState: (USState) => dispatch(setUSState(USState)), setCity: (city) => dispatch(setCity(city)), setPic: (pic) => dispatch(setPic(pic)) }); } export default connect(null, mapDispatchToProps)(App1); <file_sep>/dbhelpers/postgres/tableModels.sql DROP DATABASE IF EXISTS sdc_pg; CREATE DATABASE sdc_pg OWNER = student ENCODING = 'UTF8' CONNECTION LIMIT = 25; \c sdc_pg; CREATE TABLE BookingDate ( id serial NOT NULL, date VARCHAR, available BOOLEAN NOT NULL, checkin BOOLEAN NOT NULL, rate NUMERIC(10, 2), checkout BOOLEAN NOT NULL, listingid INT ) CREATE TABLE Listing ( id serial PRIMARY KEY, title VARCHAR, venuetype VARCHAR, bedrooms INT, bathrooms INT, sleepcapacity INT, squarefeet INT, reviewoverview VARCHAR, rating NUMERIC(10, 2), reviewnumber INT, owners VARCHAR, cleaningfee NUMERIC(10, 2), states VARCHAR, city VARCHAR, pic VARCHAR, listingid INT ) ALTER SEQUENCE listingid_seq RESTART WITH 10000001;<file_sep>/client/src/components/selected-dropdown.jsx // jshint esversion:6 import React from 'react'; import StarRatings from 'react-star-ratings'; import { connect } from 'react-redux'; import {selectPic, selectTitle, selectRating, selectReviewNumber} from '../redux/booking/booking.selectors.js'; const SelectedDropdown = (props) => { return ( <div className='al-selected-dropdown'> <div className='al-selected-dropdown-header-container'> <div className='al-selected-dropdown-header-text-container'> <span className='al-selected-dropdown-header-text'>Add to a Trip Board</span> </div> <div className='al-selected-dropdown-header-close-button-container' onClick={props.handleCloseSelected}> <button className='al-selected-dropdown-header-close-button'> <span className='al-selected-dropdown-header-close-button-text'>X</span> </button> </div> </div> <div className='al-selected-dropdown-footer-container'> <div className='al-selected-dropdown-footer-left-container'> <div className='al-selected-dropdown-footer-left-trip-container'> <div className='al-selected-dropdown-footer-left-image-container'> <img className='al-selected-dropdown-footer-left-image' src={props.selectPic}/> </div> <div className='al-selected-dropdown-footer-left-description-container'> <span className='al-selected-dropdown-footer-left-description-text'>{props.selectTitle}</span> </div> <div className='al-selected-dropdown-footer-left-rating-container'> <div className='al-selected-dropdown-footer-left-stars-container'> <StarRatings rating={props.selectRating} starRatedColor='black' numberOfStars={5} name='rating' starDimension='15px' starSpacing='1.5px'/> </div> <div className='al-selected-dropdown-footer-left-reviews-container'> <span className='al-selected-dropdown-footer-left-reviews-text'>{`(${props.selectReviewNumber})`}</span> </div> </div> </div> </div> <div className='al-selected-dropdown-footer-right-container'> <div className='al-selected-dropdown-footer-right-create-form-container'> <div className='al-selected-dropdown-footer-right-create-form-title'> <div className='al-selected-dropdown-footer-right-create-form-button-container'> <span className='al-selected-dropdown-footer-right-create-form-button-text'>+</span> </div> <div className='al-selected-dropdown-footer-right-text-container'> <span className='al-booking-footer-right-text'>Create new Trip Board</span> </div> </div> </div> </div> </div> </div> ); }; const mapStateToProps = (state) => { return ({ selectPic: selectPic(state), selectTitle: selectTitle(state), selectRating: selectRating(state), selectReviewNumber: selectReviewNumber(state) }); }; export default connect(mapStateToProps, null)(SelectedDropdown);<file_sep>/client/src/components/shared-dropdown.jsx // jshint esversion:6 import React from 'react'; import SVG from 'react-inlinesvg'; import FacebookIcon from '../../dist/icons/facebook.svg'; import TwitterIcon from '../../dist/icons/twitter.svg'; import PinterestIcon from '../../dist/icons/pinterest.svg'; import LinkIcon from '../../dist/icons/link.svg'; import { connect } from 'react-redux'; import {selectPic, selectTitle} from '../redux/booking/booking.selectors.js'; const SharedDropdown = (props) => { let link = './icons/sampleimage.jpg'; return ( <div className='al-shared-dropdown'> <div className='al-shared-dropdown-header-container'> <div className='al-shared-dropdown-image-container'> <img className='al-shared-dropdown-image' src={props.selectPic}/> </div> <div className='al-shared-dropdown-header-text-container'> <span className='al-shared-dropdown-header-text'>{props.selectTitle}</span> </div> <div className='al-shared-dropdown-header-close-button-container'> <button onClick={props.handleCloseShared} className='al-shared-dropdown-header-close-button'> <span className='al-shared-dropdown-header-close-button-text'>X</span> </button> </div> </div> <div className='al-shared-dropdown-footer-container'> <div className='al-shared-dropdown-footer'> <div className='al-shared-dropdown-link-container'> <div className='al-shared-dropdown-icon-container'> <SVG className='al-shared-dropdown-icon' src={FacebookIcon}/> </div> <div className='al-shared-dropdown-text-container'> <span className='al-shared-dropdown-text'>Share</span> </div> </div> <div className='al-shared-dropdown-link-container'> <div className='al-shared-dropdown-icon-container'> <SVG className='al-shared-dropdown-icon' src={TwitterIcon}/> </div> <div className='al-shared-dropdown-text-container'> <span className='al-shared-dropdown-text'>Tweet</span> </div> </div> <div className='al-shared-dropdown-link-container'> <div className='al-shared-dropdown-icon-container'> <SVG className='al-shared-dropdown-icon' src={PinterestIcon}/> </div> <div className='al-shared-dropdown-text-container'> <span className='al-shared-dropdown-text'>Pin</span> </div> </div> <div className='al-shared-dropdown-link-container'> <div className='al-shared-dropdown-icon-container'> <SVG className='al-shared-dropdown-icon' src={LinkIcon}/> </div> <div className='al-shared-dropdown-text-container'> <span className='al-shared-dropdown-text'>Copy Link</span> </div> </div> </div> </div> </div> ); }; const mapStateToProps = (state) => { return ({ selectPic: selectPic(state), selectTitle: selectTitle(state) }); }; export default connect(mapStateToProps, null)(SharedDropdown);<file_sep>/client/src/redux/booking/booking.selectors.js // jshint esversion:6 import { createSelector } from 'reselect'; const selectBooking = state => state.booking; export const selectCheckInDate = createSelector( [selectBooking], booking => booking.check_in ); export const selectSearchTerm = createSelector( [selectBooking], booking => booking.searchterm ); export const selectCheckOutDate = createSelector( [selectBooking], booking => booking.check_out ); export const selectCheckInDate1 = createSelector( [selectBooking], booking => booking.check_in1 ); export const selectCheckOutDate1 = createSelector( [selectBooking], booking => booking.check_out1 ); export const selectRate = createSelector( [selectBooking], booking => booking.rate ); export const selectTotal = createSelector( [selectBooking], booking => booking.total ); export const selectFee = createSelector( [selectBooking], booking => booking.fee ); export const selectValid = createSelector( [selectBooking], booking => booking.valid ); export const selectTitle = createSelector( [selectBooking], booking => booking.title ); export const selectSleepCapacity = createSelector( [selectBooking], booking => booking.sleep_capacity ); export const selectReviewOverview = createSelector( [selectBooking], booking => booking.review_overview ); export const selectRating = createSelector( [selectBooking], booking => booking.rating ); export const selectGuests = createSelector( [selectBooking], booking => booking.guests ); export const selectReviewNumber = createSelector( [selectBooking], booking => booking.review_number ); export const selectOwner = createSelector( [selectBooking], booking => booking.owner ); export const selectCalendar = createSelector( [selectBooking], booking => booking.calendar ); export const selectGuestsForm = createSelector( [selectBooking], booking => booking.guestsform ); export const selectCleaningFee = createSelector( [selectBooking], booking => booking.cleaning_fee ); export const selectUSState = createSelector( [selectBooking], booking => booking.us_state ); export const selectCity = createSelector( [selectBooking], booking => booking.city ); export const selectPic = createSelector( [selectBooking], booking => booking.pic ); export const selectLoading = createSelector( [selectBooking], booking => booking.loading ); export const selectDays = createSelector( [selectBooking], booking => booking.days );<file_sep>/client/src/components/header.jsx // jshint esversion:6 import React from 'react'; import LogoTitle from './logo-title.jsx'; import HeaderOptions from './header-options.jsx'; import SearchForm from './search-form.jsx'; class Header extends React.Component { constructor() { super(); this.state = { }; } componentDidMount() { } render() { return ( <div className='al-header-container'> <div className='al-header-upper-container'> <LogoTitle /> <HeaderOptions /> </div> <div className='al-header-lower-container'> <SearchForm /> </div> </div> ); } } export default Header;<file_sep>/client/src/redux/booking/booking.reducer.js // jshint esversion:6 const INITIAL_STATE = { check_in: '', check_out: '', check_in1: '', check_out1: '', rate: 0.00, total: 0.00, fee: 50.00, valid: false, title: '', sleep_capacity: 1, review_overview: '', rating: 0, review_number: 0, owner: '', cleaning_fee: 0.00, us_state: '', city: '', pic: '', loading: false, guests: 1, days: 0, guestsform: false, calendar: false, searchterm: '' }; const BookingReducer = (state=INITIAL_STATE, action) => { switch (action.type) { case 'SET_SEARCH_TERM': return ({ ...state, searchterm: action.payload }); case 'TOGGLE_GUESTS_FORM': return ({ ...state, guestsform: !state.guestsform }); case 'TOGGLE_CALENDAR': return ({ ...state, calendar: !state.calendar }); case 'SET_CHECK_IN_DATE': return ({ ...state, check_in: action.payload }); case 'SET_DAYS': return ({ ...state, days: action.payload }); case 'SET_CHECK_OUT_DATE': return ({ ...state, check_out: action.payload }); case 'SET_CHECK_IN_DATE1': return ({ ...state, check_in1: action.payload }); case 'SET_CHECK_OUT_DATE1': return ({ ...state, check_out1: action.payload }); case 'SET_RATE': return ({ ...state, rate: action.payload }); case 'SET_TOTAL': return ({ ...state, total: action.payload }); case 'SET_FEE': return ({ ...state, fee: action.payload }); case 'MAKE_VALID': return ({ ...state, valid: true }); case 'MAKE_INVALID': return ({ ...state, valid: false }); case 'SET_TITLE': return ({ ...state, title: action.payload }); case 'SET_SLEEP_CAPACITY': return ({ ...state, sleep_capacity: action.payload }); case 'SET_REVIEW_OVERVIEW': return ({ ...state, review_overview: action.payload }); case 'SET_RATING': return ({ ...state, rating: action.payload }); case 'SET_REVIEW_NUMBER': return ({ ...state, review_number: action.payload }); case 'SET_OWNER': return ({ ...state, owner: action.payload }); case 'SET_CLEANING_FEE': return ({ ...state, cleaning_fee: action.payload }); case 'SET_US_STATE': return ({ ...state, us_state: action.payload }); case 'SET_CITY': return ({ ...state, city: action.payload }); case 'SET_URL': return ({ ...state, pic: action.payload }); case 'START_LOADING': return ({ ...state, loading: true }); case 'STOP_LOADING': return ({ ...state, loading: false }); case 'SET_GUESTS': return ({ ...state, guests: action.payload }); default: return state; } }; export default BookingReducer;<file_sep>/server/mongodb/controllers.js dbListingHelpers = require("../../dbhelpers/mongodb/listingsModel"); dbBookingDateHelpers = require("../../dbhelpers/mongodb/bookingDatesModel"); module.exports = { createListing: (req, res) => { console.log(`you made it into controllers.createListing`); dbListingHelpers.createListing(req, (err, results) => { if (err) { console.log(err); res.status(404).send(err); } else { console.log(`successful controllers.createListing`); res.status(200).send(results); } }); }, getListingById: (req, res) => { console.log(`you made it into controllers.getListingById`); dbListingHelpers.getListingById(req, (err, results) => { if (err) { console.log(err); res.status(404).send(err); } else { console.log(`successful controllers.getListingById`); res.status(200).send(results); } }); }, updateListingById: (req, res) => { console.log(`you made it into controllers.updateListingById`); dbListingHelpers.updateListingById(req, (err, results) => { if (err) { console.log(err); res.status(404).send(err); } else { console.log(`successful controllers.updateListingById`); res.status(200).send(results); } }); }, deleteListingById: (req, res) => { console.log(`you made it into controllers.deleteListingById`); dbListingHelpers.deleteListingById(req, (err, results) => { if (err) { console.log(err); res.status(404).send(err); } else { console.log(`successful controllers.deleteListingById`); res.status(200).send(results); } }); }, getLimit10: (req, res) => { console.log(`you made it into controllers.getLimit10`); dbListingHelpers.getLimit10(req, (err, results) => { if (err) { console.log(err); res.status(404).send(err); } else { console.log(`successful controllers.getLimit10`); res.status(200).send(results); } }); }, getBookingDateById: (req, res) => { console.log(`you made it into controllers.getBookingDateById`); dbBookingDateHelpers.getBookingDateById(req, (err, results) => { if (err) { console.log(err); res.status(404).send(err); } else { console.log(`successful controllers.getBookingDateById`); res.status(200).send(results); } }); } }; <file_sep>/client/src/components/booking-footer.jsx // jshint esversion:6 import React from 'react'; const BookingFooter = () => { return ( <div className='al-booking-footer'> <div className='al-booking-footer-line1-container'> <span className='al-booking-footer-line1-text'>For booking assistance, call HomeAway at <strong className='al-darken-text'>888-640-7927</strong></span> </div> <div className='al-booking-footer-line2-container'> <span className='al-booking-footer-line2-text'><strong className='al-darken-text'>Property #</strong> 411294vb</span> </div> </div> ); }; export default BookingFooter;<file_sep>/client/src/components/logo-title.jsx // jshint esversion:6 import React from 'react'; const LogoTitle = () => { return ( <div className='al-logo-title-container'> <h1 className='al-logo-title'>A Way Home</h1> </div> ); }; export default LogoTitle;<file_sep>/dbhelpers/mongodb/mongoBookingDatesSeed.js // USING CSV-WRITER LIBRARY... // const createCsvStringifier = require("csv-writer").createObjectCsvStringifier;// using csv-writer const mongoose = require("mongoose"); // only necessary if we plan to seed CSV directly into MongoDB // const db = require("./index.js"); // USING CSV-WRITER // const fs = require("fs"); // const file = fs.createWriteStream( // "../../dbhelpers/mongodb/mongoBookingDates.csv" // ); const path = require("path"); const fs = require("fs"); const file = path.join(__dirname, "mongoBookingDates.csv"); const stream = fs.createWriteStream(file); const header = "date,available,checkin,rate,checkout,listingid\n"; stream.write(header, "utf8"); months = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" ]; datesInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; years = [2019, 2020]; dates = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" ]; // USING CSV-WRITER // const csvStringifier = createCsvStringifier({ // header: [ // { id: "date", title: "date" }, // { id: "available", title: "available" }, // { id: "checkin", title: "checkin" }, // { id: "rate", title: "rate" }, // { id: "checkout", title: "checkout" }, // { id: "listingid", title: "listingid" } // ] // }); let bookingDates = []; // let date; let data; var increment = 0; let date; let available; let checkin; let checkout; let rate; let listingid; writeCSV = async () => { for (let i = 0; i < years.length; i++) { for (let j = 0; j < datesInMonths.length; j++) { for (let k = 0; k < datesInMonths[j]; k++) { for (let l = 1; l < 13700; l++) { date = years[i] + "-" + months[j] + "-" + dates[k]; available = true; checkin = false; checkout = false; rate = Math.floor(Math.random() * 750 + 50); listingid = l; data = `${date},${available},${checkin},${checkout},${rate},${listingid}\n`; let ok = true; function generateData() { if (l === 0) { stream.write(data); // needs callback as a parameter to write() (inherited method of fs) } else { increment++; if (increment % 10000 === 0) { console.log(increment); } ok = stream.write(data); } } // do { if (l > 0 && ok) { generateData(); } // } while (l > 0 && ok); } } } if (i > 0) { stream.once("drain", generateData); } } // await mongoose.connection.close(); console.log(`you've successfully written the CSV file, export to database`); }; writeCSV(() => { console.log(`done writing CSV...`); }); // .then(() => mongoose.connection.close()) // .catch(err => mongoose.connection.close()); // THIS CAN SEED 73,000 DATES USING CSV-WRITER // const writeCSV = async () => { // let bookingDates = []; // let date; // function generateData() { // let increment; // for (let i = 0; i < years.length; i++) { // for (let j = 0; j < datesInMonths.length; j++) { // for (let k = 0; k < datesInMonths[j]; k++) { // for (let l = 1; l < 101; l++) { // date = years[i] + "-" + months[j] + "-" + dates[k]; // bookingDates.push({ // date, // available: true, // checkin: false, // checkout: false, // rate: Math.floor(Math.random() * 750 + 50), // listingid: l // }); // // console.log(increment); // log which record number currently working // increment++; // increment record number // // if (increment % 1000 === 0) { // // console.log(increment); // // } // } // } // } // } // } // await generateData(); // await file.write(csvStringifier.stringifyRecords(bookingDates)); // mongoose.connection.close(); // only necessary if we need to seed directly into MongoDB // }; // const asyncWrite = async () => { // await writeCSV(); // console.log(`successfully wrote booking dates to CSV file`); // }; // file.write(csvStringifier.getHeaderString()); // writes the CSV header row // asyncWrite(); <file_sep>/dbhelpers/postgres/pgListingsSeed.sql \c sdc_pg; COPY listing FROM '/Users/aaronsouthammavong/hrla/sdc-service-aaron/dbhelpers/mongodb/mongoListings.csv' DELIMITER ',' CSV HEADER; CREATE INDEX listing_title_index ON listing (title varchar_pattern_ops); CREATE INDEX listing_states_index ON listing (states varchar_pattern_ops); CREATE INDEX listing_city_index ON listing (city varchar_pattern_ops); CREATE INDEX listing_table_id_index ON listing (id);<file_sep>/dbhelpers/mongodb/bookingDatesModel.js const mongoose = require("mongoose"); const db = require("./index.js"); mongoose.Promise = require("bluebird"); const bookingDateSchema = new mongoose.Schema({ date: String, available: Boolean, checkin: Boolean, rate: Number, checkout: Boolean, listingid: { type: Number, index: true } }); const BookingDate = mongoose.model("BookingDate", bookingDateSchema); const getBookingDateById = (req, callback) => { // console.log(req.params); BookingDate.findOne({ listingid: req.params.id }).exec((err, results) => { if (err) { console.log(`error in database model.getListingById`); callback(err); } else { console.log(`you hit database model.getListingById`); callback(null, results); } }); }; module.exports.BookingDate = BookingDate; module.exports.getBookingDateById = getBookingDateById; <file_sep>/client/src/components/help-dropdown.jsx // jshint esversion:6 import React from 'react'; const HelpDropdown = () => { const options = ['Traveler Help', 'Owner Help', 'Property Manager Help', 'Trust & Safety']; return ( <div className='al-help-dropdown'> { options.length ? ( options.map((option, i) => { return (<div key={i} className='al-help-option-container'><span className='al-help-option-text'>{option}</span></div>); }) ) : ( null ) } </div> ); }; export default HelpDropdown;<file_sep>/client/src/components/owner-info.jsx // jshint esversion:6 import React from 'react'; import {selectOwner, selectPic} from '../redux/booking/booking.selectors.js'; import { connect } from 'react-redux'; class OwnerInfo extends React.Component { constructor(props) { super(props); this.state = { profileUrl: './icons/sampleimage.jpg' }; } componentDidMount() { } render() { return ( <div className='al-owner-info'> <div className='al-owner-info-pic-container'> <img className='al-owner-info-pic' src={this.props.selectPic}/> </div> <div className='al-owner-info-text-container'> <div className='al-owner-info-owner-name-container'> <span className='al-owner-info-owner-name-text'>{this.props.selectOwner}</span> </div> <div className='al-owner-info-question-link-container'> <span className='al-owner-info-question-link-text'>Ask owner a question</span> </div> </div> </div> ); } }; const mapStateToProps = (state) => { return ({ selectOwner: selectOwner(state), selectPic: selectPic(state) }); }; export default connect(mapStateToProps, null)(OwnerInfo);<file_sep>/dbhelpers/postgres/pgBookingDatesSeed.sql \c sdc_pg; COPY bookingdate FROM '/Users/aaronsouthammavong/hrla/sdc-service-aaron/dbhelpers/mongodb/mongoBookingDates.csv' DELIMITER ',' CSV HEADER; CREATE INDEX listingid_index ON bookingdate (listingid);<file_sep>/client/src/components/help-button.jsx // jshint esversion:6 import React from 'react'; import SVG from 'react-inlinesvg'; import QuestionIcon from '../../dist/icons/information.svg'; import UpArrowIcon from '../../dist/icons/iconmonstr-arrow-65.svg'; import DownArrowIcon from '../../dist/icons/iconmonstr-arrow-66.svg'; import HelpDropdown from './help-dropdown.jsx'; class HelpButton extends React.Component { constructor(props) { super(props); this.state = { selected: false }; this.toggleHelpButton = this.toggleHelpButton.bind(this); } toggleHelpButton() { this.setState({selected: !this.state.selected}); } render() { return ( <div className='al-header-option-container al-help-button'> <table onClick={this.props.handleSelected} className='al-header-option-table'> <tbody> <tr> <td className='al-header-option-icon-container al-question-mark'><SVG src={QuestionIcon} className='al-header-option-icon'/></td> <td><span className='al-header-option-text'>Help</span></td> <td className='al-header-option-arrow-container'> { this.props.selected ? ( <SVG src={DownArrowIcon} className='al-header-option-arrow'/> ) : ( <SVG src={UpArrowIcon} className='al-header-option-arrow'/> ) } </td> </tr> </tbody> </table> { this.props.selected ? ( <div className='al-help-dropdown-container'> <HelpDropdown /> </div> ) : ( null ) } </div> ); } } export default HelpButton;<file_sep>/client/src/components/loading-dots.jsx // jshint esversion:6 import React from 'react'; export const LoadingDots = () => { return ( <div className='al-loading-dots'> <div className="al-saving"><div className='al-dot'></div><div className='al-dot'></div><div className='al-dot'></div><div className='al-dot'></div> </div> </div> ); }; export const MainLoadingDots = () => { return ( <div className='al-main-loading-dots'> <div className="al-saving"><div className='al-main-dot'></div><div className='al-main-dot'></div><div className='al-main-dot'></div><div className='al-main-dot'></div> </div> </div> ); }; <file_sep>/client/src/components/overlay.jsx // jshint esversion:6 import React from 'react'; const Overlay = () => { return ( <div className='al-overlay'> </div> ); }; export default Overlay;<file_sep>/dbhelpers/postgres/pgListingsSeed.js // jshint esversion:6 const faker = require("faker"); // const BookingDate = require("./models").BookingDate; // const Listing = require("./models").Listing; // const pgp = require("pg-promise"); const { Pool, Client } = require("pg"); const connectLocation = "postgres://localhost:5432/sdc_pg"; const path = require("path"); const db = require("./index.js"); const fs = require("fs"); const file = path.join(__dirname, "pglistings.csv"); const string = ""; const stream = fs.createWriteStream(file); // const header = // "title;venuetype;bedrooms;sleepcapacity;bathrooms;squarefeet;reviewoverview;rating;reviewnumber;owners;cleaningfee;states;city;pic;listingid\n"; // stream.write(header, "utf8"); listingAdjectives = [ "sunset roost", "lux", "perfect nest", "private pool", "lakefront", "charming", "family-friendly", "secluded", "beach front", "relaxing", "lake cabin", "pine cone", "stunning", "gorgeous modern", "estes mountain", "river front", "water front", "charming", "winter special", "beautiful", "magnificent", "ocean view", "mountain getaway", "colonial", "rustic", "wondrous", "perfect getaway", "quiet", "historical", "modern", "gulf front", "relaxing river", "summer breezes", "enchanting rockwood", "cowell beach", "rustic country", "resort", "panoramic ocean view", "executive mountain", "executive beach", "executive", "comfortable and spacious", "private", "mountain lookout", "scenic luxury", "great escape", "stone lodge", "dream retreat", "dream guesthouse", "enchanting", "luxury", "lighthouse view", "comfortable", "bay front", "perfect & affordable", "beach", "scenic", "location, location!", "delightful vacation", "grand", "large", "beautiful contemporary", "ocean block", "elegant", "breathtaking", "new", "riverside", "beach bungalow", "wild dunes", "stargazer lodge", "quaint & cozy", "downtown", "amazing views", "centrally located", "seaside", "newly remodeled", "family vacation spot", "palm", "luxury", "dune", "fine-private", "winter views", "summer views", "fall views", "spring views", "restored", "expansive", "conveniently located", "total remodel", "hidden", "chic", "victorian", "sandy pines", "<NAME>", "stylish", "greek", "revival style", "spacious", "good value", "at the water edge", "designer", "fun", "sandcastle", "sky ledge", "alpine", "free night!", "summer beach", "absolutely gorgeous", "asian-inspired", "autumn", "wine country", "classic", "bayside", "vacation", "southwest", "immaculate", "island style", "beautiful slope", "upscale", "vintage", "picturesque", "redwood retreat", "tuscan", "cliffside", "foresty", "artistic", "paradise", "jet luxury", "skyline view" ]; listingStyles = [ "home", "loft", "chalet", "house", "beachhouse", "guesthouse", "cabin", "skyloft", "ranch", "cottage", "mansion", "treehouse", "lakehouse", "townhouse", "apartment", "condo", "resort", "lodge", "lodging", "country house", "manor", "estate", "summer home", "winter lodge", "retreat", "log home", "rental", "castle" ]; listingType = ["House", "Apartment", "Condo", "Townhouse"]; listingAmenities = [ "family-friendly", "pet-friendly", "pool", "gated community", "fooseball", "trampoline", "spa", "close walk to beach", "close walk to town", "close to village", "surrounded by woods", "golf resort", "ski resort", "gourmet kitchen", "fishing", "hiking-friendly", "amazing garden", "backyard wilderness", "yacht", "boating", "close to downtown", "game room", "ac/heating", "hot tub", "jacuzzi", "bicycles", "surf", "great amenities", "nearby pond", "fireplace", "nearby lake", "garage parking", "great for photography", "gym", "loofers", "fireplace", "wildlife", "nearby trails", "close to train station", "stargazing", "vineyards", "paddle-boat", "kayak", "dock", "fitness center" ]; listingReview = [ "Great.", "Great find.", "Beautiful view.", "Great bargain.", "Good ammenities.", "Spectacular views.", "Convenient location.", "Excellent.", "Wonderful.", "Exceptional.", "Very good.", "Good for families." ]; months = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" ]; datesInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; years = [2019, 2020]; dates = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" ]; writeCSV = callback => { let i = 1000000; function generateData() { let ok = true; do { i--; if (i % 10000 === 0) { console.log(i); } let listings = []; let obj; let listingcount = 0; obj = {}; let title = listingAdjectives[ Math.floor(Math.random() * listingAdjectives.length) ] + " " + listingStyles[Math.floor(Math.random() * listingStyles.length)] + " " + listingAmenities[Math.floor(Math.random() * listingStyles.length)] + " " + listingAmenities[Math.floor(Math.random() * listingStyles.length)]; title = title.slice(0, 1).toUpperCase() + title.slice(1); let venuetype = listingType[Math.floor(Math.random() * listingType.length)]; let bedrooms = Math.floor(Math.random() * 5 + 1); let sleepcapacity = bedrooms * 2 + Math.floor(Math.random() * 3 + 1); let bathrooms = Math.floor(Math.random() * 3 + 1); let squarefeet = Math.floor(Math.random() * 600 + 1) * 10 + 1000; let reviewoverview = listingReview[Math.floor(Math.random() * listingReview.length)]; let rating = Math.floor(Math.random() * 10) / 10 + 4; let reviewnumber = Math.floor(Math.random() * 200 + 15); let owners = faker.name.findName(); let cleaningfee = Math.floor(Math.random() * 100) + 10; let states = faker.address.state(); let city = faker.address.city(); let pic = faker.image.image(); // let listingid = i; let data = `${title};${venuetype};${bedrooms};${sleepcapacity};${bathrooms};${squarefeet};${reviewoverview};${rating};${reviewnumber};${owners};${cleaningfee};${states};${city};${pic}\n`; if (i === 0) { stream.write(data, callback); // stream.end(); // we are going to end the connection after writing to CSV inside of seedDB's function definition INSTEAD } else { ok = stream.write(data); } } while (i > 0 && ok); if (i > 0) { stream.once("drain", generateData); } } console.log(i); generateData(); console.log(`you've successfully written the CSV file, export to database`); }; writeCSV(() => { console.log(`you're seeding CSV...`); stream.end(err => { console.log(`ended stream`); if (err) { console.log(err); } else { db.query( `COPY listings FROM '/Users/aaronsouthammavong/hrla33/sdc-service-aaron/dbhelpers/postgres/pglistings.csv' DELIMITER ';' CSV` ) .then(() => { db.query(`ALTER TABLE listings ADD id serial;`); console.log(`successfully seeded database`); // db.end(); }) .then(() => { db.query(`create index idx_listings_listingid on listings(id);`); console.log(`indexed id`); }) .catch(err => { throw err; }); } }); }); // seedDB(stream); // console.log(`wrote CSV`); // writeCSV(() => { // console.log(`you're writing to database`); // stream.end(err => { // if (err) { // console.log(err); // } else { // db.query(`COPY listings FROM './listings.csv' DELIMITER ',' CSV HEADER`) // .then(() => { // console.log(`successfully wrote to database`); // db.end(); // }) // .catch(err => { // throw err; // }); // } // }); // }); // generateBookingDates = async listing_id => { // let datecount = 0; // let bookingDates = []; // let date; // for (let i = 0; i < years.length; i++) { // for (let j = 0; j < datesInMonths.length; j++) { // for (let k = 0; k < datesInMonths[j]; k++) { // for (let l = 1; l < 101; l++) { // date = years[i] + "-" + months[j] + "-" + dates[k]; // // date = "2020-09-17"; // bookingDates.push({ // date, // available: true, // checkin: false, // checkout: false, // rate: Math.floor(Math.random() * 750 + 50), // listingid: l // }); // datecount++; // } // } // } // } // // using vanilla Postgres... // try { // // console.log(`connected under generateBookings()`); // for (var i = 0; i < bookingDates.length; i++) { // await db // .query( // `INSERT INTO dates (date, available, checkin, checkout, rate, listingid) VALUES ('${bookingDates[i].date}', '${bookingDates[i].available}', '${bookingDates[i].checkin}', '${bookingDates[i].checkout}', '${bookingDates[i].rate}', '${bookingDates[i].listingid}')` // ) // .then(res => console.log(i)) // .catch(err => console.log(err, "error")); // } // } catch (error) { // console.log(`can't seed: ${error}`); // } finally { // // await db.end(); // close connection // console.log(`disconnected from db`); // } // // using Sequelize on MySQL... // // await BookingDate.sync({ force: true }) // // .then(() => BookingDate.bulkCreate(bookingDates, { validate: true })) // // .then(() => console.log("Created " + datecount + " bookings.")) // // .catch(err => console.log("failed to create bookings", err)); // // await db.none() // }; // generateListings = async () => { // let k; // let listings = []; // let obj; // let listingcount = 0; // for (let i = 0; i < 1000000; i++) { // obj = {}; // let title = // listingAdjectives[Math.floor(Math.random() * listingAdjectives.length)] + // " " + // listingStyles[Math.floor(Math.random() * listingStyles.length)] + // " " + // listingAmenities[Math.floor(Math.random() * listingStyles.length)] + // " " + // listingAmenities[Math.floor(Math.random() * listingStyles.length)]; // obj.title = title.slice(0, 1).toUpperCase() + title.slice(1); // obj.venuetype = listingType[Math.floor(Math.random() * listingType.length)]; // obj.bedrooms = Math.floor(Math.random() * 5 + 1); // obj.sleepcapacity = obj.bedrooms * 2 + Math.floor(Math.random() * 3 + 1); // obj.bathrooms = Math.floor(Math.random() * 3 + 1); // obj.squarefeet = Math.floor(Math.random() * 600 + 1) * 10 + 1000; // obj.reviewoverview = // listingReview[Math.floor(Math.random() * listingReview.length)]; // obj.rating = Math.floor(Math.random() * 10) / 10 + 4; // obj.reviewnumber = Math.floor(Math.random() * 200 + 15); // obj.owners = faker.name.findName(); // obj.cleaningfee = Math.floor(Math.random() * 100) + 10; // obj.states = faker.address.state(); // obj.city = faker.address.city(); // // k = i + 1; // obj.pic = faker.image.image(); // listings.push(obj); // listingcount = listingcount + 1; // } // // using vanilla Postgres... // try { // // console.log(`connected under generateBookings()`); // for (var i = 0; i < listings.length; i++) { // await db // .query( // `INSERT INTO listings (title, venuetype, bedrooms, sleepcapacity, bathrooms, squarefeet, reviewoverview, rating, reviewnumber, owners, cleaningfee, states, city, pic) VALUES ($$${listings[i].title}$$, $$${listings[i].venuetype}$$, $$${listings[i].bedrooms}$$, $$${listings[i].sleepcapacity}$$, $$${listings[i].bathrooms}$$, $$${listings[i].squarefeet}$$, $$${listings[i].reviewoverview}$$, $$${listings[i].rating}$$, $$${listings[i].reviewnumber}$$, $$${listings[i].owners}$$, $$${listings[i].cleaningfee}$$, $$${listings[i].states}$$, $$${listings[i].city}$$, $$${listings[i].pic}$$)` // ) // .then(res => console.log(i)) // .catch(err => console.log(err, "error")); // } // } catch (error) { // console.log(`can't seed: ${error}`); // } finally { // await db.end(); // close connection // console.log(`disconnected from db`); // } // // using Sequelize on MySQL... // // console.log(listings); // // await Listing.sync({ force: true }) // // .then(() => Listing.bulkCreate(listings, { validate: true })) // // .then(() => console.log("Created " + listingcount + " listings.")) // // .catch(err => console.log("failed to create listings", err)); // }; // generateBookingDates(); // generateListings(); <file_sep>/client/src/components/view-details-form.jsx // jshint esversion:6 import React from 'react'; import { connect } from 'react-redux'; import { selectCheckInDate, selectCheckOutDate, selectRate, selectCleaningFee, selectFee, selectGuests, selectTotal, selectDays} from '../redux/booking/booking.selectors.js'; import {toggleCalendar, toggleGuestsForm} from '../redux/booking/booking.action.js'; import SVG from 'react-inlinesvg'; import CheckIcon from '../../dist/icons/tick.svg'; import InfoIcon from '../../dist/icons/Info_Simple.svg'; class ViewDetailsForm extends React.Component { constructor(props) { super(props); this.state = { }; this.toggleCalendarView = this.toggleCalendarView.bind(this); this.toggleGuestsFormView = this.toggleGuestsFormView.bind(this); } componentDidMount() { } toggleCalendarView(e) { this.props.toggleCalendar(); } toggleGuestsFormView(e) { this.props.toggleGuestsForm(); } render() { return ( <div className='al-view-details-form'> <div className='al-view-details-form-title-container'> <span className='al-view-details-form-title-text'>Booking summary</span> </div> <div className='al-view-details-form-close-button-container'> <span onClick={this.props.closeView} className='al-view-details-form-title-text-close al-gray'>x</span> </div> <div className='al-view-details-form-valid-dates-container'> <div className='al-view-details-form-icon-container'> <SVG className='al-view-details-form-icon' src={CheckIcon} /> </div> <div className='al-view-details-form-valid-dates-text-container'> <span className='al-view-details-form-valid-dates-text'>Your dates are available</span> </div> </div> <div className='al-view-details-form-dates-container' onClick={this.toggleCalendarView}> <div className='al-view-details-form-check-in-container'> <div className='al-view-details-form-check-in-label-container'> <span className='al-view-details-form-check-in-label-text'>Check In</span> </div> <div className='al-view-details-form-check-in-date-container'> <span className='al-view-details-form-check-in-date-text'>{this.props.selectCheckInDate}</span> </div> </div> <div className='al-view-details-form-check-out-container'> <div className='al-view-details-form-check-in-label-container'> <span className='al-view-details-form-check-in-label-text'>Check Out</span> </div> <div className='al-view-details-form-check-in-date-container'> <span className='al-view-details-form-check-in-date-text'>{this.props.selectCheckOutDate}</span> </div> </div> </div> <div className='al-view-details-form-guests-container' onClick={this.toggleGuestsFormView}> <div className='al-view-details-form-check-in-label-container'> <span className='al-view-details-form-check-in-label-text'>Guests</span> </div> <div className='al-view-details-form-check-in-date-container'> <span className='al-view-details-form-check-in-date-text'>{`${this.props.selectGuests} ${this.props.selectGuests === 1 ? 'guest' : 'guests'}`}</span> </div> </div> <div className='al-view-details-form-fee-container'> <div className='al-view-details-form-fee-breakdown-container'> <div className='al-view-details-form-field-container'> <span className='al-view-details-form-breakdown-text'>{`$${this.props.selectRate} x ${this.props.selectDays} ${this.props.selectDays === 1 ? 'night' : 'nights'}`}</span> </div> <div className='al-view-details-form-cost-container'> <span className='al-view-details-form-breakdown-text'>{`$${(this.props.selectRate * this.props.selectDays).toFixed(2)}`}</span> </div> </div> <div className='al-view-details-form-fee-breakdown-container'> <div className='al-view-details-form-field-container'> <span className='al-view-details-form-breakdown-text'>Cleaning Fee</span> </div> <div className='al-view-details-form-cost-container'> <span className='al-view-details-form-breakdown-text'>{`$${(this.props.selectCleaningFee * Math.pow(this.props.selectGuests, 0.5)).toFixed(2)}`}</span> </div> </div> <div className='al-view-details-form-fee-breakdown-container'> <div className='al-view-details-form-field-container'> <div className='al-view-details-form-breakdown-line-container al-gap'> <span className='al-view-details-form-breakdown-text'>Service Fee</span> </div> <div className='al-view-details-form-breakdown-line-container'> <SVG className='al-view-details-form-icon al-clickable' src={InfoIcon}/> </div> </div> <div className='al-view-details-form-cost-container'> <span className='al-view-details-form-breakdown-text'>{`$${this.props.selectFee}.00`}</span> </div> </div> <div className='al-view-details-form-fee-breakdown-container'> <div className='al-view-details-form-field-container'> <span className='al-view-details-form-breakdown-text'>Tax</span> </div> <div className='al-view-details-form-cost-container'> <span className='al-view-details-form-breakdown-text'>{`$${((this.props.selectRate * this.props.selectDays + this.props.selectCleaningFee * Math.pow(this.props.selectGuests, 0.5) + this.props.selectFee) * 0.1).toFixed(2)}`}</span> </div> </div> </div> <div className='al-top-dotted-line'> <hr className='al-dotted-line'/> </div> <div className='al-view-details-form-fee-container-second'> <div className='al-view-details-form-fee-breakdown-container'> <div className='al-view-details-form-field-container'> <span className='al-view-details-form-breakdown-text'><strong>Total</strong></span> </div> <div className='al-view-details-form-cost-container'> <span className='al-view-details-form-breakdown-text'><strong>{`$${((this.props.selectRate * this.props.selectDays + this.props.selectCleaningFee * Math.pow(this.props.selectGuests, 0.5) + this.props.selectFee) * 1.1).toFixed(2)}`}</strong></span> </div> </div> <div className='al-view-details-form-fee-breakdown-container'> <div className='al-view-details-form-field-container'> <div className='al-view-details-form-breakdown-line-container al-gap'> <span className='al-view-details-form-breakdown-text'>Refundable Damage Deposit</span> </div> <div className='al-view-details-form-breakdown-line-container'> <SVG className='al-view-details-form-icon al-clickable' src={InfoIcon}/> </div> </div> <div className='al-view-details-form-cost-container'> <span className='al-view-details-form-breakdown-text'>{`$250.00`}</span> </div> </div> <div className='al-view-details-form-fee-breakdown-container'> <div className='al-view-details-form-field-container'> <span className='al-view-details-form-breakdown-text'>Total + deposit</span> </div> <div className='al-view-details-form-cost-container'> <span className='al-view-details-form-breakdown-text'>{`$${(this.props.selectTotal + 250).toFixed(2)}`}</span> </div> </div> </div> <div className='al-top-dotted-line'> <hr className='al-dotted-line'/> </div> <div className='al-view-details-form-fee-container-third'> <div className='al-view-details-form-cost-container1'> <span className='al-view-details-form-breakdown-text'><strong>{`Your payment is $${(this.props.selectTotal + 250).toFixed(2)}`}</strong></span> </div> </div> <div className='al-top-dotted-line2'> <hr className='al-dotted-line'/> </div> <div className='al-view-details-form-fee-container-third'> <div className='al-view-details-form-footer-first-line-container'> <span className='al-view-details-form-breakdown-text'>Due Onsite:</span> </div> <div className='al-view-details-form-footer-second-line-container'> <span className='al-view-details-form-breakdown-text'>Extra charges may be applied by the property manager (including amounts related to optional goods and services)</span> </div> </div> <div className='al-view-details-form-fee-container-fourth'> <div className='al-view-details-form-bottom-button-container'> <button className='al-view-details-form-bottom-button'><span className='al-view-details-form-bottom-button-text'>Continue booking</span></button> </div> </div> </div> ); } }; const mapStateToProps = (state) => { return ({ selectCheckInDate: selectCheckInDate(state), selectCheckOutDate: selectCheckOutDate(state), selectRate: selectRate(state), selectFee: selectFee(state), selectCleaningFee: selectCleaningFee(state), selectGuests: selectGuests(state), selectTotal: selectTotal(state), selectDays: selectDays(state) }); }; const mapDispatchToProps = (dispatch) => { return ({ toggleCalendar: () => dispatch(toggleCalendar()), toggleGuestsForm: () => dispatch(toggleGuestsForm()) }); } export default connect(mapStateToProps, mapDispatchToProps)(ViewDetailsForm);<file_sep>/client/src/components/search-result.jsx // jshint esversion:6 import React from "react"; class SearchResult extends React.Component { constructor(props) { super(props); this.state = {}; this.handleClick = this.handleClick.bind(this); } componentDidMount() {} handleClick(e) { this.props.selectSearchResult(Number(this.props.searchlisting.id)); } render() { return ( <div className="al-search-result" onClick={this.handleClick}> <div className="al-search-result-pic-container"> <img className="al-search-result-pic" src={this.props.searchlisting.pic} /> </div> <div className="al-search-result-text-container"> <div className="al-search-result-title-container"> <span className="al-search-result-text al-gray">{`${this.props.searchlisting.title.slice( 0, 61 )}`}</span> </div> <div className="al-search-result-location-container"> <div className="al-search-result-city-container"> <span className="al-search-result-text">{`${this.props.searchlisting.city}`}</span> </div> <div className="al-search-result-state-container"> <span className="al-search-result-text">{`, ${this.props.searchlisting.states}`}</span> </div> <div className="al-search-result-country-container"> <span className="al-search-result-text">, USA </span> </div> </div> </div> </div> ); } } export default SearchResult; <file_sep>/dbhelpers/mongodb/mongoListingsSeed.js const mongoose = require("mongoose"); const faker = require("faker"); const db = require("./index.js"); // const Listing = require("./model.js"); const path = require("path"); const fs = require("fs"); const file = path.join(__dirname, "mongoListings.csv"); const stream = fs.createWriteStream(file); const header = "title,venuetype,bedrooms,sleepcapacity,bathrooms,squarefeet,reviewoverview,rating,reviewnumber,owners,cleaningfee,states,city,pic,listingid\n"; stream.write(header, "utf8"); listingAdjectives = [ "sunset roost", "lux", "perfect nest", "private pool", "lakefront", "charming", "family-friendly", "secluded", "beach front", "relaxing", "lake cabin", "pine cone", "stunning", "gorgeous modern", "estes mountain", "river front", "water front", "charming", "winter special", "beautiful", "magnificent", "ocean view", "mountain getaway", "colonial", "rustic", "wondrous", "perfect getaway", "quiet", "historical", "modern", "gulf front", "relaxing river", "summer breezes", "enchanting rockwood", "cowell beach", "rustic country", "resort", "panoramic ocean view", "executive mountain", "executive beach", "executive", "comfortable and spacious", "private", "mountain lookout", "scenic luxury", "great escape", "stone lodge", "dream retreat", "dream guesthouse", "enchanting", "luxury", "lighthouse view", "comfortable", "bay front", "perfect & affordable", "beach", "scenic", "location, location!", "delightful vacation", "grand", "large", "beautiful contemporary", "ocean block", "elegant", "breathtaking", "new", "riverside", "beach bungalow", "wild dunes", "stargazer lodge", "quaint & cozy", "downtown", "amazing views", "centrally located", "seaside", "newly remodeled", "family vacation spot", "palm", "luxury", "dune", "fine-private", "winter views", "summer views", "fall views", "spring views", "restored", "expansive", "conveniently located", "total remodel", "hidden", "chic", "victorian", "sandy pines", "<NAME>", "stylish", "greek", "revival style", "spacious", "good value", "at the water edge", "designer", "fun", "sandcastle", "sky ledge", "alpine", "free night!", "summer beach", "absolutely gorgeous", "asian-inspired", "autumn", "wine country", "classic", "bayside", "vacation", "southwest", "immaculate", "island style", "beautiful slope", "upscale", "vintage", "picturesque", "redwood retreat", "tuscan", "cliffside", "foresty", "artistic", "paradise", "jet luxury", "skyline view" ]; listingStyles = [ "home", "loft", "chalet", "house", "beachhouse", "guesthouse", "cabin", "skyloft", "ranch", "cottage", "mansion", "treehouse", "lakehouse", "townhouse", "apartment", "condo", "resort", "lodge", "lodging", "country house", "manor", "estate", "summer home", "winter lodge", "retreat", "log home", "rental", "castle" ]; listingType = ["House", "Apartment", "Condo", "Townhouse"]; listingAmenities = [ "family-friendly", "pet-friendly", "pool", "gated community", "fooseball", "trampoline", "spa", "close walk to beach", "close walk to town", "close to village", "surrounded by woods", "golf resort", "ski resort", "gourmet kitchen", "fishing", "hiking-friendly", "amazing garden", "backyard wilderness", "yacht", "boating", "close to downtown", "game room", "ac/heating", "hot tub", "jacuzzi", "bicycles", "surf", "great amenities", "nearby pond", "fireplace", "nearby lake", "garage parking", "great for photography", "gym", "loofers", "fireplace", "wildlife", "nearby trails", "close to train station", "stargazing", "vineyards", "paddle-boat", "kayak", "dock", "fitness center" ]; listingReview = [ "Great.", "Great find.", "Beautiful view.", "Great bargain.", "Good ammenities.", "Spectacular views.", "Convenient location.", "Excellent.", "Wonderful.", "Exceptional.", "Very good.", "Good for families." ]; writeCSV = callback => { let i = 10000000; function generateData() { let ok = true; do { i--; if (i % 10000 === 0) { console.log(i); } let listings = []; let obj; let listingcount = 0; // let data = // "title,venuetype,bedrooms,sleepcapacity,bathrooms,squarefeet,reviewoverview,rating,reviewnumber,owners,cleaningfee,states,city,pic,listingid"; obj = {}; let title = listingAdjectives[ Math.floor(Math.random() * listingAdjectives.length) ] + " " + listingStyles[Math.floor(Math.random() * listingStyles.length)] + " " + listingAmenities[Math.floor(Math.random() * listingStyles.length)] + " " + listingAmenities[Math.floor(Math.random() * listingStyles.length)]; title = title.slice(0, 1).toUpperCase() + title.slice(1); let venuetype = listingType[Math.floor(Math.random() * listingType.length)]; let bedrooms = Math.floor(Math.random() * 5 + 1); let sleepcapacity = bedrooms * 2 + Math.floor(Math.random() * 3 + 1); let bathrooms = Math.floor(Math.random() * 3 + 1); let squarefeet = Math.floor(Math.random() * 600 + 1) * 10 + 1000; let reviewoverview = listingReview[Math.floor(Math.random() * listingReview.length)]; let rating = Math.floor(Math.random() * 10) / 10 + 4; let reviewnumber = Math.floor(Math.random() * 200 + 15); let owners = faker.name.findName(); let cleaningfee = Math.floor(Math.random() * 100) + 10; let states = faker.address.state(); let city = faker.address.city(); let pic = faker.image.image(); let listingid = i; data = `${title},${venuetype},${bedrooms},${sleepcapacity},${bathrooms},${squarefeet},${reviewoverview},${rating},${reviewnumber},${owners},${cleaningfee},${states},${city},${pic},${listingid}\n`; // listings.push(obj); // listingcount = listingcount + 1; if (i === 0) { stream.write(data, callback); // needs callback as a parameter to write() (inherited method of fs) // stream.end(); // we are going to end the connection after writing to CSV inside of seedDB's function definition INSTEAD } else { ok = stream.write(data); } } while (i > 0 && ok); if (i > 0) { stream.once("drain", generateData); } } console.log(i); generateData(); console.log(`you've successfully written the CSV file, export to database`); mongoose.connection.close(); }; writeCSV(() => { console.log(`done writing CSV...`); }); /** * * * */ // ASYNC SEEDING; USES RAW MONGOOSE INSERTMANY() QUERIES // // let k; // // let listings = []; // let obj; // // let listingcount = 0; // const seedDatabase = async (outer, inner) => { // Listing.deleteMany({}); // console.log(`deleted previous collection...`); // let listingcount = 0; // for (let i = 0; i < outer; i++) { // let listings = []; // for (let j = 0; j < inner; j++) { // obj = {}; // obj.title = // listingAdjectives[ // Math.floor(Math.random() * listingAdjectives.length) // ] + // " " + // listingStyles[Math.floor(Math.random() * listingStyles.length)] + // " " + // listingAmenities[Math.floor(Math.random() * listingStyles.length)] + // " " + // listingAmenities[Math.floor(Math.random() * listingStyles.length)]; // obj.title = obj.title.slice(0, 1).toUpperCase() + obj.title.slice(1); // obj.venuetype = // listingType[Math.floor(Math.random() * listingType.length)]; // obj.bedrooms = Math.floor(Math.random() * 5 + 1); // obj.sleepcapacity = obj.bedrooms * 2 + Math.floor(Math.random() * 3 + 1); // obj.bathrooms = Math.floor(Math.random() * 3 + 1); // obj.squarefeet = Math.floor(Math.random() * 600 + 1) * 10 + 1000; // obj.reviewoverview = // listingReview[Math.floor(Math.random() * listingReview.length)]; // obj.rating = Math.floor(Math.random() * 10) / 10 + 4; // obj.reviewnumber = Math.floor(Math.random() * 200 + 15); // obj.owners = faker.name.findName(); // obj.cleaningfee = Math.floor(Math.random() * 100) + 10; // obj.states = faker.address.state(); // obj.city = faker.address.city(); // // k = i + 1; // obj.pic = faker.image.image(); // // let data = `${title};${venuetype};${bedrooms};${sleepcapacity};${bathrooms};${squarefeet};${reviewoverview};${rating};${reviewnumber};${owners};${cleaningfee};${states};${city};${pic}\n`; // listings.push(obj); // listingcount = listingcount + 1; // } // await Listing.insertMany(listings) // .then(() => { // console.log(`listings inserted:`, listingcount); // }) // .catch(err => { // console.log(err); // }); // } // }; // seedDatabase(100, 10000).then(() => { // mongoose.connection.close(); // }); /** * * * */ // THIS IS PRIOR TO SWITCHING TO ASYNC SEED FUNCTION // // let k; // let listings = []; // let obj; // let listingcount = 0; // const createListings = () => { // for (let i = 0; i < 1000; i++) { // obj = {}; // obj.title = // listingAdjectives[Math.floor(Math.random() * listingAdjectives.length)] + // " " + // listingStyles[Math.floor(Math.random() * listingStyles.length)] + // " " + // listingAmenities[Math.floor(Math.random() * listingStyles.length)] + // " " + // listingAmenities[Math.floor(Math.random() * listingStyles.length)]; // obj.title = obj.title.slice(0, 1).toUpperCase() + obj.title.slice(1); // obj.venuetype = listingType[Math.floor(Math.random() * listingType.length)]; // obj.bedrooms = Math.floor(Math.random() * 5 + 1); // obj.sleepcapacity = obj.bedrooms * 2 + Math.floor(Math.random() * 3 + 1); // obj.bathrooms = Math.floor(Math.random() * 3 + 1); // obj.squarefeet = Math.floor(Math.random() * 600 + 1) * 10 + 1000; // obj.reviewoverview = // listingReview[Math.floor(Math.random() * listingReview.length)]; // obj.rating = Math.floor(Math.random() * 10) / 10 + 4; // obj.reviewnumber = Math.floor(Math.random() * 200 + 15); // obj.owners = faker.name.findName(); // obj.cleaningfee = Math.floor(Math.random() * 100) + 10; // obj.states = faker.address.state(); // obj.city = faker.address.city(); // // k = i + 1; // obj.pic = faker.image.image(); // // let data = `${title};${venuetype};${bedrooms};${sleepcapacity};${bathrooms};${squarefeet};${reviewoverview};${rating};${reviewnumber};${owners};${cleaningfee};${states};${city};${pic}\n`; // listings.push(obj); // listingcount = listingcount + 1; // } // }; // // THIS WORKS FOR < 100K RECORDS // const seedDatabase = () => { // Listing.deleteMany({}); // Listing.insertMany(listings) // .then(() => { // mongoose.connection.close(); // }) // .catch(err => console.log(err)); // }; // // db.deleteMany(); // createListings(); // // db.deleteAll(); // seedDatabase(); <file_sep>/client/src/components/search-bar.jsx // jshint esversion:6 import React from 'react'; class SearchBar extends React.Component { constructor(props) { super(props); this.state = { }; } componentDidMount() { } render() { return ( <div className='al-search-bar-container'> <input className='al-input-bar' size="66.5" value={this.props.term} onChange={this.props.handleChange}/> <label className={`${this.props.term.length ? 'al-shrink' : ''} al-form-input-label al-search-bar`}>{this.props.term.length ? 'Where' : 'Where to?'}</label> </div> ); } }; export default SearchBar;<file_sep>/client/src/components/feedback-button.jsx // jshint esversion:6 import React from 'react'; import FeedbackForm from './feedback-form.jsx'; import Overlay from './overlay.jsx'; class FeedbackButton extends React.Component { constructor() { super(); this.state = { selected: false }; this.toggleFeedbackButton = this.toggleFeedbackButton.bind(this); } toggleFeedbackButton() { this.setState({selected: !this.state.selected}); } render() { return ( <div onClick={this.props.handleSelected} className='al-header-option-container2 al-feedback-button al-feedback-text'> <span className='al-header-option-text'>Feedback</span> <div className='al-feedback-form-container'> { this.props.selected ? ( <Overlay /> ) : ( null ) } { this.props.selected ? ( <FeedbackForm /> ) : ( null ) } </div> </div> ); } } export default FeedbackButton;<file_sep>/client/src/components/login-dropdown.jsx // jshint esversion:6 import React from 'react'; const LoginDropdown = () => { const options = ['Traveler Login', 'Owner Login']; return ( <div className='al-login-dropdown'> { options.length ? ( options.map((option, i) => { return (<div key={i} className='al-login-option-container'><span className='al-login-option-text'>{option}</span></div>); }) ) : ( null ) } </div> ); }; export default LoginDropdown;<file_sep>/client/src/components/trip-boards-button.jsx // jshint esversion:6 import React from 'react'; import SVG from 'react-inlinesvg'; import HeartIcon from '../../dist/icons/iconmonstr-heart-thin.svg'; const TripBoardsButton = () => { return ( <div className='al-header-option-container al-trip-boards-button'> <table className='al-header-option-table'> <tbody> <tr> <td className='al-header-option-icon-container'><SVG src={HeartIcon} className='al-header-option-icon'/></td> <td><span className='al-header-option-text'>Trip Boards</span></td> </tr> </tbody> </table> </div> ); }; export default TripBoardsButton;<file_sep>/dbhelpers/sqlfiles/pg-promise-index.js const { QueryFile } = require("pg-promise"); const path = require("path"); // module.exports = { // dates: { // create: sql("./dates.sql") // }, // listings: { // create: sql("./listings.sql") // } // }; function sql(fullPath) { // const fullPath = path.join(__dirname, file); // generating full path const options = { // minifying the SQL is always advised; // see also option 'compress' in the API; minify: true // See also property 'params' for two-step template formatting }; const qf = new QueryFile(fullPath, options); if (qf.error) { // Something is wrong with our query file :( // Testing all files through queries can be cumbersome, // so we also report it here, while loading the module: console.error(qf.error); } return qf; // See QueryFile API: // http://vitaly-t.github.io/pg-promise/QueryFile.html } module.exports = sql; <file_sep>/client/src/redux/booking/booking.action.js // jshint esversion:6 export const setCheckInDate = (date) => { return ({ type: 'SET_CHECK_IN_DATE', payload: date }); }; export const setCheckOutDate = (date) => { return ({ type: 'SET_CHECK_OUT_DATE', payload: date }); }; export const setCheckInDate1 = (date) => { return ({ type: 'SET_CHECK_IN_DATE1', payload: date }); }; export const setCheckOutDate1 = (date) => { return ({ type: 'SET_CHECK_OUT_DATE1', payload: date }); }; export const setRate = (rate) => { return ({ type: 'SET_RATE', payload: rate }); }; export const setTotal = (total) => { return ({ type: 'SET_TOTAL', payload: total }); }; export const setFee = (fee) => { return ({ type: 'SET_FEE', payload: fee }); }; export const makeValid = () => { return ({ type: 'MAKE_VALID' }); }; export const makeInvalid = () => { return ({ type: 'MAKE_INVALID' }); }; export const setTitle = (title) => { return ({ type: 'SET_TITLE', payload: title }); }; export const setSleepCapacity = (sleepCapacity) => { return ({ type: 'SET_SLEEP_CAPACITY', payload: sleepCapacity }); }; export const setReviewOverview = (reviewOverview) => { return ({ type: 'SET_REVIEW_OVERVIEW', payload: reviewOverview }); }; export const setRating = (rating) => { return ({ type: 'SET_RATING', payload: rating }); }; export const setReviewNumber = (number) => { return ({ type: 'SET_REVIEW_NUMBER', payload: number }); }; export const setOwner = (owner) => { return ({ type: 'SET_OWNER', payload: owner }); }; export const setCleaningFee = (cleaningFee) => { return ({ type: 'SET_CLEANING_FEE', payload: cleaningFee }); }; export const setUSState = (USState) => { return ({ type: 'SET_US_STATE', payload: USState }); }; export const setCity = (city) => { return ({ type: 'SET_CITY', payload: city }); }; export const setPic = (url) => { return ({ type: 'SET_URL', payload: url }); }; export const startLoading = () => { return ({ type: 'START_LOADING' }); }; export const stopLoading = () => { return ({ type: 'STOP_LOADING' }); }; export const setGuests = (guests) => { return ({ type: 'SET_GUESTS', payload: guests }); }; export const setDays = (days) => { return ({ type: 'SET_DAYS', payload: days }); }; export const toggleGuestsForm = () => { return ({ type: 'TOGGLE_GUESTS_FORM' }); }; export const toggleCalendar = () => { return ({ type: 'TOGGLE_CALENDAR' }); }; export const setSearchTerm = (e) => { return ({ type: 'SET_SEARCH_TERM', payload: e }); }
0e662f2fc14b52d4a1103d9b466ab22dd7484008
[ "JavaScript", "SQL", "Markdown" ]
47
JavaScript
objectobject-hr/sdc-service-aaron
6f7c46d4f48d7131cacffbde0548e7ebf56bf078
b8e2e112347528368f9e6e7d93a17aabcd0b464e
refs/heads/master
<file_sep>import os import main import unittest class FlaskrTestCase(unittest.TestCase): """ It's a main application test class for funtional testing. A|B testing engine can be devided by three modules which are controller, service and database access object. Each modules need to do unit testing and finally get a 80% code coverage rate. Functional test that have been described and implemented in this class is a key to keep application quality high and will be used for load test. """ def setUp(self): """ set up initialize steps before test begin like creating db connection or test client """ self.app = main.app.test_client() def tearDown(self): """ finalize step after whole tests are end """ pass def test_admin(self): """ It's test function for admin URL" """ rv = self.app.get('/admin') assert "It's admin URL" in rv.data.decode('utf-8') def test_collecting(self): """ It's test function for collecting URL" """ rv = self.app.get('/collecting') assert "It's collecting URL" in rv.data.decode('utf-8') def test_routing(self): """ It's test function for routing url """ rv = self.app.get('/routing') assert "It's routing URL" in rv.data.decode('utf-8') def test_reporting(self): """ It's test function for reporting url """ rv = self.app.get('/reporting') assert "It's reporting URL" in rv.data.decode('utf-8') if __name__ == '__main__' : unittest.main() <file_sep># Author : <EMAIL> # This images is made for ab-testing web apllication server, which is based on ubuntu16.10 FROM ubuntu:16.10 #install essential modules and dependency RUN apt-get update && apt-get -y install \ git \ wget \ vim \ curl \ python3.6 \ && rm -rf /var/lib/apt/lists/* #create working directory to manage applicaion WORKDIR /home/runtime #pip setting with get-pip.oy then install flask using pip3 RUN wget https://bootstrap.pypa.io/get-pip.py && python3.6 get-pip.py && rm get-pip.py && pip3 install flask #deploy application RUN mkdir flask_app COPY main.py flask_app/main.py ENV FLASK_APP flask_app/main.py && LC_ALL=C.UTF-8 && LANG=C.UTF-8 CMD [ "flask" , "run" , "--host=0.0.0.0" ] <file_sep># Author : <EMAIL> # This images is made to test ab-testing engine. It can be rebuild later with another structure. FROM flask-app:latest #install coverage test module RUN pip3 install coverage && pip3 install nose RUN mkdir /var/log/flask #copy source file for testing into images COPY main_test.py flask_app/test/main_test.py #add pythonpath for application source code import ENV PYTHONPATH=/home/runtime/flask_app #add env value for running test flask application. Every flask application have to have APP_NAME env value, so we need to mocki that environment ENV APP_NAME=test_application #running test CMD python3.6 /home/runtime/flask_app/test/main_test.py <file_sep>#It's repository for ab-testing engine. Currently this project is stopped by some reasons. huha.." <file_sep>FROM ubuntu:16.04 RUN [ "mkdir","/var/log/nginx" ] RUN [ "mkdir","/var/log/flask" ] VOLUME /var/log/nginx VOLUME /var/log/flask <file_sep>from flask import Flask from flask import request import logging import os logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='/var/log/flask/'+os.getenv('APP_NAME')+'_app_info.log', filemode='w') info_logger = logging.getLogger('app_logger') app = Flask(__name__) def shutdown_server(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError( 'Not Running with Werkezeug Server' ) func() @app.route("/admin") def admin(): info_logger.info("admin URL") return "It's admin URL" @app.route("/collecting") def collecting(): info_logger.info("collecting URL") return "It's collecting URL" @app.route("/reporting") def reporting(): info_logger.info("reporting URL") return "It's reporting URL" @app.route("/routing") def routing(): info_logger.info("routing URL") return "It's routing URL" @app.route('/shutdown',methods=['POST']) def shutdown(): """ API for gracefully shutdown flask application. Flask application can be shut down when all requests requested to flask apllication are complete. It will help application rollout process. """ shutdown_server() return 'Server shutting down.....' if __name__ == "__main__": info_logger.info("engine application start!") app.run()
806746bdb59ba4e95b8c47b0c50f718754f749a8
[ "Markdown", "Python", "Dockerfile" ]
6
Python
sjh8543/ab-testing
66c231f95eca255f7a7d0717f4a97405e09b4052
7176be4e4d4ae9365b801f06d42b4bbf5c3c411d
refs/heads/master
<repo_name>Npikeulg/HT-BEC<file_sep>/database_generator.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author: <NAME> Purpose: Analysis data generated by Guido and found on Materials project for high-thoughput calculations of the phonon band structure. We need to extract both structural information, the BEC, and the bader charge from various database files. """ # import functions import json import numpy as np import numpy.linalg as la import pandas as pd import matplotlib.pyplot as plt from monty.serialization import loadfn from mendeleev import element from pymatgen import MPRester print('Starting program') # Important variables MPKEY = '<KEY>' DIFF_MIN = 0.02 # create the database as a dictionary database = dict() print(' Loading databases') # load already generated databases with open('bader_data.json') as bader: baderdata = json.load(bader) with open('becs.json') as bec: becsdata = json.load(bec) with open('structure_with_chem_env_simple.json') as structure: structuredata = json.load(structure) print(' Finished loading databases\n') print('Gathering materials project data') print(' Program will count each database found...') # loop through mp-numbers in the simple environment database c = 0 structdata = loadfn('structure_with_chem_env_simple.json') for mp_id, struct in structdata.items(): data_array = [] # open MPRester with MPRester(MPKEY) as mp: c += 1 print(c) # a simple counter so we know that MPRester is working data = mp.get_data(mp_id) # if c >= 75: # break # extract some data from materials project try: get_sym = data[0]['spacegroup']['crystal_system'] spgnum = data[0]['spacegroup']['number'] formula = data[0]['pretty_formula'] bandgap = data[0]['band_gap'] volume = data[0]['volume'] engatom = data[0]['energy_per_atom'] except IndexError: continue # should move to the next mp_id # elastic data from materials project (if available) try: elastic = data[0]['elasticity']['elastic_tensor'] # tensor! GV = data[0]['elasticity']['G_Voigt'] KV = data[0]['elasticity']['K_Voigt'] poisson = data[0]['elasticity']['poisson_ratio'] except TypeError: elastic = np.full([6,6],np.nan) GV = np.nan KV = np.nan poisson = np.nan try: dielectric = data[0]['diel']['e_total'] # tensor! except TypeError: dielectric = np.full([3,3],np.nan) # extract data from predetermined databases atom_charges = baderdata[mp_id]['total']['atomic_charges'] bader_ch_trans = baderdata[mp_id]['total']['bader_charges_transfer'] # array of bader charge for each atom bec_charges = becsdata[mp_id]['data']#gives arrays of all bec for each atom strct = structuredata[mp_id]['structure'] #structure object for mp_number coordenv = structuredata[mp_id]['coordination_environments'] #array alatt = strct['lattice']['a'] blatt = strct['lattice']['b'] clatt = strct['lattice']['c'] alpha = strct['lattice']['alpha'] beta = strct['lattice']['beta'] gamma = strct['lattice']['gamma'] # manipulation of bec data bec_weird = False odd_atom = 0 atcharge = 0 coord_env = '' zatom = [0,0,0] for i in range(len(atom_charges)): first = 0 odd_atom = i atcharge = atom_charges[i] try: coord_env = coordenv[i][0]['ce_symbol'] except TypeError: coord_env = '' zatom[0] = np.real(la.eig(bec_charges[i])[0][0]) zatom[1] = np.real(la.eig(bec_charges[i])[0][1]) zatom[2] = np.real(la.eig(bec_charges[i])[0][2]) for j in range(3): if np.sign(bader_ch_trans[i]) != np.sign(la.eig(bec_charges[i])[0][j]) and np.abs(bader_ch_trans[i] - la.eig(bec_charges[i])[0][j]) >= DIFF_MIN and first == 0: first = 1 bec_weird = True # add data to data_array data_array.append(formula) data_array.append(bec_weird) data_array.append(coord_env) data_array.append(get_sym) data_array.append(spgnum) data_array.append(bandgap) data_array.append(volume) data_array.append(engatom) data_array.append(GV) data_array.append(KV) data_array.append(poisson) data_array.append(elastic[0][1]-elastic[3][3]) data_array.append(elastic[0][0]) data_array.append(elastic[1][1]) data_array.append(elastic[2][2]) data_array.append(elastic[3][3]) data_array.append(elastic[4][4]) data_array.append(elastic[5][5]) data_array.append(dielectric[0][0]) data_array.append(dielectric[1][1]) data_array.append(dielectric[2][2]) data_array.append(odd_atom) data_array.append(atcharge) data_array.append(zatom[0]) data_array.append(zatom[1]) data_array.append(zatom[2]) data_array.append(alatt) data_array.append(blatt) data_array.append(clatt) data_array.append(1.0/alatt**2) data_array.append(1.0/blatt**2) data_array.append(1.0/clatt**2) data_array.append(alpha) data_array.append(beta) data_array.append(gamma) # extract physical data about the odd atom name = str(structuredata[mp_id]['structure']['sites'][odd_atom]['label']) data_array.append(element(name).en_pauling) data_array.append(element(name).en_allen) data_array.append(element(name).en_ghosh) data_array.append(element(name).group_id) data_array.append(element(name).period) data_array.append(element(name).electron_affinity) data_array.append(element(name).block) data_array.append(element(name).vdw_radius) data_array.append(element(name).atomic_radius) data_array.append(element(name).atomic_weight) data_array.append(element(name).atomic_number) # Add data_array to database database[mp_id] = data_array print('Completed gathering all data.\n') print('Starting analysis of full database.\n') columns = ['formula','bec_odd','coord_env', 'sym','spgnum','Eg','volume','eng/atom','Gvoigt','kvoigt', 'poisson', 'cauchy','sxx','syy','szz','sxy','syz','sxz','exx','eyy','ezz', 'odd_atom','atcharge','zxx','zyy','zzz', 'a','b','c','a^-2','b^-2','c^-2','alpha','beta','gamma','E_p','E_a', 'E_g','group','period','E_aff','block','R_vdw','R_at','atmass', 'atnum'] #build dataframe df = pd.DataFrame.from_dict(database,orient='index',columns=columns) pd.set_option('display.max_rows',len(columns)) pd.set_option('display.max_columns',len(columns)) print('Generating csv files.') # note that string based data will be excluded by the dataframe algorithm fullcorr = df.corr(method='pearson') # print(fullcorr) # Dumps data to a csv file fullcorr.to_csv('database_corr_full.csv') # Dumps data to a csv file df.to_csv('database_full.csv') # We can now extract specific data from our dataframe using pandas # by searching the column header that contain strings, finding the unique strings, # and then finding the pearson correlation strcolumns = [col for col, dt in df.dtypes.items() if dt == object] boolcolumns = [col for col,dt in df.dtypes.items() if dt == bool] for col in strcolumns: if col != 'formula': # formula is always unique.. that is way too many files! # get column values colvalues = df[col] # find unique values unicol = np.unique(colvalues) # iterate over unique values for that column for uniq in unicol: # filter database col by its uniq entry dffilter = df.loc[df[col]== uniq] # dump filtered matrix to a csv file dffilter.to_csv('database_filtered_'+col+'_'+uniq+'.csv') # find correlation matrix again corr_filter = dffilter.corr(method='pearson') # Dumps data to a csv file corr_filter.to_csv('pearson_filtered_'+col+'_'+uniq+'.csv') # for each unique value in the column, we want to iterate over the # unique boolean types for col2 in boolcolumns: # get column values boolvalues = dffilter[col2] # find unique values unibool = np.unique(boolvalues) for uniq2 in unibool: # filter database again with respect to boolean columns dfBEC = dffilter.loc[dffilter[col2]==uniq2] # dump filtered matrix to a csv file dfBEC.to_csv('database_filtered_'+col+'_'+uniq+'_'+col2+'_'+str(uniq2)+'.csv') # find correlation matrix again corr_BEC= dfBEC.corr(method='pearson') # dump correlation to a file corr_BEC.to_csv('pearson_filtered_'+col+'_'+uniq+'_'+col2+'_'+str(uniq2)+'.csv') lendata = len(dfBEC.index) print(' Number of data with filters %s and %s is %i' %(uniq,uniq2,lendata)) # ends script
8b8c9e2c4d534a0d7941c9d04c6f85490390617e
[ "Python" ]
1
Python
Npikeulg/HT-BEC
e3d999f4bec3afbcb2216916de4f7e31e43d77d9
6991971f632bf06ef91927a41f16e73c0dee03e4
refs/heads/master
<file_sep>vagrant-lamp-centos65 ===================== "# evovagrant" # evovagrant <file_sep># .bashrc # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi source ~/git-completion.bash # User specific aliases and functions alias r="screen -r" alias gr="git log --graph --full-history --all --color --pretty=tformat:\"%x1b[31m%h%x09%x1b[32m%d%x1b[0m%x20%s%x20%x1b[33m(%an)%x1b[0m;\"" alias grd="git log --graph --full-history --all --color --pretty=tformat:\"%x1b[31m%h%x09%x1b[36m%ad%x1b[32m%d%x1b[0m%x20%s%x20%x1b[33m(%an)%x1b[0m;\" --date=iso" alias st="git status" alias ci="git commit" alias ud="git add -u; d" alias cim="git commit -m" gitCPNC(){ hashkey=$1 message=$2 git cherry-pick -n $hashkey git commit -m "$2" } alias gcpnc=gitCPNC gitCPN(){ hashkey=$1 git cherry-pick -n $hashkey } alias gcpn=gitCPN gitDiffHead(){ # --no-prefix git diff HEAD -C "$@" > diff.diff git diff --stat HEAD } alias d=gitDiffHead alias dh=gitDiffHead gitDiffCurrent() { git diff "$@" > diff.diff git diff --stat } alias dc=gitDiffCurrent gitDiffStaged() { git diff --staged "$@" > diff.diff git diff --staged --stat } alias ds=gitDiffStaged alias a="git add" # alias c="vim _commit-message.commit-message;git commit -F _commit-message.commit-message; rm _commit-message.commit-message" alias bcc="bash cache-clear.sh" alias cc="bash cache-clear.sh" alias sfs="php symfony --shell" # projects alias cdevo="cd ~/www/evolution" # gulp alias gw="gulp watch & " # rmhist <from> <to> rmhist() { start=$1 end=$2 count=$(( end - start )) while [ $count -ge 0 ] ; do history -d $start ((count--)) done } unchanger(){ oldname=$1 newname=$2 git checkout HEAD -- $oldname git rm -f $newname git mv $oldname $newname git diff -C -D --staged > diff.diff } # SVN alias svnsti="svn st --ignore-externals" alias svnst="svn st" alias svnadd="svn changelist TO-COMMIT" alias svnci="svn commit --changelist TO-COMMIT" <file_sep>#!/usr/bin/env python # vim: set syntax=python: ask_for_type = False ask_for_type = True """ Git hook to insert a commit message marker. This hook is specific to the Psignifit-3.x project. It will insert an appropriate commit message marker, e.g. [C++/NF] into the first line of the commit message. Author: <NAME> <<EMAIL>> Licence: WTFPL http://en.wikipedia.org/wiki/WTFPL Usage: symlink the file to a .git/hooks directory $ git clone git://github.com/esc/commit-marker $ cd ${project} $ ln -s ${path-to}/commit-prefix/prepare-commit-msg .git/hooks When committing, the script will interactively ask you for input using the prompt '?:'. You may then input one or more numbers, separated by space. The script will parse you input and construct the desired commit marker. For example: $ git co -b testing $ git commit -m "commit message" Where did you make your change? 1: C++ -- C++ code base 2: swig -- swig interface 3: py -- Python code 4: R -- R code 5: matlab -- matlab code 6: build -- Build system 7: docs -- Documentation 8: debian -- Debian directory ?:3 What kind of modification did you make? 1: NF -- new feature 2: BF -- bug fix 3: RF -- refactor 4: FO -- formatting 5: DOC -- documentation ?:3 4 [testing da33f2f] [py/RF/FO] commit message $ git log -1 --pretty="format:%s" [py/RF/FO] commit message Although the example works with the '-m' flag for simplicity, the script also works when 'git commit' opens the editor of you choice. In this case the commit marker will already have been inserted and you must only write the message. This also gives you the chance to amend or modify the marker to you liking. If you don't enter a number, the script will simply insert the empty string. If you wish to abort the commit when you have reached the editor, you have to delete the commit message marker and save an empty commit message. Vim users could use ':cq' to exit with a non-zero status, which will also abort the commit. """ import sys import commands import subprocess import os import re # cwd = os.path.dirname( '/ext/home/rakesh.kumar/workspace/myproject/' ) pr = subprocess.Popen( "git symbolic-ref HEAD 2>/dev/null" , cwd = os.getcwd(), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) (out, error) = pr.communicate() # print "Error : " + str(error) # git symbolic-ref HEAD 2>/dev/null # refs/heads/T-30927-time-update # print "out : " + str(out) branch = str(out) ticket = "" if len(branch): branch = branch.rstrip() branch = branch[branch.rfind("/")+1:] REG = r"^\w+-([\d]+)-.+" if re.match(REG, branch): ticket = re.sub(REG, r"\1", branch ) mod_type = [('NF ', 'new feature'), ('BF ', 'bug fix'), ('RF ', 'refactor'), ('CH ', 'changes'), ('FO ', 'formatting'), ('UT ', 'unit test'), ] mod_type = dict( (str(index+1), option) for index, option in enumerate(mod_type)) area_type = [('PHP ', 'pure PHP'), ('SQL ', 'SQL'), ('JS ', 'web development JS'), ('angular ', 'angular JS and HTML'), ('HTML ', 'web development HTML'), ('CSS ', 'web development CSS'), ('py ', 'Python code'), # ('C++ ', 'C++ code base'), ('docs ', 'Documentation'), # ('R ', 'R code'), # ('matlab ', 'matlab code'), # ('build ', 'Build system'), # ('debian ', 'Debian directory'), ] area_type = dict( (str(index+1), option) for index, option in enumerate(area_type)) def print_and_read_selection(option_dict): for key, val in sorted(option_dict.items()): print '%s: %s -- %s' % (key, val[0], val[1]) # needed to run raw_input in git-hook sys.stdin = open('/dev/tty') try: user_input = raw_input('?:') except KeyboardInterrupt: print "Canceled by user!" sys.exit(1) if not user_input: return '' tokenized_input = user_input.strip().split(' ') try: descriptors = [option_dict[i][0].rstrip() for i in tokenized_input] except KeyError: print 'Fatal: number %s is invalid' % i sys.exit(1) else: return '/'.join(descriptors) def get_marker_from_user(): output_list = [] if ticket: output_list.insert(0,'#'+ticket+' ') if ask_for_type: changesArr = [] print 'Where did you make your change?' workType = print_and_read_selection(area_type) if workType: changesArr.append(workType) print 'What kind of modification did you make?' technology = print_and_read_selection(mod_type) if technology: changesArr.append(technology) if len(changesArr): output_list.append('[') output_list.append(', '.join(changesArr)) output_list.append('] ') return ''.join(output_list) def prepend_to_file(marker): f = open(sys.argv[1], 'r') lines = f.readlines() lines[0] = marker + lines[0] f.close() f = open(sys.argv[1], 'w') f.write(''.join(lines)) f.close() if __name__ == '__main__': prepend_to_file(get_marker_from_user())
72fd942ade68a0b170fec77af7e909a4136452a2
[ "Markdown", "Python", "Shell" ]
3
Markdown
vladimirgolub/evovagrant
7da288adc567e205c5fcb2b86d73146732725824
f15a1117b5bb5d33054ccfd9c548a8d5044d1099
refs/heads/master
<file_sep>@states = { OR: 'Oregon', FL: 'Florida', CA: 'California', NY: 'New York', MI: 'Michigan' } # Task 1 @states[:AL] = "Albama" @states[:AK] = "Alaska" # @states = @states.merge({AL: "Alabama", AK: "Alaska"}) # @states.merge!({AL: "Alabama", AK: "Alaska"}) # Task 2 @cities = { OR: ['Salem','Bend'], FL: ['Tampa','Miami'], CA: ['Los Angeles','Sacramento'], NY: ['Buffalo','Yonkers'], MI: ['Lansing','Detroit'], AL: ['Birmingham','Huntsville','Mobile'], AK: ['Anchorage','Juneau'] } # Task 3 def describe_state(state) state = state.to_sym if not @states.has_key? state.to_sym puts "Sorry we do not have any relevant data" else puts "#{state} is for #{@states[state]}. It has #{@cities[state].length} major cities: #{@cities[state].join(", ")}" end end # Task 4 @taxes = { OR: 7.5, FL: 9.0, CA: 2.0, NY: 3.5, MI: 5.0, AL: 3.4, AK: 2.1 } # Task 5 def calculate_tax(state,amount) if not @states.has_key? state.to_sym puts "Sorry we do not have any relevant data" else puts (amount*(@taxes[state.to_sym].to_f)/100).round(2) end end # Task 6 def find_state_for_city(city) @containsCity = false @cities.each{|key,value| if @cities[key].include? city @region = key @containsCity = true end } if @containsCity puts "#{city} belongs to this #{@region}" else puts "Sorry we do not have any relevant data" end end # Input puts "Enter an Option:1 => Describe The State 2 => Calculate your tax 3 => Find the State" option = gets.chomp.to_i case option when 1 puts "Enter a State" state = gets.chomp.upcase describe_state(state) when 2 puts "Enter a State" state = gets.chomp.upcase puts "Enter the amount" amount = gets.chomp.to_i calculate_tax(state,amount) when 3 puts "Enter the City" city = gets.chomp find_state_for_city(city) else puts "Try Again" end<file_sep>@states = { OR: ['Oregon',['Salem','Bend']], FL: ['Florida',['Tampa','Miami']], CA: ['California',['Los Angeles','Sacramento']], NY: ['New York',['Buffalo','Yonkers']], MI: ['Michigan',['Lansing','Detroit']] # #GOT TO LEARN HOW TO INPUT DATA TO SERVERS # params = { # user: { # first_name: "test", # last_name: "last" # } # } # } # Got to try this AGAIN # @states = { # OR: {name: 'Oregon', cities: ['']} # } # Task 1 @states[:AL] = ["Albama",['Birmingham','Huntsville','Mobile']] @states[:AK] = ["Alaska",['Anchorage','Juneau']] # # Task 2 # @cities = { # OR: ['Salem','Bend'], # FL: ['Tampa','Miami'], # CA: ['Los Angeles','Sacramento'], # NY: ['Buffalo','Yonkers'], # MI: ['Lansing','Detroit'], # AL: ['Birmingham','Huntsville','Mobile'], # AK: ['Anchorage','Juneau'] # } # Task 3 def describe_state(state) if not @states.has_key? state.to_sym puts "Sorry we do not have any relevant data" else @state[state].cities puts "#{state} is for #{(@states[state.to_sym])[0]}. It has #{(@states[state.to_sym])[1].length} major cities: #{(@states[state.to_sym])[1].join(", ")}" end end # Task 4 @taxes = { OR: 7.5, FL: 9.0, CA: 2.0, NY: 3.5, MI: 5.0, AL: 3.4, AK: 2.1 } # Task 5 def calculate_tax(state,amount) if not @states.has_key? state.to_sym puts "Sorry we do not have any relevant data" else puts (amount*(@taxes[state.to_sym].to_f)/100).round(2) end end # Task 6 def find_state_for_city(city) @containsCity = false @states.each{|key,value| if value[1].include? city @region = key @containsCity = true end } if @containsCity puts "#{city} belongs to this #{@region}" else puts "Sorry we do not have any relevant data" end end # Input puts "Enter an Option:1 => Describe The State 2 => Calculate your tax 3 => Find the State" option = gets.chomp.to_i case option when 1 puts "Enter a State" state = gets.chomp.upcase describe_state(state) when 2 puts "Enter a State" state = gets.chomp.upcase puts "Enter the amount" amount = gets.chomp.to_i calculate_tax(state,amount) when 3 puts "Enter the City" city = gets.chomp find_state_for_city(city) else puts "Try Again" end
98509c38860ab9a97690059307a13c76ab29a6a5
[ "Ruby" ]
2
Ruby
am52saif/States-Cities
4d76675201aa6e2923d623638841808ccf62b552
53a9f6a5260456caed649b826321d80d175b8eca
refs/heads/master
<file_sep>#define LED_ERROR 9 #define DHT_PIN 7 #define WATERDETECTION_PIN A0 #define ACCURACY 5000<file_sep># temperature-humidity-leak-mqtt <file_sep>#include <Arduino.h> #include <Ethernet.h> #include <SPI.h> #include <DHT.h> #include <Adafruit_Sensor.h> #include <ArduinoJson.h> #include "config.h" // Inicializo variables DHT dht(DHT_PIN, DHT22); const int capacity = JSON_OBJECT_SIZE(3); const int threshold = 100; EthernetClient client; // Network configuration byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; boolean readWaterSensor(){ int confirmations = 1; int requiredConfirmations = 10; while (confirmations <= requiredConfirmations) { delay(100); if(analogRead(WATERDETECTION_PIN) >= threshold){ confirmations++; }else{ return false; } } return true; } void printNetworkInformation(){ Serial.print("IP address . . . . . . : "); Serial.println(Ethernet.localIP()); Serial.print("Subnet mask. . . . . . : "); Serial.println(Ethernet.subnetMask()); Serial.print("Gateway ip address . . : "); Serial.println(Ethernet.gatewayIP()); Serial.print("Dns server . . . . . . : "); Serial.println(Ethernet.dnsServerIP()); } void printNetworkError(){ if(Ethernet.hardwareStatus() == EthernetNoHardware){ Serial.println("Ethernet shield was not found."); }else{ switch (Ethernet.linkStatus()) { case LinkON: Serial.println("Link status: On"); break; case LinkOFF: Serial.println("Link status: Off"); break; default: Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500."); break; } } } void errorLed(boolean turn){ if(turn){ digitalWrite(LED_ERROR, HIGH); }else{ digitalWrite(LED_ERROR, LOW); } } void setup() { pinMode(LED_ERROR, OUTPUT); dht.begin(); // Start Serial.begin(115200); Serial.print("Initialize Ethernet with DHCP: "); if(Ethernet.begin(mac) == 0){ Serial.println("Failed to configure Ethernet using DHCP"); errorLed(true); printNetworkError(); }else{ Serial.println("Connected"); printNetworkInformation(); } } void loop() { StaticJsonDocument<capacity> doc; float temperature = dht.readTemperature(); float humidity = dht.readHumidity(); if(isnan(humidity) || isnan(temperature)){ Serial.println("Failed to read from DHT sensor!"); errorLed(true); }else{ doc["temperature"] = dht.readHumidity(); doc["humidity"] = dht.readTemperature(); } doc["leak"] = (readWaterSensor()) ? 1 : 0; if(!doc.isNull()){ serializeJsonPretty(doc,Serial); Serial.println(); } delay(ACCURACY); }
5f39b7d7192303d6b77039d154bee2d035464860
[ "Markdown", "C", "C++" ]
3
C
kntsoft/temperature-humidity-leak-mqtt
5ac803b3ecc7a3047c43c8822f2a20fa4380c431
3a57b2b46529f2ed52b409770d890ba8e019aaac
refs/heads/master
<repo_name>chsj1/JNIDemo-1<file_sep>/mylibrary/src/main/cpp/cppCallJava.cpp // // Created by sunalong on 17/3/17 10:24. // Email:<EMAIL> // #include "cppCallJava.h" JNIEnv *CppCallJava::callJavaMethod(JNIEnv *jniEnv, const _jstring *nameJstr, const _jstring *toastJstr, jobject activity) { //找到 class 类 jclass classId = jniEnv->FindClass("com/itcode/mylibrary/ForNativeCall"); //获取类的构造函数 jmethodID constructorMethodId = jniEnv->GetMethodID(classId, "<init>", "(Ljava/lang/String;Landroid/app/Activity;)V"); //使用构造函数创建对象 jobject forNativeCallObj = jniEnv->NewObject(classId, constructorMethodId, nameJstr, activity); //获取要调用的方法 jmethodID showToastId = jniEnv->GetMethodID(classId, "showToast", "(Ljava/lang/String;)J"); //对象调用方法 jniEnv->CallLongMethod(forNativeCallObj, showToastId, toastJstr); return jniEnv; } JNIEnv *CppCallJava::callJavaMethodStr(JNIEnv *jniEnv, const _jstring *nameJstr, const _jstring *toastJstr, jobject activity) { //找到 class 类 jclass classId = jniEnv->FindClass("com/itcode/mylibrary/ForNativeCall"); //获取类的构造函数 jmethodID constructorMethodId = jniEnv->GetMethodID(classId, "<init>", "(Ljava/lang/String;Landroid/app/Activity;)V"); //使用构造函数创建对象 jobject forNativeCallObj = jniEnv->NewObject(classId, constructorMethodId, nameJstr, activity); //获取要调用的方法 jmethodID getLoginUserInfoId = jniEnv->GetMethodID(classId, "getLoginUserInfo", "()Ljava/lang/String;"); //对象调用方法 jstring retJstr = (jstring) jniEnv->CallObjectMethod(forNativeCallObj, getLoginUserInfoId); const char *retChar = jniEnv->GetStringUTFChars(retJstr, 0); LOGD("cppCallJava callJavaMethodStr:%s", retChar); jniEnv->ReleaseStringUTFChars(retJstr, retChar); return jniEnv; } /** * 把数据从 Cpp 传到 Java * 有可能在子线程中调用 */ void CppCallJava::retDataToJava(ResponseType type, ResponseCode code, const char *dataPtr) { JNIEnv *jniEnv; bool isAttached = false; if (!JNIHelper::getJvmGlobal()) { LOGD("CppCallJava::retDataToJava jvm is null"); return; } jint retCode = JNIHelper::getJvmGlobal()->GetEnv((void **) &jniEnv, JNI_VERSION_1_4); if (retCode != JNI_OK) { jint res = JNIHelper::getJvmGlobal()->AttachCurrentThread(&jniEnv, nullptr); if (res < 0 || !jniEnv) { LOGD("CppCallJava::retDataToJava retCode:%d !=JNI_OK:%d,AttachCurrentThread:%d", retCode, JNI_OK, res); return; } isAttached = true; } //找到 class 类 // jclass classId = jniEnv->FindClass("com/itcode/mylibrary/ForNativeCall");//子线程中调用 FindClass 不会成功 jclass classId = JNIHelper::getForNativeCallClassId(); //获取类的构造函数 jmethodID constructorMethodId = jniEnv->GetMethodID(classId, "<init>", "()V"); //使用构造函数创建对象 jobject forNativeCallObj = jniEnv->NewObject(classId, constructorMethodId); //获取要调用的方法 jmethodID receiveDataFromC = jniEnv->GetMethodID(classId, "receiveDataFromC", "(IILjava/lang/String;)V"); //对象调用方法 jstring jstr; if (dataPtr == nullptr) jstr = jniEnv->NewStringUTF("nullStr"); else jstr = jniEnv->NewStringUTF(dataPtr); jniEnv->CallVoidMethod(forNativeCallObj, receiveDataFromC, type, code, jstr); if (jstr) { jniEnv->DeleteLocalRef(jstr); } if (isAttached) { if (JNIHelper::getJvmGlobal()->DetachCurrentThread() < 0) LOGD("cppCallJava retDataToJava could not detach thread from jvm"); } } <file_sep>/mylibrary/src/main/cpp/jni_onLoad.cpp // // Created by sunalong on 17/3/16 22:57. // Email:<EMAIL> // /** * JNI 启动时的入口 */ #include "jniHelper.h" extern "C" { jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { LOGD("JNI_OnLoad threadId:%d", std::this_thread::get_id()); JNIHelper::setJvmGlobal(vm);//保存全局的 javaVM,以便后来使用 return JNI_VERSION_1_4; } }<file_sep>/mylibrary/src/main/cpp/cppNetUtils.h // // Created by sunalong on 17/3/17 11:35. // Email:<EMAIL> // #ifndef JNIDEMO_CPPNETUTILS_H #define JNIDEMO_CPPNETUTILS_H #include "define.h" class CppNetUtils{ public: /** * Todo:第一个参数为何强行加上 const? */ bool getDeviceInfo(const CallbackFunc & callbackFunc,const char* deviceModel,int timeout); }; #endif //JNIDEMO_CPPNETUTILS_H <file_sep>/mylibrary/src/main/cpp/native-lib.cpp #include "jniHelper.h" #include "cppCallJava.h" #include "cppNetUtils.h" JNIEnv *envTemp = NULL; jobject activityGlobal = NULL; extern "C" { void callback(ResponseType responseType,ResponseCode responseCode,const char* dataPtr){ LOGD("【jni_log】callback: responseType:%d,responseCode:%d,dataStr:%s,threadId:%d",responseType,responseCode,dataPtr,std::this_thread::get_id()); CppCallJava cppCallJava; cppCallJava.retDataToJava(responseType,responseCode,dataPtr); } JNIEXPORT jboolean JNICALL Java_com_itcode_mylibrary_NativeEngine_getDeviceInfo(JNIEnv *env, jobject instance, jstring deviceModel_, jint timeout) { const char *deviceModel = env->GetStringUTFChars(deviceModel_, 0); CppNetUtils cppNetUtils; bool retBool = cppNetUtils.getDeviceInfo(callback,deviceModel,timeout); env->ReleaseStringUTFChars(deviceModel_, deviceModel); return retBool; } JNIEXPORT void JNICALL Java_com_itcode_mylibrary_NativeEngine_register(JNIEnv *env, jobject instance, jobject activity) { // activityGlobal = activity;//注意与下一句的区别,报错为:E/dalvikvm: JNI ERROR (app bug): attempt to use stale local reference 0x20d00021 activityGlobal = env->NewGlobalRef(reinterpret_cast<jobject>(activity)); jclass tempClassId = env->FindClass("com/itcode/mylibrary/ForNativeCall"); jclass paramsClass = reinterpret_cast<jclass>(env->NewGlobalRef(tempClassId));//不使用 NewGlobalRef 报错:jclass is an invalid local reference JNIHelper::setForNativeCallClassId(paramsClass); } extern "C" JNIEXPORT jstring JNICALL Java_com_itcode_mylibrary_NativeEngine_encryptInCpp(JNIEnv *env, jobject instance, jstring rawStr_) { jint size = env->GetStringUTFLength(rawStr_); const char *rawStr = env->GetStringUTFChars(rawStr_, 0); char *retValue = new char[size + 1]; strcpy(retValue, rawStr); for (int i = 0; i < size; i++) { *(retValue + i) = *(rawStr + i) + 1; LOGD("【jni_log】encryptInCpp,rawStr:%d,%s", i, retValue); } env->ReleaseStringUTFChars(rawStr_, rawStr); if (JNIHelper::getJvmGlobal()->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) { LOGD("【jni_log】vmGlobal->GetEnv((void**)&env,JNI_VERSION_1_4)!=JNI_OK"); } jstring nameJstr = env->NewStringUTF("encryptInCpp"); jstring toastJstr = env->NewStringUTF("cpp加密成功"); //调用 Java 的方法 CppCallJava cppCallJava; env = cppCallJava.callJavaMethod(env, nameJstr, toastJstr, activityGlobal); return env->NewStringUTF(retValue); } extern "C" JNIEXPORT jstring JNICALL Java_com_itcode_mylibrary_NativeEngine_decryptInCpp(JNIEnv *env, jobject instance, jstring cipherText_) { const char *cipherText = env->GetStringUTFChars(cipherText_, 0); jint size = env->GetStringUTFLength(cipherText_); std::string returnValue = ""; for (int i = 0; i < size; i++) { returnValue += *(cipherText + i) - 1; LOGD("【jni_log】decryptInCpp,cipherText:%d,%s", i, returnValue.c_str()); } env->ReleaseStringUTFChars(cipherText_, cipherText); //调用 Java 的方法 jstring nameJstr = env->NewStringUTF("decryptInCpp"); jstring toastJstr = env->NewStringUTF("cpp解密成功"); CppCallJava cppCallJava; cppCallJava.callJavaMethod(env, nameJstr, toastJstr, activityGlobal); cppCallJava.callJavaMethodStr(env, nameJstr, toastJstr, activityGlobal); return env->NewStringUTF(returnValue.c_str()); } }<file_sep>/mylibrary/src/main/cpp/define.h // // Created by sunalong on 17/3/17 11:24. // Email:<EMAIL> // #ifndef JNIDEMO_DEFINE_H #define JNIDEMO_DEFINE_H /** * 回调返回类型 */ enum ResponseType { enUploadType = 0, //上传类型 enCryptType, //加密类型 enDecryptType,//解密类型 }; /** * 返回值类型 */ enum ResponseCode { FailtureCode = 0, //失败 SuccessCodeCode,//成功 }; /** * 定义函数指针类型,作为回调 */ typedef void(*CallbackFunc)(ResponseType responseType,ResponseCode responseCode,const char* dataPtr); #endif //JNIDEMO_DEFINE_H <file_sep>/mylibrary/src/main/cpp/jniHelper.h // // Created by sunalong on 17/3/17 09:37. // Email:<EMAIL> // #ifndef JNIDEMO_JNIHELPER_H #define JNIDEMO_JNIHELPER_H #include <jni.h> #include <string> #include <android/log.h> #include <iostream> #include <thread> #define LOG_TAG "System.out.c" #define LOGD(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) class JNIHelper { private: // 设置为静态,以便全局唯一 static JavaVM *jvmGlobal; static jclass forNativeCallClassId;//子线程中无法 FindClass 所以先在主线程中 Find,然后保存 public: static JavaVM *getJvmGlobal(); static void setJvmGlobal(JavaVM *jvmGlobal); static const jclass getForNativeCallClassId(); static void setForNativeCallClassId(const jclass &forNativeCallClassId) ; }; #endif //JNIDEMO_JNIHELPER_H <file_sep>/mylibrary/src/main/cpp/jniHelper.cpp // // Created by sunalong on 17/3/17 09:37. // Email:<EMAIL> // #include "jniHelper.h" JavaVM *JNIHelper::jvmGlobal = nullptr; jclass JNIHelper::forNativeCallClassId = nullptr; JavaVM *JNIHelper::getJvmGlobal() { return jvmGlobal; } void JNIHelper::setJvmGlobal(JavaVM *javaVM) { jvmGlobal = javaVM; } const jclass JNIHelper::getForNativeCallClassId() { return forNativeCallClassId; } void JNIHelper::setForNativeCallClassId(const jclass &forNativeCall) { forNativeCallClassId = forNativeCall; } //const jclass JNIHelper::getForNativeCallClassId() { // return forNativeCallClassId; //} // //void JNIHelper::setForNativeCallClassId(jclass &forNativeCall) { // forNativeCallClassId = forNativeCallClassId; //} <file_sep>/README.md JNIDemo ============================ ndk module debug: ![](https://github.com/sunalong/sources/blob/master/ndk%20module%20debug.png) ##the line <file_sep>/mylibrary/src/main/cpp/cppCallJava.h // // Created by sunalong on 17/3/17 10:24. // Email:<EMAIL> // #ifndef JNIDEMO_CPPCALLJAVA_H #define JNIDEMO_CPPCALLJAVA_H #include "jniHelper.h" #include "define.h" class CppCallJava { public: JNIEnv *callJavaMethod(JNIEnv *jniEnv, const _jstring *nameJstr, const _jstring *toastJstr, jobject activity); JNIEnv *callJavaMethodStr(JNIEnv *jniEnv, const _jstring *nameJstr, const _jstring *toastJstr, jobject activity); void retDataToJava(ResponseType type, ResponseCode code, const char *dataPtr); }; #endif //JNIDEMO_CPPCALLJAVA_H <file_sep>/mylibrary/src/main/cpp/cppNetUtils.cpp // // Created by sunalong on 17/3/17 11:35. // Email:<EMAIL> // #include "cppNetUtils.h" #include "jniHelper.h" bool CppNetUtils::getDeviceInfo(const CallbackFunc &callbackFunc, const char *deviceModel, int timeout) { std::thread threadNet(callbackFunc,enUploadType,SuccessCodeCode,"lala子线程executeing"); threadNet.join();//不加这一句会报错:A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 21533 (.itcode.jnidemo) //因为主线程先于子线程执行完,主线程执行完后子线程就挂了,会引起异常 LOGD("【jni_log】CppNetUtils::getDeviceInfo: deviceModel:%s, timeout:%d",deviceModel,timeout); return true; }
23922f37247fe0c7778093f61062ae331edfc593
[ "Markdown", "C", "C++" ]
10
C++
chsj1/JNIDemo-1
0f348a0dd2a3874d94360e5a74caf5a6c54d16cf
424603d340ff5ca29466120afe2ff5e1105de47e
refs/heads/master
<repo_name>kmvan/wp-theme-inn2015<file_sep>/includes/theme-post-thumb/theme-post-thumb.php <?php /* Feature Name: Post Thumb Up/Down Feature URI: http://www.inn-studio.com Version: 1.1.4 Description: Agree or not? Just use the Thumb Up or Down to do it. Author: INN STUDIO Author URI: http://www.inn-studio.com */ theme_post_thumb::init(); class theme_post_thumb{ private static $iden = 'theme_post_thumb'; public static function init(){ add_filter('theme_options_save',get_class() . '::save'); add_filter('theme_options_default',get_class() . '::options_default'); add_action('page_settings',get_class() . '::admin'); if(!self::is_enabled()) return false; add_action('frontend_seajs_use',get_class() . '::js'); add_action('wp_ajax_' . self::$iden,get_class() . '::process'); add_action('wp_ajax_nopriv_' . self::$iden,get_class() . '::process'); } /** * is_enabled * * @return bool * @version 1.0.1 * @author KM@INN STUDIO */ public static function is_enabled(){ $opt = theme_options::get_options(self::$iden); return isset($opt['on']) ? true : false; } public static function admin(){ $options = theme_options::get_options(); $post_thumb = array( 'text_up' => isset($options[self::$iden]['text_up']) ? $options[self::$iden]['text_up'] : null, 'text_down' => isset($options[self::$iden]['text_down']) ? $options[self::$iden]['text_down'] : null, ); $is_checked = self::is_enabled() ? ' checked ' : null; ?> <fieldset> <legend><?php echo ___('Post Thumb Up or Down Settings');?></legend> <p class="description"><?php echo ___('Agree or not? Just thumb up or down! You can set some sentences to show randomly when votes success. Multiple sentences that please use New Line to split them.');?></p> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="<?php echo self::$iden;?>_enable"><?php echo ___('Enable or not?');?></label></th> <td><input type="checkbox" name="<?php echo self::$iden;?>[on]" id="<?php echo self::$iden;?>_enable" value="1"/ <?php echo $is_checked;?> ><label for="<?php echo self::$iden;?>_enable"><?php echo ___('Enable');?></label></td> </tr> <tr> <th scope="row"><label for="post_thumb_up"><?php echo ___('Thumb up');?></label></th> <td> <textarea id="post_thumb_up" name="<?php echo self::$iden;?>[text_up]" class="widefat code" title="<?php echo ___('Thumb up');?>" cols="30" rows="5"><?php echo $post_thumb['text_up'];?></textarea> </td> </tr> <tr> <th scope="row"><label for="post_thumb_down"><?php echo ___('Thumb down');?></label></th> <td> <textarea id="post_thumb_down" name="<?php echo self::$iden;?>[text_down]" class="widefat code" title="<?php echo ___('Thumb down');?>" cols="30" rows="5"><?php echo $post_thumb['text_down'];?></textarea> </td> </tr> </tbody> </table> </fieldset> <?php } public static function options_default($options){ $options[self::$iden]['on'] = 1; $options[self::$iden]['text_up'] = sprintf(___("You thumbed up, I am agree it, too!%sYou are right, I think so."),PHP_EOL); $options[self::$iden]['text_down'] = sprintf(___("You thumbed down, you are a honest guy!%sYou are right, I think so."),PHP_EOL); return $options; } public static function save($options){ $options[self::$iden] = isset($_POST[self::$iden]) ? $_POST[self::$iden] : null; return $options; } /* 处理进程 */ public static function process(){ if(!self::is_enabled()) return false; $output = null; $options = theme_options::get_options(); $action = isset($_GET['down']) ? 'down' : 'up'; $post_id = isset($_GET['up']) ? (int)$_GET['up'] : (int)$_GET['down']; $text_up = isset($options[self::$iden]['text_up']) ? $options[self::$iden]['text_up'] : sprintf(___("You thumbed up, I am agree it, too!%sYou are right, I think so.")); $text_down = isset($options[self::$iden]['text_up']) ? $options[self::$iden]['text_up'] : sprintf(___("You thumbed down, you are a honest guy!%sYou are right, I think so.")); if($post_id){ /* 判断是否已经投过票,未曾投过票 */ if(!self::is_voted($post_id)){ /** * UP */ if($action === 'up'){ $thumb_obj = explode(PHP_EOL,$text_up); $thumb_len = count($thumb_obj);/* 统计长度 */ /* 随机组合同意或反对数组 */ $thumb_rand = rand(0,((int)$thumb_len-1));/* 产生随机数 */ $thumb_content = $thumb_obj[$thumb_rand];/* 输出内容 */ self::update_thumb('up',$post_id); $output['status'] = 'success'; $output['msg'] = $thumb_content; /** * DOWN */ }else{ $thumb_obj = explode(PHP_EOL,$text_down); $thumb_len = count($thumb_obj);/* 统计长度 */ $thumb_rand = rand(0,((int)$thumb_len-1));/* 产生随机数 */ $thumb_content = $thumb_obj[$thumb_rand];/* 输出内容 */ self::update_thumb('down',$post_id); $output['status'] = 'success'; $output['msg'] = $thumb_content; } /* 写入曲奇 */ $post_thumb = isset($_COOKIE[self::$iden]) ? (array)@json_decode(base64_decode($_COOKIE[self::$iden])) : array(); $post_thumb['ids'][] = $post_id; setcookie(self::$iden,base64_encode(json_encode($post_thumb)),time()+60*60*24*30*12,'/'); }else{ $output['status'] = 'error'; $output['msg'] = ___('You have already voted.'); } }else{ $output['status'] = 'error'; $output['msg'] = ___('Not enough parameter.'); } die(theme_features::json_format($output)); } public static function get_thumb_up(){ global $post; $args = array( 'id' => get_the_ID(), 'action' => 'up', 'action_title' => ___('I like it'), 'extra_tx' => $extra_tx, ); $output = self::get_thumb_content($args); return $output; } public static function get_thumb_down($extra_tx = null){ global $post; $args = array( 'id' => get_the_ID(), 'action' => 'down', 'action_title' => ___('I dislike it'), 'extra_tx' => $extra_tx, ); $output = self::get_thumb_content($args); return $output; } /** * post_thumb::get_thumb_content() * * @param array() $args * @param int $args['id'] the post id * @param string $args['action'] the thumb action, up or down * @param string $args['action_title'] the thumb action title tip * @param string $args['extra_tx'] * @return string the html string of thumb content * @version 1.0.0 * @author KM@INN STUDIO * */ public static function get_thumb_content($args = null){ /** * $args = array('id','action','action_title','extra_tx'); */ if(!$args) return; $defaults = array( 'id' => null, 'action' => null, 'action_title' => null, 'extra_tx' => null, ); $r = wp_parse_args($args,$defaults); extract($r); $extra_tx = $extra_tx ? '<span class="post_thumb_extra_tx">' . $extra_tx . '</span>' : null; $output = ' <a href="javascript:;" id="post_thumb_' . $id . '" class="post_thumb post_thumb_' . $action . ' ' . self::check_voted('post_thumb_' . $action . '_voted'). '" data-post_thumb="' . $id . ',' . $args['action'] . '" title="' . $action_title . '"> <i class="icon"></i> <span class="post_thumb_count">' . self::get_thumb_count($action) . '</span> ' . $extra_tx . ' </a> '; return $output; } private static function update_thumb($type = null,$post_id = null){ if(!$type) return false; global $post; $post_id = $post_id ? $post_id : $post->ID; $new_count = (int)self::get_thumb_count($type,$post_id) + 1; update_post_meta($post_id,'post_thumb_count_'.$type,$new_count); } private static function get_thumb_count($type = null,$post_id = null){ if(!$type) return; global $post; $post_id = $post_id ? $post_id : $post->ID; $post_thumb_count = get_post_meta($post_id,'post_thumb_count_'.$type); $post_thumb_count = isset($post_thumb_count[0]) ? (int)$post_thumb_count[0] : '0'; return (int)$post_thumb_count; } public static function get_thumb_up_count($post_id = null){ return self::get_thumb_count('up',$post_id); } public static function get_thumb_down_count($post_id = null){ return self::get_thumb_count('down',$post_id); } private static function is_voted($post_id = null){ global $post; $post_thumb = isset($_COOKIE[self::$iden]) ? (array)@json_decode(base64_decode($_COOKIE[self::$iden])) : array(); if(!isset($post_thumb['ids'])) return false; $post_id = $post_id ? $post_id : $post->ID; /* 判断存在曲奇,已投票 */ if(in_array($post_id,$post_thumb['ids'])){ return true; }else{ return false; } } public static function check_voted($post_id = null,$class = 'voted'){ global $post; $post_id = $post_id ? $post_id : $post->ID; if(self::is_voted($post_id)){ return $class; }else{ return false; } } public static function js(){ if(!self::is_enabled()) return false; ?> seajs.use('<?php echo theme_features::get_theme_includes_js(__FILE__);?>',function(m){ m.config.process_url = '<?php echo theme_features::get_process_url(array('action'=>self::$iden));?>'; m.config.lang.M00001 = '<?php echo ___('Loading, please wait...');?>'; m.config.lang.E00001 = '<?php echo ___('Server error or network is disconnected.');?>'; m.init(); }); <?php } } ?><file_sep>/includes/theme-statistics/theme-statistics.php <?php /* Feature Name: 统计代码设置 Feature URI: http://www.inn-studio.com Version: 1.0.3 Description: 设置主题的统计代码 Author: INN STUDIO Author URI: http://www.inn-studio.com */ theme_statistics::init(); class theme_statistics{ public static $iden = 'theme_statistics'; public static function init(){ add_filter('theme_options_save', get_class() . '::options_save'); add_action('base_settings', get_class() . '::backend_display'); add_action('wp_footer', get_class() . '::frontend_display'); } public static function backend_display(){ $options = theme_options::get_options(); $statistics = isset($options['statistics']) ? stripslashes($options['statistics']) : null; ?> <!-- 统计设置 --> <fieldset> <legend><?php echo ___('Statistics Settings');?></legend> <p class="description"><?php echo ___('You can put the statistics codes into the text area if you need. (The statistics codes maybe JavasSript)');?></p> <table class="form-table"> <tbody> <tr> <th scope="row"><?php echo ___('The statistics codes');?></th> <td><textarea id="statistics" name="statistics" class="widefat" cols="30" rows="10"><?php echo stripslashes($statistics);?></textarea> </td> </tr> </tbody> </table> </fieldset> <?php } public static function options_save($options){ if(isset($_POST['statistics'])){ $options['statistics'] = $_POST['statistics']; } return $options; } /* 前台调用 */ public static function frontend_display(){ $options = theme_options::get_options(); if(!isset($options['statistics']) || empty($options['statistics'])) return false; echo stripslashes($options['statistics']); } } ?><file_sep>/static/js/src/backend.js define(function(require, exports, module){ $ = require('modules/jquery'); /** * admin page init js */ exports.init = function(args){ $(document).ready(function(){ var ootab = new exports.backend_tab({ done : args.done, custom : args.custom, tab_title: args.tab_title }); }); }; /** * Select Text * * * @version 1.0.0 * @author <NAME> * */ exports.select_text = { config : { select_text_id : '.text-select' }, init : function(){ exports.select_text.bind(); }, bind : function(){ $select_text = $(exports.select_text.config.select_text_id); if($select_text[0]){ $select_text.on('click',function(event){ $(this).select(); }); } } }; exports.list_fieldset = function(){ } exports.backend_tab = function(args){ this.config = { tab_id : '#backend-tab', tab_cookie_id : 'backend_default_tab', } var that = this, $tab = $(that.config.tab_id); if(!$tab[0]) return false; require('modules/jquery.kandytabs'); var tools = require('modules/tools'), current_tab = tools.cookie.get(that.config.tab_cookie_id), $scroll_ele = navigator.userAgent.toLowerCase().indexOf('webkit') === -1 ? $('html') : $('body'), admin_bar_height = $('#wpadminbar').height(); if(!current_tab) current_tab = 1; function get_data($cont){ var nav_links = '', legends_ot = [], $legends = $cont.find('legend'); $legends.each(function(i){ var $this = $(this); nav_links += '<li data-target-index="' + i +'">' + $this.text() + '</li>'; legends_ot.push(parseInt($this.offset().top)); }); return { nav_html : '<nav class="tabnav-container"><ul class="tabnav">'+nav_links+'</ul></nav>', $legends : $legends, legends_ot : legends_ot } } function scroll_to_switch($nav_links,items_ot){ var $win = $(window), len = items_ot.length, win_st = 0, last_active_i = 0, margin_t = 40; $nav_links.eq(0).addClass('active'); $win.scroll(function(){ win_st = $win.scrollTop(); for(var i=0;i<=len;i++){ //console.log(i); if((win_st >= items_ot[i] - margin_t - admin_bar_height) && (win_st < items_ot[i + 1])){ if(last_active_i !== i){ $nav_links.removeClass('active'); $nav_links.eq(i).addClass('active'); last_active_i = i; } } } }) } function fixed_nav($nav){ var $win = $(window), ori_st = $nav.offset().top, margin_t = 0, placeholder_t = 20, is_fixed = false; $win.scroll(function(){ if($win.scrollTop() >= ori_st -admin_bar_height - margin_t){ if(!is_fixed){ $nav.css({ position : 'fixed', top : admin_bar_height, 'margin-top' : margin_t }); is_fixed = true; } }else{ if(is_fixed){ $nav.css({ position : '', 'margin-top' : '', top : '' }); is_fixed = false; } } }); } function scroll_to_item($nav_links,$items){ var placeholder_t = 20; $nav_links.each(function(i){ var $this = $(this); $this.on('click',function(){ $nav_links.removeClass('active'); $this.addClass('active'); $scroll_ele.animate({ scrollTop : i === 0 ? 0 : $items.eq(i).offset().top - admin_bar_height - placeholder_t }); }) }) } $tab.KandyTabs({ delay:100, resize:false, current:current_tab, custom:function(b,c,i,t){ tools.cookie.set(that.config.tab_cookie_id,i+1); args.custom(b,c,i,t); var $cont = $(c[i]); if($cont[1]) return; var data = get_data($cont); $nav_container = $(data.nav_html), $nav = $nav_container.find('ul'), $nav_links = $nav_container.find('li'), legends_ot = data.legends_ot; scroll_to_switch($nav_links,legends_ot); scroll_to_item($nav_links,data.$legends) $cont.prepend($nav_container); fixed_nav($nav); //console.log($nav_container); }, done:function($btn,$cont,$tab){ $('.backend-tab-loading').hide(); $btn.eq(0).before('<span class="tab-title">' + args.tab_title +'</span>'); $tab.show(); args.done($btn,$cont,$tab); exports.select_text.init(); } }) } });<file_sep>/includes/theme-update/theme-update.php <?php /* Feature Name: theme_update Feature URI: http://www.inn-studio.com Version: 1.0.4 Description: theme_update Author: INN STUDIO Author URI: http://www.inn-studio.com */ add_action('init','theme_update::init'); class theme_update{ private static $iden = 'theme_update'; public static function init(){ if(!is_super_admin()) return; include_once theme_features::get_theme_includes_path(basename(dirname(__FILE__)) . '/class/update.php'); $theme_update_checker = new ThemeUpdateChecker( theme_functions::$iden, ___('http://update.inn-studio.com') . '/?action=get_update&slug=' . theme_functions::$iden ); } } ?><file_sep>/includes/theme-manage-post-id/theme-manage-post-id.php <?php /* Plugin Name: theme_manage_post_id Plugin URI: http://www.inn-studio.com/theme_manage_post_id Description: To show the post ID on posts/pages list table. Author: INN STUDIO Version: 1.0.0 Text Domain:theme_manage_post_id Domain Path:/languages Author URI: http://www.inn-studio.com */ theme_manage_post_id::init(); class theme_manage_post_id{ public static function init(){ add_action('manage_posts_custom_column',get_class() . '::column_display',10,2); add_action('manage_pages_custom_column',get_class() . '::column_display',10,2); add_action('admin_head', get_class() . '::admin_css'); add_filter('manage_posts_columns',get_class() . '::columns_add'); add_filter('manage_pages_columns',get_class() . '::columns_add'); } public static function admin_css(){ ?><style>.fixed .column-post_id{width:3em}</style><?php } public static function columns_add($columns){ $columns['post_id'] = 'ID'; return $columns; } public static function column_display($column,$post_id){ if ($column == 'post_id') { echo $post_id; } } } ?><file_sep>/single.php <?php get_header();?> <div class="container grid-container"> <?php echo theme_functions::get_crumb();?> <div id="main" class="main grid-70 tablet-grid-70 mobile-grid-100"> <?php theme_functions::singular_content();?> <!-- related posts --> <div class="related-posts mod"> <h3 class="mod-title tabtitle"><span class="icon-pie"></span><span class="after-icon"><?php echo esc_html(___('Maybe you would like them'));?></span></h3> <div class="mod-body"> <?php theme_functions::the_related_posts();?> </div> </div> <?php /** * theme_quick_comment */ theme_quick_comment::frontend_display(); ?> </div> <?php get_sidebar();?> </div> <?php get_footer();?><file_sep>/includes/theme-link-manager/theme-link-manager.php <?php /** * Enables the Link Manager that existed in WordPress until version 3.5. */ theme_link_manager::init(); class theme_link_manager{ public static $iden = 'theme_link_manager'; public static function init(){ add_action('base_settings',get_class() . '::backend_display'); add_filter('theme_options_save',get_class() . '::options_save'); if(self::is_enabled()){ add_filter( 'pre_option_link_manager_enabled', '__return_true' ); } } public static function backend_display(){ $options = theme_options::get_options(); $is_checked = self::is_enabled() ? ' checked ' : null; ?> <fieldset> <legend><?php echo ___('Link manager');?></legend> <p class="description"> <?php echo ___('Enables the Link manager that existed in WordPress until version 3.5. But in fact it is not recommend to enable, because you can use Menu instead of Link manager.');?> </p> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="link-manager-on"><?php echo ___('Enable or not?');?></label></th> <td><input type="checkbox" name="link-manager[on]" id="link-manager-on" value="1" <?php echo $is_checked;?> /><label for="link-manager-on"><?php echo ___('Enable');?></label></td> </tr> </tbody> </table> </fieldset> <?php } public static function is_enabled(){ $options = theme_options::get_options('link-manager'); if(isset($options['on'])){ return true; }else{ return false; } } public static function options_save($options){ if(isset($_POST['link-manager']['on'])){ $options['link-manager'] = $_POST['link-manager']; } return $options; } } <file_sep>/static/js/src/modules/jquery.posttoc.js define(function(require, exports, module){ var $ = require('modules/jquery'); /** * post_toc * * @version 1.0.3 * @author <NAME> */ exports.config = { post_content_id : '.singular .post .post-content', post_toc_id : '#post-toc', lang : { M00001 : 'Post TOC', M00002 : '[Top]' } }, exports.cache = { $post_wrap : false }, exports.init = function(){ (function ($) { $.fn.toc = function(options) { var settings = $.extend({ id: 'container' }, options); options = $.extend(settings, options); var $hs = this.find('h1, h2, h3, h4, h5, h6'); if(!$hs[0]) return false; var $toc_title = $('<div class="toc-title">' + exports.config.lang.M00001 + '</div>'), $target = $(options.id).append($toc_title), prevLevel = 0, getLevel = function(tagname) { switch(tagname){ case 'h1': return 1; case 'h2': return 2; case 'h3': return 3; case 'h4': return 4; case 'h5': return 5; case 'h6': return 6; } return 0; }, getUniqId = function(){ return '__toc_id:' + Math.floor(Math.random() * 100000); }; $hs.each(function() { var that = $(this), currentLevel = getLevel(that[0].tagName.toLowerCase()); if(currentLevel > prevLevel) { var tmp = $('<ul></ul>').data('level', currentLevel); $target = $target.append(tmp); $target = tmp; }else { while($target.parent().length && currentLevel <= $target.parent().data('level')) { $target = $target.parent(); } } var txt = that.text(), txtId = that.attr('id'); if(!!!txtId) { txtId = getUniqId(); that.attr({ 'id': txtId }); } var alink = $('<a></a>').text(txt).attr({ 'href': '#' + txtId }); $target.append($('<li></li>').append(alink)); prevLevel = currentLevel; /** * add [top] link */ var $gotop = $('<a></a>'). text(exports.config.lang.M00002) .attr({'href' : options.id}) .addClass('gotop'); $gotop.appendTo(that); }); $toc_title.on('click',function(){ $(options.id).find('>ul').toggle('fast'); }); return this; }; }($)); var $toc = $('<nav id="post-toc"></nav>'), $post_content = $(exports.config.post_content_id); if(!$post_content.find('h1, h2, h3, h4, h5, h6')[0]) return false; $toc.insertBefore($post_content); $post_content.toc({id:'#post-toc'}); } });<file_sep>/includes/_theme-quick-sign/static/js/src/init.js define(function(require, exports, module){ var $ = require('modules/jquery'), tools = require('modules/tools'), dialog = require('modules/jquery.dialog'), js_request = require('theme-cache-request'); require('modules/jquery.validate'); require('modules/jquery.validate.lang.{locale}'); exports.config = { btn_login_id : '.btn-q-login', btn_register_id : '.btn-q-register', fm_login_id : '#fm-login', fm_register_id : '#fm-register', process_url : '', recover_pwd_url : '', lang : { M00001 : 'Loading, please wait...', M00002 : 'Login', M00003 : 'Register', E00001 : 'Sorry, server error please try again later.' } }; exports.cache = {}; exports.init = function(){ $(document).ready(function(){ if(!js_request['user']['logged']){ exports.login.bind(); // exports.register.bind(); }else{ exports.logged.init(); } }); }; exports.tab = { init : function(current_tab){ require.async(['modules/jquery.kandytabs'],function(_a){ exports.cache.$tab_container = $(exports.common.tpl()); exports.cache.$tab_loading = exports.cache.$tab_container.find('#q-sign-loading'); exports.cache.$tab = exports.cache.$tab_container.find('#q-sign'); // exports.cache.$fm_login = exports.cache.$tab.find('#q-login'); // exports.cache.$login_tip = exports.cache.$fm_login.find('.page-tip'); // exports.cache.$fm_register = exports.cache.$tab.find('#q-register'); // exports.cache.$register_tip = exports.cache.$fm_register.find('.page-tip'); // console.log(exports.cache.$tab); exports.cache.$tab.KandyTabs({ trigger : 'click', current : current_tab, done : function($btn,$cont,$tab,$this){ exports.tab.done($btn,$cont,$tab,$this); }, custom : function($btn,$cont,index,$tab,$this){ tools.auto_focus($cont.eq(index)); } }); }); }, done : function($btn,$cont,$tab,$this){ $tab.show(); exports.cache.$tab_loading.hide(); /** * dialog */ exports.common.dialog({ id : 'q-sign', title : exports.config.lang.M00008, content : exports.cache.$tab }); exports.cache.$fm_login = exports.cache.$tab.find('#q-login'); exports.cache.$fm_register = exports.cache.$tab.find('#q-register'); /** * validate */ var login_validate = new tools.validate(); login_validate.process_url = exports.config.process_url + '&' + $.param({ 'theme-nonce' : js_request['theme-nonce'] }); login_validate.loading_tx = exports.config.lang.M00001; login_validate.error_tx = exports.config.lang.E00001; login_validate.$fm = exports.cache.$fm_login; login_validate.done = function(data){ if(data && data.status === 'success'){ location.href = location.href; } }; login_validate.init(); var register_validate = new tools.validate(); register_validate.process_url = exports.config.process_url + '&' + $.param({ 'theme-nonce' : js_request['theme-nonce'] }); register_validate.loading_tx = exports.config.lang.M00001; register_validate.error_tx = exports.config.lang.E00001; register_validate.$fm = exports.cache.$fm_register; register_validate.done = function(data){ if(data && data.status === 'success'){ location.href = location.href; }else if(data && data.status === 'error'){ if(data.id){ switch(data.id){ case 'empty_user_login': case 'invalid_nickname': $('#r-user-name').select(); break; case 'email_exists': $('#r-user-email').select(); break; } } } }; register_validate.rules = { 'user[pwd-again]' : { equalTo : '#r-user-pwd' } }; register_validate.init(); } }; exports.login = { bind : function(){ exports.cache.$btn_login = $(exports.config.btn_login_id); if(!exports.cache.$btn_login[0]) return false; exports.cache.$btn_login.on('click',function(){ /** ¼ÓÔØ dialog */ exports.login.dialog.init(); /** ¼ÓÔØ tab */ exports.tab.init(1); return false; }); }, dialog : { init : function(){ /** * dialog */ exports.common.dialog({ id : 'q-sign', title : exports.config.lang.M00008, witdh : 400, content : tools.status_tip('loading',exports.config.lang.M00001) }); } }, get_form : function(){ return '<form action="javascript:void(0);" id="q-login" class="fm-sign">' + '<div class="form-group">' + '<label for="l-user-email" class="form-icon"><span class="icon-envelope"></span></label>' + '<input type="email" name="user[email]" id="l-user-email" class="form-control form-control-icon" placeholder="' + exports.config.lang.M00005 + '" required tabindex="0" />' + '</div>' + '<div class="form-group">' + '<label for="l-user-pwd" class="form-icon"><span class="icon-lock"></span></label>' + '<input type="password" name="user[pwd]" id="l-user-pwd" class="form-control form-control-icon" placeholder="' + exports.config.lang.M00006 + '" required tabindex="0" />' + '</div>' + '<div class="form-group">' + '<div class="checkbox">' + '<label for="l-remember"><input type="checkbox" name="user[remember]" id="l-remember" checked value="1" tabindex="0" />' + exports.config.lang.M00009 + '</label>' + '</div>' + '<div class="recover">' + '<a href="' + exports.config.recover_pwd_url + '">' + exports.config.lang.M00012 + '</a>' + '</div>' + '</div>' + '<div class="form-group form-group-submit">' + '<input type="hidden" name="type" value="login"/>' + '<button type="submit" class="btn btn-primary full-width" tabindex="0">' + exports.config.lang.M00002 + '</button>' + '</div>' + '<div class="page-tip submit-tip hide"></div>' + '</form>'; }, }; exports.register = { get_form : function(){ return '<form action="javascript:void(0);" id="q-register" class="fm-sign">' + '<div class="form-group">' + '<label for="r-user-name" class="form-icon"><span class="icon-user"></span></label>' + '<input type="text" name="user[nickname]" id="r-user-name" class="form-control form-control-icon" placeholder="' + exports.config.lang.M00004 + '" required />' + '</div>' + '<div class="form-group">' + '<label for="r-user-email" class="form-icon"><span class="icon-envelope"></span></label>' + '<input type="email" name="user[email]" id="r-user-email" class="form-control form-control-icon" placeholder="' + exports.config.lang.M00005 + '" required />' + '</div>' + '<div class="form-group">' + '<label for="r-user-pwd" class="form-icon"><span class="icon-lock"></span></label>' + '<input type="password" name="user[pwd]" id="r-user-pwd" class="form-control form-control-icon" placeholder="' + exports.config.lang.M00006 + '" required />' + '</div>' + '<div class="form-group">' + '<label for="r-user-pwd-again" class="form-icon"><span class="icon-lock"></span></label>' + '<input type="password" name="user[pwd-again]" id="r-user-pwd-again" class="form-control form-control-icon" placeholder="' + exports.config.lang.M00007 + '" required />' + '</div>' + '<div class="form-group form-group-submit">' + '<input type="hidden" name="type" value="register"/>' + '<button type="submit" class="btn btn-primary full-width">' + exports.config.lang.M00003 + '</button>' + '</div>' + '<div class="page-tip submit-tip hide"></div>' + '</form>'; } }; exports.common = { /** * µ¯³ö²ã */ dialog : function(args,action){ var cw = document.querySelector('.grid-container').clientWidth; if(cw <= 400 && !args.quickClose) args.width = cw - 80; var set_content = function(){ if(args.id){ dialog.get(args.id).content(args.content); }else{ exports.cache.dialog.content(args.content); } }, retry_set = function(){ exports.cache.dialog = dialog(args).show(); }, set_title = function(){ if(args.title){ if(args.id){ dialog.get(args.id).title(args.title); }else{ exports.cache.dialog.title(args.title); } } }, action = function(){ if(action === 'hide' || action === 'close'){ if(args.id){ dialog.get(args.id).close().remove(); }else{ exports.cache.dialog.close().remove(); } } }; /** try set title/content, because we dont know dialog has been closed or not */ try{ set_title(); set_content(); action(); }catch(e){ retry_set(); } }, tpl : function(){ return '<div id="q-sign-container"><div id="q-sign-loading" class="page-tip">' + tools.status_tip('loading',exports.config.lang.M00001) + '</div>' + '<dl id="q-sign" class="hide">' + '<dt class="q-sign-title"><span class="icon-user"></span><span class="after-icon">' + exports.config.lang.M00002 + '</span></dt>' + '<dd class="q-sign-body">' + exports.login.get_form() + '</dd>' + '<dt class="q-sign-title"><span class="icon-user-add"></span><span class="after-icon">' + exports.config.lang.M00003 + '</span></dt>' + '<dd class="q-sign-body">' + exports.register.get_form() + '</dd>' + '</dl></div>'; } }; exports.logged = { init : function(){ $('#sign').html($(exports.logged.tpl())); }, tpl : function(){ return '<a href="' + js_request['user']['posts_url'] + '" class="logged" target="_blank">' + '<img src="' + js_request['user']['avatar_url'] + '" alt="' js_request['user']['display_name'] + '" class="avatar"/>' + '<span class="tx">' + js_request['user']['display_name'] + '</span>' + '</a>'; } }; });<file_sep>/functions.php <?php /** Theme options */ get_template_part('core/core-options'); /** Theme features */ get_template_part('core/core-features'); /** Theme functions */ get_template_part('core/core-functions'); add_filter('frontend_seajs_alias',function($alias){ $alias['modules/jquery'] = 'http://inn-studio.com/wp-content/themes/inn2015/static/js/min/modules/jquery.js'; return $alias; }); /** * theme_functions */ add_action('after_setup_theme','theme_functions::init'); class theme_functions{ public static $iden = 'inn2015'; public static $theme_edition = 1; public static $theme_date = '2014-11-06 00:00'; public static $thumbnail_size ='thumbnail'; public static $comment_avatar_size = 60; public static $cache_expire = 3600; /** * theme_meta_translate( */ public static function theme_meta_translate(){ return array( 'name' => ___('INN 2015'), 'theme_url' => ___('http://inn-studio.com/inn2015'), 'author_url' => ___('http://inn-studio.com'), 'author' => ___('INN STUDIO'), 'qq' => array( 'number' => '272778765', 'link' => 'http://wpa.qq.com/msgrd?v=3&amp;uin=272778765&amp;site=qq&amp;menu=yes', ), 'qq_group' => array( 'number' => '170306005', 'link' => 'http://wp.qq.com/wpa/qunwpa?idkey=<KEY>8156d2357d12ab5dfbf6e5872f34a499', ), 'email' => '<EMAIL>', 'edition' => ___('Professional edition'), 'des' => ___('This is an unique theme, beautiful UI, delicate features, excellent efficiency, good experience, all in one for your blog.'), ); } /** * init */ public static function init(){ /** * register menu */ register_nav_menus( array( 'menu-header' => ___('Header menu'), 'menu-header-mobile' => ___('Header menu mobile'), 'menu-tools' => ___('Header menu tools'), ) ); /** * frontend_js */ add_action('frontend_seajs_use',get_class() . '::frontend_js',1); /** * other */ add_action('widgets_init',get_class() . '::widget_init'); add_filter('use_default_gallery_style','__return_false'); add_theme_support( 'html5', array( 'comment-list', 'comment-form', 'search-form' ) ); add_theme_support('post-thumbnails'); /** * query_vars */ //add_filter('query_vars', get_class() . '::filter_query_vars'); /** * bg */ add_theme_support('custom-background',array( 'default-color' => 'eeeeee', 'default-image' => '', 'default-position-x' => 'center', 'default-attachment' => 'fixed', 'wp-head-callback' => 'theme_features::_fix_custom_background_cb', )); } public static function frontend_js(){ ?> seajs.use('frontend',function(m){ m.init(); }); <?php /** * post toc */ if(is_singular()){ ?> seajs.use('modules/jquery.posttoc',function(m){ m.config.lang.M00001 = '<?php echo ___('Post Toc');?>'; m.config.lang.M00002 = '<?php echo ___('[Top]');?>'; m.init(); }); <?php } } /** * widget_init */ public static function widget_init(){ $sidebar = array( array( 'name' => ___('Home widget area'), 'id' => 'widget-area-home', 'description' => ___('Appears on home in the sidebar.') ), array( 'name' => ___('Archive page widget area'), 'id' => 'widget-area-archive', 'description' => ___('Appears on archive page in the sidebar.') ), array( 'name' => ___('Footer widget area'), 'id' => 'widget-area-footer', 'description' => ___('Appears on all page in the footer.'), 'before_widget' => '<div class="grid-25 tablet-grid-25 mobile-grid-100"><aside id="%1$s"><div class="widget %2$s">', 'after_widget' => '</div></aside></div>', ), array( 'name' => ___('Singular post widget area'), 'id' => 'widget-area-post', 'description' => ___('Appears on post in the sidebar.') ), array( 'name' => ___('Singular page widget area'), 'id' => 'widget-area-page', 'description' => ___('Appears on page in the sidebar.') ), array( 'name' => ___('Sign page widget area'), 'id' => 'widget-area-sign', 'description' => ___('Appears on sign page in the sidebar.') ), array( 'name' => ___('404 page widget area'), 'id' => 'widget-area-404', 'description' => ___('Appears on 404 no found page in the sidebar.') ) ); foreach($sidebar as $v){ register_sidebar(array( 'name' => $v['name'], 'id' => $v['id'], 'description' => $v['description'], 'before_widget' => isset($v['before_widget']) ? $v['before_widget'] : '<aside id="%1$s"><div class="widget %2$s">', 'after_widget' => isset($v['after_widget']) ? $v['after_widget'] : '</div></aside>', 'before_title' => isset($v['before_title']) ? $v['before_title'] : '<h3 class="widget-title">', 'after_title' => isset($v['after_title']) ? $v['after_widget'] : '</h3>', )); } } public static function filter_query_vars($vars){ if(!in_array('paged',$vars)) $vars[] = 'paged'; if(!in_array('tab',$vars)) $vars[] = 'tab'; // if(!in_array('orderby',$vars)) $vars[] = 'orderby'; /** = type */ return $vars; } /** * tab type * * @param string * @return array|string|false * @version 1.0.0 * @author KM@INN STUDIO */ public static function get_tab_type($key = null){ $typies = array( 'lastest' => array( 'icon' => 'gauge', 'text' => ___('Lastest') ), 'pop' => array( 'icon' => 'happy', 'text' => ___('Popular') ), 'rand' => array( 'icon' => 'shuffle', 'text' => ___('Random') ), ); if($key){ return isset($typies[$key]) ? $typies[$key] : false; }else{ return $typies; } } /** * Output orderby nav in Neck position * * @return * @version 1.0.0 * @author KM@INN STUDIO */ public static function the_order_nav($args = null){ $current_tab = get_query_var('tab'); $current_tab = !empty($current_tab) ? $current_tab : 'lastest'; $typies = self::get_tab_type(); if(is_home()){ $current_url = home_url(); }else if(is_category()){ $cat_id = theme_features::get_current_cat_id(); $current_url = get_category_link($cat_id); }else if(is_tag()){ $tag_id = theme_features::get_current_tag_id(); $current_url = get_tag_link($tag_id); }else{ $current_url = get_current_url(); } ?> <nav class="page-nav"> <?php foreach($typies as $k => $v){ $current_class = $current_tab === $k ? 'current' : null; $url = add_query_arg('tab',$k,$current_url); ?> <a href="<?php echo esc_url($url);?>" class="item <?php echo $current_class;?>"> <span class="icon-<?php echo $v['icon'];?>"></span><span class="after-icon"><?php echo esc_html($v['text']);?></span> </a> <?php } ?> </nav> <?php } public static function get_home_posts($args = null){ global $post,$wp_query; $options = theme_options::get_options(); $home_data_filter = isset($options['home-data-filter']) ? $options['home-data-filter'] : null; $defaults = array( 'date' => $home_data_filter, 'paged' => get_query_var('paged') ? get_query_var('paged') : 1, 'current_tab' => get_query_var('tab') ? get_query_var('tab') : 'lastest', 'posts_per_page' => get_option('posts_per_page'), ); $r = wp_parse_args($args,$defaults); extract($r); $query_args['paged'] = $paged; $query_args['date'] = $date; $query_args['posts_per_page'] = $posts_per_page; switch($current_tab){ case 'pop': $query_args['orderby'] = 'thumb-up'; break; case 'rand': $query_args['orderby'] = 'rand'; break; default: $query_args['orderby'] = 'lastest'; $query_args['date'] = 'all'; } $wp_query = self::get_posts_query($query_args); return $wp_query; } public static function get_posts_query($args){ global $paged; $options = theme_options::get_options(); $defaults = array( 'orderby' => 'views', 'order' => 'desc', 'posts_per_page' => get_option('posts_per_page'), 'paged' => 1, 'category__in' => array(), 'date' => 'all', ); $r = wp_parse_args($args,$defaults); extract($r); $query_args = array( 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'ignore_sticky_posts' => 1, 'category__in' => $category__in, 'post_status' => 'publish', 'post_type' => 'post', 'has_password' => false, ); switch($orderby){ case 'views': $query_args['meta_key'] = 'views'; $query_args['orderby'] = 'meta_value_num'; break; case 'thumb-up': case 'thumb': $query_args['meta_key'] = 'post_thumb_count_up'; $query_args['orderby'] = 'meta_value_num'; break; case 'rand': case 'random': $query_args['orderby'] = 'rand'; break; case 'latest': $query_args['orderby'] = 'date'; break; case 'comment': $query_args['orderby'] = 'comment_count'; break; case 'recomm': case 'recommended': if(class_exists('theme_recommended_post')){ $query_args['post__in'] = (array)theme_options::get_options(theme_recommended_post::$iden); }else{ $query_args['post__in'] = (array)get_option( 'sticky_posts' ); unset($query_args['ignore_sticky_posts']); } unset($query_args['post__not_in']); break; default: $query_args['orderby'] = 'date'; } if($date && $date != 'all'){ /** * date query */ switch($date){ case 'daily' : $after = 'day'; break; case 'weekly' : $after = 'week'; break; case 'monthly' : $after = 'month'; break; default: $after = 'day'; break; } $query_args['date_query'] = array( array( 'column' => 'post_date_gmt', 'after' => '1 ' . $after . ' ago', ) ); } return theme_cache::get_queries($query_args); } /** * archive_img_content * * @return * @version 1.0.0 * @author <NAME> */ public static function archive_img_content($args = array()){ $defaults = array( 'classes' => array('grid-50','tablet-grid-50','mobile-grid-50'), 'lazyload' => true, ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); global $post; $classes[] = 'post-list post-img-list'; $post_title = get_the_title(); $excerpt = get_the_excerpt() ? ' - ' . get_the_excerpt() : null; $thumbnail_real_src = theme_functions::get_thumbnail_src($post->ID); ?> <li class="<?php echo esc_attr(implode(' ',$classes));?>"> <a class="post-list-bg" href="<?php echo get_permalink();?>"> <img class="post-list-img" src="data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" data-original="<?php echo esc_url($thumbnail_real_src);?>" alt="<?php echo esc_attr($post_title);?>" width="150" height="150"/> <h3 class="post-list-title" title="<?php echo esc_attr($post_title),esc_attr($excerpt);?>"><?php echo esc_html($post_title);?></h3> </a> </li> <?php } /** * get_meta_type * * @param string $type * @return array * @version 1.0.1 * @author KM@INN STUDIO */ public static function get_meta_type($type){ global $post; $output = array(); switch($type){ case 'thumb-up': $output = array( 'icon' => 'thumbs-o-up', 'num' => (int)get_post_meta($post->ID,'post_thumb_count_up',true), 'tx' => ___('Thumb up'), ); break; case 'comments': $output = array( 'icon' => 'comment', 'num' => $post->comment_count, 'tx' => ___('Comment count'), ); break; case 'views': case 'view': $output = array( 'icon' => 'play', 'num' => (int)get_post_meta($post->ID,'views',true), 'tx' => ___('Views'), ); break; default: return false; } return $output; } public static function archive_tx_content($args = array()){ global $post; $defaults = array( 'classes' => array(), 'meta_type' => 'views', ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); $post_title = get_the_title(); /** * classes */ $classes[] = 'post-list post-tx-list'; $classes = implode(' ',$classes); $meta_type = self::get_meta_type($meta_type); ?> <li class="<?php echo esc_attr($classes);?>"> <a href="<?php echo esc_url(get_permalink());?>" title="<?php echo esc_attr($post_title);?>"> <?php if(empty($meta_type)){ echo esc_html($post_title); }else{ ?> <span class="post-list-meta" title="<?php echo esc_attr($meta_type['tx']);?>"> <span class="icon-<?php echo $meta_type['icon'];?>"></span><span class="after-icon"><?php echo $meta_type['num'];?></span> </span> <span class="tx"><?php echo esc_html($post_title);?></span> <?php } ?> </a> </li> <?php } /** * archive_content */ public static function archive_content($args = array()){ global $post; $defaults = array( 'classes' => array('grid-50','tablet-grid-50','mobile-grid-100'), 'show_author' => true, 'show_date' => true, 'show_views' => true, 'show_comms' => true, 'show_rating' => true, 'lazyload' => true, ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); global $post; $classes[] = 'post-list post-mixed-list'; $post_title = get_the_title(); $excerpt = get_the_excerpt() ? get_the_excerpt() : null; /** * classes */ $thumbnail_real_src = theme_functions::get_thumbnail_src($post->ID); ?> <section <?php post_class($classes);?>> <?php if(is_sticky()){ ?> <div class="sticky-post" title="<?php echo esc_attr(___('Sticky post'));?>"></div> <?php } ?> <a class="post-list-bg" href="<?php echo get_permalink();?>"> <img class="post-list-img" src="data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" data-original="<?php echo esc_url($thumbnail_real_src);?>" alt="<?php echo esc_attr($post_title);?>" width="150" height="150"/> <div class="area-tx"> <h3 class="post-list-title" title="<?php echo esc_attr($post_title);?>"><?php echo esc_html($post_title);?></h3> <p class="excerpt" title="<?php echo esc_attr($excerpt);?>"><?php echo esc_html($excerpt);?></p> <div class="exten"> <div class="item"></div> </div> </div> </a> </section> <?php } public static function widget_rank_tx_content($args){ self::archive_tx_content($args); } public static function widget_rank_img_content(){ self::archive_img_content(array( 'classes' => array('grid-50 tablet-grid-50 mobile-grid-50') )); } public static function page_content($args = array()){ global $post; $defaults = array( 'target' => '_blank', 'classes' => array('grid-100','tablet-grid-100','mobile-grid-100'), 'show_author' => true, 'show_date' => true, 'show_views' => true, 'show_comms' => true, 'show_rating' => true, 'lazyload' => true, ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); $post_title = get_the_title(); $target = $target ? ' target="' . $target . '" ' : null; /** * classes */ $classes[] = 'singluar-post'; /** * cache author datas */ $author = get_user_by('id',$post->post_author); ?> <article id="post-<?php the_ID();?>" <?php post_class($classes);?>> <?php if(!empty($post_title)){ ?> <h3 class="entry-title"><?php echo esc_html($post_title);?></h3> <?php } ?> <!-- post-content --> <div class="post-content content-reset"> <?php the_content();?> </div> <?php// self::the_post_pagination();?> </article> <?php } /** * singular_content */ public static function singular_content($args = array()){ global $post; $defaults = array( 'classes' => array('grid-100','tablet-grid-100','mobile-grid-100'), 'show_author' => true, 'show_date' => true, 'show_views' => true, 'show_comms' => true, 'show_rating' => true, 'lazyload' => true, ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); $post_title = get_the_title(); /** * classes */ $classes[] = 'singluar-post'; ?> <article id="post-<?php the_ID();?>" <?php post_class($classes);?>> <?php if(!empty($post_title)){ ?> <h3 class="entry-title"><?php echo esc_html($post_title);?></h3> <?php } ?> <!-- author avatar --> <header class="post-header post-metas"> <!-- category --> <?php $cats = get_the_category_list(', '); if(!empty($cats)){ ?> <span class="post-meta post-category" title="<?php echo esc_attr(___('Category'));?>"> <span class="icon-folder"></span><span class="after-icon"><?php echo $cats;?></span> </span> <?php } ?> <!-- time --> <time class="post-meta post-time" datetime="<?php echo esc_attr(get_the_time('Y-m-d H:i:s'));?>"> <span class="icon-clock"></span><span class="after-icon"><?php echo esc_html(friendly_date((get_the_time('U'))));?></span> </time> <!-- author link --> <a class="post-meta post-author" href="<?php echo get_author_posts_url(get_the_author_meta('ID'));?>" title="<?php echo esc_attr(sprintf(___('Views all post by %s'),get_the_author()));?>"> <span class="icon-user"></span><span class="after-icon"><?php the_author();?></span> </a> <!-- views --> <?php if(class_exists('theme_post_views') && theme_post_views::is_enabled()){ ?> <span class="post-meta post-views" title="<?php echo esc_attr(___('Views'));?>"> <span class="icon-play"></span><span class="after-icon"><?php echo esc_html(theme_post_views::display());?></span> </span> <?php } ?> <!-- edit link --> <?php if(is_user_logged_in() && current_user_can('edit_post',$post->ID)){ ?> <a href="<?php echo get_edit_post_link();?>" class="post-meta edit-post-link"><span class="icon-pencil"></span><span class="after-icon"><?php echo esc_html(___('Edit post'));?></span></a> <?php } ?> <!-- permalink --> <a href="<?php echo get_permalink();?>" class="post-meta permalink" title="<?php echo esc_attr(___('Post link'));?>"> <span class="icon-link"></span><span class="after-icon"><?php echo esc_html(___('Post link'));?></span> </a> </header> <!-- post-content --> <div class="post-content content-reset"> <?php the_content();?> </div> <?php echo theme_features::get_prev_next_pagination(array( 'numbers_class' => array('btn btn-primary') ));?> <?php /** * tags */ // self::the_post_tags(); $tags = get_the_tags(); if(!empty($tags)){ ?> <div class="post-tags"> <?php foreach($tags as $tag){ ?> <a href="<?php echo get_tag_link($tag->term_id);?>" class="post-meta tag" title="<?php echo sprintf(___('Views all posts by %s tag'),esc_attr($tag->name));?>"> <span class="icon-tag"></span><span class="after-icon"><?php echo esc_html($tag->name);?></span> </a> <?php } ?> </div> <?php } ?> <!-- post-footer --> <footer class="post-footer post-metas"> <?php /** * thumb-up */ if(class_exists('theme_post_thumb') && theme_post_thumb::is_enabled()){ ?> <div class="post-thumb"> <a data-post-thumb="<?php echo $post->ID;?>,up" href="javascript:void(0);" class="post-meta theme-thumb theme-thumb-up" title="<?php echo ___('Good! I like it.');?>"> <span class="icon-thumbs-o-up"></span><span class="after-icon count"><?php echo theme_post_thumb::get_thumb_up_count();?></span> <span class="tx hide-on-mobile"><?php echo ___('Good');?></span> </a> <a data-post-thumb="<?php echo $post->ID;?>,down" href="javascript:void(0);" class="post-meta theme-thumb theme-thumb-down" title="<?php echo ___('Bad idea!');?>"> <span class="icon-thumbs-o-down"></span><span class="after-icon count"><?php echo theme_post_thumb::get_thumb_down_count();?></span> <span class="tx hide-on-mobile"><?php echo ___('Bad');?></span> </a> </div> <?php } /** end thumb-up */ ?> <?php /** * post-share */ if(class_exists('theme_post_share') && theme_post_share::is_enabled()){ ?> <div class="post-meta"> <?php echo theme_post_share::display();?> </div> <?php } /** end post-share */ ?> <?php /** * comment */ $comment_count = (int)get_comments_number(); $comment_tx = $comment_count <= 1 ? ___('comment') : ___('comments'); ?> <a href="javascript:void(0);" class="post-meta quick-comment comment-count" data-post-id="<?php echo $post->ID;?>"> <span class="icon-comment"></span><span class="after-icon"><span class="comment-count-number"><?php echo esc_html($comment_count);?></span> <span class="hide-on-mobile"><?php echo esc_html($comment_tx);?></span></span> </a> </footer> </article> <?php } public static function the_post_tags(){ global $post; $tags = get_the_tags(); if(empty($tags)) return false; $first_tag = array_shift($tags); $split_str = '<span class="split">' . ___(', ') . '</span>'; ?> <div class="post-tags"> <?php /** * first tag html */ ob_start(); ?> <a href="<?php echo get_tag_link($first_tag->term_id);?>" class="tag" title="<?php echo sprintf(___('Views all posts by %s tag'),esc_attr($first_tag->name));?>"> <span class="icon-tags"></span><span class="after-icon"><?php echo esc_html($first_tag->name);?></span> </a> <?php $tags_str = array(ob_get_contents()); ob_end_clean(); // $i = 0; foreach($tags as $tag){ // if($i === 0){ // ++$i; // continue; // } ob_start(); ?> <a href="<?php echo get_tag_link($tag->term_id);?>" class="tag" title="<?php echo sprintf(___('Views all posts by %s tag'),esc_attr($tag->name));?>"> <?php echo esc_html($tag->name);?> </a> <?php $tags_str[] = ob_get_contents(); ob_end_clean(); } echo implode($split_str,$tags_str); ?> </div> <?php } /** * get_thumbnail_src * * @return * @version 1.0.1 * @author KM@INN STUDIO */ public static function get_thumbnail_src($post_id = null,$size = null){ global $post; $size = $size ? $size : self::$thumbnail_size; $post_id = $post_id ? $post_id : $post->ID; $src = null; if(empty($src)){ $src = get_img_source(get_the_post_thumbnail($post_id,$size)); } if(!$src){ $src = theme_features::get_theme_images_url('frontend/thumb-preview.png'); } return $src; } /** * get_content * * @return string * @version 1.0.0 * @author KM@INN STUDIO */ private static function get_content(){ global $post; $content = str_replace(']]>', ']]&raquo;', $post->post_content); return $content; } /** * get_adjacent_posts * * @param string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ public static function get_adjacent_posts($class = 'adjacent-posts'){ global $post; $next_post = get_adjacent_post(true,null,false); $next_post = $next_post ? $next_post : get_adjacent_post(false,null,false); $prev_post = get_adjacent_post(true,null); $prev_post = $prev_post ? $prev_post : get_adjacent_post(false,null); if(!$next_post && ! $prev_post) return; ob_start(); ?> <nav class="grid-100 grid-parent <?php echo $class;?>"> <ul> <li class="adjacent-post-prev grid-50 tablet-grid-50 mobile-grid-100"> <?php if(!$prev_post){ ?> <span class="adjacent-post-not-found button"><?php echo ___('No more post found');?></span> <?php }else{ ?> <a href="<?php echo get_permalink($prev_post->ID);?>" title="<?php echo esc_attr(sprintf(___('Previous post: %s'),$prev_post->post_title));?>" class="button"> <span class="aquo"><?php echo esc_html(___('&laquo;'));?></span> <?php echo esc_html($prev_post->post_title);?> </a> <?php } ?> </li> <li class="adjacent-post-next grid-50 tablet-grid-50 mobile-grid-100"> <?php if(!$next_post){ ?> <span class="adjacent-post-not-found button"><?php echo ___('No more post found');?></span> <?php }else{ ?> <a href="<?php echo get_permalink($next_post->ID);?>" title="<?php echo esc_attr(sprintf(___('Next post: %s'),$next_post->post_title));?>" class="button"> <?php echo esc_html($next_post->post_title);?> <span class="aquo"><?php echo esc_html(___('&raquo;'));?></span> </a> <?php } ?> </li> </ul> </nav> <?php $content = ob_get_contents(); ob_end_clean(); return $content; } /** * get_crumb * * * @return string The html code * @version 2.0.4 * @author KM@INN STUDIO * */ public static function get_crumb($args = null){ $defaults = array( 'header' => null, 'footer' => null, ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); $links = array(); if(is_home()) return null; $links['home'] = '<a href="' . home_url() . '" class="home" title="' .___('Back to Homepage'). '"><span class="icon-home"></span><span class="after-icon hide-on-mobile">' . esc_html(___('Home')) . '</span></a>'; $split = '<span class="split">&raquo;</span>'; /* category */ if(is_category()){ $cat_curr = theme_features::get_current_cat_id(); if($cat_curr > 1){ $links_cat = get_category_parents($cat_curr,true,'%split%'); $links_cats = explode('%split%',$links_cat); array_pop($links_cats); $links['category'] = implode($split,$links_cats); $links['curr_text'] = esc_html(___('Category Browser')); } /* tag */ }else if(is_tag()){ $tag_id = theme_features::get_current_tag_id(); $tag_obj = get_tag($tag_id); $links['tag'] = '<a href="'. esc_url(get_tag_link($tag_id)).'">' . esc_html(theme_features::get_current_tag_name()).'</a>'; $links['curr_text'] = esc_html(___('Tags Browser')); /* date */ }else if(is_date()){ global $wp_query; $day = $wp_query->query_vars['day']; $month = $wp_query->query_vars['monthnum']; $year = $wp_query->query_vars['year']; /* day */ if(is_day()){ $date_link = get_day_link(null,null,$day); /* month */ }else if(is_month()){ $date_link = get_month_link($year,$month); /* year */ }else if(is_year()){ $date_link = get_year_link($year); } $links['date'] = '<a href="'.$date_link.'">' . esc_html(wp_title('',false)).'</a>'; $links['curr_text'] = esc_html(___('Date Browser')); /* search*/ }else if(is_search()){ // $nav_link = null; $links['curr_text'] = esc_html(sprintf(___('Search Result: %s'),get_search_query())); /* author */ }else if(is_author()){ global $author; $user = get_user_by('id',$author); $links['author'] = '<a href="'.get_author_posts_url($author).'">'.esc_html($user->display_name).'</a>'; $links['curr_text'] = esc_html(___('Author posts')); /* archive */ }else if(is_archive()){ $links['archive'] = '<a href="'.get_current_url().'">'.wp_title('',false).'</a>'; $links['curr_text'] = esc_html(___('Archive Browser')); /* Singular */ }else if(is_singular()){ global $post; /* The page parent */ if($post->post_parent){ $links['singluar'] = '<a href="' .get_page_link($post->post_parent). '">' .esc_html(get_the_title($post->post_parent)). '</a>'; } /** * post / page */ if(theme_features::get_current_cat_id() > 1){ $categories = get_the_category(); foreach ($categories as $key => $row) { $parent_id[$key] = $row->category_parent; } array_multisort($parent_id, SORT_ASC,$categories); foreach($categories as $cat){ $links['singluar'] = '<a href="' . esc_html(get_category_link($cat->cat_ID)) . '" title="' . esc_attr(sprintf(___('View all posts in %s'),$cat->name)) . '">' . esc_html($cat->name) . '</a>'; } } $links['curr_text'] = esc_html(get_the_title()); /* 404 */ }else if(is_404()){ // $nav_link = null; $links['curr_text'] = esc_html(___('Not found')); } $output = ' <div class="crumb-container"> ' .$header. ' <nav class="crumb"> ' . implode($split,apply_filters('crumb_home_link',$links)) . ' </nav> ' .$footer. ' </div> '; return $output; } /** * get_post_pagination * show pagination in archive or searching page * * @param string The class of molude * @return string * @version 1.0.1 * @author KM@INN STUDIO * */ public static function get_post_pagination( $class = 'posts-pagination' ) { global $wp_query,$paged; if ( $wp_query->max_num_pages > 1 ){ $big = 9999999; $args = array( 'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'echo' => false, 'current' => max( 1, get_query_var('paged') ), 'prev_text' => ___('&laquo;'), 'next_text' => ___('&raquo;'), 'total' => $wp_query->max_num_pages, ); $posts_page_links = paginate_links($args); $output = '<nav class="'.$class.'">'.$posts_page_links.'</nav>'; return $output; } } public static function get_theme_respond($args = null){ global $post,$current_user; $defaults = array( 'post_id' => $post->ID ? $post->ID : null, 'parent_id' => 0, ); $r = wp_parse_args($args,$defaults); extract($r); $current_commenter = wp_get_current_commenter(); // $comment_author = isset($current_commenter['comment_author']) && !empty($$current_commenter['comment_author']) ? $current_commenter['comment_author'] : get_currentuserinfo(); ob_start(); ?> <div id="respond" class="comment-respond"> <h3 id="reply-title" class="comment-reply-title"> <span class="icon-bubble"></span><span class="after-icon"><?php echo esc_html(___('Leave a comment'));?></span> <small><a rel="nofollow" id="cancel-comment-reply-link" href="javascript:void(0);" style="display:none;"><span class="icon-cancel-circle"></span><span class="after-icon"><?php echo esc_html(___('Cancel reply'));?></span></a></small> </h3> <form action="javascript:void(0);" method="post" id="commentform" class="comment-form"> <div class="area-user"> <?php if(!is_user_logged_in()){ if(empty($current_commenter['comment_author'])){ ?> <p><input type="text" name="author" id="comment-author" class="form-control mod" placeholder="<?php echo esc_attr(___('Name'));?>"/></p> <p><input type="email" name="email" id="comment-email" class="form-control mod" placeholder="<?php echo esc_attr(___('Email'));?>"/></p> <?php }else{ ?> <a href="<?php echo !empty($current_commenter['comment_author_url']) ? $current_commenter['comment_author_url'] : 'javascript:void(0);';?>" class="area-avatar" <?php echo !empty($current_commenter['comment_author_url']) ? 'target="_blank"' : null;?>"> <img src="<?php echo esc_url(!empty($current_commenter['comment_author_email']) ? get_gravatar($current_commenter['comment_author_email']) : theme_features::get_theme_images_url('frontend/author-vcard.jpg'));?>" title="<?php echo esc_attr($current_commenter['comment_author']);?>" alt="<?php echo esc_attr($current_commenter['comment_author']);?>"/> </a> <?php } ?> <?php }else{ ?> <a href="<?php echo !empty($current_user->user_url) ? $current_user->user_url : 'javascript:void(0);';?>" class="area-avatar" <?php echo !empty($current_user->user_url) ? 'target="_blank"' : null;?>"> <img src="<?php echo esc_url(!empty($current_user->user_email) ? get_gravatar($current_user->user_email) : theme_features::get_theme_images_url('frontend/author-vcard.jpg'));?>" title="<?php echo esc_attr($current_user->display_name);?>" alt="<?php echo esc_attr($current_user->display_name);?>"/> </a> <?php } ?> </div> <div class="area-comment mod"> <textarea id="comment" name="comment" cols="45" rows="8" required placeholder="<?php echo esc_html(___('Write a omment'));?>" class="form-control"></textarea> <!-- #comment face system --> <?php $options = theme_options::get_options(); $emoticons = theme_comment_face::get_emoticons(); $a_content = null; if($emoticons){ foreach($emoticons as $text){ $a_content .= '<a href="javascript:void(0);" data-id="' . esc_attr($text) . '">' . esc_html($text) . '</a>'; } }else{ $a_content = '<a href="javascript:void(0);" data-id="' . esc_html(___('No data')) . '">' . esc_html(___('No data')) . '</a>'; } ?> <div id="comment-face" class="hide-no-js"> <ul class="comment-face-btns grid-parent grid-40 tablet-grid-40 mobile-grid-30"> <li class="btn grid-parent grid-50 tablet-grid-50 mobile-grid-50" data-faces=""> <a title="<?php echo esc_attr(___('Pic-face'));?>" href="javascript:void(0);" class="comment-face-btn"> <span class="icon-happy"></span><span class="after-icon hide-on-mobile"><?php echo esc_html(___('Pic-face'));?></span> </a> <div class="comment-face-box type-image"></div> </li> <li class="btn grid-parent grid-50 tablet-grid-50 mobile-grid-50"> <a title="<?php echo esc_attr(___('Emoticons'));?>" href="javascript:void(0);" class="comment-face-btn"> <span class="icon-happy2"></span><span class="after-icon hide-on-mobile"><?php echo esc_html(___('Emoticons'));?></span> </a> <div class="comment-face-box type-text"><?php echo $a_content;?></div> </li> </ul> <!-- submit --> <div class="grid-parent grid-60 tablet-grid-60 mobile-grid-70"> <input class="btn btn-primary" type="submit" id="comment-submit" value="<?php echo esc_html(___('Post comment'));?>"> <input type="hidden" name="comment_post_ID" value="<?php echo esc_html((int)$post_id);?>" id="comment_post_ID"> <input type="hidden" name="comment_parent" id="comment_parent" value="<?php echo esc_html((int)$parent_id);?>"> </div> </div> <!-- #comment face system --> </div> </form> </div> <?php $content = ob_get_contents(); ob_end_clean(); return $content; } /** * get the comment pagenavi * * * @param string $class Class name * @param bool $below The position where show. * @return string * @version 1.0.0 * @author KM@INN STUDIO * */ public static function get_comment_pagination( $args ) { $options = theme_options::get_options(); /** Check the comment is open */ $page_comments = get_option('page_comments'); /** if comment is closed, return */ if(!$page_comments) return; /** * defaults args */ $defaults = array( 'classes' => 'comment-pagination', 'cpaged' => max(1,get_query_var('cpage')), 'cpp' => get_option('comments_per_page'), 'thread_comments' => get_option('thread_comments') ? true : false, // 'default_comments_page' => get_option('default_comments_page'), 'default_comments_page' => 'oldest', 'max_pages' => get_comment_pages_count(null,get_option('comments_per_page'),get_option('thread_comments')), ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); /** * if enable ajax */ if(isset($options['comment_ajax']) && $options['comment_ajax']['on'] == 1){ $add_fragment = '&amp;pid=' . get_the_ID(); }else{ $add_fragment = false; } /** If has page to show me */ if ( $max_pages > 1 ){ $big = 999; $args = array( 'base' => str_replace($big,'%#%',get_comments_pagenum_link($big)), 'total' => $max_pages, 'current' => $cpaged, 'echo' => false, 'prev_text' => ___('&laquo;'), 'next_text' => ___('&raquo;'), 'add_fragment' => $add_fragment, ); $comments_page_links = paginate_links($args); $output = '<div class="'. $classes .'">'.$comments_page_links.'</div>'; return $output; } } /** * the_post_0 */ public static function the_post_0(){ global $post; ?> <div id="post-0"class="post no-results not-found mod"> <?php echo status_tip('info','large',___( 'Sorry, I was not able to find what you need, what about look at other content :)')); ?> </div><!-- #post-0 --> <?php } /** * get_rank_data */ public static function get_rank_data($id = null){ $content = array( 'all' => ___('All'), 'daily' => ___('Daily'), 'weekly' => ___('Weekly'), 'monthly' => ___('Monthly'), ); if($id) return isset($content[$id]) ? $content[$id] : false; return $content; } /** * smart_page_pagination */ public static function smart_page_pagination($args = null){ global $post,$page,$numpages; $output = null; $defaults = array( 'add_fragment' => 'post-' . $post->ID ); $r = wp_parse_args($args,$defaults); extract($r); $output['numpages'] = $numpages; $output['page'] = $page; /** * prev post */ $prev_post = get_previous_post(true); $prev_post = empty($prev_post) ? get_previous_post() : $prev_post; if(!empty($prev_post)){ $output['prev_post'] = $prev_post; } /** * next post */ $next_post = get_next_post(true); $next_post = empty($next_post) ? get_next_post() : $next_post; // var_dump($next_post); if(!empty($next_post)){ $output['next_post'] = $next_post; } /** * exists multiple page */ if($numpages != 1){ /** * if has prev page */ if($page > 1){ $prev_page_number = $page - 1; $output['prev_page']['url'] = theme_features::get_link_page_url($prev_page_number,$add_fragment); $output['prev_page']['number'] = $prev_page_number; } /** * if has next page */ if($page < $numpages){ $next_page_number = $page + 1; $output['next_page']['url'] = theme_features::get_link_page_url($next_page_number,$add_fragment); $output['next_page']['number'] = $next_page_number; } } // var_dump(array_filter($output)); return array_filter($output); } public static function filter_prev_pagination_link($link,$page,$numpages){ global $post; // var_dump($page); // var_dump($numpages); if($page > 1) return $link; $prev_post = get_previous_post(true); // var_dump($prev_post); $prev_post = empty($prev_post) ? get_previous_post() : $prev_post; if(empty($prev_post)) return $link; ob_start(); ?> <a href="<?php echo get_permalink($prev_post->ID);?>" class="nowrap page-numbers page-next btn btn-success grid-40 tablet-grid-40 mobile-grid-50 numbers-first" title="<?php echo esc_attr($prev_post->post_title);?>"> <?php echo esc_html(___('&lsaquo; Previous'));?> - <?php echo esc_html($prev_post->post_title);?> </a> <?php $link = ob_get_contents(); ob_end_clean(); return $link; } public static function filter_next_pagination_link($link,$page,$numpages){ global $post; // var_dump($page); // var_dump($numpages); if($page < $numpages) return $link; $next_post = get_next_post(true); // var_dump($prev_post); $next_post = empty($next_post) ? get_next_post() : $next_post; if(empty($next_post)) return $link; ob_start(); ?> <a href="<?php echo get_permalink($next_post->ID);?>" class="nowrap page-numbers page-next btn btn-success grid-40 tablet-grid-40 mobile-grid-50 numbers-first" title="<?php echo esc_attr($next_post->post_title);?>"> <?php echo esc_html($next_post->post_title);?> - <?php echo esc_html(___('Next &rsaquo;'));?> </a> <?php $link = ob_get_contents(); ob_end_clean(); return $link; } public static function the_post_pagination(){ global $post,$page,$numpages; ?> <nav class="prev-next-pagination"> <?php $prev_next_pagination = theme_smart_pagination::get_post_pagination(); /** * exists prev page and next page, just show them */ if(isset($prev_next_pagination['prev_page']) && isset($prev_next_pagination['next_page'])){ ?> <a href="<?php echo esc_url($prev_next_pagination['prev_page']['url']);?>" class="prev-page nowrap btn btn-primary grid-parent grid-50 tablet-grid-50 mobile-grid-50"><?php echo esc_html(___('&larr; Preview page'));?></a> <a href="<?php echo esc_url($prev_next_pagination['next_page']['url']);?>" class="next-page nowrap btn btn-primary grid-parent grid-50 tablet-grid-50 mobile-grid-50"><?php echo esc_html(___('Next page &rarr;'));?></a> <?php /** * exists prev page, show prev page and next post */ }else if(isset($prev_next_pagination['prev_page'])){ $grid_class = isset($prev_next_pagination['prev_post']) ? ' grid-50 tablet-grid-50 mobile-grid-50 ' : ' grid-100 tablet-grid-100 mobile-grid-100'; ?> <a href="<?php echo esc_url($prev_next_pagination['prev_page']['url']);?>" class="prev-page nowrap btn btn-primary grid-parent <?php echo $grid_class;?>"><?php echo esc_html(___('&larr; Preview page'));?></a> <?php if(isset($prev_next_pagination['prev_post'])){ ?> <a href="<?php echo get_permalink($prev_next_pagination['prev_post']->ID);?>" class="next-page nowrap btn btn-success grid-parent <?php echo $grid_class;?>"><span class="tx"><?php echo ___('Next post &rarr;');?></span><span class="next-post-tx hide"><?php echo esc_html(sprintf(___('%s &rarr;'),$prev_next_pagination['prev_post']->post_title));?></span></a> <?php } /** * exists next page, show next page and prev post */ }else if(isset($prev_next_pagination['next_page'])){ $grid_class = isset($prev_next_pagination['prev_post']) ? ' grid-50 tablet-grid-50 mobile-grid-50 ' : ' grid-100 tablet-grid-100 mobile-grid-100'; if(isset($prev_next_pagination['next_post'])){ ?> <a href="<?php echo get_permalink($prev_next_pagination['next_post']->ID);?>" class="prev-post nowrap btn btn-success grid-parent <?php echo $grid_class;?>"><span class="tx"><?php echo ___('&larr; Preview post');?></span><span class="prev-post-tx hide"><?php echo esc_html(sprintf(___('&larr; %s'),$prev_next_pagination['next_post']->post_title));?></span></a> <?php } ?> <a href="<?php echo esc_url($prev_next_pagination['next_page']['url']);?>" class="next-page nowrap btn btn-primary grid-parent <?php echo $grid_class;?>"><?php echo esc_html(___('Next page &rarr;'));?></a> <?php /** * only exists next post and prev post, show them */ }else{ $grid_class = isset($prev_next_pagination['prev_post']) && isset($prev_next_pagination['next_post']) ? ' grid-50 tablet-grid-50 mobile-grid-50 ' : ' grid-100 tablet-grid-100 mobile-grid-100'; if(isset($prev_next_pagination['next_post'])){ ?> <a href="<?php echo get_permalink($prev_next_pagination['next_post']->ID);?>" class="prev-post nowrap btn btn-success grid-parent <?php echo $grid_class;?>"><span class="tx"><?php echo ___('&larr; Preview post');?></span><span class="prev-post-tx hide"><?php echo esc_html(sprintf(___('&larr; %s'),$prev_next_pagination['next_post']->post_title));?></span></a> <?php } if(isset($prev_next_pagination['prev_post'])){ ?> <a href="<?php echo get_permalink($prev_next_pagination['prev_post']->ID);?>" class="next-page nowrap btn btn-success grid-parent <?php echo $grid_class;?>"><span class="tx"><?php echo ___('Next post &rarr;');?></span><span class="next-post-tx hide"><?php echo esc_html(sprintf(___('%s &rarr;'),$prev_next_pagination['prev_post']->post_title));?></span></a> <?php } } ?> </nav> <?php } /** * the_related_posts */ public static function the_related_posts($args_content = null,$args_query = null){ global $post; $defaults_query = array( 'posts_per_page' => 10 ); $args_query = wp_parse_args($args_query,$defaults_query); $defaults_content = array( 'classes' => array('grid-20 tablet-grid-20 mobile-grid-50'), ); $args_content = wp_parse_args($args_content,$defaults_content); $posts = theme_related_post::get_posts($args_query); if(!is_null_array($posts)){ ?> <ul class="related-posts-img"> <?php foreach($posts as $post){ setup_postdata($post); echo self::archive_img_content($args_content); } ?> </ul> <?php }else{ ?> <div class="no-post page-tip"><?php echo status_tip('info',___('No data yet'));?></div> <?php } wp_reset_postdata(); } /** * get_page_pagenavi * * * @return * @version 1.0.0 * @author KM@INN STUDIO * */ public static function get_page_pagenavi(){ // var_dump( theme_features::get_pagination()); global $page,$numpages; $output = null; if($numpages < 2) return; if($page < $numpages){ $next_page = $page + 1; $output = '<a href="' . theme_features::get_link_page_url($next_page) . '" class="next_page">' . ___('Next page') . '</a>'; }else{ $prev_page = $page - 1; $output = '<a href="' . theme_features::get_link_page_url($prev_page) . '" class="prev_page">' . ___('Previous page') . '</a>'; } $output = $output ? '<div class="singluar_page">' . $output . '</div>' : null; $args = array( 'range' => 3 ); $output .= theme_features::get_pagination($args); return $output; } } ?> <file_sep>/README.md # wp-theme-inn2015 inn studio theme - inn2015 主题官网: [http://inn-studio.com](http://inn-studio.com) > 在即将过去的 2014 年里,我们学会并掌握了许多知识。不断学习与运用这些知识,相信在未来 2015 年, 我们面对一系列的机遇与挑战,都会应付得游刃有余。 * 主题名称:INN 2015 * 主题类型:博客型主题 * 主题售价:99 元 (点击[《如何购买》](http://inn-studio.com/how-to-buy/) 或联系客服QQ:[272778765](http://wpa.qq.com/msgrd?v=3&amp;uin=272778765&site=qq&&amp;menu=yes) 购买) * 展示网址:[INN STUDIO](http://inn-studio.com) # 预览图 ![Homepage](http://inn-studio.com/wp-content/uploads/2014/11/inn2015-home-pre-150x150.jpg) ![Comment](http://inn-studio.com/wp-content/uploads/2014/11/inn2015-add-comment-pre-150x150.jpg) # 主题描述 > INN 2015 主题,使用了偏向商务色彩的深蓝色,以沉稳的风格展示不同类型的内容。INN STUDIO 预测 2015 年, 将会是更以移动流量为主的 Web 年头,所以 INN 2015 主题以移动优先,兼顾桌面的体验理念理念来开发,使得桌面或手机 都能得到十分友好的体验。主题的所有功能,例如“评论、菜单、侧栏”等,比起以往的主题作出了十分大的优化,无论性能或 外观,都有了成倍的提升。相信 INN 2015 主题,可使您的博客变得多姿而稳重。 # 主题特色 * 使用 HTML5 和 CSS3 编写前端,兼容现代浏览器 * 使用响应式设计,PC 和 手机都能很好访问 * 使用异步加载资源,访问速度十分令人愉悦 * 使用字体图标,无论放大或缩小都不会失真 * 使用 AJAX 加载评论和添加评论,体验友好 * 拥有详尽的多个侧栏小工具,随心所欲设计每种页面 * 拥有多功能的排行榜小工具,各种文章排行按需显示 * 拥有在线升级功能 * 零插件,效率更高 * 更多功能等您发现 # 注意事项 * 请确保 WordPress 运行环境为 PHP5.4+ * 建议仅使用 Memcache 作为缓存组件([如何使用 Memcache 组件?](http://inn-studio.com/memcche-for-wordpress/)) * 使用前需同意[授权声明](http://inn-studio.com/faq/) # 使用前注意 * 安装主题后,请设置相应的“菜单”项和小工具项 * 请为您的博客添加 SEO 优化和统计代码 #更新日志 ## 2015-02-27 1.4.2 - 功能完善 - 更换 gravatar 头像资源 ## 2015-01-31 1.4.1 - 功能完善 - 优化在调整窗口大小时候的 js 计算量 - 优化小工具最新评论链接指向 - 修正在 page 页面中评论 js 不加载问题 ## 2015-01-31 1.4.0 - 新增特性 - 增加文章编辑链接 - 增加顶置文章样式 - 增加小工具最新评论样式 - 增加 page 页面评论 - 功能完善 - 优化智能浮动 - 修正在 hhvm 下部分跳转链接变成 https 的问题 - 修正在 hhvm 下部分主题组件错误 <file_sep>/includes/theme-widget-category-post/theme-widget-category-post.php <?php /* Feature Name: theme-widget-category-post Feature URI: http://www.inn-studio.com Version: 1.0.3 Description: theme-widget-category-post Author: INN STUDIO Author URI: http://www.inn-studio.com */ add_action('widgets_init','widget_posts::register_widget' ); class widget_posts extends WP_Widget{ public static $iden = 'widget_posts'; function __construct(){ $this->alt_option_name = self::$iden; $this->WP_Widget( self::$iden, ___('Category posts <small>(custom)</small>'), array( 'classname' => self::$iden, 'description' => ___('Show your posts by category.') ) ); } /** * display_frontend * * @param array * @return * @version 1.0.0 * @author KM@INN STUDIO */ public static function display_frontend($args = null){ $defaults = array( 'title' => ___('Category posts'), 'class' => 'category-posts', 'selected' => -1, 'posts_per_page' => 8, 'show_date' => 0, ); $r = wp_parse_args($args,$defaults); /** * theme cache */ // $cache_id = md5(serialize($r) . get_current_url()); extract($r); /** * get category posts */ global $post; $query_args = array( 'posts_per_page' => $posts_per_page, // 'paged' => 1, 'category' => $selected, ); $posts = get_posts($query_args); ?> <div class="widget-container"> <ul> <?php if($posts){ foreach($posts as $post){ setup_postdata($post); ?> <li> <a href="<?php echo esc_url(get_permalink());?>"> <span class="title"><?php echo esc_html(get_the_title());?></span> <?php if($show_date === 1){ ?> <small class="date"> - <?php echo esc_html(friendly_date(get_post_time('U', true)));?></small> <?php } ?> </a> </li> <?php } }else{ ?> <li><?php echo status_tip('info',___('No post in this category'));?></li> <?php } wp_reset_postdata(); ?> </ul> </div> <?php } function widget($args,$instance){ $args = array_merge($args,$instance); extract($args); $title = apply_filters('widget_title',empty($instance['title']) ? null : $instance['title']); $class = empty($instance['class']) ? self::$iden : $instance['class']; $title = $title ? $title . '<a class="more" href="' . get_category_link((int)$instance['selected']) . '">' . ___('More &raquo;') . '</a>' : null; echo $before_widget; echo $title ? $before_title . $title . $after_title : null; echo self::display_frontend($args); echo $after_widget; } function form($instance){ $defaults = array( 'title' => ___('Category posts'), 'selected' => -1, 'posts_per_page' => 8, 'show_date' => 0, ); $instance = wp_parse_args((array)$instance,$defaults); ?> <p> <label for="<?php echo $this->get_field_id('title');?>"><?php echo esc_html(___('Title'));?></label> <input id="<?php echo $this->get_field_id('title');?>" type="text" class="widefat" name="<?php echo $this->get_field_name('title');?>" value="<?php echo esc_attr($instance['title']);?>" /> </p> <p> <label for="<?php echo $this->get_field_id('selected');?>"><?php echo esc_html(___('Category: '));?></label> <?php $cat_args = array( 'name' => $this->get_field_name('selected'), 'id' => $this->get_field_id('selected'), 'show_option_none' => ___('Select category'), 'hierarchical' => 1, 'hide_empty' => false, 'selected' => (int)$instance['selected'], 'echo' => 0, 'show_count' => true, ); echo wp_dropdown_categories($cat_args); ?> </p> <p> <label for="<?php echo $this->get_field_id('show_date');?>"><?php echo esc_html(___('Show date: '));?></label> <select name="<?php echo $this->get_field_name('show_date');?>" id="<?php echo $this->get_field_id('show_date');?>" class="widefat" > <?php $selected = function($v,$current_v){ return (int)$v === (int)$current_v ? ' selected ' : null; }; ?> <option value="0" <?php echo $selected(0,(int)$instance['show_date']);?>><?php echo esc_attr(___('Hide'));?></option> <option value="1" <?php echo $selected(1,(int)$instance['show_date']);?>><?php echo esc_attr(___('Show'));?></option> </select> </p> <p> <label for="<?php echo $this->get_field_id('posts_per_page');?>"><?php echo esc_html(___('Post number'));?></label> <input id="<?php echo $this->get_field_id('posts_per_page');?>" type="number" class="widefat" name="<?php echo $this->get_field_name('posts_per_page');?>" value="<?php echo esc_attr((int)$instance['posts_per_page']);?>" required /> </p> <?php } function update($new_instance,$old_instance){ $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); $instance['class'] = strip_tags($new_instance['class']); $instance['selected'] = (int)($new_instance['selected']); $instance['posts_per_page'] = (int)$new_instance['posts_per_page']; $instance['show_date'] = (int)$new_instance['show_date']; return $instance; } public static function register_widget(){ register_widget(self::$iden); } }<file_sep>/includes/theme-widget-rank/theme-widget-rank.php <?php /** * version 1.0.3 */ add_action('widgets_init','widget_rank::register_widget' ); class widget_rank extends WP_Widget{ public static $iden = 'widget_rank'; function __construct(){ $this->alt_option_name = self::$iden; parent::__construct( self::$iden, ___('Posts rank <small>(Custom)</small>'), array( 'classname' => self::$iden, 'description'=> ___('Posts rank'), ) ); } public static function frontend_display($args,$instance){ // var_dump($args); // var_dump($instance); $instance_defaults = array( 'title' => ___('Posts rank'), 'posts_per_page' => 6, 'date' => 'all', 'orderby' => 'views', 'category__in' => array(), 'content_type' => 'tx', ); $instance = wp_parse_args($instance,$instance_defaults); // var_dump($instance); global $wp_query,$post; ?> <h3 class="widget-title"> <?php if(isset($instance['category__in'][0])){ ?> <a class="link" href="<?php echo get_category_link($instance['category__in'][0]);?>" title="<?php echo esc_attr(sprintf(___('Views more about %s'),$instance['title']));?>" target="_blank"><span class="icon-bars"></span><span class="after-icon"><?php echo esc_html($instance['title']);?></span></a> <a href="<?php echo get_category_link($instance['category__in'][0]);?>" title="<?php echo esc_attr(sprintf(___('Views more about %s'),$instance['title']));?>" target="_blank" class="more"><?php echo esc_html(___('More &raquo;'));?></a> <?php }else{ ?> <span class="icon-bars"></span><span class="after-icon"><?php echo esc_html($instance['title']);?></span> <?php } ?> </h3> <?php $wp_query = theme_functions::get_posts_query(array( 'category__in' => (array)$instance['category__in'], 'posts_per_page' => (int)$instance['posts_per_page'], 'date' => $instance['date'], 'orderby' => $instance['orderby'], )); $content_type_class = $instance['content_type'] === 'tx' ? ' post-tx-lists ' : ' post-img-lists '; /** * set container tag */ switch($instance['orderby']){ case 'latest': case 'rand': case 'random': case 'recommended': case 'sticky': $container_tag = 'ul'; break; default: $container_tag = 'div'; } if(have_posts()){ ?> <ul class="tabbody post-lists <?php echo $content_type_class;?> widget-orderby-<?php echo $instance['orderby'];?>"> <?php while(have_posts()){ the_post(); if($instance['content_type'] === 'tx'){ theme_functions::widget_rank_tx_content(array( 'meta_type' => $instance['orderby'], )); }else{ theme_functions::widget_rank_img_content(); } } ?> </ul> <?php }else{ ?> <div class="page-tip not-found"> <?php echo status_tip('info',___('No data yet.'));?> </div> <?php } wp_reset_postdata(); wp_reset_query(); } function widget($args,$instance){ // var_dump($instance); extract($args); /** * theme cache */ // $cache_id = md5(serialize($args) .serialize($instance) . get_current_url()); echo $before_widget; self::frontend_display($args,$instance); echo $after_widget; } function form($instance){ $instance = wp_parse_args( (array)$instance, array( 'title'=>___('Posts ranking'), 'posts_per_page' => 6, 'category__in' => array(), 'content_type' => 'tx', 'orderby' => 'latest', ) ); ?> <p> <label for="<?php echo esc_attr(self::get_field_id('title'));?>"><?php echo esc_html(___('Title (optional)'));?></label> <input id="<?php echo esc_attr(self::get_field_id('title'));?>" class="widefat" name="<?php echo esc_attr(self::get_field_name('title'));?>" type="text" value="<?php echo esc_attr($instance['title']);?>" placeholder="<?php echo esc_attr(___('Title (optional)'));?>" /> </p> <p> <label for="<?php echo esc_attr(self::get_field_id('posts_per_page'));?>"><?php echo esc_html(___('Post number (required)'));?></label> <input id="<?php echo esc_attr(self::get_field_id('posts_per_page'));?>" class="widefat" name="<?php echo esc_attr(self::get_field_name('posts_per_page'));?>" type="number" value="<?php echo esc_attr($instance['posts_per_page']);?>" placeholder="<?php echo esc_attr(___('Post number (required)'));?>" /> </p> <p> <?php echo esc_html(___('Categories: '));?> <?php echo self::get_cat_checkbox_list( self::get_field_name('category__in'), self::get_field_id('category__in'), $instance['category__in'] );?> </p> <!-- date --> <p> <label for="<?php echo esc_attr(self::get_field_id('date'));?>"><?php echo esc_html(___('Date'));?></label> <select name="<?php echo esc_attr(self::get_field_name('date'));?>" class="widefat" id="<?php echo esc_attr(self::get_field_id('date'));?>" > <?php $dates = theme_functions::get_rank_data(); foreach($dates as $k => $v){ echo get_option_list($k,$v,$instance['date']); } ?> </select> </p> <p> <label for="<?php echo esc_attr(self::get_field_id('content_type'));?>"><?php echo esc_html(___('Content type'));?></label> <select name="<?php echo esc_attr(self::get_field_name('content_type'));?>" class="widefat" id="<?php echo esc_attr(self::get_field_id('content_type'));?>" > <?php /** * image type */ echo get_option_list('img',___('Image type'),$instance['content_type']); /** * text type */ echo get_option_list('tx',___('Text type'),$instance['content_type']);?> </select> </p> <p> <label for="<?php echo esc_attr(self::get_field_id('orderby'));?>"> <?php echo esc_html(___('Order by'));?> </label> <select name="<?php echo esc_attr(self::get_field_name('orderby'));?>" class="widefat" id="<?php echo esc_attr(self::get_field_id('orderby'));?>" > <?php /** * orderby views */ if(class_exists('theme_post_views') && theme_post_views::is_enabled()){ echo get_option_list('views',___('Most views'),$instance['orderby']); } /** * orderby thumb-up */ if(class_exists('theme_post_thumb') && theme_post_thumb::is_enabled()){ echo get_option_list('thumb-up',___('Thumb up'),$instance['orderby']); } /** * orderby recommended */ if(class_exists('theme_recommended_post')){ echo get_option_list('recommended',___('Recommended'),$instance['orderby']); } /** * orderby random */ echo get_option_list('random',___('Random'),$instance['orderby']); /** * orderby latest */ echo get_option_list('latest',___('Latest'),$instance['orderby']); ?> </select> </p> <?php } /** * * * @param * @return * @version 1.0.0 * @author KM@INN STUDIO */ private static function get_cat_checkbox_list($name,$id,$selected_cat_ids = array()){ $cats = get_categories(array( 'hide_empty' => false, 'orderby' => 'term_group', 'exclude' => '1', )); ob_start(); if($cats){ foreach($cats as $cat){ if(in_array($cat->term_id,(array)$selected_cat_ids)){ $checked = ' checked="checked" '; $selected_class = ' button-primary '; }else{ $checked = null; $selected_class = null; } ?> <label for="<?php echo $id;?>-<?php echo $cat->term_id;?>" class="item button <?php echo $selected_class;?>"> <input type="checkbox" id="<?php echo esc_attr($id);?>-<?php echo esc_attr($cat->term_id);?>" name="<?php echo esc_attr($name);?>[]" value="<?php echo $cat->term_id;?>" <?php echo $checked;?> /> <?php echo esc_html($cat->name);?> </label> <?php } }else{ ?> <p><?php echo esc_html(___('No category, pleass go to add some categories.'));?></p> <?php } $content = ob_get_contents(); ob_end_clean(); return $content; } function update($new_instance,$old_instance){ $instance = wp_parse_args($new_instance,$old_instance); return $instance; } public static function register_widget(){ register_widget(self::$iden); } }<file_sep>/includes/theme-quick-comment/theme-quick-comment.php <?php /** * @version 1.0.1 */ theme_quick_comment::init(); class theme_quick_comment{ public static $iden = 'theme_quick_comment'; public static $style_id = 'theme-quic-comment'; public static function init(){ add_action('frontend_seajs_use', get_class() . '::frontend_seajs_use'); add_filter('frontend_seajs_alias', get_class() . '::frontend_seajs_alias'); add_action('wp_ajax_' . get_class(), get_class() . '::process'); add_action('wp_ajax_nopriv_' . get_class(), get_class() . '::process'); add_action('pre_comment_on_post', get_class() . '::block_frontend_comment',1); add_action('pre_comment_on_post', get_class() . '::pre_comment_on_post'); } /** * process * @TODO add pagination, add order */ public static function process(){ !check_referer() && wp_die(___('Referer error')); theme_features::check_nonce(); $output = array(); $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : null; $post_id = isset($_REQUEST['post-id']) ? (int)$_REQUEST['post-id'] : null; /** * invail post id */ if(!$post_id){ $output['status'] = 'error'; $output['id'] = 'invalid_post_id'; $output['msg'] = ___('Invail post id.'); die(theme_features::json_format($output)); } /** * closed */ if(!comments_open($post_id)){ $output['status'] = 'error'; $output['id'] = 'comment_closed'; $output['msg'] = ___('This post comment has closed.'); die(theme_features::json_format($output)); } $current_user = wp_get_current_user(); /** * switch $type */ switch($type){ /** * get-respond */ case 'get-respond': $output['status'] = 'success'; $output['logged'] = is_user_logged_in() ? true : false; $output['require_name_email'] = get_option('require_name_email') == 1 ? true : false; if(!is_user_logged_in()){ $output['commenter'] = wp_get_current_commenter(); } break; /** * post-comment */ case 'post-comment': $comment_post_id = isset($_REQUEST['comment-post-id']) ? (int)$_REQUEST['comment-post-id'] : null; do_action('pre_comment_on_post', $comment_post_id); /** check comment parent */ $comment_parent = isset($_REQUEST['comment-parent']) ? (int)$_REQUEST['comment-parent'] : 0; /** check comment post id */ if(!$comment_post_id){ $output['status'] = 'error'; $output['id'] = 'invalid_post_id'; $output['msg'] = ___('Invail post id.'); die(theme_features::json_format($output)); } /** check comment content */ $comment_content = isset($_POST['comment-content']) && trim($_POST['comment-content']) != '' ? trim($_POST['comment-content']) : null; if(!$comment_content){ $output['status'] = 'error'; $output['id'] = 'invalid_comment_content'; $output['msg'] = ___('Invail comment content'); die(theme_features::json_format($output)); } /** * user is logged */ if(is_user_logged_in()){ $comment_author_name = !empty($current_user->display_name) ? $current_user->display_name : $current_user->nickname; $comment_author_name = !empty($comment_author_name) ? $comment_author_name : $current_user->user_login; $comment_author_name = wp_slash($comment_author_name); $comment_author_email = wp_slash($current_user->user_email); $comment_author_url = wp_slash($current_user->user_url); $comment_author_id = $current_user->ID; $output['logged'] = true; /** * visitor */ }else{ $comment_author_name = isset($_POST['comment-name']) ? trim($_POST['comment-name']) : null; if(empty($comment_author_name)) $comment_author_name = wp_slash(___('Anonymous')); $comment_author_email = isset($_POST['comment-email']) ? trim($_POST['comment-email']) : null; $comment_author_url = isset($_POST['comment-url']) ? esc_url($_POST['comment-url']) : null; /** * check name and email required */ if(get_option('require_name_email') == 1 || !empty($comment_author_email)){ /** invail email */ if(!is_email($comment_author_email)){ $output['status'] = 'error'; $output['id'] = 'invalid_email'; $output['msg'] = ___('Invail email address.'); die(theme_features::json_format($output)); } } $comment_author_id = 0; $output['logged'] = false; } $commentdata = array( 'comment_post_ID' => $comment_post_id, 'comment_author' => $comment_author_name, 'comment_author_email' => $comment_author_email, 'comment_author_url' => $comment_author_url, 'comment_content' => $comment_content, 'comment_parent' => $comment_parent, 'user_id' => $comment_author_id, 'comment_type' => '', ); $comment_id = wp_new_comment($commentdata); if($comment_id){ $comment = get_comment($comment_id); $output['status'] = 'success'; $output['comment'] = self::get_comment($comment_id); wp_update_comment_count($comment_post_id); do_action('set_comment_cookies',$comment,$current_user); }else{ $output['status'] = 'error'; $output['id'] = 'create_comment_error'; $output['msg'] = ___('System can not create comment.'); } break; /** * get-comments */ case 'get-comments': /** * get comments */ $comments = get_comments(array( 'post_id' => $post_id, 'order' => 'ASC', 'status' => 'approve', )); /** * if comment is empty */ if(empty($comments)){ $output['status'] = 'error'; $output['id'] = 'no_comment'; $output['msg'] = ___('No comment yet.'); die(theme_features::json_format($output)); } foreach($comments as $comment){ $new_comments[$comment->comment_ID] = apply_filters('api_comment',self::get_comment($comment),$comment); } $output['status'] = 'success'; $output['comments'] = $new_comments; break; default: $output['status'] = 'error'; $output['id'] = 'invalid_type'; $output['msg'] = ___('Invail type'); } die(theme_features::json_format($output)); } /** * Get comment data and output for json * * @param stdClass|int $comment Commen obj or comment id * @return stdClass Comment obj * @version 1.0.1 * @author KM@INN STUDIO */ public static function get_comment($comment){ if(is_int($comment)) $comment = get_comment($comment); $GLOBALS['comment'] = $comment; $new_comment = array( 'comment_id' => get_comment_ID(), 'comment_post_id' => $comment->comment_post_ID, 'comment_author' => array( 'name' => get_comment_author(), 'gravatar' => get_img_source( get_avatar($comment->comment_author_email,40,false,esc_attr($comment->comment_author))), 'url' => $comment->user_id ? get_author_posts_url($comment->user_id) : get_comment_author_url(), 'user_id' => (int)$comment->user_id, ), 'comment_date' => get_comment_time('U'), 'comment_friendly_date' => friendly_date(get_comment_time('U')), 'comment_date_gmt' => $comment->comment_date_gmt, 'comment_content' => get_comment_text(), 'comment_parent' => (int)$comment->comment_parent, 'comment_class' => get_comment_class(null,get_comment_ID(),$comment->comment_post_ID), ); return $new_comment; } /** * Hook block_frontend_comment */ public static function block_frontend_comment($comment_post_ID){ /** do NOT allow Contributor and Subscriber and Visitor to comment */ if(current_user_can('edit_published_posts')) return false; if(strstr(get_current_url(),'wp-comments-post.php') !== false) die(___('Blocked comment from frontend.')); } /** * Hook pre_comment_on_post */ public static function pre_comment_on_post($comment_post_ID){ // var_dump($comment_post_ID);exit; /** * check nonce */ theme_features::check_nonce(); $comment_post_ID = $comment_post_ID ? $comment_post_ID : (isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0); $post = get_post($comment_post_ID); /** * check comment_registration */ $post_status = get_post_status($post); if(get_option('comment_registration') || 'private' == $post_status){ $output['status'] = 'error'; $output['id'] = 'must_be_logged'; $output['msg'] = ___('Sorry, you must be logged in to post a comment.'); die(theme_features::json_format($output)); } /** * check comment_status */ if ( empty( $post->comment_status ) ) { do_action('comment_id_not_found', $comment_post_ID); $output['status'] = 'error'; $output['id'] = 'post_not_exists'; $output['msg'] = ___('Sorry, the post does not exist.'); die(theme_features::json_format($output)); } /** * check */ $status = get_post_status($post); $status_obj = get_post_status_object($status); /** * check comment is closed */ if(!comments_open($comment_post_ID)){ do_action('comment_closed', $comment_post_ID); $output['status'] = 'error'; $output['id'] = 'comment_closed'; $output['msg'] = ___('Sorry, comments are closed for this item.'); die(theme_features::json_format($output)); /** * If the post is trash */ }else if('trash' == $status){ do_action('comment_on_trash', $comment_post_ID); $output['status'] = 'error'; $output['id'] = 'trash_post'; $output['msg'] = ___('Sorry, can not comment on trash post.'); die(theme_features::json_format($output)); /** * If the post is draft */ } else if(!$status_obj->public && !$status_obj->private){ do_action('comment_on_draft', $comment_post_ID); $output['status'] = 'error'; $output['id'] = 'draft_post'; $output['msg'] = ___('Sorry, can not comment draft post.'); die(theme_features::json_format($output)); /** * If the post needs password */ } else if(post_password_required($comment_post_ID)){ do_action('comment_on_password_protected', $comment_post_ID); $output['status'] = 'error'; $output['id'] = 'need_pwd'; $output['msg'] = ___('Sorry, the post needs password to comment.'); die(theme_features::json_format($output)); } } public static function frontend_display(){ global $post; $comment_count = (int)get_comments_number(); $com_hide_class = is_singular() ? null : 'hide'; ?> <dl id="comment-box-<?php echo $post->ID;?>" class="comment-box mod <?php echo $com_hide_class;?>"> <dt class="comment-box-title mod-title"> <?php echo sprintf(___('Total %d comments'),$comment_count);?> <?php if(comments_open()){ ?> <a href="javascript:void(0)" class="add-comment add-comment-top add-comment-<?php echo $post->ID;?>" data-post-id="<?php echo $post->ID;?>"><span class="icon-comment"></span><span class="after-icon"><?php echo ___('Join the comments');?></span></a> <?php } ?> </dt> <dd class="mod-body"> <div class="comment-tip"><?php echo status_tip('loading',___('Loading comment list, please wait...'));?></div> <div class="comments-container"></div> <?php /** * check comment open */ if(comments_open()){ ?> <a href="javascript:void(0)" class="add-comment add-comment-bottom btn add-comment-<?php echo $post->ID;?>" data-post-id="<?php echo $post->ID;?>"><span class="icon-comment"></span><span class="after-icon"><?php echo ___('Join the comments');?></span></a> <?php } ?> </dd> </dl> <?php } public static function frontend_seajs_alias($alias){ $alias[self::$style_id] = theme_features::get_theme_includes_js(__FILE__); return $alias; } public static function frontend_seajs_use(){ // if(is_singular()) return false; ?> seajs.use('<?php echo self::$style_id;?>',function(m){ m.config.process_url = '<?php echo theme_features::get_process_url(array('action' => self::$iden));?>'; <?php if(is_singular()){ ?> m.config.is_singular = true; <?php } ?> m.config.lang.M00001 = '<?php echo ___('Loading, please wait...');?>'; m.config.lang.M00002 = '<?php echo ___('Commented successfully, thank you!');?>'; m.config.lang.M00003 = '<?php echo ___('Message');?>'; m.config.lang.M00004 = '<?php echo ___('No comment yet, you are first commenter.');?>'; m.config.lang.M00005 = '<?php echo ___('Comment');?>'; m.config.lang.M00006 = '<?php echo ___('Post comment');?>'; m.config.lang.M00007 = '<?php echo ___('Nickname');?>'; m.config.lang.M00008 = '<?php echo ___('Email');?>'; m.config.lang.M00009 = '<?php echo ___('Closing tip after 3s');?>'; m.config.lang.M00010 = '<?php echo ___('Reply');?>'; m.config.lang.M00011 = '<?php echo ___('Error');?>'; m.config.lang.E00001 = '<?php echo ___('Server error or network is disconnected.');?>'; m.init(); }); <?php } }<file_sep>/includes/theme-open-sign/static/js/src/init.js define(function(require, exports, module){ var $ = require('modules/jquery'),jQuery = $; exports.config = { open_btn : '.opensign-btn' process_url : '', }; exports.init = function(){ $(document).ready(function(){ }); }; exports.bind = function(){ }; });<file_sep>/includes/theme-clean-up/theme-clean-up.php <?php /* Feature Name: theme_clean_up Feature URI: http://www.inn-studio.com/theme_clean_up Version: 1.0.5 Description: optimizate your database Author: INN STUDIO Author URI: http://www.inn-studio.com */ add_action('advanced_settings','theme_clean_up::admin'); add_action('wp_ajax_theme_clean_up','theme_clean_up::process'); add_action('after_backend_tab_init','theme_clean_up::js'); class theme_clean_up{ private static $iden = 'theme_clean_up'; public static function admin(){ ?> <fieldset> <legend><?php echo ___('Database Optimization');?></legend> <p class="description"><?php echo ___('If your site works for a long time, maybe will have some redundant data in the database, they will reduce the operating speed of the your site, recommend to clean them regularly.');?></p> <p class="description"><strong><?php echo esc_html(___('Attention: this action will be auto clean up all theme cache.'));?></strong></p> <table class="form-table"> <tbody> <tr> <th scope="row"><?php echo ___('Clean redundant post data');?></th> <td> <p><span class="button" id="clean_redundant_posts" data-action="redundant_posts"><?php echo ___('Delete revision &amp; draft &amp; auto-draft &amp; trash posts');?></span></p> <p><span class="button" id="clean_orphan_postmeta" data-action="orphan_postmeta"><?php echo ___('Delete orphan post meta');?></span></p> </td> </tr> <tr> <th scope="row"><?php echo ___('Clean redundant comment data');?></th> <td> <p><span class="button" id="clean_redundant_comments" data-action="redundant_comments"><?php echo ___('Delete moderated &amp; spam &amp; trash comments');?></span></p> <p><span class="button" id="clean_orphan_commentmeta" data-action="orphan_commentmeta"><?php echo ___('Delete orphan comment meta');?></span></p> </td> </tr> <tr> <th scope="row"><?php echo ___('Clean redundant other data');?></th> <td> <p><span class="button" id="clean_orphan_relationships" data-action="orphan_relationships"><?php echo ___('Delete orphan relationship');?></span></p> </td> </tr> <tr> <th scope="row"><?php echo ___('Optimizate the WP Database');?></th> <td> <p><span class="button" id="database_optimization" data-action="optimizate"><?php echo ___('Optimizate Now');?></span></p> </td> </tr> </tbody> </table> </fieldset> <?php } public static function process(){ $output = null; $type = isset($_GET['type']) ? $_GET['type'] : null; if($type){ timer_start(); global $wpdb; switch($type){ /** * revision */ case 'redundant_posts': $sql = $wpdb->prepare( " DELETE posts,term,postmeta FROM `$wpdb->posts`posts LEFT JOIN `$wpdb->term_relationships` term ON (posts.ID = term.object_id) LEFT JOIN `$wpdb->postmeta` postmeta ON (posts.ID = postmeta.post_id) WHERE posts.post_type = '%s' OR posts.post_status = '%s' OR posts.post_status = '%s' OR posts.post_status = '%s' ", 'revision', 'draft', 'auto-draft', 'trash' ); break; /** * edit_lock */ case 'orphan_postmeta': $sql = $wpdb->prepare( " DELETE FROM `$wpdb->postmeta` WHERE `meta_key` = '%s' OR `post_id` NOT IN (SELECT `ID` FROM `$wpdb->posts`) ", '_edit_lock' ); break; /** * moderated */ case 'redundant_comments': $sql = $wpdb->prepare( " DELETE FROM `$wpdb->comments` WHERE `comment_approved` = '%s' OR `comment_approved` = '%s' OR `comment_approved` = '%s' ", '0','spam','trash' ); break; /** * commentmeta */ case 'orphan_commentmeta': $sql = " DELETE FROM `$wpdb->commentmeta` WHERE `comment_ID` NOT IN (SELECT `comment_ID` FROM `$wpdb->comments`) "; break; /** * relationships */ case 'orphan_relationships': $sql = $wpdb->prepare( " DELETE FROM `$wpdb->term_relationships` WHERE `term_taxonomy_id` = %d AND `object_id` NOT IN (SELECT `id` FROM `$wpdb->posts`) ", 1 ); break; /** * optimizate */ case 'optimizate': $sql = 'SHOW TABLE STATUS FROM `'.DB_NAME.'`'; $results = $wpdb->get_results($sql); foreach($results as $v){ $sql = 'OPTIMIZE TABLE '.$v->Name; $wpdb->get_results($sql); } break; default: $output['status'] = 'error'; $output['des']['content'] = ___('No param'); die(theme_features::json_format($output)); } if($type !== 'optimizate') $wpdb->query($sql); theme_cache::cleanup(); $time = timer_stop(); $output['status'] = 'success'; $output['des']['content'] = sprintf(___('Database updated in %s s.'),$time); } die(theme_features::json_format($output)); } public static function js(){ ?> seajs.use('<?php echo theme_features::get_theme_includes_js(__FILE__);?>',function(m){ m.config.process_url = '<?php echo theme_features::get_process_url(array('action'=>get_class()));?>'; m.config.lang.M00001 = '<?php echo ___('Loading, please wait...');?>'; m.config.lang.E00001 = '<?php echo ___('Server error or network is disconnected.');?>'; m.init(); }); <?php } } ?><file_sep>/includes/theme-gravatar-fix/theme-gravatar-fix.php <?php /* Plugin Name: Gravatar fix Plugin URI: http://inn-studio.com/gravatar-fix Description: A simple and easy way to fix your gravatar can not be show in China. Replace by eqoe.cn. Author: INN STUDIO Author URI: http://inn-studio.com Version: 1.0.3 */ if(!class_exists('theme_gravatar_fix')){ add_filter('get_avatar', 'theme_gravatar_fix::get_gravatar'); class theme_gravatar_fix{ public static function get_gravatar($avatar){ // $avatar = '<img src="http://1.gravatar.com/gravatar/724f95667e2fbe903ee1b4cffcae3b25?s=40&d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D40&r=G" title="" width="" height="" alt=""/>'; // $avatar = '<img src="https://secure.gravatar.com/gravatar/724f95667e2fbe903ee1b4cffcae3b25?s=40&d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D40&r=G" title="" width="" height="" alt=""/>'; $pattern = '!src=["|\'](.*?)["|\']!'; preg_match_all($pattern, $avatar, $matches); if(!isset($matches[1][0])) return $avatar; /** if is SSL */ if(strpos($matches[1][0],'https://') === 0){ $avatar = preg_replace('/(\d)?(secure)?([a-z]{0,2})\.gravatar\.com/i', 'ssl-gravatar.eqoe.cn', $avatar); /** Not SSL */ }else{ $avatar = preg_replace('/(\d)?(secure)?([a-z]{0,2})\.gravatar\.com/i', 'gravatar.eqoe.cn', $avatar); } $avatar = str_ireplace( array('d=','/gravatar/'), array('nodefault=','/avatar/'), $avatar ); return $avatar; } } }<file_sep>/footer.php <footer id="footer"> <div class="grid-container"> <div class="widget-area"> <?php if(!theme_cache::dynamic_sidebar('widget-area-footer')){ ?> <div class="grid-25 tablet-grid-25 mobile-grid-100"><?php the_widget('WP_Widget_Recent_Posts');;?></div> <div class="grid-25 tablet-grid-25 mobile-grid-100"><?php the_widget('WP_Widget_Tag_Cloud');;?></div> <div class="grid-25 tablet-grid-25 mobile-grid-100"><?php the_widget('WP_Widget_Meta');;?></div> <div class="grid-25 tablet-grid-25 mobile-grid-100"><?php the_widget('WP_Widget_Categories');;?></div> <?php } ?> </div> <p class="footer-meta copyright"> <?php echo sprintf(___('Copyright &copy; %s %s.'),'<a href="' . esc_url(home_url()) . '">' .esc_html(get_bloginfo('name')) . '</a>',esc_html(current_time('Y')));?> <?php echo sprintf(___('Theme %s by %s.'),'<a href="' . esc_url(theme_features::get_theme_info('ThemeURI')) . '" target="_blank" rel="nofollow">' . theme_features::get_theme_info('name') . '</a>','<a href="http://inn-studio.com" target="_blank" rel="nofollow">' . esc_html(___('INN STUDIO')) . '</a>');?> <?php echo sprintf(___('Powered by %s.'),'<a href="http://www.wordpress.org" target="_blank" rel="nofollow">WordPress</a>');?> </p> </div> </footer> <div id="qrcode" class="hide-no-js hide-on-tablet hide-on-mobile" title="<?php echo ___('Click to show QR code for this page');?>"> <div id="qrcode-box"></div> <div id="qrcode-zoom" class="hide"> <div id="qrcode-zoom-code"></div> <h3><?php echo ___('Scan the QR code to visit this page');?></h3> </div> </div> <?php wp_footer();?> </body></html><file_sep>/includes/theme-login-with-email/theme-login-with-email.php <?php theme_login_with_email::init(); class theme_login_with_email { private static $iden = 'theme-login-with-email'; public static function init(){ add_filter('authenticate',get_class() . '::authenticate', 20, 3); } public static function authenticate($user, $username, $password){ if(is_email($username)){ $user = get_user_by('email',$username); if($user) $username = $user->user_login; } return wp_authenticate_username_password(null,$username,$password); } } <file_sep>/includes/_theme-custom-sign/theme-custom-sign.php <?php /** * sign */ theme_custom_sign::init(); class theme_custom_sign{ public static $iden = 'theme_custom_sign'; public static $page_slug = 'sign'; public static $pages = array(); public static function init(){ /** filter */ add_filter('login_headerurl', get_class() . '::filter_login_headerurl',1); add_filter('query_vars', get_class() . '::filter_query_vars'); add_filter('frontend_seajs_alias', get_class() . '::frontend_seajs_alias'); /** action */ add_action('admin_init', get_class() . '::action_not_allow_login_backend',1); add_action('init', get_class() . '::page_create'); add_action('template_redirect', get_class() . '::template_redirect'); add_action('frontend_seajs_use', get_class() . '::frontend_seajs_use'); add_action('wp_ajax_nopriv_theme_quick_sign', 'theme_quick_sign::process'); add_filter('show_admin_bar', get_class() . '::action_show_admin_bar'); } public static function filter_login_headerurl($login_header_url){ // if(current_user_can('moderate_comments')) return $login_header_url; wp_safe_redirect(get_permalink(get_page_by_path(self::$page_slug))); die(); } public static function action_show_admin_bar(){ if(!current_user_can('manage_options')) return false; } public static function action_not_allow_login_backend(){ /** * if in backend */ if(!defined('DOING_AJAX')||!DOING_AJAX){ /** * if not administrator and not ajax,redirect to */ if(!current_user_can('moderate_comments')){ global $current_user; get_currentuserinfo(); wp_safe_redirect(get_author_posts_url($current_user->ID)); die(); } } } public static function filter_query_vars($vars){ if(!in_array('tab',$vars)) $vars[] = 'tab'; if(!in_array('return',$vars)) $vars[] = 'return'; if(!in_array('step',$vars)) $vars[] = 'step'; return $vars; } public static function get_tabs($key = null){ $baseurl = get_permalink(get_page_by_path(self::$page_slug)); $return_url = get_query_var('return'); if($return_url){ $baseurl = add_query_arg(array( 'return' => $return_url ),$baseurl); } $tabs = array( 'login' => array( 'text' => ___('Login'), 'icon' => 'user', 'url' => add_query_arg(array( 'tab' => 'login' ),$baseurl), ), 'register' => array( 'text' => ___('Register'), 'icon' => 'user-add', 'url' => add_query_arg(array( 'tab' => 'register' ),$baseurl), ), 'recover' => array( 'text' => ___('Recover password'), 'icon' => 'help', 'url' => add_query_arg(array( 'tab' => 'recover' ),$baseurl), ), ); if($key){ return isset($tabs[$key]) ? $tabs[$key] : false; }else{ return $tabs; } } public static function template_redirect(){ if(is_page(self::$page_slug) && is_user_logged_in()){ $return = get_query_var('return'); $return ? wp_redirect($return) : wp_redirect(home_url()); } } public static function page_create(){ if(!current_user_can('manage_options')) return false; $page_slugs = array( self::$page_slug => array( 'post_content' => '[' . self::$page_slug . ']', 'post_name' => self::$page_slug, 'post_title' => ___('Sign'), 'page_template' => 'page-' . self::$page_slug . '.php', ) ); $defaults = array( 'post_content' => '[post_content]', 'post_name' => null, 'post_title' => null, 'post_status' => 'publish', 'post_type' => 'page', 'comment_status' => 'closed', ); foreach($page_slugs as $k => $v){ $page = get_page_by_path($k); if(!$page){ $r = wp_parse_args($v,$defaults); $page_id = wp_insert_post($r); // $page = get_post($page_id); } // self::$pages[$k] = $page; } } public static function process(){ $output = array(); theme_features::check_referer(); theme_features::check_nonce(); $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : null; die(theme_features::json_format($output)); } public static function frontend_seajs_alias($alias){ if(is_user_logged_in() || !is_page(self::$page_slug)) return $alias; $alias[self::$iden] = theme_features::get_theme_includes_js(__FILE__); return $alias; } public static function frontend_seajs_use(){ if(is_user_logged_in() || !is_page(self::$page_slug)) return false; ?> seajs.use('<?php echo self::$iden;?>',function(m){ m.config.process_url = '<?php echo theme_features::get_process_url(array('action' => theme_quick_sign::$iden));?>'; m.config.lang.M00001 = '<?php echo esc_js(___('Loading, please wait...'));?>'; m.config.lang.E00001 = '<?php echo esc_js(___('Sorry, server error please try again later.'));?>'; m.init(); }); <?php } }<file_sep>/includes/theme-widget-comments/theme-widget-comments.php <?php /* Feature Name: widget_comments Feature URI: http://www.inn-studio.com Version: 1.0.3 Description: widget_comments Author: INN STUDIO Author URI: http://www.inn-studio.com */ add_action('widgets_init','widget_comments::register_widget'); class widget_comments extends WP_Widget{ public static $iden = 'widget_comments'; public static $avatar_size = 40; function __construct(){ $this->alt_option_name = self::$iden; parent::__construct( self::$iden, ___('Latest comments <small>(Custom)</small>'), array( 'classname' => self::$iden, 'description'=> ___('Show the latest comments'), ) ); } function widget($args,$instance){ extract($args); echo $before_widget; $comments = get_comments(array( 'status' => 'approve', 'number' => isset($instance['number']) ? (int)$instance['number'] : 6 )); if(!empty($instance['title'])){ echo $before_title; ?> <span class="icon-comment"></span><span class="after-icon"><?php echo esc_html($instance['title']);?></span> <?php echo $after_title; } if(!empty($comments)){ global $comment; $comment_bak = $comment; ?> <ul class="lastest-comments"> <?php foreach($comments as $comment){ ?> <li> <a href="<?php echo esc_url(get_permalink($comment->comment_post_ID));?>#comment-<?php echo $comment->comment_ID;?>" title="<?php echo esc_attr(get_the_title($comment->comment_post_ID));?>"> <img class="avatar" data-original="<?php echo esc_url(get_img_source(get_avatar(get_comment_author_email())));?>" src="data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" alt="<?php echo esc_attr(get_comment_author());?>" width="<?php echo self::$avatar_size;?>" height="<?php echo self::$avatar_size;?>"/> <div class="tx"> <h3> <span class="author"><?php echo esc_html(get_comment_author());?></span> <time datetime="<?php echo esc_attr(get_comment_time('c'));?>"> <small><?php echo esc_html(friendly_date(get_comment_time('U')));?></small> </time> </h3> <p class="comment-content" href="<?php echo esc_url(get_permalink($comment->comment_post_ID));?>"><?php comment_text();?></p> </div> </a> </li> <?php } ?> </ul> <?php $comment = $comment_bak; }else{ ?> <div class="lastest-comments"> <?php echo status_tip('info',esc_html(___('No any comment yet.')));?> </div> <?php } echo $after_widget; } function form($instance){ $instance = wp_parse_args( (array)$instance, array( 'title' => ___('Latest comments'), 'number' => 6 ) ); ?> <p> <label for="<?php echo esc_attr(self::get_field_id('title'));?>"><?php echo esc_html(___('Title (optional)'));?></label> <input id="<?php echo esc_attr(self::get_field_id('title'));?>" class="widefat" name="<?php echo esc_attr(self::get_field_name('title'));?>" type="text" value="<?php echo esc_attr($instance['title']);?>" placeholder="<?php echo esc_attr(___('Title (optional)'));?>" /> </p> <p> <label for="<?php echo esc_attr(self::get_field_id('number'));?>"><?php echo esc_html(___('Comments number'));?></label> <input type="number" name="<?php echo esc_attr(self::get_field_name('number'));?>" id="<?php echo esc_attr(self::get_field_id('number'));?>" class="widefat" value="<?php echo (int)$instance['number'];?>"/> </p> <?php } function update($new_instance,$old_instance){ $instance = wp_parse_args($new_instance,$old_instance); return $instance; } public static function register_widget(){ register_widget(self::$iden); } } <file_sep>/includes/_theme-quick-sign/theme-quick-sign.php <?php /** * Theme quick sign * * @version 1.0.0 * @author KM@INN STUDIO */ theme_quick_sign::init(); class theme_quick_sign{ public static $iden = 'theme_quick_sign'; public static function init(){ /** filter */ add_filter('cache-request', get_class() . '::cache_request'); add_filter('frontend_seajs_alias', get_class() . '::frontend_seajs_alias'); /** action */ // add_action('profile_update', get_class() . '::action_user_register'); // add_action('user_register', get_class() . '::action_user_register'); add_action('frontend_seajs_use', get_class() . '::frontend_seajs_use'); add_action('wp_ajax_' . get_class(), get_class() . '::process'); add_action('wp_ajax_nopriv_' . get_class(), get_class() . '::process'); } public static function cache_request($datas){ if(is_user_logged_in()){ global $current_user; get_currentuserinfo(); $datas['user'] = array( 'logged' => true, 'display_name' => $current_user->display_name, 'posts_url' => get_author_posts_url($current_user->ID), 'logout_url' => wp_logout_url(home_url()), 'avatar_url' => get_avatar($current_user->user_email), ); }else{ $datas['user'] = array( 'logged' => false, ); } return $datas; } public static function process(){ theme_features::check_nonce(); theme_features::check_referer(); $output = array(); $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : null; $user = isset($_POST['user']) ? $_POST['user'] : false; $email = (isset($user['email']) && is_email($user['email'])) ? $user['email'] : null; $pwd = isset($user['pwd']) ? $user['pwd'] : null; switch($type){ /** * login */ case 'login': $output = self::user_login(array( 'email' => $email, 'pwd' => <PASSWORD>, 'remember' => isset($user['remember']) ? true : false, )); if($output['status'] === 'success'){ $output['msg'] = ___('Login successfully, page is refreshing, please wait...'); }else{ die(theme_features::json_format($output)); } break; /** * register */ case 'register': $repwd = isset($user['pwd-again']) ? $user['pwd-again'] : null; $at_least_len = 2; if($pwd !== $repwd){ $output['status'] = 'error'; $output['id'] = 'pwd_not_match'; $output['msg'] = ___('Sorry, twice password does not match, please try again'); die(theme_features::json_format($output)); }else if(!isset($user['nickname']) || mb_strlen($user['nickname']) < $at_least_len){ $output['status'] = 'error'; $output['id'] = 'invalid_nickname'; $output['msg'] = sprintf(___('Sorry, you nick name is invalid, at least %d characters in length, please try again.'),$at_least_len); die(theme_features::json_format($output)); }else{ $output = self::user_register(array( 'email' => $email, 'pwd' => <PASSWORD>, 'nickname' => $user['nickname'], 'remember' => true, )); if($output['status'] === 'success'){ // $output['redirect'] = $output['msg'] = ___('Register successfully, page is refreshing, please wait...'); } } break; /** * lost-password */ case 'recover': if(!is_email($email)){ $output['status'] = 'error'; $output['id'] = 'invalid_email'; $output['msg'] = ___('Sorry, your email address is invalid, please check it and try again.'); die(theme_features::json_format($output)); } /** * check the email is exist */ $user_id = email_exists($email); if(!$user_id){ $output['status'] = 'error'; $output['id'] = 'email_not_exist'; $output['msg'] = ___('Sorry, the email does not exist.'); die(theme_features::json_format($output)); } /** * create and encode code */ $user = get_userdata($user_id); $encode_arr = array( 'user_id' => $user_id, 'user_email' => $user->user_email, ); $encode_str = serialize($encode_arr); $encode = authcode($encode_str,'encode',AUTH_KEY,7200); $callback_url = add_query_arg(array( 'step' => 'reset-pwd', 'token' => $encode, ),get_permalink(get_page_by_path(theme_custom_sign::$page_slug))); // $callback_url = theme_features::get_process_url(array( // 'action' => self::$ajax_lost_password, // 'token' => $encode, // )); $content = ' <h3>' . sprintf(___('Dear %s!'),$user->display_name) . '</h3> <p> ' . sprintf(___('You are receiving this email because you forgot your password. We already made an address for your account, you can access this address ( %s ) to log-in and change your password in 3 hours.'),'<a href="' . $callback_url . '" target="_blank">' . $callback_url . '</a>') . ' </p> <p>' . sprintf(___('-- From %s'),'<a href="' . home_url() . '" target="_blank">' . get_bloginfo('name') . '</a>') . '</p> '; $title = ___('You are applying to retrieve your password.'); // $phpmailer = new theme_phpmailer(); // $phpmailer->FromName = ___('Notification'); // $wp_mail = $phpmailer->send( // $user->user_email, // $title, // $content // ); add_filter( 'wp_mail_content_type',get_class() . '::set_html_content_type'); $wp_mail = wp_mail( $user->user_email, $title, $content ); remove_filter( 'wp_mail_content_type',get_class() . '::set_html_content_type'); /** * check wp_mail is success or not */ // if($wp_mail['status'] == 'success'){ if($wp_mail === true){ update_user_meta($user_id,'_tmp_lost_pwd',1); $output['status'] = 'success'; $output['msg'] = ___('Success, we sent an email that includes how to retrieve your password, please check it out in 3 hours.'); }else{ $output['status'] = 'error'; $output['id'] = 'server_error'; $output['detial'] = $wp_mail['msg']; $output['msg'] = ___('Error, server can not send email, please contact the administrator.'); } break; /** * reset */ case 'reset': $post_user = isset($_POST['user']) ? $_POST['user'] : null; if(!$post_user){ $output['status'] = 'error'; $output['id'] = 'invalid_param'; $output['msg'] = ___('Invalid param.'); die(theme_features::json_format($output)); } /** email */ $post_email = isset($post_user['email']) ? $post_user['email'] : null; if(!is_email($post_user['email'])){ $output['status'] = 'error'; $output['id'] = 'invalid_email'; $output['msg'] = ___('Invalid email.'); die(theme_features::json_format($output)); } /** pwd */ $post_pwd_new = isset($post_user['pwd-new']) ? $post_user['pwd-new'] : null; $post_pwd_again = isset($post_user['pwd-again']) ? $post_user['pwd-again'] : null; if(empty($post_pwd_new) || empty($post_pwd_again) || $post_pwd_new !== $post_pwd_again){ $output['status'] = 'error'; $output['id'] = 'invalid_twice_pwd'; $output['msg'] = ___('Invalid twice password.'); die(theme_features::json_format($output)); } /** token */ $post_token = isset($post_user['token']) ? $post_user['token'] : null; if(empty($post_token)){ $output['status'] = 'error'; $output['id'] = 'empty_token'; $output['msg'] = ___('Empty token.'); die(theme_features::json_format($output)); } /** decode token */ $token_decode = authcode($post_token,'decode',AUTH_KEY); if(!$token_decode){ $output['status'] = 'error'; $output['id'] = 'expired_token'; $output['msg'] = ___('This token is expired.'); die(theme_features::json_format($output)); } /** unserialize token */ $token_arr = @unserialize($token_decode); if(!$token_arr || !is_array($token_arr)){ $output['status'] = 'error'; $output['id'] = 'invalid_token'; $output['msg'] = ___('This token is expired.'); die(theme_features::json_format($output)); } $token_user_id = isset($token_arr['user_id']) ? (int)$token_arr['user_id'] : null; $token_user_email = isset($token_arr['user_email']) ? $token_arr['user_email'] : null; /** check token email is match post email */ if($token_user_email != $post_email){ $output['status'] = 'error'; $output['id'] = 'token_email_not_match'; $output['msg'] = ___('The token email and you account email do not match.'); die(theme_features::json_format($output)); } /** check post email exists */ $user_id = (int)email_exists($post_email); if(!$user_id){ $output['status'] = 'error'; $output['id'] = 'email_not_exist'; $output['msg'] = ___('Sorry, your account email is not exist.'); } /** check user already apply to recover password */ if(!get_user_meta($user_id,'_tmp_recover_pwd',true)){ $output['status'] = 'error'; $output['id'] = 'not_apply_recover'; $output['msg'] = ___('Sorry, the user do not apply recover yet.'); } /** all ok, just set new password */ delete_user_meta($user_id,'_tmp_recover_pwd'); wp_set_password($post_pwd_new,$user_id); wp_set_current_user($user_id); wp_set_auth_cookie($user_id,true); $output['status'] = 'success'; $output['redirect'] = home_url(); $output['msg'] = ___('Congratulation, your account has been recovered! Password has been updated. Redirecting home page, please wait...'); break; default: $output['status'] = 'error'; $output['id'] = 'invalid_type'; $output['msg'] = ___('Invalid type.'); } die(theme_features::json_format($output)); } /** * hook to pre_user_nicename */ public static function action_user_register($user_id){ wp_update_user(array( 'ID' => $user_id, 'user_nicename' => $user_id )); } /** * user_login */ public static function user_login($args){ $defaults = array( 'email' => null, 'pwd' => <PASSWORD>, 'remember' => false, ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); // var_dump($pwd);exit; if(!$pwd){ $output['status'] = 'error'; $output['id'] = 'invalid_pwd'; $output['msg'] = ___('Sorry, password is invalid, please try again.'); }else if(!is_email($email)){ $output['status'] = 'error'; $output['id'] = 'invalid_email'; $output['msg'] = ___('Sorry, email is invalid, please try again.'); }else{ $creds = array(); $creds['user_login'] = $email; $creds['user_password'] = $pwd; $creds['remember'] = $remember; $user = wp_signon( $creds ); if(is_wp_error($user)){ $output['status'] = 'error'; $output['id'] = 'email_pwd_not_match'; $output['msg'] = ___('Sorry, your email and password do not match, please try again.'); }else{ $output['status'] = 'success'; } } return $output; } /** * user_register */ public static function user_register($args){ $defaults = array( 'email' => null, 'pwd' => <PASSWORD>, 'nickname' => null, 'remember' => true, ); $r = wp_parse_args($args,$defaults); extract($r,EXTR_SKIP); if(!$pwd){ $output['status'] = 'error'; $output['msg'] = ___('Sorry, password is invalid, please try again.'); $output['id'] = 'invalid_pwd'; }else if(!is_email($email)){ $output['status'] = 'error'; $output['msg'] = ___('Sorry, email is invalid, please try again.'); $output['id'] = 'invalid_email'; }else if(!trim($nickname) || !validate_username($nickname)){ $output['status'] = 'error'; $output['id'] = 'invalid_nickname'; $output['msg'] = ___('Sorry, nickname is invalid, please try again.'); /** * check email exists */ }else if(email_exists($email)){ $output['status'] = 'error'; $output['id'] = 'email_exists'; $output['msg'] = ___('Sorry, email already exists, please change another one and try again.'); }else{ /** * create user and get user id */ $user_data = array( 'user_login' => sanitize_user($nickname), 'user_pass' => <PASSWORD>, 'nickname' => $nickname, 'display_name' => $nickname, 'user_email' => $email, ); $user_id = wp_insert_user($user_data); if(is_wp_error($user_id)){ $output['status'] = 'error'; $output['id'] = $user_id->get_error_code(); $output['msg'] = $user_id->get_error_message(); }else{ /** rename nicenian */ wp_update_user(array( 'ID' => $user_id, 'user_nicename' => $user_id )); /** * go to login */ $output = self::user_login(array( 'email' => $email, 'pwd' => <PASSWORD>, 'remember' => $remember )); } } return $output; } /** * set_html_content_type */ public static function set_html_content_type(){ return 'text/html'; } public static function frontend_seajs_alias($alias){ $alias[self::$iden] = theme_features::get_theme_includes_js(__FILE__); return $alias; } public static function frontend_seajs_use(){ ?> seajs.use('<?php echo self::$iden;?>',function(m){ m.config.process_url = '<?php echo theme_features::get_process_url(array('action' => self::$iden));?>'; m.config.recover_pwd_url = '<?php echo esc_url(theme_custom_sign::get_tabs('recover')['url']);?>'; m.config.lang.M00001 = '<?php echo esc_js(___('Loading, please wait...'));?>'; m.config.lang.M00002 = '<?php echo esc_js(___('Login'));?>'; m.config.lang.M00003 = '<?php echo esc_js(___('Register'));?>'; m.config.lang.M00004 = '<?php echo esc_js(___('Nickname'));?>'; m.config.lang.M00005 = '<?php echo esc_js(___('Email'));?>'; m.config.lang.M00006 = '<?php echo esc_js(___('Password'));?>'; m.config.lang.M00007 = '<?php echo esc_js(___('Re-type password'));?>'; m.config.lang.M00008 = '<?php echo esc_js(___('Login / Register'));?>'; m.config.lang.M00009 = '<?php echo esc_js(___('Remember me'));?>'; m.config.lang.M00010 = '<?php echo esc_js(sprintf(___('Login successful, closing tip after %d seconds.'),3));?>'; m.config.lang.M00011 = '<?php echo esc_js(___('Login successful, page is refreshing, please wait..'));?>'; m.config.lang.M00012 = '<?php echo esc_js(___('Forgot my password?'));?>'; m.config.lang.E00001 = '<?php echo esc_js(___('Server error or network is disconnected.'));?>'; m.init(); }); <?php } }<file_sep>/includes/theme-min-rebuild/theme-min-rebuild.php <?php /* Feature Name: theme_min_rebuild Feature URI: http://www.inn-studio.com Version: 1.0.2 Description: Rebuild the minify version file of JS and CSS. If you have edit JS or CSS file. Author: INN STUDIO Author URI: http://www.inn-studio.com */ add_action('base_settings','theme_min_rebuild::admin',90); add_action('wp_ajax_theme_min_rebuild','theme_min_rebuild::process'); class theme_min_rebuild{ private static $iden = 'theme_min_rebuild'; /** * Admin Display */ public static function admin(){ $options = theme_options::get_options(); $process_param = array( 'action' => 'theme_min_rebuild', 'return_url' => get_current_url() . '&theme_min_rebuild=1' ); $process_url = theme_features::get_process_url($process_param); ?> <!-- theme_min_rebuild --> <fieldset> <legend><?php echo ___('Rebuild minify version');?></legend> <p class="description"><?php echo ___('Rebuild the minify version file of JS and CSS. If you have edit JS or CSS file, please run it. May take several minutes.');?></p> <table class="form-table"> <tbody> <tr> <th scope="row"><?php echo ___('Control');?></th> <td> <?php if(isset($_GET['theme_min_rebuild'])){ echo status_tip('success',___('Files have been rebuilt.')); } ?> <p> <a href="<?php echo $process_url;?>" class="button" onclick="javascript:this.innerHTML='<?php echo ___('Rebuilding, please wait...');?>'"><?php echo ___('Start rebuild');?></a> <span class="description"><?php echo ___('Save your settings before rebuild');?></span> </p> </td> </tr> </tbody> </table> </fieldset> <?php } /** * process */ public static function process(){ $output = null; if(isset($_GET['action']) && $_GET['action'] === 'theme_min_rebuild' && isset($_GET['return_url'])){ ini_set('max_input_nesting_level','10000'); ini_set('max_execution_time','300'); remove_dir(get_stylesheet_directory() . theme_features::$basedir_js_min); remove_dir(get_stylesheet_directory() . theme_features::$basedir_css_min); theme_features::minify_force(get_stylesheet_directory() . theme_features::$basedir_js_src); theme_features::minify_force(get_stylesheet_directory() . theme_features::$basedir_css_src); theme_features::minify_force(get_stylesheet_directory() . theme_features::$basedir_includes); header('Location: ' .$_GET['return_url']); } die(theme_features::json_format($output)); } } ?><file_sep>/includes/theme-setting-import/theme-setting-import.php <?php /* Feature Name: theme_import_settings Feature URI: http://www.inn-studio.com Version: 1.0.3 Description: theme_import_settings Author: INN STUDIO Author URI: http://www.inn-studio.com */ add_action('wp_ajax_tis_download','theme_import_settings::process'); add_action('wp_ajax_tis_upload','theme_import_settings::process'); add_action('after_backend_tab_init','theme_import_settings::js'); add_action('backend_css','theme_import_settings::style'); add_action('advanced_settings','theme_import_settings::admin',99); class theme_import_settings{ public static $iden = 'theme_import_settings'; public static function admin(){ $options = theme_options::get_options(); ?> <fieldset> <legend><?php echo ___('Import & Export Theme Settings');?></legend> <p class="description"> <?php echo ___('You can select the settings file to upload and restore settings if you have the *.txt file. If you want to export the settings backup, please click the export button.');?> </p> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php echo ___('Import: ');?> </th> <td> <div id="tis_tip"></div> <div id="tis_upload_area"> <a href="javascript:void(0);" id="tis_upload" class="button"><?php echo ___('Select a setting file to restore');?></a> <input id="tis_file" type="file"/> </div> </td> </tr> <tr> <th scope="row"> <?php echo ___('Export: ');?> </th> <td> <a href="<?php echo theme_features::get_process_url(array('action'=>'tis_download'));?>" id="tis_export" class="button"><?php echo ___('Start export settings file');?></a> </td> </tr> </tbody> </table> </fieldset> <?php } /** * Process * * * @return * @version 1.0.0 * @author KM@INN STUDIO * */ public static function process(){ $output = null; /** * tis_upload */ if(isset($_GET['action']) && $_GET['action'] === 'tis_upload'){ /** * is administrator */ if(current_user_can('administrator')){ $contents = isset($_POST['tis_content']) ? @unserialize(base64_decode($_POST['tis_content'])) : null; if(is_array($contents) && !empty($contents)){ update_option('theme_options',$contents); $output['status'] = 'success'; $output['des']['content'] = ___('Settings has been restored, refreshing page, please wait... '); /** * invalid contents */ }else{ $output['status'] = 'error'; $output['des']['content'] = ___('Invalid content. '); } /** * invalid user */ }else{ $output['status'] = 'error'; $output['des']['content'] = ___('Invalid user. '); } } /** * download */ if(isset($_GET['action']) && $_GET['action'] === 'tis_download'){ if(current_user_can('administrator')){ $options = theme_options::get_options(); $contents = base64_encode(serialize($options)); /** * write content to a tmp file */ $tmp = tempnam('/tmp','tis'); $handle = fopen($tmp,"w"); fwrite($handle,$contents); fclose($handle); /** * output file download */ header('Content-type: application/txt'); $download_fn = str_ireplace('http://','',home_url()); $download_fn = str_ireplace('https://','',$download_fn); $download_fn = str_ireplace('/','-',$download_fn); $download_fn = $download_fn . '.' . date('Ydm') . '.txt'; header('Content-Disposition: attachment; filename=" ' . $download_fn . '"'); readfile($tmp); unlink($tmp); exit; $output['status'] = 'success'; $output['des']['content'] = ___('Settings has been restored, refreshing page, please wait... '); }else{ $output['status'] = 'error'; $output['des']['content'] = ___('Invalid user. '); } } die(theme_features::json_format($output)); } /** * Load style * * * @return string HTML * @version 1.0.0 * @author KM@INN STUDIO * */ public static function style(){ ?> <link href="<?php echo theme_features::get_theme_includes_css(__FILE__);?>" rel="stylesheet" media="all"/> <?php } /** * Load js * * * @return * @version 1.0.0 * @author KM@INN STUDIO * */ public static function js(){ ?> seajs.use('<?php echo theme_features::get_theme_includes_js(__FILE__);?>',function(m){ m.config.lang.M00001 = '<?php echo ___('Processing, please wait...');?>'; m.config.lang.M00002 = '<?php echo ___('Error: Your browser does not support HTML5. ');?>'; m.config.lang.E00001 = '<?php echo ___('Error: failed to complete the operation. ');?>'; m.config.lang.E00002 = '<?php echo ___('Error: Not match file. ');?>'; m.config.process_url = '<?php echo theme_features::get_process_url();?>'; m.init(); }); <?php } } ?> <file_sep>/includes/theme-post-copyright/theme-post-copyright.php <?php /* Feature Name: Post Copyright Feature URI: http://www.inn-studio.com Version: 1.1.0 Description: Your post notes on copyright information, although this is not very rigorous. Author: INN STUDIO Author URI: http://www.inn-studio.com */ theme_post_copyright::init(); class theme_post_copyright{ private static $iden = 'theme_post_copyright'; public static function init(){ add_action('page_settings',get_class() . '::admin'); add_filter('theme_options_default',get_class() . '::options_default'); add_filter('theme_options_save',get_class() . '::save'); } public static function admin(){ $options = theme_options::get_options(); $code = isset($options[self::$iden]['code']) ? stripslashes($options[self::$iden]['code']) : null; $is_checked = isset($options[self::$iden]['on']) ? ' checked ' : null; ?> <fieldset> <legend><?php echo ___('Post Copyright Settings');?></legend> <p class="description"> <?php echo ___('Posts copyright settings maybe protect your word. Here are some keywords that can be used:');?></p> <p class="description"> <input type="text" class="small-text text-select" value="%post_title_text%" title="<?php echo ___('Post Title text');?>" readonly="true"/> <input type="text" class="small-text text-select" value="%post_url%" title="<?php echo ___('Post URL');?>" readonly="true"/> <input type="text" class="small-text text-select" value="%blog_name%" title="<?php echo ___('Blog name');?>" readonly="true"/> <input type="text" class="small-text text-select" value="%blog_url%" title="<?php echo ___('Blog URL');?>" readonly="true"/> </p> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="<?php echo self::$iden;?>_on"><?php echo ___('Enable or not?');?></label></th> <td><input type="checkbox" name="<?php echo self::$iden;?>[on]" id="<?php echo self::$iden;?>_on" value="1" <?php echo $is_checked;?> /><label for="<?php echo self::$iden;?>_on"><?php echo ___('Enable');?></label></td> </tr> <tr> <th scope="row"><?php echo ___('HTML code:');?></th> <td> <textarea id="<?php echo self::$iden;?>_code" name="<?php echo self::$iden;?>[code]" class="widefat code" rows="10"><?php echo $code;?></textarea> </td> </tr> <tr> <th scope="row"><?php echo esc_html(___('Restore'));?></th> <td> <label for="<?php echo self::$iden;?>_restore"> <input type="checkbox" id="<?php echo self::$iden;?>_restore" name="<?php echo self::$iden;?>[restore]" value="1"/> <?php echo ___('Restore the post copyright settings');?> </label> </td> </tr> </tbody> </table> </fieldset> <?php } public static function is_enabled(){ $opt = theme_options::get_options(self::$iden); return isset($opt['on']) ? true : false; } /** * options_default * * * @return array * @version 1.0.0 * @author KM@INN STUDIO * */ public static function options_default($options){ $options[self::$iden]['code'] = ' <ul> <li> ' . esc_html(___('Permanent URL: ')). '<a href="%post_url%">%post_url%</a> </li> <li> ' . esc_html(___('Welcome to reprint: ')). ___('Addition to indicate the original, the article of <a href="%blog_url%">%blog_name%</a> comes from internet. If infringement, please contact me to delete.'). ' </li> </ul>'; $options[self::$iden]['on'] = 1; return $options; } /** * save */ public static function save($options){ if(isset($_POST[self::$iden]) && !isset($_POST[self::$iden]['restore'])){ $options[self::$iden] = isset($_POST[self::$iden]) ? $_POST[self::$iden] : null; } return $options; } /** * output */ public static function display(){ global $post; $options = theme_options::get_options(); $tpl_keywords = array('%post_title_text%','%post_url%','%blog_name%','%blog_url%'); $output_keywords = array(get_the_title(),get_permalink(),get_bloginfo('name'),home_url()); $codes = str_ireplace($tpl_keywords,$output_keywords,$options[self::$iden]['code']); echo stripslashes($codes); } } <file_sep>/includes/theme-cache-request/theme-cache-request.php <?php /** * 1.1.2 */ theme_cache_request::init(); class theme_cache_request { private static $iden = 'theme-cache-request'; public static function init(){ add_action('frontend_seajs_use', get_class() . '::frontend_js'); add_action('wp_ajax_' . self::$iden, get_class() . '::process'); add_action('wp_ajax_nopriv_' . self::$iden, get_class() . '::process'); add_filter('frontend_seajs_alias', get_class() . '::frontend_alias'); } public static function process(){ $output = null; /** * check referer */ !check_referer() && die(___('Referer error')); $output = apply_filters('cache-request',$output); $output['theme-nonce'] = wp_create_nonce(AUTH_KEY); header('Content-type: text/javascript'); echo html_compress(' define(' . theme_features::json_format($output) . '); '); die(); } public static function frontend_alias($alias){ $datas = apply_filters('js-cache-request',array()); $datas['action'] = self::$iden; $alias[self::$iden] = theme_features::get_process_url($datas); return $alias; } public static function frontend_js(){ ?> seajs.use('<?php echo self::$iden;?>',function(m){ }); <?php } } <file_sep>/includes/theme-post-thumb/static/js/src/init.js /** * post_thumb * * @version 1.0.3 * @author KM@INN STUDIO */ define(function(require, exports, module){ var $ = require('modules/jquery'), tools = require('modules/tools'), dialog = require('modules/jquery.dialog'); /** * init * * @return * @example * @version 1.0.0 * @author KM (<EMAIL>) * @copyright Copyright (c) 2011-2013 INN STUDIO. (http://www.inn-studio.com) **/ exports.init = function(){ $(document).ready(function(){ exports.bind(); }); }; /** * config for post_thumb * * @version 1.0.1 * @author KM@INN STUDIO * */ exports.config = { post_thumb_id : '.theme-thumb', post_thumb_count_id : '.count', post_thumb_up_id : '.theme-thumb .theme-thumb-up', post_thumb_down_id : '.theme-thumb .theme-thumb-down', post_thumb_up_count_id : '.theme-thumb .theme-thumb-up .count', post_thumb_down_count_id : '.theme-thumb .theme-thumb-down .count', lang : { M00001 : 'Loading, please wait...', E00001 : 'Server error or network is disconnected.' }, process_url : '' }; exports.init = function(){ $(document).ready(function(){ exports.bind(); }); }; exports.cache = {}; /** * Binding the <a> tag * * @version 1.0.2 * @author KM@INN STUDIO * */ exports.bind = function(){ $(exports.config.post_thumb_id).on('click',function(){ exports.cache.$post_thumb = $(this); /** * need data-post-thumb="post_id,up" */ var attr_data = exports.cache.$post_thumb.data('postThumb'), attr_data_array = attr_data.split(','); eval('var ajax_data = {' + attr_data_array[1] + ' : parseInt(attr_data_array[0])}'); /** * ajax start */ exports.hook.dialog({ id : 'post-thumb', content : tools.status_tip('loading',exports.config.lang.M00001) }); $.ajax({ url : exports.config.process_url, dataType : 'json', data : ajax_data }).done(function(data){ if(data && data.status && data.status === 'success'){ // console.log(exports.hook.dialog); exports.hook.dialog({ content : tools.status_tip('success',data.msg) }); /** * add a new vote */ var $count = exports.cache.$post_thumb.find(exports.config.post_thumb_count_id); $count.text(parseInt($count.text()) + 1); }else if(data && data.status && data.status === 'error'){ exports.hook.dialog({ content : tools.status_tip('warning',data.msg) }); }else{ exports.hook.dialog({ content : tools.status_tip('error',exports.config.lang.E00001) }); } try{ exports.cache.dialog.show(exports.cache.$post_thumb[0]); }catch(e){} }).fail(function(){ exports.hook.dialog.content({ content : tools.status_tip('error',exports.config.lang.E00001) }); }); }); }; exports.hook = { dialog : function(args){ args.quickClose = true; var set_content = function(){ if(args.id){ dialog.get(args.id).content(args.content).show(exports.cache.$post_thumb[0]); }else{ exports.cache.dialog.content(args.content).show(exports.cache.$post_thumb[0]); } }, retry_set = function(){ exports.cache.dialog = dialog(args).show(exports.cache.$post_thumb[0]); }; try{ set_content(); }catch(e){ retry_set(); } } }; });<file_sep>/core/core-functions.php <?php /** * Output select tag html * * @param string $value Option value * @param string $text Option text * @param string $current_value Current option value * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function get_option_list($value,$text,$current_value){ ob_start(); $selected = $value == $current_value ? ' selected ' : null; ?> <option value="<?php echo esc_attr($value);?>" <?php echo $selected;?>><?php echo esc_html($text);?></option> <?php $content = ob_get_contents(); ob_end_clean(); return $content; } /** * mult_search_array * * @param array * @param string * @param string * @return array * @version 1.0.0 * @author KM@INN STUDIO */ function mult_search_array($key,$value,$array){ $results = array(); if (is_array($array)){ if (isset($array[$key]) && $array[$key] == $value) $results[] = $array; foreach ($array as $subarray){ $results = array_merge($results, mult_search_array($key, $value,$subarray)); } } return $results; } /** * check_referer * * @param string * @return bool * @version 1.0.0 * @author KM@INN STUDIO */ function check_referer($referer = null){ $referer = $referer ? : home_url(); if(!isset($_SERVER["HTTP_REFERER"]) || stripos($_SERVER["HTTP_REFERER"],$referer) !== 0){ return false; }else{ return true; } } /** * array_multiwalk * * @param array * @param string function name * @return array * @version 1.0.0 * @author KM@INN STUDIO */ function array_multiwalk($a,$fn){ if(!$a || !$fn) return false; foreach($a as $k => $v){ if(is_array($v)){ $a[$k] = array_multiwalk($v,$fn); continue; }else{ $a[$k] = $fn($v); } } return $a; } /** * is_null_array * * @param array * @return bool * @version 1.0.0 * @author KM@INN STUDIO */ function is_null_array($arr = null){ if(is_array($arr)){ foreach($arr as $k=>$v){ if($v && !is_array($v)){ return false; } $t = is_null_array($v); if(!$t){ return false; } } return true; }elseif(!$arr){ return true; }else{ return false; } } /** * chmodr * * @param string $path path or filepath * @param int $filemode * @return bool * @version 1.0.0 * @author KM@INN STUDIO */ function chmodr($path = null, $filemode = 0777) { if(!is_dir($path)) return chmod($path,$filemode); $dh = opendir($path); while(($file = readdir($dh)) !== false){ if($file != '.' && $file != '..'){ $fullpath = $path.'/'.$file; if(is_link($fullpath)){ return false; }else if(!is_dir($fullpath)&& !chmod($fullpath, $filemode)){ return false; }else if(!chmodr($fullpath,$filemode)){ return false; } } } closedir($dh); if(chmod($path,$filemode)){ return true; }else{ return false; } } /** * mk_dir * * * @param string $target * @return bool * @version 1.0.1 * @author KM@INN STUDIO * */ function mk_dir($target = null){ if(!$target) return false; $target = str_replace('//', '/', $target); if(file_exists($target)) return is_dir($target); if(@mkdir($target)){ $stat = stat(dirname($target)); chmod($target, 0755); return true; }else if(is_dir(dirname($target))){ return false; } /* If the above failed, attempt to create the parent node, then try again. */ if(($target != '/')&&(mk_dir(dirname($target)))){ return mk_dir($target); } return false; } /** * remove_dir * * * @param string $path * @return * @version 1.0.2 * @author KM@INN STUDIO * */ function remove_dir($path = null){ if(!$path || !file_exists($path)) return false; if(file_exists($path) || is_file($path)) @unlink($path); if($handle = opendir($path)){ while(false !==($item = readdir($handle))){ if($item != "." && $item != ".."){ if(is_dir($path . '/' . $item)){ remove_dir($path . '/' . $item); }else{ unlink($path . '/' . $item); } } } closedir($handle); rmdir($path); } } /** * esc_html___ * * @param string * @param string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function esc_html___($text,$tdomain = null){ $tdomain = $tdomain ? $tdomain : theme_features::$iden; return esc_html__($text,$tdomain); } /** * esc_attr___ * * @param string * @param string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function esc_attr___($text,$tdomain = null){ $tdomain = $tdomain ? $tdomain : theme_features::$iden; return esc_attr__($text,$tdomain); } /** * __n * * @param string * @param string * @param int * @param string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function __n($single,$plural,$number,$tdomain = null){ $tdomain = $tdomain ? $tdomain : theme_features::$iden; return _n($single,$plural,$number,$tdomain); } /** * __ex * * @param string * @param string * @param string * @return n/a * @version 1.0.0 * @author KM@INN STUDIO */ function __ex($text,$content,$tdomain = null){ echo __x($text,$content,$tdomain); } /** * __x * * @param string * @param string * @param string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function __x($text,$content,$tdomain = null){ $tdomain = $tdomain ? $tdomain : theme_functions::$iden; return _x($text,$content,$tdomain); } /** * __e() * translate function * * @param string $text your translate text * @param string $tdomain your translate tdomain * @return string display * @version 1.0.2 * @author KM@INN STUDIO * */ function __e($text = null,$tdomain = null){ echo ___($text,$tdomain); } /** * ___() * translate function * * @param string $text your translate text * @param string $tdomain your translate domain * @version 1.0.4 * @author KM@INN STUDIO * */ function ___($text = null,$tdomain = null){ if(!$text) return false; $tdomain = $tdomain ? $tdomain : theme_functions::$iden; return __($text,$tdomain); } /** * status_tip * * @param mixed * @return string * @example status_tip('error','content'); * @example status_tip('error','big','content'); * @example status_tip('error','big','content','span'); * @version 2.0.0 * @author KM@INN STUDIO */ function status_tip(){ $args = func_get_args(); if(empty($args)) return false; $defaults = array('type','size','content','wrapper'); $types = array('loading','success','error','question','info','ban','warning'); $sizes = array('small','middle','large'); $wrappers = array('div','span'); $type = null; $size = null; $wrapper = null; switch(count($args)){ case 1: $content = $args[0]; break; case 2: $type = $args[0]; $content = $args[1]; break; default: foreach($args as $k => $v){ $$defaults[$k] = $v; } } $type = $type ? $type : $types[0]; $size = $size ? $size : $sizes[0]; $wrapper = $wrapper ? $wrapper : $wrappers[0]; switch($type){ case 'success': $icon = 'checkmark-circle'; break; case 'error' : $icon = 'cancel-circle'; break; case 'info': case 'warning': $icon = 'warning'; break; case 'question': case 'help': $icon = 'help'; break; case 'ban': $icon = 'minus'; break; case 'loading': case 'spinner': $icon = 'spinner'; break; default: $icon = $type; } $tpl = '<' . $wrapper . ' class="tip-status tip-status-' . $size . ' tip-status-' . $type . '"><span class="icon-' . $icon . '"></span><span class="after-icon">' . $content . '</span></' . $wrapper . '>'; return $tpl; } /** * Get remote server file size * * * @param string $url The remote file * @return int The file size, false if file is not exist * @version 1.0.0 * @author KM@INN STUDIO * */ function get_remote_size($url = null){ if(!$url) return false; $uh = curl_init(); curl_setopt($uh, CURLOPT_URL, $url); // set NO-BODY to not receive body part curl_setopt($uh, CURLOPT_NOBODY, 1); // set HEADER to be false, we don't need header curl_setopt($uh, CURLOPT_HEADER, 0); // retrieve last modification time curl_setopt($uh, CURLOPT_FILETIME, 1); curl_exec($uh); // assign filesize into $filesize variable $filesize = curl_getinfo($uh,CURLINFO_CONTENT_LENGTH_DOWNLOAD); // assign file modification time into $filetime variable $filetime = curl_getinfo($uh,CURLINFO_FILETIME); curl_close($uh); // push out return array("size"=>$filesize,"time"=>$filetime); } /** * multidimensional searching * * * @param array $parents The parents array * @param array $searched What want you search, * like this: array('date'=>1320883200, 'uid'=>5) * @return string If exists return the key name, or false * @version 1.0.0 * @author revoke * */ function multidimensional_search($parents, $searched) { if(empty($searched) || empty($parents)) return false; foreach($parents as $key => $value){ $exists = true; foreach ($searched as $skey => $svalue) { $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue); } if($exists){ return $key; } } return false; } /** * html_compress * * * @param string The html code * @return string The clear html code * @version 1.0.2 * @author higrid.net * @author KM@INN STUDIO 20131211 * */ function html_compress($html = null){ if(!$html) return false; $chunks = preg_split( '/(<pre.*?\/pre>)/ms', $html, -1, PREG_SPLIT_DELIM_CAPTURE ); $html = null; foreach ( $chunks as $c ){ if ( strpos( $c, '<pre' ) !== 0 ){ // remove html comments $c = preg_replace( '/<!--[^!]*-->/', ' ', $c ); //[higrid.net] remove new lines & tabs $c = preg_replace( '/[\\n\\r\\t]+/', ' ', $c ); // [higrid.net] remove extra whitespace $c = preg_replace( '/\\s{2,}/', ' ', $c ); // [higrid.net] remove inter-tag whitespace $c = preg_replace( '/>\\s</', '><', $c ); // [higrid.net] remove CSS & JS comments $c = preg_replace( '/\\/\\*.*?\\*\\//i', '', $c ); } $html .= $c; } return $html; } /** * Refer to url address * * * @param string $url The want to go url * @param string/array $param The wnat to go url's param * @return bool false that not enough param, otherwise refer to the url * @version 1.0.1 * @author <NAME> * */ function refer_url($url = null,$param = null){ if(!$url) return false; $param = is_array($param) ? http_build_query($param) : $param; $url_obj = parse_url($url); if(isset($url_obj['query'])){ $header = $param ? 'Location: ' .$url. '&' .$param : 'Location: ' .$url; }else{ $header = $param ? 'Location: ' .$url. '?' .$param : 'Location: ' .$url; } header($header); // exit; } /** * encode * @param string $string 原文或者密文 * @param string $operation 操作(encode | decode), 默认为 decode * @param string $key 密钥 * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文 * @example * $a = authcode('abc', 'encode', 'key'); * $b = authcode($a, 'decode', 'key'); // $b(abc) * * $a = authcode('abc', 'encode', 'key', 3600); * $b = authcode('abc', 'decode', 'key'); // 在一个小时内,$b(abc),否则 $b 为空 */ function authcode($string, $operation = 'decode', $key = null, $expiry = 0) { $ckey_length = 4; $key = md5($key ? $key : 'innstudio'); $keya = md5(substr($key, 0, 16)); $keyb = md5(substr($key, 16, 16)); $keyc = $ckey_length ? ($operation == 'decode' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : null; $cryptkey = $keya.md5($keya.$keyc); $key_length = strlen($cryptkey); $string = $operation == 'decode' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; $string_length = strlen($string); $result = null; $box = range(0, 255); $rndkey = array(); for($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } for($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if($operation == 'decode') { if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { return substr($result, 26); } else { return false; } } else { return $keyc.str_replace('=', '', base64_encode($result)); } } /** * Get client IP * * @return string * @version 2.0.0 * @author KM@INN STUDIO */ function get_client_ip(){ return preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] ); } /** * Name: delete_files * Author: Km.Van * Version: 1.0 * Type: function 函数 * Return: string(bool) * Explain: 删除文件 * Example: delete_files(file_path) * Update: PM 06:10 2011/9/2 */ function delete_files($file_path = null){ if(!$file_path || !file_exists($file_path)) return false; return unlink($file_path); } /** * Name: download_files * Author: Km.Van * Version: 1.0 * Type: function 函数 * Return: string(display) * Explain: 下载文件名,保存路径,保存文件名,下载时限 * Example: download_files(str) * Update: PM 11:28 2011/8/19 */ function download_files($url = null,$dir = null,$name = null,$time_limit = 300){ if(!$url) return false; set_time_limit($time_limit); $dir = $dir ? $dir : dirname(__FILE__); if(!$name){ $default_name = explode('/',$url); $default_name = $default_name[count($default_name) - 1]; $name = $default_name; } $fp = fopen($dir.'/'.$name, 'w'); $ch = curl_init($url); curl_setopt($ch, CURLOPT_FILE, $fp); $data = curl_exec($ch); curl_close($ch); fclose($fp); return true; } /** * Name: err * Author: Km.Van * Version: 1.0 * Type: function 函数 * Return: string(display) * Explain: 错误提示功能 * Example: err(str) * Update: PM 11:28 2011/8/19 */ function err($ErrMsg){ header('HTTP/1.1 405 Method Not Allowed'); echo $ErrMsg; exit; } /** * Name: get_filemtime * Author: Km.Van * Version: 1.2 * Type: function 函数 * Return: string(display) * Explain: 獲取文件修改日期 * Example: get_filemtime() * Update: 20130208 */ function get_filemtime($file_name = null,$format = 'YmdHis'){ if(!$file_name || !file_exists($file_name) || !is_file($file_name)) return false; $file_date = filemtime($file_name); $file_date = date($format,$file_date); return $file_date; } /** * get_img_source * * @param string * @return string * @version 1.0.2 * @author KM@INN STUDIO */ function get_img_source($str = null){ $output = null; if($str){ $pattern = '!<img.*?src=["|\'](.*?)["|\']!'; preg_match_all($pattern, $str, $matches); $output = isset($matches['1'][0]) ? $matches['1'][0] : false; } return $output; } /** * friendly_date * * @param string time * @return string * @version 1.0.1 * @author KM@INN STUDIO */ function friendly_date($time = null){ $text = null; $current_time = current_time('timestamp'); $time = $time === null || $time > $current_time ? $current_time : intval($time); $t = $current_time - $time; //时间差 (秒) switch($t){ case ($t < 3) : $text = ___('Just'); break; /** * 60 */ case ($t < 60) : $text = sprintf(___('%d seconds ago'),$t); // 一分钟内 break; /** * 60 * 60 = 3600 */ case ($t < 3600) : if($t < 2){ $text = ___('a minute ago'); //一小时内 }else{ $text = sprintf(___('%d minutes ago'),floor($t / 60)); //一小时内 } break; /** * 60 * 60 * 24 = 86400 */ case ($t < 86400) : if($t < 2){ $text = ___('an hour ago'); // 一天内 }else{ $text = sprintf(___('%d hours ago'),floor($t / 3600)); // 一天内 } break; /** * 60 * 60 * 24 * 2 = 172800 */ case ($t < 172800) : $text = ___('yesterday'); //两天内 break; /** * 60 * 60 * 24 * 7 = 604800 */ case ($t < 604800) : $text = sprintf(___('%d days ago'),floor($t / 86400)); // N天内 break; /** * 60 * 60 * 24 * 365 = 31,536,000 */ case ($t < 31536000) : $text = date(___('M j'), $time); //一年内 break; default: $text = date(___('M j, Y'), $time); //一年以前 } return $text; } /** * Name: get_server_os_type * Author: Km.Van * Version: 1.0 * Type: function 函数 * Return: string(not display) * Explain: 获取主机操作系统类型 * Example: get_server_os_type() * Update: AM 10:59 2011/2/16 */ function get_server_os_type(){ $output = null; if(PATH_SEPARATOR==':'){ $output = 'linux'; }else{ $output = 'windows'; } return $output; } /** * kill_html * * @param string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function kill_html($str = null){ $html = array( /* 过滤多余空白*/ "/\s+/", /* 过滤 <script>等 */ "/<(\/?)(script|i?frame|style|html|body|title|link|meta|\?|\%)([^>]*?)>/isU", /* 过滤javascript的on事件 */ "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU" ); $tarr = array( " ", "<\1\2\3>",//如果要直接清除不安全的标签,这里可以留空 "\1\2", ); $str = nl2br($str); $str = preg_replace($html,'',$str); return $str; } /** * Get either a Gravatar URL or complete image tag for a specified email address. * * @param string $email The email address * @param string $s Size in pixels, defaults to 80px [ 1 - 512 ] * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ] * @param string $r Maximum rating (inclusive) [ g | pg | r | x ] * @param boole $img True to return a complete IMG tag False for just the URL * @param array $atts Optional, additional key/value attributes to include in the IMG tag * @return String containing either just a URL or a complete image tag * @source http://gravatar.com/site/implement/images/php/ */ function get_gravatar( $email, $url_only = 1, $s = 80, $d = 'mm', $r = 'g', $atts = array() ) { $server_domains = array( '0', '1', '2', 'cn', 'en' ); $rand_i = array_rand($server_domains); $url = 'http://' . $server_domains[$rand_i] . '.gravatar.com/avatar/'; $url .= md5( strtolower( trim( $email ) ) ); $url .= "?s=$s&d=$d&r=$r"; if(!$url_only){ $url = '<img src="' . $url . '"'; foreach ( $atts as $key => $val ) $url .= ' ' . $key . '="' . $val . '"'; $url .= ' />'; } return $url; } /** * get_current_url * * @return string * @version 1.0.1 * @author KM@INN STUDIO */ function get_current_url(){ $output = $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://'; $output .= $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"]; return $output; } /** * str_sub * * @param string * @param int * @param string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function str_sub($str,$len = null,$extra = '...'){ if(!trim($str)) return; if(!$len || mb_strlen(trim($str)) <= $len){ return $str; }else{ $str = mb_substr($str,0,$len); $str .= $extra; } return $str; } /** * url_sub * * @param string * @param int * @param int * @param int * @return string * @version 1.0.0 * @author KM@INN STUDIO */ function url_sub($url = null,$before_len = 30,$after_len = 20,$extra_len = 10,$middle_str = ' ... '){ if(!$url) return; $url_len = mb_strlen($url); /* url 小于指定长度 */ if($url_len <= ($before_len + $after_len + $extra_len)){ return $url; }else{ $url_before = mb_substr($url,0,$before_len); $url_after = mb_substr($url,-$after_len); return $url_before.$middle_str.$url_after; } } /* 检测浏览器 */ class get_browser{ private static function detection(){ $u_agent = $_SERVER['HTTP_USER_AGENT']; $bname = 'Unknown'; $platform = 'Unknown'; $version= ""; //First get the platform? if (preg_match('/linux/i', $u_agent)) { $platform = 'linux'; } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) { $platform = 'mac'; } elseif (preg_match('/windows|win32/i', $u_agent)) { $platform = 'windows'; } // Next get the name of the useragent yes seperately and for good reason if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) { $bname = 'Internet Explorer'; $ub = "MSIE"; } elseif(preg_match('/Firefox/i',$u_agent)) { $bname = 'Mozilla Firefox'; $ub = "Firefox"; } elseif(preg_match('/Chrome/i',$u_agent)) { $bname = 'Google Chrome'; $ub = "Chrome"; } elseif(preg_match('/Safari/i',$u_agent)) { $bname = 'Apple Safari'; $ub = "Safari"; } elseif(preg_match('/Opera/i',$u_agent)) { $bname = 'Opera'; $ub = "Opera"; } elseif(preg_match('/Netscape/i',$u_agent)) { $bname = 'Netscape'; $ub = "Netscape"; } // finally get the correct version number $known = array('Version', $ub, 'other'); $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#'; if (!preg_match_all($pattern, $u_agent, $matches)) { // we have no matching number just continue } // see how many we have $i = count($matches['browser']); if ($i != 1) { //we will have two since we are not using 'other' argument yet //see if version is before or after the name if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){ $version= $matches['version'][0]; } else { $version= $matches['version'][1]; } } else { $version= $matches['version'][0]; } // check if we have a number if ($version==null || $version=="") {$version="?";} return array( 'userAgent' => $u_agent, 'long_name' => strtolower($bname), 'name' => strtolower($ub), 'version' => strtolower($version), 'platform' => strtolower($platform), 'pattern' => $pattern ); } static function get_long_name(){ $ua = self::detection(); return $ua['long_name']; } static function get_name(){ $ua = self::detection(); return $ua['name']; } static function get_version(){ $ua = self::detection(); $version = $ua['version']; $version_len = strlen($version); $version_dot = strpos($version,'.') + 2; $version = substr($version,0,$version_dot); $version = strtr($version,'.','_'); return $version; } static function get_platform(){ $ua = self::detection(); return $ua['platform']; } private static function get_pattern(){ $ua = self::detection(); return $ua['pattern']; } } ?><file_sep>/core/core-options.php <?php /** * Theme Options * the theme options and show admin control planel * * @version 4.2.2 * @author KM@INN STUDIO * */ add_action('admin_init','theme_options::init' ); add_action('admin_menu','theme_options::add_page'); add_action('admin_bar_menu','theme_options::add_bar',61); class theme_options{ public static $iden = 'theme_options'; /** * init * * @return * @version 1.0.1 * @author KM@INN STUDIO */ public static function init(){ if(!self::is_options_page()) return false; add_action('admin_head',get_class() . '::backend_header'); self::save_options(); self::redirect(); } /** * get the theme options from the features default value or DB. * * @usedby theme_options::get_options() * @return array * @version 1.2.1 * @since 3.1.0 * @author KM@INN STUDIO * */ public static function get_options($key = null){ /** Get first options */ $options = get_option(self::$iden); $options_default = null; /** Default options hook */ $options_default = apply_filters('theme_options_default',$options_default); $options = wp_parse_args($options,$options_default); if($key){ return isset($options[$key]) ? $options[$key] : null; }else{ return $options; } } public static function backend_header(){ if(!self::is_options_page()) return false; $options = self::get_options();/* get the options */ $preload = null; $backend_seajs_alias = apply_filters('backend_seajs_alias',array()); echo theme_features::get_theme_css('backend/fonts','normal'); echo theme_features::get_theme_css('backend/style','normal'); /** * add admin_css hook */ do_action('backend_css'); ?><script id="seajsnode" src="<?php echo theme_features::get_theme_js('seajs/sea');?>"></script> <script> <?php $config = array(); $config['base'] = esc_js(theme_features::get_theme_js()); $config['paths'] = array( 'theme_js' => esc_js(theme_features::get_theme_js()), 'theme_css' => esc_js(theme_features::get_theme_css()), ); $config['vars'] = array( 'locale' => str_replace('-','_',get_bloginfo('language')), 'theme_js' => esc_js(theme_features::get_theme_js()), 'theme_css' => esc_js(theme_features::get_theme_css()), 'process_url' => esc_js(theme_features::get_process_url()), ); $config['map'] = array( array('.css','.css?v=' . theme_features::get_theme_info('version')), array('.js','.js?v=' . theme_features::get_theme_info('version')) ); /** * seajs hook */ $config['paths'] = apply_filters('backend_seajs_paths',$config['paths']); $config['alias'] = apply_filters('backend_seajs_alias',array()); $config['vars'] = apply_filters('backend_seajs_vars',$config['vars']); $config['map'] = apply_filters('backend_seajs_map',$config['map']); ?> seajs.config(<?php echo json_encode($config);?>); <?php do_action('before_backend_tab_init');?> seajs.use('backend',function(m){ m.init({ done : function($btn,$cont,$tab){ <?php do_action('after_backend_tab_init');?> }, custom : function(b,c,i,t){ <?php do_action('after_backend_tab_custom');?> }, tab_title : '<?php echo wp_get_theme();?> <?php echo ___('theme settings');?>' }); }); </script> <?php } /** * show the options settings for admin theme setting page. * * @usedby theme_options::display() * @return string html string for options * @version 3.1.7 * @author KM@INN STUDIO * */ public static function display(){ ?> <div class="wrap"> <?php if(isset($_GET['updated'])){?> <div id="settings-updated"> <?php echo status_tip('success',___('Settings have been saved.'));?> </div> <?php } ?> <form id="backend-options-frm" method="post"> <?php /** * loading */ echo '<div class="backend-tab-loading">' . status_tip('loading',___('Loading, please wait...')) . '</div>'; ?> <dl id="backend-tab" class="backend-tab"> <?php do_action('before_base_settings');?> <dt title="<?php echo esc_attr(___('Theme common settings.'));?>"><span class="icon-setting"></span><span class="after-icon hide-on-mobile"><?php echo esc_html(___('Basic Settings'));?></span></dt> <dd> <!-- the action of base_settings --> <?php do_action('base_settings');?> </dd><!-- BASE SETTINGS --> <?php do_action('before_page_settings');?> <dt title="<?php echo esc_attr(___('Theme appearance/template settings.'));?>"><span class="icon-insert-template"></span><span class="after-icon hide-on-mobile"><?php echo esc_html(___('Page Settings'));?></span></dt> <dd> <!-- the action of page_settings --> <?php do_action('page_settings');?> </dd><!-- PAGE SETTINGS --> <?php do_action('before_advanced_settings');?> <dt title="<?php echo esc_attr(___('Theme special settings, you need to know what are you doing.'));?>"><span class="icon-settings"></span><span class="after-icon hide-on-mobile"><?php echo esc_html(___('Advanced Settings'));?></span></dt> <dd> <!-- the action of advanced_settings --> <?php do_action('advanced_settings');?> </dd><!-- ADVANCED SETTINGS --> <?php do_action('before_dev_settings');?> <dt><span class="icon-console"></span><span class="after-icon hide-on-mobile"><?php echo esc_html(___('Developer Mode'));?></span></dt> <dd> <?php do_action('dev_settings');?> </dd><!-- DEVELOPER SETTINGS --> <?php do_action('before_help_settings');?> <dt><span class="icon-help"></span><span class="after-icon hide-on-mobile"><?php echo esc_html(___('About & Help'));?></span></dt> <dd> <?php do_action('help_settings');?> </dd><!-- ABOUT and HELP --> <?php do_action('after_help_settings');?> </dl> <p> <input type="hidden" value="save_options" name="action" /> <input type="submit" value="<?php echo esc_attr(___('Save all settings'));?>" class="button button-primary button-large"/> <label for="options-reset" class="label-options-reset" title="<?php echo esc_attr(___('Something error with theme? Try to restore:)'));?>"><input id="options-reset" name="reset_options" type="checkbox" value="1"/> <?php echo esc_html(___('Restore default theme options'));?></label> </p> </form> </div> <?php } /** * Save Options * * * @return n/a * @version 1.0.0 * @author <NAME> * */ public static function save_options(){ $options = null; /** Check the action and save options */ if(isset($_POST['action']) && $_POST['action'] === 'save_options'){ /** Add Hook */ $options = apply_filters(self::$iden . '_save',$options); /** Reset the options? */ if(isset($_POST['reset_options'])){ /** Delete theme options */ delete_option(self::$iden); }else{ /** Update theme options */ update_option(self::$iden,$options); } } } /** * set_options * * @param string options key * @param mixd * @return array options * @version 1.0.2 * @author KM@INN STUDIO */ public static function set_options($key = null,$data = null){ $options = self::get_options(); if(!$key || !$data) return $options; $options[$key] = $data; update_option(self::$iden,$options); return $options; } /** * delete_options * * @param string * @return * @version 1.0.1 * @author KM@INN STUDIO */ public static function delete_options($key = null){ if(!$key) return false; $options = self::get_options(); unset($options[$key]); update_option(self::$iden,$options); } /** * is_options_page * * @return bool * @version 1.0.0 * @author KM@INN STUDIO */ private static function is_options_page(){ if(is_admin() && isset($_GET['page']) && $_GET['page'] === basename(__FILE__,'.php')){ return true; }else{ return false; } } /** * redirect * * @return n/a * @version 1.0.0 * @author KM@INN STUDIO */ private static function redirect(){ if(self::is_options_page() && isset($_POST['action']) && $_POST['action'] === 'save_options'){ if(isset($_GET['updated']) && $_GET['updated'] === 'true'){ $redirect_updated = null; }else{ $redirect_updated = '&updated=true'; } /** refer */ header('Location: '.get_current_url() . $redirect_updated); } } /** * Add to page * * * @return n/a * @version 1.0.0 * @author K<NAME> * */ public static function add_page(){ /* Add to theme setting menu */ add_theme_page(___('Theme settings'),___('Theme settings'), 'edit_themes', 'core-options','theme_options::display'); } /** * Add admin bar * * * @return * @version 1.0.1 * @author KM@IN<NAME> * */ public static function add_bar(){ if(!current_user_can('manage_options')) return false; global $wp_admin_bar; $wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'theme_settings', 'title' => ___('Theme settings'), 'href' => admin_url('themes.php?page=core-options') )); } } /* End Theme Options */ ?><file_sep>/includes/theme-post-views/theme-post-views.php <?php /* Feature Name: Post Views Feature URI: http://www.inn-studio.com Version: 1.2.0 Description: Count the post views. Author: INN STUDIO Author URI: http://www.inn-studio.com */ theme_post_views::init(); class theme_post_views{ private static $iden = 'theme_post_views'; private static $log_key = 'views'; private static $cookie_key = 'vids'; private static $cookie_expire = 3600;/** 1 hour */ private static $cache_expire = 2505600;/** memcache max 29 days */ private static $storage_times = 10; public static function init(){ add_filter('cache-request',get_class() . '::cache_request'); add_filter('js-cache-request',get_class() . '::js_cache_request',1); add_action('admin_head', get_class() . '::admin_css'); add_action('manage_posts_custom_column',get_class() . '::admin_show',10,2); add_filter('manage_posts_columns', get_class() . '::admin_add_column'); } public static function save_post($post_id){ /** * check the revision */ if ($parent_id = wp_is_post_revision($post_id)) { $post_id = $parent_id; } /** * update the meta */ add_post_meta($post_id,self::$log_key,1,true); } /** * update_views * * * @return * @version 1.0.2 * @author KM@INN STUDIO * */ public static function update_views($post_id = null){ global $post; $post_id = $post_id ? (int)$post_id : $post->ID; $cache = (array)theme_cache::get(self::$iden); $old_meta_view = (int)get_post_meta($post_id,self::$log_key,true); $tmp_view = isset($cache[$post_id]) ? (int)$cache[$post_id] : 0; ++$tmp_view; /** * max storage time, save to database */ if(self::is_max_storage_time($post_id)){ $new_meta_view = $old_meta_view + $tmp_view; update_post_meta($post_id,self::$log_key,(int)$new_meta_view); /** * reset tmp_view */ $cache[$post_id] = 0; }else{ $cache[$post_id] = $tmp_view; } theme_cache::set(self::$iden,$cache,null,self::$cache_expire); return self::get_view_from_cache($post_id); } public static function is_viewed($post_id = null){ global $post; $post_id = $post_id ? (int)$post_id : $post->ID; $cookie_view_ids = isset($_COOKIE[self::$cookie_key]) ? @unserialize($_COOKIE[self::$cookie_key]) : array(); $is_viewed = false; if(in_array($post_id,$cookie_view_ids)){ $is_viewed = true; }else{ $cookie_view_ids[] = $post_id; } /** * set cookie */ if(!$is_viewed){ $expire = time()+ self::$cookie_expire; setcookie(self::$cookie_key,serialize($cookie_view_ids),$expire); } return $is_viewed; } /** * display * show the views * * @params int $post_id * @return int the views * @version 1.0.1 * @author KM@IN<NAME> * */ public static function display($post_id = null){ global $post; $post_id = $post_id ? (int)$post_id : $post->ID; return self::get_view_from_cache($post_id); } public static function is_enabled(){ return true; } public static function options_save($options){ if(isset($_POST[self::$iden])){ $options[self::$iden] = $_POST[self::$iden]; } return $options; } private static function is_max_storage_time($post_id){ $cache = (array)theme_cache::get(self::$iden); $tmp_view = isset($cache[$post_id]) ? (int)$cache[$post_id] : 0; /** * add a new view number */ ++$tmp_view; /** * Exceed the maximum, update meta */ if($tmp_view >= self::$storage_times){ return true; }else{ return false; } } public static function get_view_from_cache($post_id){ $cache = (array)theme_cache::get(self::$iden); $tmp_view = isset($cache[$post_id]) ? (int)$cache[$post_id] : 0; $old_meta_view = (int)get_post_meta($post_id,self::$log_key,true); $view = $old_meta_view + $tmp_view; return (int)$view; } /** * process * * * @return array * @version 1.0.3 * @author KM@INN STUDIO * */ public static function cache_request($output){ if(isset($_GET[self::$iden]) && (int)$_GET[self::$iden] != 0){ $post_id = (int)$_GET[self::$iden]; /** * check is viewed */ if(!self::is_viewed($post_id)){ self::update_views($post_id); } $output[self::$iden] = self::get_view_from_cache($post_id); } return $output; } public static function js_cache_request($data){ if(!is_singular()) return $data; global $post; $data[self::$iden] = $post->ID; return $data; } /** * admin_add_column * * * @params * @return * @version 1.0.0 * @author K<NAME> * */ public static function admin_add_column($columns){ $columns[self::$log_key] = ___('Views'); return $columns; } public static function admin_show($column_name,$id){ if ($column_name != 'views') return; $views = get_post_meta($id,self::$log_key,true); echo (int)$views; } public static function admin_css(){ ?><style>.fixed .column-views{width:3em}</style><?php } } ?><file_sep>/includes/theme-post-share/theme-post-share.php <?php /* Feature Name: Post Share Feature URI: http://www.inn-studio.com Version: 1.3.0 Description: Author: INN STUDIO Author URI: http://www.inn-studio.com */ theme_post_share::init(); class theme_post_share{ public static $iden = 'theme_post_share'; public static function init(){ add_filter('theme_options_default',get_class() . '::options_default'); add_filter('theme_options_save',get_class() . '::options_save'); add_action('page_settings',get_class() . '::backend_display'); if(!self::is_enabled()) return false; add_action('wp_head',get_class() . '::frontend_css'); add_action('frontend_seajs_use',get_class() . '::frontend_js'); } public static function display($args = array()){ global $post; $options = theme_options::get_options(); $img_url = theme_features::get_thumbnail_src(); $defaults = array( 'post_title_text' => esc_attr(get_the_title()), 'post_url' => esc_url(get_permalink()), 'blog_name' => esc_attr(get_bloginfo('name')), 'blog_url' => esc_url(home_url()), 'img_url' => esc_url($img_url), 'post_excerpt' => esc_attr(mb_substr(html_compress(strip_tags(get_the_excerpt())),0,120)), 'post_content' => esc_attr(mb_substr(html_compress(strip_tags(get_the_content())),0,120)), 'author' => esc_attr(get_the_author_meta('display_name',$post->post_author)), ); $output_keywords = wp_parse_args($args,$defaults); $tpl_keywords = array( '%post_title_text%', '%post_url%', '%blog_name%', '%blog_url%', '%img_url%', '%post_excerpt%', '%post_content%', '%author%' ); $post_share_code = stripslashes(str_ireplace($tpl_keywords,$output_keywords,$options[self::$iden]['code'])); echo $post_share_code; } public static function backend_display(){ $options = theme_options::get_options(); $is_checked = self::is_enabled() ? ' checked ' : null; ?> <fieldset> <legend><?php echo ___('Posts share settings');?></legend> <p class="description"> <?php echo ___('Share your post to everywhere. Here are some keywords that can be used:');?> </p> <p class="description"> <input type="text" class="small-text text-select" value="%post_title_text%" title="<?php echo ___('Post Title text');?>" readonly /> <input type="text" class="small-text text-select" value="%post_url%" title="<?php echo ___('Post URL');?>" readonly /> <input type="text" class="small-text text-select" value="%blog_name%" title="<?php echo ___('Blog name');?>" readonly /> <input type="text" class="small-text text-select" value="%blog_url%" title="<?php echo ___('Blog URL');?>" readonly /> <input type="text" class="small-text text-select" value="%img_url%" title="<?php echo ___('The first picture of the post.');?>" readonly /> <input type="text" class="small-text text-select" value="%post_excerpt%" title="<?php echo ___('The excerpt of post.');?>" readonly /> <input type="text" class="small-text text-select" value="%post_content%" title="<?php echo ___('The content of post.');?>" readonly /> </p> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="<?php echo self::$iden;?>_on"><?php echo ___('Enable or not?');?></label></th> <td><input type="checkbox" name="<?php echo self::$iden;?>[on]" id="<?php echo self::$iden;?>_on" value="1" <?php echo $is_checked;?> /><label for="<?php echo self::$iden;?>_on"><?php echo ___('Enable');?></label></td> </tr> <tr> <th scope="row"><?php echo ___('HTML codes');?></th> <td><textarea id="<?php echo self::$iden;?>_code" name="<?php echo self::$iden;?>[code]" class="widefat" cols="30" rows="10"><?php echo stripslashes($options[self::$iden]['code']);?></textarea> </td> </tr> <tr> <th scope="row"><?php echo esc_html(___('Restore'));?></th> <td> <label for="<?php echo self::$iden;?>_restore"> <input type="checkbox" id="<?php echo self::$iden;?>_restore" name="<?php echo self::$iden;?>[restore]" value="1"/> <?php echo ___('Restore the post share settings');?> </label> </td> </tr> </tbody> </table> </fieldset> <?php } public static function options_default($options){ ob_start(); ?> <div class="bdshare_t bds_tools get-codes-bdshare" data-bdshare="{ 'text':'%post_title_text% by %author% <?php echo ___('-- from %blog_name%');?>', 'url':'%post_url%', 'pic':'%img_url%' }"> <span class="description"><?php echo esc_html(___('Share to: '));?></span> <a class="bds_tsina" data-cmd="tsina" title="<?php echo esc_attr(sprintf(___('Share to %s'),___('Sina Weibo')));?>" href="javascript:void(0);"></a> <a class="bds_qzone" data-cmd="qzone" href="javascript:void(0);" title="<?php echo esc_attr(sprintf(___('Share to %s'),___('QQ zone')));?>"></a> <a class="bds_baidu" data-cmd="baidu" title="<?php echo esc_attr(sprintf(___('Share to %s'),___('Baidu')));?>" href="javascript:void(0);"></a> <a class="bds_more" data-cmd="more" href="javascript:void(0);"></a> </div> <?php $content = ob_get_contents(); ob_end_clean(); $options[self::$iden]['on'] = 1; $options[self::$iden]['code'] = $content; return $options; } public static function is_enabled(){ $options = theme_options::get_options(); if(isset($options[self::$iden]['on'])){ return true; }else{ return false; } } public static function options_save($options){ if(isset($_POST[self::$iden]) && !isset($_POST[self::$iden]['restore'])){ $options[self::$iden] = $_POST[self::$iden]; } return $options; } public static function frontend_css(){ ?> <link rel="stylesheet" href="<?php echo theme_features::get_theme_includes_css(__FILE__);?>"> <?php } public static function frontend_js(){ $options = theme_options::get_options(); if(!isset($options[self::$iden]) || strstr($options[self::$iden]['code'],'bdshare') === false) return false; ?> seajs.use('<?php echo theme_features::get_theme_includes_js(__FILE__);?>',function(m){ m.config.bdshare_js = '<?php echo esc_url(theme_features::get_theme_includes_js(__FILE__,'bdshare'));?>'; m.init(); }); <?php } } ?><file_sep>/static/js/src/frontend.js define(function(require, exports, module){ /** * theme.init() init for the theme js * * @author <NAME> * */ var $ = require('modules/jquery'), jQuery = $; exports.config = { is_home : false }; exports.init = function(){ $(document).ready(function(){ exports.lbox.init(); exports.hide_no_js(); exports.lazyload(); exports.search(); exports.mobile_menu.init(); setTimeout(function(){exports.qrcode.init();},1000); exports.scroll_top_fixed(); }); }; exports.scroll_top_fixed = function(){ var $sidebar = $('#sidebar'), $footer = $('#footer'), $main_container = $('#main'), win_min_width = 768, is_desktop = true, $win = $(window), sidebar_height = $sidebar.outerHeight(), sidebar_width = $sidebar.outerWidth(), sidebar_offset_left = parseInt($sidebar.offset().left), sidebar_offset_top = parseInt($sidebar.offset().top), original_sidebar_offset_top = sidebar_offset_top, win_height = parseInt($win.height()), win_width = parseInt($win.width()), fixed_top = false, fixed_bottom = false, is_absolute = false, is_bottom = false, is_top = false, is_static = true, limit_bottom = parseInt($footer.offset().top - 20), last_scroll_pos = 0, footer_top, timer, resize_timer; if(win_width <= win_min_width) return false; function check_fit_to_float(){ if($main_container.outerHeight() <= sidebar_height){ return false; } if(win_width <= win_min_width){ if($sidebar.attr('style')) $sidebar.attr('style',''); return false; } return true; } function adjust(event){ var type = event && event.type, resize = type !== 'scroll', win_pos = parseInt($win.scrollTop()); limit_bottom = parseInt($footer.offset().top -20); //console.log(is_absolute); /** * scrolling down */ if(win_pos > last_scroll_pos){ /** sidebar高度小于窗口高度*/ if(sidebar_height <= win_height){ /** 边栏顶高小于窗口顶高 & 边栏底高小于限制底高,进行fixedtop, */ if((parseInt($sidebar.offset().top) <= win_pos) && (parseInt($sidebar.offset().top + sidebar_height) < limit_bottom)){ //console.log((parseInt($sidebar.offset().top + sidebar_height)) + ',' + limit_bottom); if(!fixed_top){ $sidebar.css({ position:'fixed', top:0, width:sidebar_width, bottom:'' }); fixed_top = true; fixed_bottom = false; is_bottom = false; is_top = false; is_absolute = false; is_static = false; } /** 边栏底高大于限制底高,进行绝对定位 */ }else if((parseInt($sidebar.offset().top + sidebar_height) >= limit_bottom)){ console.log('a'); if(!is_absolute){ sidebar_offset_top = $sidebar.offset().top; $sidebar.css({ position:'absolute', top:sidebar_offset_top, width:sidebar_width, bottom:'' }); is_absolute = true; fixed_top = false; fixed_bottom = false; is_bottom = false; is_top = false; is_static = false; } } }else{ /** sidebar底高大于footer顶高,则进行绝对定位 */ if(parseInt(sidebar_height + $sidebar.offset().top) > limit_bottom){ if(!is_absolute){ sidebar_offset_top = $sidebar.offset().top; $sidebar.css({ position:'absolute', top:sidebar_offset_top, width:sidebar_width, bottom:'' }); is_absolute = true; fixed_top = false; fixed_bottom = false; is_bottom = false; is_top = false; is_static = false; } /** sidebar高度,小于窗口高度则一直保持fixed top */ //}else if(win_height >= sidebar_height){ // if(!fixed_top){ // $sidebar.css({ // position:'fixed', // top:0, // left:sidebar_offset_left, // width:sidebar_width // }); // fixed_top = true; // fixed_bottom = false; // is_bottom = false; // is_top = false; // is_absolute = false; // is_static = false; // } /** sidebar底高小于极限底高,向下滚动时进行智能浮动 */ }else{ /** sidebar底高大于窗口底高 & & sidebar底高小于极限顶高 & sidebar处于static状态时,不进行操作 */ if(parseInt(sidebar_height + $sidebar.offset().top) > ($win.scrollTop() + win_height) && parseInt(sidebar_height + $sidebar.offset().top) < limit_bottom ){ if(!is_static){ sidebar_offset_top = $sidebar.offset().top; $sidebar.attr('style',''); is_static = true; is_bottom = false; is_top = false; fixed_top = false; fixed_bottom = false; is_absolute = false; } /** sidebar底高大于窗口底高,则进行滚动 */ }else if(parseInt(sidebar_height + $sidebar.offset().top) > ($win.scrollTop() + win_height)){ // console.log('sidebar底高大于窗口底高,则进行滚动'); if(!is_absolute || fixed_top){ sidebar_offset_top = $sidebar.offset().top; $sidebar.css({ position:'absolute', top:sidebar_offset_top, width:sidebar_width, bottom:'' }); is_absolute = true; fixed_top = false; fixed_bottom = false; is_bottom = false; is_top = false; is_static = false; } }else{ /** 已经处于fixed bottom状态不操作 */ if(!fixed_bottom){ // console.log('已经处于fixed bottom状态不操作'); $sidebar.css({ position:'fixed', bottom:0, top:'', width:sidebar_width }); fixed_top = false; fixed_bottom = true; is_absolute = false; is_bottom = false; is_top = false; } } } } /** end if sidebar_height <= win_height */ /** * scrolling up */ }else if(win_pos < last_scroll_pos){ /** 边栏高度小于窗口高度 */ if(sidebar_height <= win_height){ /** 边栏顶高大于窗口顶高,进行fixed top */ if((parseInt($sidebar.offset().top) > win_pos) && (parseInt($sidebar.offset().top) > original_sidebar_offset_top) ){ if(!fixed_top){ sidebar_offset_top = $sidebar.offset().top; $sidebar.css({ position:'fixed', top:0, width:sidebar_width, bottom:'' }); fixed_top = true; fixed_bottom = false; is_bottom = false; is_top = false; is_static = false; is_absolute = false; } /** 边栏顶高处于极限高度,不进行操作 */ }else if(parseInt($sidebar.offset().top) <= original_sidebar_offset_top){ if(!is_static){ sidebar_offset_top = $sidebar.offset().top; $sidebar.attr('style',''); is_static = true; is_bottom = false; is_top = false; fixed_top = false; fixed_bottom = false; is_absolute = false; } } }else{ /** 边栏顶高小于原始边栏顶高,则取消所有css */ if(parseInt($sidebar.offset().top) <= original_sidebar_offset_top){ if(fixed_top){ $sidebar.attr('style',''); fixed_top = false; fixed_bottom = false; is_absolute = false; is_bottom = false; is_top = false; } /** 边栏顶高大于窗口顶高,则进行fixed top */ }else if(parseInt($sidebar.offset().top) >= last_scroll_pos){ /** 边栏顶高小于或等于初始边栏顶高,则取消所有css */ if(parseInt($sidebar.offset().top) <= original_sidebar_offset_top){ if(!is_static){ $sidebar.attr('style',''); fixed_top = false; fixed_bottom = false; is_bottom = false; is_top = false; is_static = true; is_absolute = false; } /** 不处于最顶处 */ }else{ // console.log('不再最顶'); if(!fixed_top){ $sidebar.css({ position:'fixed', top:0, width:sidebar_width }); fixed_top = true; fixed_bottom = false; is_bottom = false; is_top = false; is_static = false; is_absolute = false; } } /** 边栏顶高小于当前窗口顶高,则进行绝对定位 */ }else{ if(!is_absolute){ sidebar_offset_top = parseInt($sidebar.offset().top); $sidebar.css({ position:'absolute', top:sidebar_offset_top, bottom:'' }); is_absolute = true; fixed_top = false; fixed_bottom = false; is_bottom = false; is_top = false; is_static = false; } } } } // console.log('is_absolute:',is_absolute,'fixed_top:',fixed_top,'fixed_bottom:',fixed_bottom); /** 获取最后一次滚动的位置 */ last_scroll_pos = win_pos; } $win.on({ resize : resize, scroll : function(){ if(!check_fit_to_float()) return; adjust(); after_scroll(); /** 定时器不起作用啊,快速滚动时候,位置都乱了 */ } }); function resize(){ clearTimeout(resize_timer); resize_timer = setTimeout(function(){ if($sidebar.attr('style')) $sidebar.attr('style',''); limit_bottom = parseInt($footer.offset().top - 20); sidebar_width = $sidebar.outerWidth(); sidebar_height = $sidebar.outerHeight(); win_width = $win.width(); },1000); } function readjust(){ if(parseInt($sidebar.offset().top + $sidebar.outerHeight()) >= parseInt($footer.offset().top)){ if(!is_bottom){ $sidebar.css({ position:'absolute', top:parseInt($footer.offset().top - $sidebar.outerHeight()), bottom:'' }); is_absolute = true; is_bottom = true; fixed_top = false; fixed_bottom = true; is_top = false; } }else if(parseInt($sidebar.offset().top) < original_sidebar_offset_top){ if(!is_top){ $sidebar.css({ position:'static', top:'', bottom:'', left:'' }); is_top = true; is_absolute = false; is_bottom = false; fixed_top = false; fixed_bottom = false; } } } function after_scroll(){ clearTimeout(timer); timer = setTimeout(readjust,10); } } exports.zoom = { that : this, config : { content_reset_id : '.content-reset', img_id : '.content-reset a img' }, init : function() { var _this = this, that = _this.that, $content_resets = $(_this.config.content_reset_id), $imgs = $(_this.config.img_id), scroll_ele = navigator.userAgent.toLowerCase().indexOf('webkit') === -1 ? 'html' : 'body'; if(!$imgs[0]) return false; $content_resets.each(function(i){ var $content_reset = $(this), $img = $content_reset.find('a>img'), $a = $img.parent(), content_reset_top = $content_reset.offset().top, img_small_src = $img.attr('src'), img_large_src = $a.attr('href'); $a.on('click',function(){ var $this = $(this), img_large = new Image(); img_large.src = img_large_src; // load from cache if($this.hasClass('zoomed')){ // scroll to content_reset_top if($(scroll_ele).scrollTop() > $content_reset.offset().top){ $(scroll_ele).scrollTop($content_reset.offset().top - 80); } $img.attr({ src : img_small_src, }).removeAttr('width') .removeAttr('height'); $this.removeClass('zoomed'); }else{ var check = function(){ if(img_large.width > 0 || img_large.height > 0){ $img.attr({ width : img_large.width, height : img_large.height }); clearInterval(set); } }; var set = setInterval(check,200); if(img_large.complete){ $img.attr('src',img_large_src); }else{ $img.fadeTo('slow','0.5',function(){ if(img_large.complete){ $img.fadeTo('fast',1) .attr('src',img_large_src); } }); } $this.addClass('zoomed'); } return false; }); }); } }; /* exports.fixed_box = { config : { aside_id : '.widget-area aside' }, init : function(){ var $asides = $(exports.fixed_box.config.aside_id); if(!$asides[0]) return false; if(!exports.fixed_box.eligible_screen()) return false; $(window).resize(function(){ exports.fixed_box.eligible_screen(); }); var $last_aside = $asides.eq($asides.length - 1), last_ot = $last_aside.offset().top, last_h = $last_aside.height(), last_w = $last_aside.width(), t; console.log(last_ot+last_h); $(window).scroll(function(){ if(t) clearTimeout(t); t = setTimeout(function(){ exports.fixed_box.fixed_action($last_aside,last_ot+last_h,last_w); },200); }); }, eligible_screen : function(){ var w = $(window).width(); if(w <= 768) return false; return true; // console.log(w); }, fixed_action : function($fixed_ele,fixed_ele_ot,fixed_ele_w){ if($(window).scrollTop() > fixed_ele_ot){ $fixed_ele. addClass('aside-fixed') .css({ 'width' : fixed_ele_w + 'px' }) }else{ $fixed_ele.removeClass('aside-fixed'); } } }; */ exports.thumbnail_fix = { config : { }, init : function(){ var _this = this; _this.bind(); $(window).resize(function(){ _this.bind(); }); }, bind : function(){ var $a = $('.post-img-lists .post-list-link'); if(!$a[0]) return false; var prev_h = 0; $a.each(function(i){ var $this = $(this), w = $this.width(), h = $this.height(), new_h = Math.round(w*3/4), abs_h = Math.abs(prev_h - new_h); if(prev_h != 0 && abs_h > 0 && abs_h < 2){ new_h = prev_h; } $this.height(new_h); prev_h = new_h; }); } }; exports.qrcode = { config : { id : '#qrcode', box_id : '#qrcode-box', zoom_id : '#qrcode-zoom' }, cache : {}, init : function(){ var $qr = $(this.config.id); if(!$qr[0]) return false; var $box = $qr.find(this.config.box_id), $zoom = $qr.find(this.config.zoom_id); require.async(['modules/jquery.qrcode'],function(_a){ $zoom.find('#qrcode-zoom-code').qrcode(window.location.href); $qr.fadeIn(); $box.qrcode(window.location.href).on('click',function(){ require.async(['modules/jquery.dialog'],function(dialog){ $zoom.show(); var d = dialog({ title : false, quickClose: true, content : $zoom, fixed: true }); d.show(); }); }); }); } }; exports.search = function(){ var $fm = $('.fm-search'), st = false; if(!$fm) return false; var $box = $fm.find('.box'), $input = $fm.find('[name="s"]'); $fm.find('label').on('click',function(){ if($fm.hasClass('active')){ $fm.removeClass('active'); }else{ $fm.addClass('active'); $input.focus().select(); } }); $input.on('blur',function(){ st = setTimeout(function(){ $fm.removeClass('active'); },5000); }); $input.on('focus',function(){ st && clearTimeout(st); }); $fm.on('submit',function(){ if($.trim($input.val()) === ''){ $input.focus(); return false; } }); }; exports.hide_no_js = function(){ var $no_js = $('.hide-no-js'), $on_js = $('.hide-on-js'); $on_js[0] && $on_js.hide(); $no_js[0] && $no_js.show(); }; exports.mobile_menu = { config : { toggle_menu_id : '.menu-mobile-toggle' }, init : function(){ var $toggle_menu = $(this.config.toggle_menu_id); if(!$toggle_menu[0]) return false; $toggle_menu.each(function(){ $(this).find('a.toggle').on('click',function(){ var $target_menu = $($(this).data('target')); $target_menu.toggle(); }); }); } }; /** * lazyload for img * * @version 1.0.1 * @author KM@INN STUDIO * */ exports.lazyload = function(){ var $img = $('img[data-original]'); if(!$img[0]) return false; require.async(['modules/tools','modules/jquery.lazyload'],function(tools,_a){ $img.each(function(){ var $this = $(this); if(tools.in_screen($this)){ $this.attr('src',$this.data('original')); }else{ $this.lazyload(); } }); }); }; /** * Lbox for img of post content * * @version 1.0.0 * @author KM@INN STUDIO * */ exports.lbox = { config : { img_id : '.content-reset a>img', no_a_img_id : '.content-reset img' }, init : function(){ var _this = this, $img = $(_this.config.img_id); if(!$img[0]) return false; $img.each(function(){ $(this).parent().attr({ 'target' : '_blank', 'rel' : 'fancybox-button' }).addClass('lbox'); }); require.async(['modules/jquery.fancybox','modules/jquery.fancybox-buttons'],function(_a,_b){ $('.content-reset a.lbox').fancybox({ helpers : { buttons : {}, title : { type : 'float' } } }); }); } }; });<file_sep>/includes/theme-dev-mode/theme-dev-mode.php <?php /* Feature Name: Developer mode Feature URI: http://www.inn-studio.com Version: 1.2.0 Description: 启用开发者模式,助于维护人员进行调试,运营网站请禁用此模式 Author: INN STUDIO Author URI: http://www.inn-studio.com */ theme_dev_mode::init(); class theme_dev_mode{ public static $iden = 'theme_dev_mode'; private static $data = array(); public static function init(){ add_filter('theme_options_save',get_class() . '::options_save'); add_action('after_setup_theme',get_class() . '::mark_start_data',0); add_action('wp_footer',get_class() . '::hook_footer',9999); add_action('dev_settings',get_class() . '::display_backend'); } public static function mark_start_data(){ // if(!self::is_enabled()) return false; self::$data = array( 'start-time' => timer_stop(0), 'start-query' => get_num_queries(), 'start-memory' => sprintf('%01.3f',memory_get_usage()/1024/1024) ); } public static function is_enabled(){ $opt = (array)theme_options::get_options(self::$iden); return isset($opt['on']); } public static function display_backend(){ $opt = (array)theme_options::get_options(self::$iden); $checked = self::is_enabled() ? ' checked ' : null; ?> <fieldset> <legend><?php echo ___('Related Options');?></legend> <p class="description"><?php echo ___('For developers to debug the site and it will affect the user experience if enable, please note.');?></p> <table class="form-table"> <tbody> <tr> <th scope="row"> <label for="<?php echo self::$iden;?>"><?php echo ___('Developer mode');?></label> </th> <td> <label for="<?php echo self::$iden;?>"><input id="<?php echo self::$iden;?>" name="<?php echo self::$iden;?>[on]" type="checkbox" value="1" <?php echo $checked;?> /> <?php echo ___('Enabled');?></label> </td> </tr> </tbody> </table> </fieldset> <fieldset> <legend><?php echo ___('Theme Options');?></legend> <textarea class="code widefat" cols="50" rows="50" ><?php esc_textarea(print_r(theme_options::get_options()));?></textarea> </fieldset> <?php } /** * save * * * @params array * @return array * @version 1.0.2 * @author KM@INN STUDIO * */ public static function options_save($options){ $old_opt = (array)theme_options::get_options(self::$iden); if(isset($old_opt['on']) && !isset($_POST[self::$iden]['on'])){ @ini_set('max_input_nesting_level','9999'); @ini_set('max_execution_time','300'); remove_dir(get_stylesheet_directory() . theme_features::$basedir_js_min); remove_dir(get_stylesheet_directory() . theme_features::$basedir_css_min); theme_features::minify_force(get_stylesheet_directory() . theme_features::$basedir_js_src); theme_features::minify_force(get_stylesheet_directory() . theme_features::$basedir_css_src); theme_features::minify_force(get_stylesheet_directory() . theme_features::$basedir_includes); } if(isset($_POST[self::$iden]['on'])){ $options[self::$iden] = $_POST[self::$iden]; } return $options; } /** * compress * * @return * @version 1.0.0 * @author KM<NAME> */ public static function compress(){ $options = theme_options::get_options(); /** * if dev_mode is off */ if(!self::is_enabled() && !is_admin()){ ob_start('html_compress'); } } public static function hook_footer(){ $options = theme_options::get_options(); // if(!self::is_enabled()) return false; ?> <script> try{ <?php self::$data['end-time'] = timer_stop(0); self::$data['end-query'] = get_num_queries(); self::$data['end-memory'] = sprintf('%01.3f',memory_get_usage()/1024/1024); self::$data['theme-time'] = self::$data['end-time'] - self::$data['start-time']; self::$data['theme-query'] = self::$data['end-query'] - self::$data['start-query']; self::$data['theme-memory'] = self::$data['end-memory'] - self::$data['start-memory']; $data = array( ___('Theme Performance') => array( ___('Time (second)') => self::$data['theme-time'], ___('Query') => self::$data['theme-query'], ___('Memory (MB)') => self::$data['theme-memory'], ), ___('Basic Performance') => array( ___('Time (second)') => (float)self::$data['start-time'], ___('Query') => (float)self::$data['start-query'], ___('Memory (MB)') => (float)self::$data['start-memory'], ), ___('Final Performance') => array( ___('Time (second)') => (float)self::$data['end-time'], ___('Query') => (float)self::$data['end-query'], ___('Memory (MB)') => (float)self::$data['end-memory'], ), ); ?> (function(){ var data = <?php echo json_encode($data);?>; console.table(data); })(); }catch(e){} </script> <?php } } ?><file_sep>/includes/theme-defender/theme-defender.php <?php /* Feature Name: theme-defender Feature URI: http://www.inn-studio.com Version: 1.0.9 Description: Improve the seo friendly Author: INN STUDIO Author URI: http://www.inn-studio.com */ add_action('init','theme_defender::init',1); class theme_defender{ public static $iden = 'theme_defender'; private static $expire = 60; private static $connection = 45; private static $block_time = 60; public static function init(){ if(is_user_logged_in()) return false; $cache_id = md5(get_client_ip()); $connection = (int)theme_cache::get($cache_id) + 1; if($connection > self::$connection){ theme_cache::set($cache_id,$connection,null,self::$block_time); ob_start(); ?> <script> (function(){ var $number = document.getElementsByTagName('strong')[0], seconds = parseInt($number.innerHTML), si = setInterval(function(){ seconds--; $number.innerHTML = seconds; if(seconds === 0){ clearInterval(si); location.reload(); } },1050); })(); </script> <?php $js = ob_get_contents(); ob_end_clean(); wp_die( sprintf(___('Your behavior looks like brute Force attack, page will be refreshed after %s seconds automatically.'),'<strong>' . self::$block_time . '</strong>') . $js, ___('Defender'), array( 'response' => 403, ) ); }else{ theme_cache::set($cache_id,$connection,null,self::$expire); } } } ?><file_sep>/includes/theme-setting-import/static/js/src/init.js define(function(require, exports, module){ var $ = require('modules/jquery'), jQuery = $; exports.init = function(){ jQuery(document).ready(function(){ exports.bind(); }); }; exports.config = { frm_id : '#tis_frm', file_id : '#tis_file', tip_id : '#tis_tip', upload_area_id : '#tis_upload_area', upload_link_id : '#tis_upload', process_url : '', lang : { M00001 : 'Processing, please wait...', M00002 : 'Error: Your browser does not support HTML5. ', E00001 : 'Error: failed to complete the operation. ', E00002 : 'Error: Not match file. ' } }; exports.bind = function(){ if(!exports.hook.html5_check()){ alert(exports.config.lang.M00002); return false; } var $upload_link = jQuery(exports.config.upload_link_id); jQuery(exports.config.file_id).on('mouseover mouseout mousedown mouseup change',function(event){ if(event.type === 'mouseover'){ jQuery(exports.config.upload_link_id).addClass('hover'); } if(event.type === 'mouseout'){ jQuery(exports.config.upload_link_id).removeClass('hover').removeClass('active'); } if(event.type === 'mousedown'){ jQuery(exports.config.upload_link_id).addClass('active'); } if(event.type === 'mouseup'){ jQuery(exports.config.upload_link_id).removeClass('active'); } }); /** * html5 upload */ jQuery(exports.config.file_id)[0].addEventListener('change',exports.hook.file_select, false); }; exports.hook = { /** * html5_check */ html5_check : function(){ if(window.File && window.FileList && window.FileReader){ return true; }else{ return false; } }, /** * file_select */ file_select : function(e){ var files = e.target.files || e.dataTransfer.files; for(var i = 0,file;file = files[i];i++){ exports.hook.upload_file(file); } }, /** * upload_file */ upload_file : function(file){ if(file.type.indexOf('text') == 0){ var reader = new FileReader(), tools = require('modules/tools'); reader.onload = function(e){ exports.hook.text = e.target.result; var ajax_data = { 'tis_content' : e.target.result }; /** * start ajax */ jQuery.ajax({ url : exports.config.process_url + '?action=tis_upload', type : 'post', dataType : 'json', data : ajax_data, beforeSend : function(){ exports.hook.tip('loading',exports.config.lang.M00001); },success : function(data){ if(data && data.status === 'success'){ exports.hook.tip('success',data.des.content); location.reload(true); }else if(data && data.status === 'error'){ exports.hook.tip('error',data.des.content); }else{ exports.hook.tip('error',exports.config.lang.E00001); } },error : function(){ } }); }; reader.readAsText(file); }else{ exports.hook.tip('error',exports.config.lang.E00002); } }, /** * tip */ tip : function(type,str){ var tools = require('modules/tools'), $tip = jQuery(exports.config.tip_id), $upload_area = jQuery(exports.config.upload_area_id); switch(type){ case 'loading': $upload_area.hide(); $tip.html(tools.status_tip('loading',str)); break; case 'success': $upload_area.show(); $tip.html(tools.status_tip('success',str)); break; case 'error': $upload_area.show(); $tip.html(tools.status_tip('error',str)); break; default: $tip.html(str); } } }; /** * download */ exports.tis_download = function(){ jQuery('#tis_export').on('click',function(){ }); }; });<file_sep>/category.php <?php get_header();?> <div class="container grid-container"> <div id="main" class="main grid-70 tablet-grid-70 mobile-grid-100"> <dl class="mod mod-mixed"> <dt class="hide"><?php echo esc_html(single_cat_title('',false));?></dt> <dd class="mod-title"><?php echo theme_functions::get_crumb();?></dd> <?php if($paged > 1){ ?> <dd> <div class="area-pagination"> <?php echo theme_functions::get_post_pagination('posts-pagination posts-pagination-top');?> </div> </dd> <?php } ?> <dd class="mod-body"> <?php if(have_posts()){ while(have_posts()){ the_post(); theme_functions::archive_content(array( 'classes' => array('grid-parent grid-50 tablet-grid-50 mobile-grid-100') )); ?> <?php }/** end while */ }else{/** end have_posts */ echo status_tip('info',___('No data yet.')); } ?> </dd> </dl> <div class="area-pagination"> <?php echo theme_functions::get_post_pagination('posts-pagination posts-pagination-bottom');?> </div> </div> <?php get_sidebar();?> </div> <?php get_footer();?><file_sep>/includes/_theme-comment-face/theme-comment-face.php <?php /* Feature Name: theme_comment_face Feature URI: http://inn-studio.com Version: 1.0.1 Description: Author: INN STUDIO Author URI: http://inn-studio.com */ theme_comment_face::init(); class theme_comment_face{ public static $iden = 'theme_comment_face'; public static $key_style = 'theme-comment-face'; public static function init(){ add_filter('theme_options_save',get_class() . '::options_save'); add_filter('theme_options_default',get_class() . '::options_default'); add_action('frontend_seajs_use',get_class() . '::frontend_seajs_use'); add_action('page_settings',get_class() . '::options_display'); add_filter('get_comment_text',get_class() . '::filter_comment_output'); } public static function options_default($options){ $options[self::$iden] = array( 'emoticons' => array( '(⊙⊙!) ', 'ƪ(‾ε‾“)ʃƪ(', 'Σ(°Д°;', '눈_눈', '(๑>◡<๑) ', '(❁´▽`❁)', '(,,Ծ▽Ծ,,)', '(⺻▽⺻ )', '乁( ◔ ౪◔)「', 'ლ(^o^ლ)', '(◕ܫ◕)', '凸(= _=)凸' ) ); return $options; } public static function options_save($options){ $emoticons = isset($_POST[self::$iden]['emoticons']) ? $_POST[self::$iden]['emoticons'] : null; if($emoticons){ $options[self::$iden] = array( 'emoticons' => array_filter(explode(PHP_EOL,$emoticons)) ); } return $options; } public static function options_display(){ $options = theme_options::get_options(); $emoticons = (array)self::get_emoticons(); ?> <fieldset> <legend><?php echo ___('Face settings');?></legend> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="<?php echo self::$iden;?>-emoticons"><?php echo ___('Theme comment face emoticons (one per line)');?></label></th> <td> <textarea name="<?php echo self::$iden;?>[emoticons]" id="<?php echo self::$iden;?>-emoticons" cols="30" rows="10" class="widefat"><?php echo implode(PHP_EOL,$emoticons);?></textarea> </td> </tr> </tbody> </table> </fieldset> <?php } public static function get_emoticons(){ $options = theme_options::get_options(); $emoticons = isset($options[self::$iden]['emoticons']) ? array_map('stripslashes',$options[self::$iden]['emoticons']) : array(); return $emoticons; } public static function filter_comment_output($comment_text){ $pattern = '/\[([a-z]+\-[0-9]+\.[a-z]+)\]/i'; $comment_text = preg_replace_callback($pattern,function($matches){ if($matches[1]){ $output = '<img src="' . theme_features::get_theme_images_url('modules/theme-comment-face/' .$matches[1]) . '" alt="' . ___('Face') . '"/>'; return $output; } },$comment_text); return $comment_text; } public static function frontend_seajs_use(){ if(!is_singular()) return false; $faces_cache = theme_cache::get(self::$iden); if(empty($faces_cache)){ $face_dirs = theme_features::get_theme_path(theme_features::$basedir_images_min . 'modules/theme-comment-face/'); $files = glob($face_dirs . '*'); $faces_cache = array(); foreach($files as $file){ $faces_cache[] = basename($file); } theme_cache::set(self::$iden,$faces_cache); } ?> seajs.use(['<?php echo esc_js(theme_features::get_theme_includes_js(__FILE__));?>'],function(m){ m.config.faces_url = '<?php echo esc_js(theme_features::get_theme_images_url('modules/theme-comment-face/'));?>'; m.config.faces = <?php echo json_encode($faces_cache);?>; m.init(); }); <?php } } ?><file_sep>/includes/theme-comment-notify/theme-comment-notify.php <?php /** * @version 1.0.1 */ theme_comment_notify::init(); class theme_comment_notify { public static $iden = 'theme-comment-notify'; public static function init(){ add_action('page_settings',get_class() . '::display_backend'); add_filter('theme_options_default',get_class() . '::options_default'); add_filter('theme_options_save',get_class() . '::options_save'); if(!self::is_enabled()) return; add_action('comment_post',get_class() . '::reply_notify'); add_action('comment_unapproved_to_approved', get_class() . '::approved_notify'); } public static function is_enabled(){ $opt = theme_options::get_options(self::$iden); return isset($opt['on']) && $opt['on'] == 1 ? true : false; } public static function display_backend(){ $opt = theme_options::get_options(self::$iden); $is_checked = isset($opt['on']) && $opt['on'] == 1 ? ' checked ' : null; ?> <fieldset> <legend><?php echo ___('Comment reply notifier');?></legend> <p class="description"> <?php echo ___('It will send a mail to notify the being reply comment author when comment has been reply, if your server supports.');?></p> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="<?php echo self::$iden;?>-on"><?php echo ___('Enable or not?');?></label></th> <td><label for="<?php echo self::$iden;?>-on"><input type="checkbox" name="<?php echo self::$iden;?>[on]" id="<?php echo self::$iden;?>-on" value="1" <?php echo $is_checked;?> /><?php echo ___('Enable');?></label></td> </tr> </tbody> </table> </fieldset> <?php } public static function options_default($opts){ $opts[self::$iden]['on'] = 1; return $opts; } public static function options_save($opts){ if(isset($_POST[self::$iden])){ $opts[self::$iden] = $_POST[self::$iden]; }else{ $opts[self::$iden]['on'] = -1; } return $opts; } public static function approved_notify($comment){ global $comment; if(!is_email($comment->comment_author_email)) return false; $to = $comment->comment_author_email; $post_title = get_the_title($comment->comment_post_ID); $post_url = get_permalink($comment->comment_post_ID); $mail_title = sprintf(___('[%s] Your comment has been approved in "%s".'),get_bloginfo('name'),$post_title); ob_start(); ?> <p><?php echo sprintf(___('Your comment has been approved in "%s".'),'<a href="' . $post_url . '" target="_blank"><strong>' . $post_title . '</strong></a>');?></p> <p><?php echo esc_html(sprintf(___('Comment content: %s')),get_comment_text($comment->comment_ID));?></p> <p><?php echo sprintf(___('Article URL: %s'),'<a href="' . esc_url($post_url) . '">' . esc_url($post_url) . '</a>');?></p> <p><?php echo sprintf(___('Comment URL: %s'),'<a href="' . esc_url($post_url) . '#comment-' . $comment->comment_ID . '" target="_blank">' . esc_url($post_url) . '#comment-' . $comment->comment_ID . '</a>');?></p> <?php $mail_content = ob_get_contents(); ob_get_clean(); add_filter('wp_mail_content_type',get_class() . '::set_html_content_type'); wp_mail($to,$mail_title,$mail_content); remove_filter('wp_mail_content_type',get_class() . '::set_html_content_type'); } public static function reply_notify($comment_id){ $current_comment = get_comment($comment_id); /** * if current comment has not parent or current comment is unapproved, return false */ if($current_comment->comment_parent == 0 || $current_comment->comment_approved != 1) return false; $parent_comment = get_comment($current_comment->comment_parent); /** * send start */ self::send_email($parent_comment,$current_comment); } private static function send_email($parent_comment,$child_comment){ if(!is_email($parent_comment->comment_author_email)) return false; /** if parent email equal child email, do nothing */ if($parent_comment->comment_author_email == $child_comment->comment_author_email) return false; $post_id = $parent_comment->comment_post_ID; $post_title = get_the_title($post_id); $mail_title = sprintf(___('[%s] Your comment has a reply in "%s".'),esc_html(get_bloginfo('name')),esc_html($post_title)); ob_start(); ?> <p><?php echo sprintf(___('Your comment: %s'),get_comment_text($parent_comment->comment_ID));?></p> <p><?php echo sprintf(___('%s\'s reply: %s'),get_comment_author($child_comment->comment_ID),get_comment_text($child_comment->comment_ID));?></p> <p><?php echo sprintf(___('Views the comment: %s'),'<a href="' . esc_url(get_permalink($post_id)) . '#comment-' . $parent_comment->comment_post_ID . '" target="_blank">' . esc_html(get_permalink($post_id)) . '#comment-' . $parent_comment->comment_post_ID . '</a>');?></p> <?php $mail_content = ob_get_contents(); ob_end_clean(); add_filter('wp_mail_content_type',get_class() . '::set_html_content_type'); wp_mail($parent_comment->comment_author_email,$mail_title,$mail_content); remove_filter('wp_mail_content_type',get_class() . '::set_html_content_type'); } public static function set_html_content_type(){ return 'text/html'; } } ?> <file_sep>/includes/theme-open-sign/theme-open-sign.php <?php theme_open_sign::init(); class theme_open_sign{ public static $iden = 'theme_open_sign'; public static $open_types = array('sina','qq'); public static $key_user_open = array( 'id' => 'isos_open_id', 'type' => 'isos_open_type', 'avatar' => 'isos_open_avatar', 'token' => '<PASSWORD>', 'expire' => 'isos_open_expire', 'access' => 'isos_open_access', ); private static $open_url = 'http://opensign.inn-studio.com/api/'; private static $open_keys = array( 'sina' => array( 'akey' => '3461043641', 'skey' => '<KEY>', ) ); public static function init(){ add_action('wp_ajax_nopriv_isos_cb', get_class() . '::process_cb'); add_action('wp_ajax_nopriv_isos_redirect_get_auth', get_class() . '::process_redirect_get_auth'); } public static function get_process_auth_url($type){ if(!in_array($type,self::$open_types)) return false; $url = theme_features::get_process_url(array( 'action' => 'isos_redirect_get_auth', 'type' => $type, )); return $url; } private static function get_auth_url($type,$nonce){ if(!in_array($type,self::$open_types)) return false; switch($type){ case 'sina': // include dirname(__FILE__) . '/inc/sina/saetv2.ex.class.php'; $process_cb_url = urlencode(theme_features::get_process_url(array( 'action' => 'isos_cb', 'sina' => 'set-auth', 'uri' => isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : home_url(), 'nonce' => $nonce, ))); $open_url = add_query_arg(array( 'sina' => 'get-auth', 'uri' => $process_cb_url, // 'redirect_uri' => urlencode($process_cb_url), 'state' => $nonce, // 'mobile' => 'mobile', ),self::$open_url); break; default: $open_url = false; } return $open_url; } public static function process_redirect_get_auth(){ // !check_referer() && wp_die(___('Referer error')); // theme_features::check_nonce(); // echo 'asdf'; $type = isset($_GET['type']) ? $_GET['type'] : false; if(!in_array($type,self::$open_types)) return false; $nonce = wp_create_nonce(AUTH_KEY); switch($type){ case 'sina': $url = self::get_auth_url('sina',$nonce); // var_dump($url);exit; wp_redirect($url); exit; break; } } public static function process_cb(){ theme_features::check_nonce('nonce'); // print_r($_GET); /** * sina */ if(isset($_GET['sina'])){ /** * set-auth */ if($_GET['sina'] === 'set-auth'){ /** check nonce */ theme_features::check_nonce('nonce'); $access_token = isset($_GET['access_token']) ? $_GET['access_token'] : null; $expires_in = isset($_GET['expires_in']) ? (int)$_GET['expires_in'] : null; /** * check callback data */ if(!$access_token || !$expires_in){ $output['status'] = 'error'; $output['id'] = 'invalid_callback_data'; $output['msg'] = ___('Invalid callback data.'); die(theme_features::json_format($output)); } /** * auth */ include dirname(__FILE__) . '/inc/sina/saetv2.ex.class.php'; $sina = new SaeTClientV2( self::$open_keys['sina']['akey'] , self::$open_keys['sina']['skey'] , $access_token ); /** get uid */ $sina_uid = $sina->get_uid(); $sina_uid = $sina_uid['uid']; $sina_userdata = $sina->show_user_by_id($sina_uid); /** register insert user */ $user = self::user_exists_by_openid($sina_uid); if(empty($user)){ $user_id = wp_insert_user(array( 'user_login' => sanitize_user($sina_userdata['screen_name']), 'user_pass' => <PASSWORD>(), 'nickname' => $sina_userdata['screen_name'], 'display_name' => $sina_userdata['screen_name'], 'user_email' => self::get_tmp_email(), )); if(!is_wp_error($user_id)){ /** rename nicenian */ wp_update_user(array( 'ID' => $user_id, 'user_nicename' => $user_id )); add_user_meta($user_id,self::$key_user_open['id'],$sina_uid,$sina_uid); add_user_meta($user_id,self::$key_user_open['type'],'sina'); if(!empty($sina_userdata['avatar_large'])){ update_user_meta($user_id,'avatar',$sina_userdata['avatar_large']); } $user = get_user_by('id',$user_id); }else{ $output['status'] = 'error'; $output['id'] = $user_id->get_error_code(); $output['msg'] = $user_id->get_error_message(); die(theme_features::json_format($output)); } /** exists user */ }else{ // if(!empty($sina_userdata['avatar_large'])){ // $old_avatar = get_user_meta($user->ID,self::$key_user_open['avatar'],true); // if($old_avatar !== $sina_userdata['avatar_large']){ // update_user_meta($user->ID,self::$key_user_open['avatar'],$sina_userdata['avatar_large']); // } // } } /** update open data */ update_user_meta($user->ID,self::$key_user_open['token'],$access_token); update_user_meta($user->ID,self::$key_user_open['expire'],$expires_in); update_user_meta($user->ID,self::$key_user_open['access'],time()); wp_set_current_user($user->ID); wp_set_auth_cookie($user->ID); do_action('wp_login',$user->user_login); // var_dump($sina_userdata); // die(); /** redirect */ $redirect_uri = isset($_GET['uri']) ? urldecode($_GET['uri']) : null; if($redirect_uri){ wp_safe_redirect($redirect_uri); }else{ wp_safe_redirect(home_url()); } wp_die( ___('Redirecting, please wait...'), ___('Redirecting'), 302 ); }else if(isset($_GET['qq']) && $_GET['qq'] === 'get-auth'){ } /** * qq */ }else if(isset($_GET['qq'])){ } die(); } public static function get_tmp_email(){ return time() . mt_rand(100,999) . '@outlook.com'; } public static function process(){ $output = array(); $type = isset($_GET['type']) ? $_GET['type'] : false; if(!$type){ $output['status'] = 'error'; $output['id'] = 'invalid_type'; $output['msg'] = ___('Invalid type param.'); } switch($type){ case 'sina': break; } die(theme_features::json_format($output)); } public static function user_exists_by_openid($openid){ $users = get_users(array( 'meta_key' => self::$key_user_open['id'], 'meta_value' => $openid, 'number' => 1, )); return empty($users) ? null : $users[0]; } public static function frontend_seajs_use(){ if(is_user_logged_in() || !is_page(self::$page_slug)) return false; ?> seajs.use('<?php echo self::$iden;?>',function(m){ m.config.process_url = '<?php echo theme_features::get_process_url(array('action' => theme_quick_sign::$iden));?>'; m.config.lang.M00001 = '<?php echo esc_js(___('Loading, please wait...'));?>'; m.config.lang.E00001 = '<?php echo esc_js(___('Sorry, server error please try again later.'));?>'; m.init(); }); <?php } }<file_sep>/header.php <!DOCTYPE html><html <?php language_attributes(); ?>><head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <title><?php echo class_exists('theme_seo_plus') ? theme_seo_plus::wp_title( '-', false, 'right' ) : wp_title( '-', false, 'right' );?></title> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /><![endif]--> <meta name="renderer" content="webkit" /> <meta name="viewport" content="width=device-width" /> <meta name="author" content="INN STUDIO" /> <meta http-equiv="Cache-Control" content="no-transform" /> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> <?php echo theme_features::get_theme_css('modules/unsemantic-grid-responsive-tablet-no-ie7','normal');?> <?php echo theme_features::get_theme_css('frontend/fonts','normal');?> <?php echo theme_features::get_theme_css('frontend/style','normal',true);?> <link rel="shortcut icon" href="<?php echo theme_features::get_theme_images_url('frontend/favicon.ico',true);?>" type="image/x-icon" /> <?php wp_head();?> </head> <body <?php body_class(); ?>> <!--[if lte IE 8]> <style> #ie-notice{ clear: both; color: #555; font-size: 15px; padding: 5px; text-align: center; } </style> <div id="ie-notice"> <?php echo status_tip('ban','middle',sprintf(___('We recommend that you upgrade your web browser so that you can get the most of the %s website. Upgrading your browser should only take a few minutes. Please download the latest version of one of the following free browsers:'),get_bloginfo('name')) . ' <p class="ie-notice-browsers"> <a href="https://chrome.google.com" target="_blank" title="' . ___('Chrome') . '"><img src="https://cdn1.iconfinder.com/data/icons/all_google_icons_symbols_by_carlosjj-du/64/chrome.png" alt="' . ___('Chrome') . '"/></a> <a href="https://firefox.com" target="_blank" title="' . ___('Firefox') . '"><img src="https://aful.org/media/image/interop/mozilla-firefox_logo.png" alt="' . ___('Firefox') . '"/></a> <a href="http://opera.com" target="_blank" title="' . ___('Opera') . '"><img src="https://cdn1.iconfinder.com/data/icons/android-png/64/Android-Opera-Mini.png" alt="' . ___('Opera') . '"/></a> <a href="http://www.maxthon.com" target="_blank" title="' . ___('Maxthon') . '"><img src="http://upload.wikimedia.org/wikipedia/zh/thumb/0/02/Maxthonlogo.png/64px-Maxthonlogo.png" alt="' . ___('Maxthon') . '"/></a> <a href="http://windows.microsoft.com/' . strtolower(get_bloginfo('language')) . '/internet-explorer/download-ie" target="_blank" title="' . ___('Internet Explorer') . '"><img src="http://upload.wikimedia.org/wikipedia/en/thumb/1/10/Internet_Explorer_7_Logo.png/64px-Internet_Explorer_7_Logo.png" alt="' . ___('Internet Explorer') . '"/></a> </p> ' );?> </div> <![endif]--> <header class="header-bar-container"> <div class="header-bar-bg"> <div class="header-bar grid-container"> <!-- .left --> <div class="left"> <h1 class="blog-name hide-on-mobile" title="<?php echo esc_attr(get_bloginfo('description'));?>"><a href="<?php echo esc_url(home_url());?>"><span class="icon-home"></span><span class="after-icon"><?php echo esc_html(get_bloginfo('name'));?></span></a></h1> <h2 class="blog-description hide"><?php echo esc_attr(get_bloginfo('description'));?></h2> <div class="menu-desktop hide-on-mobile"> <?php /** * menu tools */ echo theme_cache::get_nav_menu(array( 'theme_location' => 'menu-header', 'menu_class' => 'menu', 'container' => 'nav', 'menu_id' => 'menu-header', )); ?> </div> <div class="menu-mobile-toggle hide-on-desktop hide-on-tablet"> <a href="javascript:void(0);" class="toggle" data-target="#menu-mobile-header"> <span class="icon-menu"></span><span class="after-icon"><?php echo esc_html(___('Navigation'));?></span> </a> </div> </div><!-- .left --> <!-- .right --> <div class="right"> <div class="left"> <?php /** * menu tools */ echo theme_cache::get_nav_menu(array( 'theme_location' => 'menu-tools', 'menu_class' => 'menu', 'container' => 'nav', 'menu_id' => 'menu-tools', )); ?> </div> <!-- .search --> <form role="search" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>" class="header-bar-meta meta-extra fm-search"> <div class="box"> <input id="header-bar-search" type="search" class="form-control" title="<?php echo esc_attr(___('Search'));?>" name="s" placeholder="<?php echo esc_attr(___('Search keyword'));?>" value="<?php echo esc_attr(get_search_query())?>" required /> <button type="submit" class="submit" title="<?php echo esc_attr(___('Submit'));?>"><span class="icon-search"></span><span class="after-icon hide"><?php echo esc_html(___('Search'));?></span></button> </div> <label for="header-bar-search"> <span class="icon-search"></span><span class="after-icon hide"><?php echo esc_html(___('Search'));?></span> </label> </form> </div><!-- .right --> <div class="clr"></div> <?php echo theme_cache::get_nav_menu( array( 'theme_location' => 'menu-header-mobile', 'menu_class' => 'menu menu-mobile hide clr', 'container' => 'nav', 'menu_id' => 'menu-mobile-header', ) ); ?> </div><!-- .grid-container --> </div><!-- .header-bar-bg --> </header><!-- .header-bar-container --> <file_sep>/static/js/src/modules/tools.js define(function(require, exports, module){ var $ = require('modules/jquery'),jQuery = $; /** * validate * * @return object * @version 1.0.0 * @author K<NAME> */ exports.validate = function(){ /** config */ this.process_url = ''; this.loading_tx = 'Loading, please wait...'; this.error_tx = 'Sorry, server error please try again later.'; this.$fm = ''; this.rules = {}; this.done = function(data){}; this.before = function(){}; this.always = function(){}; var that = this; this.cache = {}; this.init = function(){ that.$fm.validate({ rules : that.rules, submitHandler : function(fm){ that.$fm = $(fm); that.ajax.init(); } }); }; this.ajax = { init : function(){ that.before();/** callback before */ that.cache.$tip = that.$fm.find('.submit-tip'); that.tip('loading',that.loading_tx); that.$fm.find('.form-group-submit').hide(); that.$fm.find('.submit').attr('disabled',true); $.ajax({ url : that.process_url, type : 'post', data : that.$fm.serialize(), dataType : 'json' }).done(function(data){ if(data && data.status === 'success'){ that.tip(data.status,data.msg); if(data.redirect){ setTimeout(function(){ location.href = data.redirect; },1000); }else if(exports.$_GET['return']){ setTimeout(function(){ location.href = exports.$_GET['return']; },1000); } }else if(data && data.status === 'error'){ that.tip(data.status,data.msg); that.$fm.find('.form-group-submit').show(); that.$fm.find('.submit').removeAttr('disabled'); }else{ that.tip(data.status,that.error_tx); that.$fm.find('.form-group-submit').show(); that.$fm.find('.submit').removeAttr('disabled'); } /** callback done */ that.done(data); }).fail(function(){ that.tip('error',that.error_tx); that.$fm.find('.form-group-submit').show(); that.$fm.find('.submit').removeAttr('disabled'); }).always(function(){ /** callback always */ that.always(); }); } }; this.tip = function(t,s){ if(t === 'hide'){ that.cache.$tip.hide(); }else{ that.cache.$tip.html(exports.status_tip(t,s)).show(); } }; return this; } /** * $_GET */ exports.$_GET = {}; document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () { function decode(s) { return decodeURIComponent(s.split("+").join(" ")); } exports.$_GET[decode(arguments[1])] = decode(arguments[2]); }); /** * String.prototype.format */ String.prototype.format = function(){ var args = arguments; return this.replace(/\{(\d+)\}/g, function(m,i){ return args[i]; }); }; /** * in_screen * * @param object $(selector) * @return bool * @version 1.0.1 * @author KM@INN STUDIO */ exports.in_screen = function(s){ var w = $(window); return !(w.scrollTop() > s.offset().top + s.outerHeight() || w.scrollTop() + w.height() < s.offset().top); }; /** * auto_focus * * * @return $(obj) $this the focus element of jq * @version 1.0.1 * @author KM@INN STUDIO * */ exports.auto_focus = function($frm,selector){ if(typeof($frm) == 'undefined' || !$frm[0]) return false; selector = selector || '[required]'; $frm.find(selector).each(function(i){ var $this = $(this); if(!$.trim($this.val())){ $this.focus(); return false; } }); }; /** * frm_is_valid($this) 检测表单值为空 * * @params $this the form $ object * @return object * @return object.is_invalid bool The value is null or false * @return object.$this $($this) This current object * @version 1.0.1 * @author KM@INN STUDIO * */ exports.frm_is_valid = function($fm){ var _this = this, return_data = { $this : false, is_invalid : false }; fm.find("[required]").each(function(i){ var $this = $(this); if(!($.trim($this.val())) && !return_data.is_invalid){ warning_effect(100,5,function(){ $this.css({'border-color':'red'}); },function(){ $this.css({'border-color':''}); }); $this.val(''); $this.focus(); return_data.is_invalid = true; return_data.$this = $this; } }); function warning_effect(timeout,times,callback1,callback2){ var timeout = timeout ? timeout : 150, times = times ? times : 5, i = 0; var si = setInterval(function(){ /* call the callback1 */ if(i === 0 || (i % 2 == 0)){ callback1(); }else{ callback2(); } if(i >= times){ clearInterval(si); } i++; },timeout); } return return_data; }; /** * Check the value is email or not * * * @params string c the email address * @return bool true An email address if true * @version 1.0.0 * @author KM@INN STUDIO * */ exports.is_email = function(c){ if(!c) return false; var b=/^([a-zA-Z0-9])*(.)*([a-zA-Z0-9])@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/; flag=b.test(c); if(flag){ return true }else{ return false } }; /** * status_tip * * @param mixed * @return string * @version 1.1.0 * @author KM@INN STUDIO */ exports.status_tip = function(){ var defaults = ['type','size','content','wrapper'], types = ['loading','success','error','question','info','ban','warning'], sizes = ['small','middle','large'], wrappers = ['div','span'], type = null, icon = null, size = null, wrapper = null, content = null, args = arguments; switch(args.length){ case 0: return false; /** * only content */ case 1: content = args[0]; break; /** * only type & content */ case 2: type = args[0]; content = args[1]; break; /** * other */ default: for(var i in args){ eval(defaults[i] + ' = args[i];'); } } wrapper = wrapper || wrappers[0]; type = type || types[0]; size = size || sizes[0]; switch(type){ case 'success': icon = 'checkmark-circle'; break; case 'error' : icon = 'cancel-circle'; break; case 'info': case 'warning': icon = 'warning'; break; case 'question': case 'help': icon = 'help'; break; case 'ban': icon = 'minus'; break; case 'loading': case 'spinner': icon = 'spinner'; break; default: icon = type; } var tpl = '<' + wrapper + ' class="tip-status tip-status-' + size + ' tip-status-' + type + '"><span class="icon-' + icon + '"></span><span class="after-icon">' + content + '</span></' + wrapper + '>'; return tpl; } /** * cookie */ exports.cookie = { /** * get_cookie * * @params string * @return string * @version 1.0.0 * @author KM@INN STUDIO */ get : function(c_name){ var i,x,y,ARRcookies=document.cookie.split(';'); for(i=0;i<ARRcookies.length;i++){ x=ARRcookies[i].substr(0,ARRcookies[i].indexOf('=')); y=ARRcookies[i].substr(ARRcookies[i].indexOf('=')+1); x=x.replace(/^\s+|\s+$/g,''); if(x==c_name) return unescape(y); } }, /** * set_cookie * * @params string cookie key name * @params string cookie value * @params int the expires days * @return n/a * @version 1.0.0 * @author KM@INN STUDIO */ set : function(c_name,value,exdays){ var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? '' : '; expires=' + exdate.toUTCString()); document.cookie = c_name + '=' + c_value; } }; });<file_sep>/sidebar.php <div id="sidebar-container" class="grid-30 tablet-grid-30 mobile-grid-100"> <div id="sidebar" class="widget-area" role="complementary"> <?php /** * home widget */ if(is_home() && !theme_cache::dynamic_sidebar('widget-area-home')){ the_widget('WP_Widget_Recent_Posts'); the_widget('WP_Widget_Tag_Cloud'); the_widget('WP_Widget_Meta'); the_widget('WP_Widget_Recent_Comments'); /** * archive widget */ }else if((is_category() || is_archive() || is_search()) && !theme_cache::dynamic_sidebar('widget-area-archive')){ the_widget('WP_Widget_Recent_Posts'); the_widget('WP_Widget_Tag_Cloud'); the_widget('WP_Widget_Meta'); the_widget('WP_Widget_Recent_Comments'); /** * post widget */ }else if(is_singular('post') && !theme_cache::dynamic_sidebar('widget-area-post')){ the_widget('WP_Widget_Recent_Posts'); the_widget('WP_Widget_Tag_Cloud'); the_widget('WP_Widget_Meta'); the_widget('WP_Widget_Recent_Comments'); /** * page widget */ }else if(is_page() && !theme_cache::dynamic_sidebar('widget-area-page')){ the_widget('WP_Widget_Recent_Posts'); the_widget('WP_Widget_Tag_Cloud'); the_widget('WP_Widget_Meta'); the_widget('WP_Widget_Recent_Comments'); /** * 404 widget */ }else if(is_404() && !theme_cache::dynamic_sidebar('widget-area-404')){ the_widget('WP_Widget_Recent_Posts'); the_widget('WP_Widget_Tag_Cloud'); the_widget('WP_Widget_Meta'); the_widget('WP_Widget_Recent_Comments'); } ?> </div><!-- /.widget-area --> </div><!-- /#sidebar-container --><file_sep>/includes/_theme-comment-face/static/js/src/init.js define(function(require, exports, module){ var $ = require('modules/jquery'),jQuery = $; exports.config = { face_btn_id : '#comment-face li', face_box_id : '.comment-face-box', comment_id : '#comment', faces : '', faces_url : '' }; exports.init = function(){ jQuery(document).ready(function(){ exports.bind(); }); }; exports.cache = {}; exports.bind = function(){ exports.cache.$face_btn = jQuery(exports.config.face_btn_id); if(!exports.cache.$face_btn[0]) return false; /** * set cache */ exports.cache.$comment = jQuery(exports.config.comment_id); exports.cache.$face_btn.on('click',function(e){ e.preventDefault(); e.stopPropagation(); var $face_btn = jQuery(this); $face_btn.each(function(i){ var $this = jQuery(this), $box = $this.find(exports.config.face_box_id), face_len = exports.config.faces.length, as = '', $as; if(!$box.has('a')[0]){ for(var i=0;i<face_len;++i){ as += exports.hook.tpl_image(exports.config.faces_url + exports.config.faces[i],exports.config.faces[i]); } $as = jQuery(as); $box.append($as); } /** * show box or hide box */ $box.toggle(); // $box.is(':hidden') ? $box.slideDown('fast') : $box.slideUp('fast'); /** * when click the other ele, just to hide box */ jQuery(document).off('click').on('click',function(e){ var $target = jQuery(e.target); if($target != $box && !$box.is(':hidden')){ $box.toggle(); } }); $box.find('a').off().on('click',function(){ var $this = jQuery(this); var old_value = exports.cache.$comment.val(), face_id = $box.hasClass('type-text') ? $this.data('id') : '[' + $this.data('id') + ']'; exports.cache.$comment.focus(); exports.cache.$comment.val(old_value + ' ' + face_id + ' '); }); }); }); }; exports.hook = { tpl_image : function(img_src,id){ if(!img_src || !id) return false; var content = '<a href="javascript:void(0);" data-id="' + id + '"><img src="' + img_src + '" alt="" /></a>'; return content; }, tpl_text : function(id){ if(!img_src || !id) return false; var content = '<a href="javascript:void(0);" data-id="' + id + '">' + id + '</a>'; return content; } }; });<file_sep>/includes/theme-cache/theme-cache.php <?php /* Feature Name: theme-cache Feature URI: http://inn-studio.com Version: 2.1.1 Description: theme-cache Author: INN STUDIO Author URI: http://inn-studio.com */ theme_cache::init(); class theme_cache{ public static $cache_expire = 3600; public static $iden = 'theme-cache'; public static $cache; public static $cache_skey; public static function init(){ self::$cache_skey = md5(AUTH_KEY . theme_functions::$iden); if(!wp_using_ext_object_cache()){ if(!class_exists('phpFastCache')) include dirname(__FILE__) . '/inc/phpfastcache.php'; self::$cache = new phpFastCache(); self::$cache->option('securityKey',self::$cache_skey); self::$cache->option('path',WP_CONTENT_DIR); } add_action('base_settings',get_class() . '::backend_display'); add_action('wp_ajax_' . self::$iden, get_class() . '::process'); /** * When delete menu */ add_filter('pre_set_theme_mod_nav_menu_locations',function($return){ $caches = (array)self::get(self::$cache_skey); if(!isset($caches['nav-menus'])) return $return; unset($caches['nav-menus']); self::set(self::$cache_skey,$caches); return $return; }); /** * When delete menu */ add_action('wp_delete_nav_menu',function(){ $caches = (array)self::get(self::$cache_skey); if(!isset($caches['nav-menus'])) return; unset($caches['nav-menus']); self::set(self::$cache_skey,$caches); }); /** * When update widget */ add_filter('widget_update_callback',function($instance){ $caches = (array)self::get(self::$cache_skey); if(!isset($caches['widget-sidebars'])) return $instance; unset($caches['widget-sidebars']); self::set(self::$cache_skey,$caches); return $instance; }); /** * When update option for widget */ add_action('update_option_sidebars_widgets',function($old_value, $value){ $caches = (array)self::get(self::$cache_skey); if(!isset($caches['widget-sidebars'])) return; unset($caches['widget-sidebars']); self::set(self::$cache_skey,$caches); }); /** * When delete post */ add_action('delete_post',function(){ $caches = (array)self::get(self::$cache_skey); if(!isset($caches['queries'])) return; unset($caches['queries']); self::set(self::$cache_skey,$caches); }); } private static function get_process_url($type){ return add_query_arg(array( 'action' => self::$iden, 'return' => add_query_arg(self::$iden,1,get_current_url()), 'type' => $type ),theme_features::get_process_url()); } /** * Admin Display */ public static function backend_display(){ $options = theme_options::get_options(); ?> <fieldset id="<?php echo self::$iden;?>"> <legend><?php echo ___('Theme cache');?></legend> <p class="description"><?php echo ___('Maybe the theme used cache for improve performance, you can clean it when you modify some site contents if you want.');?></p> <table class="form-table"> <tbody> <?php if(class_exists('Memcache')){ ?> <tr> <th><?php echo ___('Memcache cache');?></th> <td><p> <?php if(file_exists(WP_CONTENT_DIR . '/object-cache.php')){ ?> <a class="button" href="<?php echo self::get_process_url('disable-cache');?>" onclick="return confirm('<?php echo ___('Are you sure DELETE object-cache.php to disable theme object cache?');?>')"> <?php echo ___('Disable theme object cache');?> </a> <a class="button" href="<?php echo self::get_process_url('re-enable-cache');?>" onclick="return confirm('<?php echo ___('Are you sure RE-CREATE object-cache.php to re-enable theme object cache?');?>')"> <?php echo ___('Re-enable theme object cache');?> </a> <?php }else { ?> <a class="button-primary" href="<?php echo self::get_process_url('enable-cache');?>"> <?php echo ___('Enable theme object cache');?> </a> <?php } ?> <span class="description"><span class="icon-exclamation"></span><span class="after-icon"><?php echo ___('Save your settings before click.');?></span></span> </p></td> </tr> <?php } ?> <tr> <th scope="row"><?php echo ___('Control');?></th> <td> <?php if(isset($_GET[self::$iden])){ echo status_tip('success',___('Theme cache has been cleaned or rebuilt.')); } ?> <p> <a href="<?php echo self::get_process_url('flush');?>" class="button" onclick="javascript:this.innerHTML='<?php echo ___('Processing, please wait...');?>'"><?php echo ___('Clean all cache');?></a> <a href="<?php echo self::get_process_url('widget-sidebars');?>" class="button" onclick="javascript:this.innerHTML='<?php echo ___('Processing, please wait...');?>'"><?php echo ___('Clean widget cache');?></a> <a href="<?php echo self::get_process_url('nav-menus');?>" class="button" onclick="javascript:this.innerHTML='<?php echo ___('Processing, please wait...');?>'"><?php echo ___('Clean menu cache');?></a> <span class="description"><span class="icon-exclamation"></span><span class="after-icon"><?php echo ___('Save your settings before clean');?></span></span> </p> </td> </tr> </tbody> </table> </fieldset> <?php } private static function disable_cache(){ $result = @unlink(WP_CONTENT_DIR . '/object-cache.php'); if($result === true) return true; die(sprintf(___('Can not delete the %s file, please make sure the folder can be written.'),WP_CONTENT_DIR . '/object-cache.php')); } private static function enable_cache(){ $result = copy(dirname(__FILE__) . '/object-cache.php',WP_CONTENT_DIR . '/object-cache.php'); if($result === true) return true; die(sprintf(___('Can not create the %s file, please make sure the folder can be written.'),WP_CONTENT_DIR . '/object-cache.php')); } /** * process */ public static function process(){ $output = null; $type = isset($_GET['type']) ? $_GET['type'] : null; if(isset($_GET['return'])){ switch($type){ case 'flush': self::cleanup(); break; case 're-enable-cache': self::cleanup(); self::disable_cache(); self::enable_cache(); break; case 'disable-cache': self::cleanup(); self::disable_cache(); break; case 'enable-cache': self::enable_cache(); break; default: $caches = (array)self::get(self::$cache_skey); if(isset($caches[$type])){ unset($caches[$type]); self::set(self::$cache_skey,$caches); } } if(isset($_GET['return'])){ wp_redirect($_GET['return']); }else{ wp_redirect(admin_url('themes.php?page=core-options')); } die(); } } public static function cleanup(){ if(wp_using_ext_object_cache()){ return wp_cache_flush(); } self::$cache->clean(); } private static function build_key($key,$group = ''){ return self::$cache_skey . $group . '-' . $key; } /** * Delete cache * * @param string $key Cache key * @param string $group Cache group * @return bool * @version 2.0 * @author KM@INN STUDIO */ public static function delete($key,$group = ''){ $key = self::build_key($key,$group); if(wp_using_ext_object_cache()){ return wp_cache_delete($key,$group); } return self::$cache->delete($key); } /** * Set cache * * @param string $key Cache ID * @param mixed $data Cache contents * @param string $group Cache group * @return int $expire Cache expire time (s) * @version 2.0.1 * @author KM@INN STUDIO */ public static function set($key,$data,$group = '',$expire = 3600){ $key = self::build_key($key,$group); $keys = (array)self::get('keys'); $keys_id = self::build_key('keys'); $add_to_keys = false; if(!isset($keys[$group]) || !in_array($key,$keys[$group])){ $keys[$group][] = $key; $add_to_keys = true; } if(wp_using_ext_object_cache()){ if($add_to_keys) wp_cache_set($keys_id,$keys,'',2505600); return wp_cache_set($key,$data,$group,$expire); } if($add_to_keys) self::$cache->set($keys_id,$keys,2505600); return self::$cache->set($key,$data,$expire); } /** * Get the cache * * @param string $key Cache ID * @param string $group Cache group * @param bool $force True to get cache forced * @return mixed * @version 2.0.0 * @author KM@INN STUDIO */ public static function get($key,$group = '',$force = false){ $key = self::build_key($key,$group); if(wp_using_ext_object_cache()){ return wp_cache_get($key,$group); } return self::$cache->get($key); } /** * Get comments * * @param string $id The cache id * @param int $expire Cache expire time * @return mixed * @version 2.0.1 * @author KM@INN STUDIO */ public static function get_comments($args,$expire = 3600){ $cache_group_id = 'comments'; $id = md5(serialize($args)); $caches = (array)self::get(self::$cache_skey); $cache = isset($caches[$cache_group_id][$cache_id]) ? $caches[$cache_group_id][$cache_id] : null; if(empty($cache)){ $cache = get_comments($args); $caches[$cache_group_id][$cache_id] = $cache; self::set(self::$cache_skey,$caches,null,$expire); } return $cache; } /** * Get queries * * @param string $id The cache id * @param int $expire Cache expire time * @return mixed * @version 2.0.1 * @author KM@INN STUDIO */ public static function get_queries($args,$expire = 3600){ $cache_group_id = 'queries'; $cache_id = md5(serialize($args)); $caches = (array)self::get(self::$cache_skey); $cache = isset($caches[$cache_group_id][$cache_id]) ? $caches[$cache_group_id][$cache_id] : null; if(empty($cache)){ $cache = new WP_Query($args); $caches[$cache_group_id][$cache_id] = $cache; self::set(self::$cache_skey,$caches,null,$expire); wp_reset_query(); } return $cache; } /** * output dynamic sidebar from cache * * @param string The widget sidebar name/id * @param int Cache expire time * @return string * @version 2.0.1 * @author KM@INN STUDIO */ public static function dynamic_sidebar($id,$expire = 3600){ if(is_singular()){ global $post; $cache_id_prefix = 'post-' . $post->ID; }else if(is_home()){ $cache_id_prefix = 'home'; }else if(is_category()){ $cache_id_prefix = 'cat-' . theme_features::get_current_cat_id(); }else if(is_tag()){ $cache_id_prefix = 'tag-' . theme_features::get_current_tag_id(); }else if(is_search()){ $cache_id_prefix = 'search'; }else if(is_404()){ $cache_id_prefix = 'error404'; }else{ $cache_id_prefix = 'unknow'; } $cache_group_id = 'widget-sidebars'; $cache_id = $cache_id_prefix . $id; $caches = (array)self::get(self::$cache_skey); $cache = isset($caches[$cache_group_id][$cache_id]) ? $caches[$cache_group_id][$cache_id] : null; if(empty($cache)){ ob_start(); dynamic_sidebar($id); $cache = html_compress(ob_get_contents()); ob_end_clean(); $caches[$cache_group_id][$cache_id] = $cache; self::set(self::$cache_skey,$caches,null,$expire); } echo $cache; return empty($cache) ? false : true; } /** * Get nav menu from cache * * @param string The widget sidebar name/id * @param int Cache expire time * @return string * @version 2.0.1 * @author KM@INN STUDIO */ public static function get_nav_menu($args,$expire = 3600){ $defaults = array( 'theme_location' => null, 'menu_class' => null, 'container' => 'nav', ); $r = wp_parse_args($args,$defaults); $cache_group_id = 'nav-menus'; if(is_singular()){ global $post; $cache_id_prefix = 'post-' . $post->ID; }else if(is_home()){ $cache_id_prefix = 'home'; }else if(is_category()){ $cache_id_prefix = 'cat-' . theme_features::get_current_cat_id(); }else if(is_tag()){ $cache_id_prefix = 'cat-' . theme_features::get_current_tag_id(); }else if(is_search()){ $cache_id_prefix = 'search'; }else if(is_404()){ $cache_id_prefix = 'error404'; }else{ $cache_id_prefix = 'unknow'; } $cache_id = $cache_id_prefix . $args['theme_location']; $caches = (array)self::get(self::$cache_skey); $cache = isset($caches[$cache_group_id][$cache_id]) ? $caches[$cache_group_id][$cache_id] : null; if(empty($cache)){ ob_start(); wp_nav_menu($r); $cache = html_compress(ob_get_contents()); ob_end_clean(); $caches[$cache_group_id][$cache_id] = $cache; self::set(self::$cache_skey,$caches,null,$expire); } return $cache; } } ?><file_sep>/includes/theme-recommended-post/theme-recommended-post.php <?php /** * theme recommended post * * @version 2.0.2 * @author KM@INN STUDIO */ theme_recommended_post::init(); class theme_recommended_post{ public static $iden = 'theme_recommended_post'; public static $css_id = 'theme-recommended-post'; public static function init(){ add_action('add_meta_boxes',get_class() . '::add_meta_boxes'); add_action('page_settings',get_class() . '::display_backend'); add_filter('theme_options_save',get_class() . '::options_save'); add_action('save_post',get_class() . '::save_post'); add_action('delete_post',get_class() . '::delete_post'); } public static function add_meta_boxes(){ $screens = array('post'); foreach ( $screens as $screen ) { add_meta_box( self::$iden, ___( 'Recommended post' ), get_class() . '::box_display', $screen, 'side' ); } } public static function box_display($post){ wp_nonce_field(self::$iden,self::$iden . '-nonce' ); $recomm_posts = (array)theme_options::get_options(self::$iden); $checked = in_array($post->ID,$recomm_posts) ? ' checked ' : null; $btn_class = $checked ? ' button-primary ' : null; ?> <label for="recomm-set" class="button widefat <?php echo $btn_class;?>"> <input type="checkbox" id="recomm-set" name="<?php echo self::$iden;?>" value="1" <?php echo $checked;?> /> <?php echo esc_html(___('Set it to recommended post'));?> </label> <?php } public static function delete_post($post_id){ if ( current_user_can( 'delete_posts' ) ){ $recomm_posts = (array)theme_options::get_options(self::$iden); $k = array_search($post_id,$recomm_posts); if(!$recomm_set && $k !== false){ unset($recomm_posts[$k]); sort($recomm_posts); theme_options::set_options(self::$iden,$recomm_posts); } } } public static function save_post($post_id){ if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false; if(!isset($_POST[self::$iden . '-nonce']) || !wp_verify_nonce($_POST[self::$iden . '-nonce'], self::$iden)) return false; $recomm_posts = (array)theme_options::get_options(self::$iden); $recomm_set = isset($_POST[self::$iden]) ? (int)$_POST[self::$iden] : null; $k = array_search($post_id,$recomm_posts); //var_dump($recomm_posts,$recomm_set);exit; /** * if checked and no add yet, just add to recomm. posts */ if($recomm_set && $k === false){ $recomm_posts[] = $post_id; theme_options::set_options(self::$iden,$recomm_posts); } /** * if no checked and added, just remove it */ if(!$recomm_set && $k !== false){ unset($recomm_posts[$k]); //var_dump(empty($recomm_posts));exit; if(empty($recomm_posts)){ theme_options::delete_options(self::$iden,null); }else{ sort($recomm_posts); theme_options::set_options(self::$iden,$recomm_posts); } } //var_dump(theme_options::get_options(self::$iden));exit; } public static function display_backend(){ $recomm_posts = (array)theme_options::get_options(self::$iden); ?> <fieldset> <legend><?php echo ___('Recommended posts');?></legend> <p><?php echo esc_html(___('Some feature will be use recommended posts.'));?></p> <table class="form-table"> <tbody> <tr> <th scope="row"><?php echo ___('Posts');?></th> <td> <?php if(!empty($recomm_posts)){ global $post,$wp_query; $wp_query = new WP_Query(array( 'posts_per_page' =>-1, 'post__in' => $recomm_posts )); if(have_posts()){ while(have_posts()){ the_post(); ?> <label for="recomm-post-<?php echo $post->ID;?>" class="button"> <input type="checkbox" id="recomm-post-<?php echo $post->ID;?>" name="<?php echo self::$iden;?>[]" value="<?php echo $post->ID;?>" checked/> <?php echo esc_html(get_the_title());?> </label> <?php } }else{ echo status_tip('info',esc_html(___('No any post yet'))); } wp_reset_query(); wp_reset_postdata(); }else{ echo status_tip('info',esc_html(___('No any post yet'))); } ?> </td> </tr> </tbody> </table> </fieldset> <?php } public static function options_save($options){ if(isset($_POST[self::$iden]) && is_array($_POST[self::$iden])){ $options[self::$iden] = $_POST[self::$iden]; } return $options; } }<file_sep>/page.php <?php get_header();?> <div class="container grid-container"> <?php echo theme_functions::get_crumb();?> <div id="main" class="main grid-70 tablet-grid-70 mobile-grid-100"> <?php theme_functions::page_content();?> <div class="hide quick-comment" data-post-id="<?php the_ID();?>"></div> <?php theme_quick_comment::frontend_display();?> </div> <?php get_sidebar();?> </div> <?php get_footer();?><file_sep>/includes/theme-clean-up/static/js/src/init.js define(function(require, exports, module){ var $ = require('modules/jquery'); exports.config = { btn_ids : { redundant_post_id : '#clean_redundant_posts', orphan_postmeta_id : '#clean_orphan_postmeta', redundant_comment_id : '#clean_redundant_comments', orphan_commentmeta_id : '#clean_orphan_commentmeta', orphan_relationship_id : '#clean_orphan_relationships', database_optimization_id : '#database_optimization' }, process_url : '', lang : { M00001 : 'Loading, please wait...', E00001 : 'Server error or network is disconnected.' } }; exports.init = function(){ $(document).ready(function(){ exports.bind(); }); }; exports.bind = function(){ var btn_ids = []; for(var k in exports.config.btn_ids){ btn_ids.push(exports.config.btn_ids[k]); } btn_ids = btn_ids.join(); $(btn_ids).on('click',function(){ var $this = $(this); exports.hook.process($this); }); } exports.hook = { process : function($btn){ if(typeof $btn == 'undefined') return false; var ajax_data = { type : $btn.attr('data-action') }; $.ajax({ url : exports.config.process_url, type : 'get', dataType : 'json', data : ajax_data, beforeSend : function(){ exports.hook.tips($btn,'loading',exports.config.lang.M00001); },success : function(data){ if(data && data.status && data.status === 'success'){ exports.hook.tips($btn,'success',data.des.content); }else if(data && data.status && data.status === 'error'){ exports.hook.tips($btn,'error',data.des.content); }else{ exports.hook.tips($btn,'error',exports.config.lang.E00001); } },error : function(){ exports.hook.tips($btn,'error',exports.config.lang.E00001); } }) }, tips : function($b,t,s,hide){ require.async(['modules/tools'],function(tools){ var $next = $b.next(); if($next.hasClass('tip-status')){ $next.replaceWith(tools.status_tip(t,'small',s,'span')); }else{ $b.after(' ' + tools.status_tip(t,'small',s,'span')); } }); } } });
97294be855c9c5b713490edbb9cbc34473629e83
[ "JavaScript", "Markdown", "PHP" ]
47
PHP
kmvan/wp-theme-inn2015
6c18ccba4441fe0fc3ae237f897ef27986303fd4
90587b6c8c6a52d7700593752becaa6bc67314c4
refs/heads/master
<file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using Lab1A.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Lab1A.Data { public class DealershipMgr { private static List<Dealership> Dealerships { get; set; } public DealershipMgr() { Dealerships = new List<Dealership> { new Dealership { Email = "<EMAIL>", Id = 1, Name = "<NAME>", PhoneNumber = "(111) 111-1111" }, new Dealership { Email = "<EMAIL>", Id = 2, Name = "<NAME>", PhoneNumber = "(222) 222-2222" } }; } public DealershipMgr(List<Dealership> dealerships) { Dealerships = dealerships; } public List<Dealership> Get() { return Dealerships; } public Dealership Get(int? id) { if (id == null) { return null; } return Dealerships.SingleOrDefault(d => d.Id == id); } public void Post(Dealership dealership) { if (dealership != null) { Dealerships.Add(dealership); } } public void Put(int id, Dealership updated) { if (id == updated.Id) { var dealership = Dealerships.SingleOrDefault(d => d.Id == updated.Id); if (dealership != null) { dealership = updated; } } } public void Delete(int id) { Dealerships.RemoveAll(d => d.Id == id); } } } <file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using Lab1A.Data; using Lab1A.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace Lab1ATest { [TestClass] public class UnitTest1 { private static DealershipMgr _dealershipMgr; [ClassInitialize] public static void Initialize(TestContext tc) { List<Dealership> dealerships = new List<Dealership> { new Dealership { Email = "<EMAIL>", Id = 1, Name = "<NAME>", PhoneNumber = "(111) 111-1111" }, new Dealership { Email = "<EMAIL>", Id = 2, Name = "<NAME>", PhoneNumber = "(222) 222-2222" } }; _dealershipMgr = new DealershipMgr(dealerships); } [TestMethod] public void ValidGet() { // Arrange // Act Dealership dealership = _dealershipMgr.Get(1); // Assert Assert.AreEqual("<EMAIL>", dealership.Email); Assert.AreEqual(1, dealership.Id); Assert.AreEqual("<NAME>", dealership.Name); Assert.AreEqual("(111) 111-1111", dealership.PhoneNumber); } [TestMethod] public void InvalidGet() { // Arrange // Act Dealership dealership = _dealershipMgr.Get(3); // Assert Assert.IsNull(dealership); } [TestMethod] public void ValidPost() { // Arrange Dealership dealership = new Dealership { Email = "<EMAIL>", Id = 3, Name = "<NAME>", PhoneNumber = "(333) 333-3333" }; // Act _dealershipMgr.Post(dealership); // Assert Assert.AreEqual(3, _dealershipMgr.Get().Count); } [TestMethod] public void InvalidPost() { // Arrange Dealership dealership = null; // Act _dealershipMgr.Post(dealership); // Assert Assert.AreEqual(3, _dealershipMgr.Get().Count); } } } <file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Lab1A.Data; using Lab1A.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace Lab1A.Controllers { [Route("api/[controller]")] [ApiController] public class DealershipApiController : ControllerBase { private static DealershipMgr _dealershipMgr; public DealershipApiController() { _dealershipMgr = new DealershipMgr(); } // GET: api/DealershipApi [HttpGet] public IEnumerable<Dealership> Get() { return _dealershipMgr.Get(); } // GET: api/DealershipApi/5 [HttpGet("{id}", Name = "Get")] public Dealership Get(int id) { return _dealershipMgr.Get(id); } // POST: api/DealershipApi [HttpPost] public void Post([FromBody] string dealership) { _dealershipMgr.Post(JsonConvert.DeserializeObject<Dealership>(dealership)); } // PUT: api/DealershipApi/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string dealership) { _dealershipMgr.Put(id, JsonConvert.DeserializeObject<Dealership>(dealership)); } // DELETE: api/ApiWithActions/5 [HttpDelete("{id}")] public void Delete(int id) { _dealershipMgr.Delete(id); } } } <file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Lab1A.Models { public class Car { [Key] public int Id { get; set; } [Required] public string Make { get; set; } [Required] public string Model { get; set; } [Required] public int Year { get; set; } [Required] public int Vin { get; set; } public string Color { get; set; } public int DealershipId { get; set; } } } <file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Lab1A.Models; namespace Lab1A.Models { public class Lab1AContext : DbContext { public Lab1AContext (DbContextOptions<Lab1AContext> options) : base(options) { } public DbSet<Lab1A.Models.Car> Car { get; set; } public DbSet<Lab1A.Models.Member> Member { get; set; } } } <file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Lab1B.Data; using Lab1B.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace Lab1B.Controllers { public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; public AccountController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) { _userManager = userManager; _roleManager = roleManager; } public async Task<IActionResult> Seed() { ApplicationUser user1 = new ApplicationUser { FirstName = "User", LastName = "One", BirthDate = DateTime.Now, Email = "<EMAIL>", UserName = "<EMAIL>" }; ApplicationUser user2 = new ApplicationUser { FirstName = "User", LastName = "Two", BirthDate = DateTime.Now, Email = "<EMAIL>", UserName = "<EMAIL>" }; IdentityResult result = await _userManager.CreateAsync(user1, "Password1!"); if (!result.Succeeded) return View("Error", new ErrorViewModel { RequestId = "Failed to add new user." }); result = await _userManager.CreateAsync(user2, "Password2!"); if (!result.Succeeded) return View("Error", new ErrorViewModel { RequestId = "Failed to add new user." }); result = await _roleManager.CreateAsync(new IdentityRole("Staff")); if (!result.Succeeded) return View("Error", new ErrorViewModel { RequestId = "Failed to add new role." }); result = await _roleManager.CreateAsync(new IdentityRole("Manager")); if (!result.Succeeded) return View("Error", new ErrorViewModel { RequestId = "Failed to add new role." }); result = await _userManager.AddToRoleAsync(user1, "Staff"); if (!result.Succeeded) return View("Error", new ErrorViewModel { RequestId = "Failed to assign role." }); result = await _userManager.AddToRoleAsync(user2, "Manager"); if (!result.Succeeded) return View("Error", new ErrorViewModel { RequestId = "Failed to assign role." }); return RedirectToAction("Index", "Home"); } } }<file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Lab1B.Models; namespace Lab1B.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Lab1B.Models.Dealership> Dealership { get; set; } } } <file_sep>// I, <NAME>, student number 000730702, certify that this material is my // original work. No other person's work has been used without due // acknowledgement and I have not made my work available to anyone else. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Lab1A.Models { public class Member { [Key] public int Id { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required] public string UserName { get; set; } [Required] public string Email { get; set; } public string Company { get; set; } public string Position { get; set; } public DateTime BirthDate { get; set; } } }
bdff5c5085957c17e5918e12f4f7729e7544fa01
[ "C#" ]
8
C#
000730702/Lab1B
bdadfd3f29650a4ad21279c7916a58e9bf45d5c4
003cadc3c805e8bdf111bd0651cf6172401d4000
refs/heads/master
<repo_name>willskemp/ExData_Plotting1<file_sep>/Plot4.R # Load 'lattice' package require(lattice) # Set working directory to file location setwd("C:/Users/william.kemp/Desktop/Data Science - <NAME>/4. Exploratory Data Analysis/Week 1 Peer Review/Dataset") # Read in the data file with ";" separator plotdata <- read.table("household_power_consumption.txt",sep=";",header =T, na.strings ="?") # Convert date and time data to "POSIXct" format. Create new merged DateTime variable. plotdata$DateTime <- with(plotdata,as.POSIXct(paste(Date,Time),format="%d/%m/%Y %H:%M:%S")) plotdata$Date <- as.Date(plotdata$Date,format ="%d/%m/%Y") plotdata$Time <- strptime(plotdata$Time,format="%H:%M:%S") # Create new dataset called 'subdata' #This will consists of plotdata filtered to the data range 2007-02-01 and 2007-02-02 subdata <- subset(plotdata,Date>="2007-02-01" & Date <="2007-02-02") # Plot 4 png(filename ="Plot4.png", height = 480,width =480) par(mfrow=c(2,2)) plot(subdata$DateTime,subdata$Global_active_power,type="l", xlab="",ylab="Global Active Power (kilowatts") plot(subdata$DateTime,subdata$Voltage,type="l", xlab="datetime",ylab="Voltage") plot(subdata$DateTime,subdata$Sub_metering_1,type="l", xlab="",ylab="Energy sub metering") lines(subdata$DateTime,subdata$Sub_metering_2,col = 2) lines(subdata$DateTime,subdata$Sub_metering_3,col = 4) legend("topright",legend = c("sub_metering_1","sub_metering_2","sub_metering_3"), lwd = c(0.5,0.5,0.5),col= c(1,2,4),cex=0.75) plot(subdata$DateTime,subdata$Global_reactive_power,type="l", xlab="datetime",ylab="Global_reactive_power") dev.off()
825d0fde1d0f828559fa75ddfa85a7ee443cc91f
[ "R" ]
1
R
willskemp/ExData_Plotting1
17795977388c80bd0662060e90efeb20a7274ea4
dc83a5496eedc9cc6f764948bb44ac679c1a8060
refs/heads/master
<repo_name>fertlthomas/Spendenportal<file_sep>/user_mgmt.sql -- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Erstellungszeit: 13. Sep 2016 um 16:35 -- Server-Version: 10.1.10-MariaDB -- PHP-Version: 7.0.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Datenbank: `user_mgmt` -- -- -------------------------------------------------------- -- -- Tabellenstruktur für Tabelle `fos_user` -- CREATE TABLE `fos_user` ( `id` int(11) NOT NULL, `username` varchar(180) COLLATE utf8_unicode_ci NOT NULL, `username_canonical` varchar(180) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(180) COLLATE utf8_unicode_ci NOT NULL, `email_canonical` varchar(180) COLLATE utf8_unicode_ci NOT NULL, `enabled` tinyint(1) NOT NULL, `salt` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `last_login` datetime DEFAULT NULL, `locked` tinyint(1) NOT NULL, `expired` tinyint(1) NOT NULL, `expires_at` datetime DEFAULT NULL, `confirmation_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `password_requested_at` datetime DEFAULT NULL, `roles` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:array)', `credentials_expired` tinyint(1) NOT NULL, `credentials_expire_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Daten für Tabelle `fos_user` -- INSERT INTO `fos_user` (`id`, `username`, `username_canonical`, `email`, `email_canonical`, `enabled`, `salt`, `password`, `last_login`, `locked`, `expired`, `expires_at`, `confirmation_token`, `password_requested_at`, `roles`, `credentials_expired`, `credentials_expire_at`) VALUES (1, 'ricco', 'ricco', '<EMAIL>', '<EMAIL>', 1, '<PASSWORD>', '$<PASSWORD>$jspIm<PASSWORD>ZFRm<PASSWORD>OUePGiqPzt20m/zjylq2SOpz.48OnnSO', '2016-09-13 15:54:53', 0, 0, NULL, NULL, NULL, 'a:0:{}', 0, NULL); -- -- Indizes der exportierten Tabellen -- -- -- Indizes für die Tabelle `fos_user` -- ALTER TABLE `fos_user` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `UNIQ_957A647992FC23A8` (`username_canonical`), ADD UNIQUE KEY `UNIQ_957A6479A0D96FBF` (`email_canonical`), ADD UNIQUE KEY `UNIQ_957A6479C05FB297` (`confirmation_token`); -- -- AUTO_INCREMENT für exportierte Tabellen -- -- -- AUTO_INCREMENT für Tabelle `fos_user` -- ALTER TABLE `fos_user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/README.md # Spendenportal Eine Website um den "kleinen Mann" in Österreich zu helfen.
8e17d90b7d3c80601d3ace5d156e61b8eff3953f
[ "Markdown", "SQL" ]
2
SQL
fertlthomas/Spendenportal
27cc68d4a8316f080bf6d282452aa2315f4f5f92
ce570b817941ce3e75a14bc79099a9a238c54490
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson15_hw { class Program { static void PrintGame(Game g) { int number = g.TellMeHowManyPlayers(); Console.WriteLine($"Game Info:\n {g} Players number: {number}"); } static void Main(string[] args) { Game dmc = new Game("DMC-5", 20, 5.6f, "Japan"); Game forza = new Game("Forza"); Game needForSpeed = new Game() { _name = "Need For Speed", _numberOfPlayers = 2, _originCountry = "Spain" }; needForSpeed._rating = 7.8f; Game ashpalt9 = new Game("Asphalt-9", "Mexico"); PrintGame(dmc); PrintGame(forza); PrintGame(needForSpeed); } } }
1fcc1c147d9e7771a5baae915025e10e3c925bee
[ "C#" ]
1
C#
samar-mansour/Lesson15_hw
8ff98a3f90c1cb9c3f0e2f7f28e01f7e310857de
06bf834603d50d4a4252fd2d5ffd53dc12414f70
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveEnemy : MonoBehaviour { public float speed; // Start is called before the first frame update private void Start() { } // Update is called once per frame private void FixedUpdate() { Move(); } private void Move() { transform.Translate(Vector2.right * speed * Time.deltaTime); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("WallTrigger")) { Debug.Log("Colliding"); enabled = false; } } }<file_sep># FarmEngage Your job is to protect your hut from enemies. Build, upgrade, recruit helpers and keep shooting. ![Preview](https://github.com/FuhrmannMaciej/FarmEngage/blob/master/MarketingAssets/startgamescreen.png) ## Built With Unity - Unity Version 2019.2.17f1 C# Aseprite - software for pixel art creation ## Authors <NAME> ## License This project is licensed under the MIT License - see the LICENSE.md file for details Project under development. <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { private int enemyDamage = 5; private int attackRate = 3; public int enemyHealth; private int enemyHealthStart = 50; public Player playerScript; public WaveSpawner waveSpawner; public List<GameObject> activeEnemies; // Start is called before the first frame update private void Start() { SetMaxEnemyHealth(); } // Update is called once per frame private void Update() { } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("WallTrigger")) { StartCoroutine(Attack()); } } private IEnumerator Attack() { while (playerScript.playerHealth >= 0) { playerScript.HurtPlayer(enemyDamage); yield return new WaitForSeconds(attackRate); } } public void EnemyHurt(int damage) { enemyHealth -= damage; } public void SetMaxEnemyHealth() { enemyHealth = enemyHealthStart; } public void EnemyDied() { if (waveSpawner.enemyToSpawn != null && waveSpawner.enemyToSpawn.activeInHierarchy) { waveSpawner.enemiesAlive--; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public bool isGamePaused = false; #region Singleton private static GameManager gameManagerInstance; public static GameManager Instance => gameManagerInstance; private void Awake() { MakeSingleton(); } private void MakeSingleton() { if (gameManagerInstance != null && gameManagerInstance != this) { Destroy(gameObject); } else { gameManagerInstance = this; DontDestroyOnLoad(gameObject); } } #endregion Singleton private void Update() { if (Time.timeScale == 0f) { isGamePaused = true; } else { isGamePaused = false; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; public class WaveSpawner : MonoBehaviour { public int enemiesAlive = 0; public Day[] days; public Day day; public int dayIndex = 0; public GameObject enemyToSpawn; public UpgradeMenu upgradeMenuScript; public GameManager gameManager; public ObjectPooler OP; #region Singleton private static WaveSpawner waveSpawnerInstance; public static WaveSpawner Instance => waveSpawnerInstance; private void MakeSingleton() { if (waveSpawnerInstance != null && waveSpawnerInstance != this) { Destroy(gameObject); } else { waveSpawnerInstance = this; } } #endregion Singleton private void Awake() { MakeSingleton(); OP = ObjectPooler.SharedInstance; } // Start is called before the first frame update private void Start() { enemiesAlive = 0; StartCoroutine(upgradeMenuScript.HidePanelWithDayNumber()); } // Update is called once per frame private void Update() { TimerPerDay(); if (enemiesAlive == 0 && day.lengthOfDay <= 0) { dayIndex++; day.lengthOfDay = 90f; upgradeMenuScript.OpenUpgradeMenu(); } } //do something about object pooler !! public IEnumerator SpawnDayWave() { if (days.Length > dayIndex) { day = days[dayIndex]; while (day.lengthOfDay > 5) { yield return new WaitForSeconds(Random.Range(2, 5)); SpawnEnemy(); } } } private void SpawnEnemy() { enemyToSpawn = OP.GetPooledObject(0); if (enemyToSpawn != null) { enemyToSpawn.SetActive(true); enemiesAlive++; } } private void TimerPerDay() { if (day.lengthOfDay > 0 && day != null) { day.lengthOfDay -= Time.deltaTime; } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Weapon { public string name; public int damage; public int ammoCapacity; public int ammo; public int reloadTime; }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UpgradeMenu : MonoBehaviour { public GameObject upgradeUI; public GameObject panelWithDayNum; public WaveSpawner waveSpawner; public Text text; public void ContinueButton() { CloseUpgradeMenu(); } public void OpenUpgradeMenu() { panelWithDayNum.SetActive(true); Time.timeScale = 0.0f; upgradeUI.SetActive(true); } public void CloseUpgradeMenu() { Time.timeScale = 1.0f; upgradeUI.SetActive(false); StartCoroutine(HidePanelWithDayNumber()); } public IEnumerator HidePanelWithDayNumber() { UpdatePanelDayNumber(); yield return new WaitForSeconds(4); panelWithDayNum.SetActive(false); StartCoroutine(waveSpawner.SpawnDayWave()); } private void UpdatePanelDayNumber() { panelWithDayNum.SetActive(true); text.text = "Day " + (waveSpawner.dayIndex + 1); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class EnemyBlueprint { public GameObject enemy; }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Day { public EnemyBlueprint[] enemiesPerDay; public float lengthOfDay = 90f; }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public int playerHealth; private int playerHealthStart = 10000; public Enemy enemyScript; private Vector3 ray; private Vector2 tapPosition; private RaycastHit2D hit; private TouchPhase touchPhase = TouchPhase.Began; public Weapon[] weapons; public Weapon equipedWeapon; public int currentWeapon = 0; public string enemyTag = "Enemy"; #region Singleton private static Player playerInstance; public static Player Instance { get { return playerInstance; } } private void Awake() { MakeSingleton(); } private void MakeSingleton() { if (playerInstance != null && playerInstance != this) { Destroy(gameObject); } else { playerInstance = this; } } #endregion Singleton // Start is called before the first frame update private void Start() { SetStartHealth(); SetStartWeapon(); } // Update is called once per frame private void Update() { if (playerHealth <= 0) { PlayerDied(); } if (IsScreenTouched()) { UpdateTarget(); Shoot(); if (equipedWeapon.ammo <= 0) { StartCoroutine(Reload()); } } } private bool IsScreenTouched() { if (Input.touchCount == 1 && equipedWeapon.ammo > 0 && Input.GetTouch(0).phase == touchPhase) { ray = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); tapPosition = new Vector2(ray.x, ray.y); return true; } else { return false; } } private void Shoot() { if (enemyScript != null) { enemyScript.EnemyHurt(equipedWeapon.damage); equipedWeapon.ammo--; if (enemyScript.enemyHealth <= 0) { enemyScript.EnemyDied(); } } else { equipedWeapon.ammo--; } } private IEnumerator Reload() { yield return new WaitForSeconds(equipedWeapon.reloadTime); equipedWeapon.ammo = equipedWeapon.ammoCapacity; } public void HurtPlayer(int damage) { playerHealth -= damage; } private void SetStartWeapon() { equipedWeapon = weapons[0]; equipedWeapon.ammo = equipedWeapon.ammoCapacity; } public void SetStartHealth() { playerHealth = playerHealthStart; } private void PlayerDied() { Time.timeScale = 0.0f; } private void UpdateTarget() { GameObject touchedObject = null; hit = Physics2D.Raycast(tapPosition, Vector2.zero); if (hit.collider != null) { touchedObject = hit.transform.gameObject; } if (touchedObject != null && touchedObject.CompareTag(enemyTag)) { enemyScript = touchedObject.GetComponent<Enemy>(); } else { enemyScript = null; } } }
72850d2cb90cfd24de75b83622349a24d55f0d3b
[ "Markdown", "C#" ]
10
C#
FuhrmannMaciej/FarmEngage
74565b181a23a0834749c43749087884ba37ee6f
d32ee947491bf55e6aa3a7bae8d0c4abbfd25e9e
refs/heads/master
<repo_name>gopinathdanda/pennapps-2015w<file_sep>/README.md # Some Pebble App Have no idea what I'm building yet. But it is going to be a Pebble app. <file_sep>/pebble/accel/src/accel.c #include "pebble.h" #define ACCEL_STEP_MS 1000 static Window *window; static TextLayer *accel_layer; static AppTimer *timer; static bool motor; static void up_click_handler(ClickRecognizerRef recognizer, void *context) { text_layer_set_text(accel_layer, "Move up"); } static void select_click_handler(ClickRecognizerRef recognizer, void *context) { if(!motor){ motor = true; text_layer_set_text(accel_layer, "Waking up"); }else{ motor = false; text_layer_set_text(accel_layer, "Sleeping"); } } static void down_click_handler(ClickRecognizerRef recognizer, void *context) { text_layer_set_text(accel_layer, "Move down"); } static void click_config_provider(void *context) { // Register the ClickHandlers window_single_click_subscribe(BUTTON_ID_UP, up_click_handler); window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler); } static void timer_callback(void *data) { AccelData accel = (AccelData) { .x = 0, .y = 0, .z = 0 }; // Get AccelData in accel variable accel_service_peek(&accel); static char move[0x100]; if(motor){ // Logic if((accel.x<500 && accel.x>-500) && accel.y>500){ snprintf(move, sizeof(move), "Turn right"); }else if((accel.x<500 && accel.x>-500) && accel.y<-500){ snprintf(move, sizeof(move), "Turn left"); }else if(accel.x>500 && (accel.y<500 && accel.y>-500)){ snprintf(move, sizeof(move), "Go back"); }else if(accel.x<-500 && (accel.y<500 && accel.y>-500)){ snprintf(move, sizeof(move), "Go ahead"); }else if(accel.x>500 && accel.y<-500){ snprintf(move, sizeof(move), "Go back and left"); }else if(accel.x<-500 && accel.y<-500){ snprintf(move, sizeof(move), "Go ahead and left"); }else if(accel.x>500 && accel.y>500){ snprintf(move, sizeof(move), "Go back and right"); }else if(accel.x<-500 && accel.y>500){ snprintf(move, sizeof(move), "Go ahead and right"); }else{ snprintf(move, sizeof(move), "Stay"); } }else{ snprintf(move, sizeof(move), "Sleeping"); } text_layer_set_text(accel_layer, move); timer = app_timer_register(ACCEL_STEP_MS, timer_callback, NULL); } static void window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect window_bounds = layer_get_bounds(window_layer); motor = false; accel_layer = text_layer_create(GRect(0, 0, window_bounds.size.w, window_bounds.size.h)); text_layer_set_font(accel_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24)); text_layer_set_text(accel_layer, "Sleeping"); text_layer_set_overflow_mode(accel_layer, GTextOverflowModeWordWrap); text_layer_set_background_color(accel_layer, GColorWhite); text_layer_set_text_color(accel_layer, GColorBlack); text_layer_set_text_alignment(accel_layer, GTextAlignmentCenter); layer_add_child(window_layer, text_layer_get_layer(accel_layer)); } static void window_unload(Window *window) { text_layer_destroy(accel_layer); } static void init(void) { window = window_create(); window_set_window_handlers(window, (WindowHandlers) { .load = window_load, .unload = window_unload }); window_stack_push(window, true /* Animated */); accel_data_service_subscribe(0, NULL); window_set_click_config_provider(window, click_config_provider); timer = app_timer_register(ACCEL_STEP_MS, timer_callback, NULL); } static void deinit(void) { accel_data_service_unsubscribe(); window_destroy(window); } int main(void) { init(); app_event_loop(); deinit(); }
0dfe7922bbfb42191854cf90fc9ff8e649ea8d68
[ "Markdown", "C" ]
2
Markdown
gopinathdanda/pennapps-2015w
2e92c83d922adb0eadeb3a2c239fb2369167b89b
90d54bf4feb6d06c2ea93aac12536a2f70f8d799
refs/heads/master
<file_sep>import BMap from '../BMap/BMap'; import FontAwesome from 'react-fontawesome'; import React, { Component } from 'react'; import './SearchBar.css'; const apiUrl = process.env.API_URL || 'https://busbud-search.herokuapp.com'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '', suggestions: {}, error: '', showMap: false, enabledMap: true, lat: '43.70011', long: '-79.4163' }; this.changeMarkerPosition = this.changeMarkerPosition.bind(this); } searchCity(term) { var url = apiUrl + `/suggestions?q=${term}`; if ((this.state.lat !== '' && this.state.long !== '') && this.state.enabledMap) { url += `&latitude=${this.state.lat}&longitude=${this.state.long}`; } fetch(url) .then(response => response.json()) .then(data => this.setState({ suggestions: data.suggestions, error: ''})) .catch(e => this.setState({error: 'Cannot request API, please retry.'})); } onChange(event) { this.setState({ term: event.target.value }); this.searchCity(event.target.value); } toggleMap(event) { this.setState(prevState => ({ showMap: !prevState.showMap})); } toggleMapFunction(event) { this.setState(prevState => ({ enabledMap: !prevState.enabledMap}), () => { this.searchCity(this.state.term); }); } changeMarkerPosition(lat, long) { this.setState(prevState => ({ lat: lat, long: long, showMap: !prevState.showMap}), () => this.searchCity(this.state.term)); } render() { const results = Object.keys(this.state.suggestions).map(key => { if (key in this.state.suggestions && this.state.suggestions[key] !== null) { return <li>{this.state.suggestions[key].name}</li> } return []; } ); return ( <div className="SearchBar"> { !this.state.showMap ? null : ( <div id="mapPopup"> <label> <span>Enable location </span> <input type="checkbox" checked={this.state.enabledMap} onChange={(e) => this.toggleMapFunction(e)} /> </label> { this.state.enabledMap ? null : ( <div id="overlay"> Map disabled </div> ) } <BMap markerHandler={this.changeMarkerPosition} lat={this.state.lat} long={this.state.long} /> </div> ) } <input type="text" onChange={(e) => this.onChange(e)} placeholder="Search for a city (eg. Montreal, Washington...)"/> <a href="#/" className="toggleMap" onClick={(e) => this.toggleMap(e)}><FontAwesome name="map-marker" size="2x"/></a> { results.length === 0 ? null : ( <div id="autocomplete"> <ul> {results} </ul> </div> ) } { this.state.error === '' ? null : ( <div id="error"> <p>{this.state.error}</p> </div> ) } <div id="results"> </div> </div> ); } } export default SearchBar;
ce378d47720a14998b53f9b767855156e551ea85
[ "JavaScript" ]
1
JavaScript
alexlionco/coding-challenge-backend-c-front
058aca12e855c5a9e757b10d71c859056f7696f9
8d16d3d3ac244ed3105665bd4ad41ffc3540b247
refs/heads/master
<file_sep>/** * Created by huyansheng on 2016/7/18. */ var a = 5; var a = a++; alert(a); var b = 5; var a = b++; alert(a);<file_sep>/** * Created by huyansheng on 2016/1/16. */ //为我们的类定义一个构造函数方法,用它来初始化circle对象的属性,每个circle对象的属性值都不同 function Circle(x,y,r){ this.x = x; this.y = y; this.r = r; } new Circle(0,0,0) //定义一个常量,即所有Circle对象共享的属性,事实上,我们只是用了Math.PI,不过这样做是为了满足本例的需求 Circle.prototype.pi =3.14159 //定义个计算圆周长的方法,首先声明一个函数,然后把他赋值给原型对象的一个属性 function Circle_circumference(){return 2.this.pi*this.r}; Circle.prototype.circumference = Circle_circumference; function Circle(radius){ //这个构造函数定义了类自身 c = new Circle(5) //r是构造函数定义并初始化的一个实例属性 this.r = radius; } //Circle是构造函数的一个类属性 Circle.PI = 3.14159; function Cicle_area(){return Cicle.PI*this.r*this.r}; Circle.prototype.area = Cicle_area; <file_sep>/** * Created by huyansheng on 2016/1/18. */ function debug(msg){ if (!debug.box){ debug.box = document.createElement("div"); debug.box.setAttribute("style"," background-color:red;font-family:monospace;border:solid black 3px ;padding:10px;"); document.body.appendChild(debug.box) debug.box.innerHTML = "<h1 style='text-align: center'>Debugging Output</h1>" } var p = document.createElement("p"); p.appendChild(document.createTextNode(msg)); debug.box.appendChild(p); }<file_sep>/** * Created by huyansheng on 2016/1/16. */ var adult = {age:28} child = Object.create(adult) child.age = 8 delete child.age var prototypeAge = child.age console.log(prototypeAge)<file_sep>/** * Created by huyansheng on 2016/1/23. */ 'use strict'; function get_primes(arr) { return arr.filter(function (x){ if (x==1){return false}; for(var i=2;i<=x/2;i++){ if (x%i == 0){ return false; } } return true; }); } <file_sep>/** * Created by huyansheng on 2016/1/23. */ function lazy_sum(arr){ var sum = function(){ return arr.reduce(function (x,y){ return x+y; }) } return sum; //将函数作为返回值 } var f = lazy_sum([12,12,24,36,5,7]) console.log(f) console.log(f())<file_sep># JavaScript-pratice 用于学习JavaScript的demo 最近在学习Python和js,发现语言的设计上确实有共通之处。 Python语法更加简洁,提供了list/dict/tuple等常见方法和数据结构,使得写出的代码非常简洁。但Python确实完整的面向对象的思想, 该点上与Java相似,唯一的不同在于变量类型属于弱类型,不需要进行定义即可直接拿过来用。 JavaScript在面向对象的方面搞了一套原型链的东西,其思想基本和Java相同,但感觉语言有些含糊,没有Java那么规范。 在使用变量时甚至都不用进行转型,会自动进行转型,而Java和Python都做不到这一点。 JavaScript的语言形式上与Java更加相近,学起来也更加快速。 web是信息技术的一种重要载体,而JavaScript是web技术的一种重要手段,可以说不会点JavaScript根本不敢说自己是个程序员。 借用js和html做出各种炫酷的特效来,甚至做个galgame来,对于程序员也是莫大的激励! 学习java、python、js,从不同的语言中了解其设计哲学,扩宽思路。但也要注意深度。 今后的学习路线也不希望增加更多的语言了,可能还会把大学里没怎么掌握的C++捡回来,但那也是以后的事了。 多多学习python和js各类库,做到原生的api熟悉,各种类库熟悉,尝试实现各种特效。 多动手写一些代码,多想几个为什么。高山仰止,景行行止。 加油! <file_sep>/** * Created by huyansheng on 2016/1/16. */ var count = 0; while (count<10){ document.write("<font color='aqua' size='10' >"+count+"</font>"+"<br>"); //console.log(count); count++; }<file_sep>/** * Created by huyansheng on 2016/1/23. */ function area_of_circle(r,pi){ if (pi){ return pi*r*r; }else { return 3.14*r*r; } }<file_sep>/** * Created by huyansheng on 2016/1/23. */ //将事件处理程序表示为JavaScript的属性,又有两点好处 //1、模块性,代码更简洁 2、可以动态的改变绑定到HTML元素的事件处理程序 function confirmLink(){ return confirm("Do you really want to vist"+this.href+"?"); } function confirmAllLinks(){ for (var i = 0;i<document.links.length;i++){ document.links[i].onclick = confirmLink; } }<file_sep>/** * Created by huyansheng on 2016/1/20. */ function makeBarChart(data,width,height,barcolor){ //指定生成的柱状图的数据、宽、高和颜色 if (!width) width=500; if (!height) height=350; if (!barcolor) barcolor="blue"; width-=24; height-=14; var chart = document.createElement("div"); chart.style.position = "relative"; chart.style.width = width+"px"; chart.style.height = height+"px"; chart.style.border = "solid black 2px"; chart.style.paddingLeft = "10px"; chart.style.paddingRight = "10px"; chart.style.paddingTop = "10px"; chart.style.paddingBottom = "0px"; chart.style.backgroundColor = "white"; var barwidth = Math.floor(width/data.length); var maxdata = Math.max.apply(this,data); var scale = height/maxdata; for (var i = 0;i<data.length;i++){ var bar = document.createElement("div"); var barheight = data[i]*scale; bar.style.position = "absolute"; bar.style.left = (barwidth*i+1+10)+"px"; bar.style.top = height-barheight+10+"px"; bar.style.width = (barwidth-2)+"px"; bar.style.height = (barheight-1)+"px"; bar.style.border = "solid black 1px"; bar.style.backgroundColor = barcolor; bar.style.fontSize = "1px"; //绕过IEbug,暂不了解 chart.appendChild(bar); } document.body.appendChild(chart); return chart; }<file_sep>/** * Created by huyansheng on 2016/1/21. */ /* * @element:要产生动画的元素 * @numFrames:动画中的总帧数 * @timePerFrame:显示每帧的毫秒数 * @animation:定义动画的对象 * @whendone:一个可选的函数,在动画结束时调用,如果设置了该参数,它的参数是element * * animateCSS(image,25,50, * { * top:function(frame,time){return 帧*8+"px";}, * left:function(frame,time){return 帧*8+"px";} * }) * */ function animateCSS(element,numFrames,timePerFrame,animation,whendone){ var frame = 0 ;//存储当前的帧号 var time = 0;//存储消耗的总时间 //每隔timePerFrame毫秒调用一次displayNextFrame()函数,这将显示每个动画的帧 //相当于每隔xx秒根据元素更改后的style重新绘制元素,进而形成动画的效果 var intervalid = setInterval(displayNextFrame,timePerFrame); function displayNextFrame(){ if (frame >= numFrames){ clearInterval(intervalid); //首先查看是否结束了,如果结束了,停止调用自身 if (whendone) whendone(element); //调用whendone函数 return; } for (var cssprop in animation){ //对于每隔属性,调用它的动画函数,传递给它帧号和消耗的时间,用该函数的返回值作为指定元素的相应样式属性的新值 try{ //用try...catch语句忽略不成功返回的异常 element.style[cssprop] = animation[cssprop](frame,time); }catch(e) {} } frame++; time+=timePerFrame; } }<file_sep>/** * Created by huyansheng on 2016/1/19. */ function maketoc(replace){ var toc = document.createElement("div"); toc.style.backgroundColor = "white"; toc.style.fontFamily = "sans-serif"; var anchor = document.createElement("a"); anchor.setAttribute("name","TOC"); toc.appendChild(anchor); anchor.appendChild(document.createTextNode("Table of Contents")); var table = document.createElement("table"); toc.appendChild(table); var tbody = document.createElement("tbody"); table.appendChild(tbody); var sectionNumbers = [0,0,0,0,0,0]; function addSections(n,toc,sectionNumbers){ //遍历n的所有节点 for(var m = n.firstChild;m!=null;m = m.nextSibling){ //检查标记名是否是h1-h6 if(m.nodeType ==1 && m.tagName.length == 2 & m.tagName.charAt(0) == "H"){ var level = parseInt(m.tagName.charAt(1)); if (!isNaN(level) && level>=1 && level <=6){ //为该级标题增加段号 sectionNumbers[level-1]++; //将所有低级标题的段号置为0 for(var i = level;i<6;i++) sectionNumbers[i]=0; //下面将所有级别的标题段号组合起来.生成如2.3.1的段号 var sectionNumber = ""; for(var i=0;i<level;i++){ sectionNumber += sectionNumbers[i]; if (i<level-1) sectionNumber+="."; } var anchor = document.createElement("a"); anchor.setAttribute("name","SECT"+sectionNumber); //创建返回TOC的链接,使它成为锚元素的子节点 var backlink = document.createElement("a"); backlink.setAttribute("href","#TOC"); backlink.appendChild(document.createTextNode("Contents")); anchor.appendChild(backlink); //把锚元素插入文档的段标题之前 n.insertBefore(anchor,m); //下面会创建该段的链接,以下代码会把他加入TOC var link = document.createElement("a"); link.setAttribute("href","#SECT"+sectionNumber); //下面定义的函数获得标题文档 var sectionTitle = getTextContent(m); //用标题的文本作为链接的内容 link.appendChild(document.createTextNode(sectionTitle)); //为TOC创建新行 var row = document.createElement("tr"); //为该行创建两个列 var col1 = document.createElement("td"); var col2 = document.createElement("td"); col1.setAttribute("align","right"); col1.appendChild(document.createTextNode(sectionNumber)); col2.appendChild(link); row.appendChild(col1); row.appendChild(col2); toc.append(row) //修改段标题自身元素,添加段号作为段标题的一部分 m.insertBefore(document.createTextNode(sectionNumber+":"), m.firstChild); } }else { //否则,这不是标题元素,所以进行递归 addSections(m,toc,sectionNumbers); } } } //这个工具将遍历节点节点,返回找到的所有Text节点的内容,舍弃html标签;它也被认定为一个嵌套函数,所以它是该模块专用。 function getTextContent(n){ var s = ""; var children = n.childNodes; for(var i = 0;i<children.length;i++){ var child = children[i]; if (child.nodeType == 3){ s += child.data; }else { getTextContent(child); } } return s; } } <file_sep>/** * Created by huyansheng on 2016/1/17. */ <file_sep>/** * Created by huyansheng on 2016/1/16. */ var add_2 = function(x){ return x+2; } var double = function(x){ return x*2; } var map = function(func,list){ var output = []; for(idx in list){ output.push(func(list[idx])); } return output; } var buildProcesser = function(func){ var process_func = function(list){ return map(func,list) } return process_func; } process_add_2 = buildProcesser(add_2); process_double = buildProcesser(double); console.log(process_add_2([2,3,4,5,6,7])); console.log(process_double([,5,6,8,2,])); <file_sep>/** * Created by huyansheng on 2016/1/16. */ outerloop: for (var i =0;i<10;i++){ innerloop: for (var j = 0;j<10;j++){ if (j>3) break; if (i==2) break innerloop; if (i==4) break outerloop; console.log("i="+i+",j="+j); } } console.log("final i="+i+",j="+j);<file_sep>/** * Created by huyansheng on 2016/1/17. */ function listanchors(d){ var newwin = window.open("","navwin","menubar=yes,scrollbars=yes,resizable=yes,width=600,height=300"); newwin.document.write("<h1>Navigation Windows:<br>"+document.title+"</h1>"); for(var i = 0;i< d.anchors.length;i++){ var a = d.anchors[i]; var text = null; if (a.text) text = a.text; else if (a.innerText) text = a.innerText; if ((text == null) || (text == "")) text = a.name; //default value newwin.document.write('<a href="#'+ a.name+'"'+'onclick = "opener.location.hash="'+ a.name+'";return false;">'); newwin.document.write(text); newwin.document.write('</a></br>'); } newwin.document.close() }<file_sep>/** * Created by huyansheng on 2016/1/16. */ function Complex(real,imaginary){ this.x = real; this.y = imaginary; } Complex.prototype.magnitude = function(){ return Math.sqrt(this.x*this.x+this.y*this.y); } Complex.prototype.negative = function(){ return new Complex(-this.x,-this.y); }
aff811a52a908a76d317765fe3d68a94b0b67a63
[ "JavaScript", "Markdown" ]
18
JavaScript
huyansheng3/JavaScript-pratice
060d1c03067c56c8d07611997d4f2bf364f80435
0929126d6b2c32ffccfd43182c7dc9b08ebb67d5
refs/heads/master
<file_sep>package org.gox.kafka; public class KafkaProperties { public static final String TOPIC = "events"; public static final String KAFKA_SERVER_URL = "172.23.221.165"; public static final int KAFKA_SERVER_PORT = 9092; } <file_sep># kafka-test
4a0d25c394af94fbfd273ce6c19f451dba640149
[ "Markdown", "Java" ]
2
Java
GoX1337/kafka-test
986e9d1e337458d15a43c63608b49dc34f149a2e
10b504a65659987beb5c24a72ffa1c8696ee9878
refs/heads/master
<repo_name>kmoneil/udacity-tournament-database<file_sep>/tournament.sql -- Table definitions for the tournament project. -- -- Put your SQL 'create table' statements in this file; also 'create view' -- statements if you choose to use it. -- -- You can write comments in this file by starting them with two dashes, like -- these lines here. -- DROP DATABASE if exists tournament; -- CREATE DATABASE tournament; DROP TABLE IF EXISTS players CASCADE; CREATE TABLE players ( id SERIAL PRIMARY KEY, name TEXT NOT NULL ); DROP TABLE IF EXISTS matchups CASCADE; CREATE TABLE matchups ( winner INTEGER REFERENCES players (id), loser INTEGER REFERENCES players (id), PRIMARY KEY (winner, loser) ); DROP VIEW IF EXISTS player_standings CASCADE; CREATE VIEW player_standings AS SELECT players.id, players.name, COALESCE(matches_played.wins, 0) AS wins, COALESCE(matches_played.losses, 0) AS losses, COALESCE(matches_played.total, 0) AS played FROM players LEFT JOIN ( SELECT player, count(CASE WHEN outcome = 'w' THEN 1 ELSE NULL END) AS wins, count(CASE WHEN outcome = 'l' THEN 1 ELSE NULL END) AS losses, count(*) AS total FROM (SELECT winner AS player, 'w' AS outcome FROM matchups UNION ALL SELECT loser AS player, 'l' AS outcome FROM matchups) AS matches GROUP BY player ) AS matches_played on matches_played.player = players.id; <file_sep>/readme.md ### Project: Tournament Database Build a database backed application that determines the winner of a swiss-style game tournament. --- Install PostgreSQL : [PostgreSQL Download Page](https://www.postgresql.org/download/) 1. Launch the psql console from the command line by typing: psql 2. Create database by typing: CREATE DATABASE tournament; 2. Connect to the tournament database by typing: \c tournament 3. Import the schema for the tournament database by typing: \i tournament.sql To run the tests: python tournament_test.py You should see: 1. countPlayers() returns 0 after initial deletePlayers() execution. 2. countPlayers() returns 1 after one player is registered. 3. countPlayers() returns 2 after two players are registered. 4. countPlayers() returns zero after registered players are deleted. 5. Player records successfully deleted. 6. Newly registered players appear in the standings with no matches. 7. After a match, players have updated standings. 8. After match deletion, player standings are properly reset. 9. Matches are properly deleted. 10. After one match, players with one win are properly paired. ***Success! All tests pass!***
4503bd1ee50fee0b1a487b8741857147fd5a0efc
[ "Markdown", "SQL" ]
2
SQL
kmoneil/udacity-tournament-database
aa8dc4436762ac206dd6b33ac527ab86eb0015e6
c6d972c3c4050c016bbdc61c511baa7e45968acf
refs/heads/master
<repo_name>magnet/metered-rs<file_sep>/Cargo.toml [workspace] members = [ "metered", "metered-macro", ] <file_sep>/demos/src/baz.rs #![allow(dead_code)] use metered::{metered, ErrorCount, HitCount, InFlight, ResponseTime}; use thiserror::Error; #[metered::error_count(name = LibErrorCount, visibility = pub)] #[derive(Debug, Error)] pub enum LibError { #[error("I failed!")] Failure, #[error("Bad input")] BadInput, } #[metered::error_count(name = BazErrorCount, visibility = pub, skip_cleared = true)] #[derive(Debug, Error)] pub enum BazError { #[error("lib error: {0}")] Lib(#[from] #[nested] LibError), #[error("io error")] Io, } #[derive(Default, Debug, serde::Serialize)] pub struct Baz { metric_reg: BazMetricRegistry, } #[metered(registry = BazMetricRegistry, /* default = self.metrics */ registry_expr = self.metric_reg, visibility = pub(self))] #[measure(InFlight)] // Applies to all methods that have the `measure` attribute impl Baz { // This is measured with an InFlight gauge, because it's the default on the block. #[measure] pub fn bir(&self) { println!("bir"); let delay = std::time::Duration::from_millis(rand::random::<u64>() % 2000); std::thread::sleep(delay); } // This is not measured pub fn bor(&self) { println!("bor"); } #[measure(ResponseTime)] pub fn foo(&self) { println!("foo !"); let delay = std::time::Duration::from_millis(rand::random::<u64>() % 2000); std::thread::sleep(delay); } #[measure(type = HitCount<metered::atomic::AtomicInt<u64>>)] #[measure(ErrorCount)] #[measure(ResponseTime)] pub fn bar(&self, should_fail: bool) -> Result<(), &'static str> { if !should_fail { println!("bar !"); Ok(()) } else { Err("I failed!") } } #[measure([ErrorCount, ResponseTime])] pub async fn baz(&self, should_fail: bool) -> Result<(), &'static str> { let delay = std::time::Duration::from_millis(rand::random::<u64>() % 2000); tokio::time::sleep(delay).await; if !should_fail { println!("baz !"); Ok(()) } else { Err("I failed!") } } #[measure([ResponseTime])] pub fn bazium( &self, should_fail: bool, ) -> impl std::future::Future<Output = Result<(), &'static str>> { async move { let delay = std::time::Duration::from_millis(rand::random::<u64>() % 2000); tokio::time::sleep(delay).await; if !should_fail { println!("baz !"); Ok(()) } else { Err("I failed!") } } } #[measure([HitCount, BazErrorCount])] pub async fn bazle(&self, should_fail: bool) -> Result<(), BazError> { if !should_fail { println!("bazle !"); Ok(()) } else { Err(LibError::Failure.into()) } } #[measure] pub unsafe fn bad(&self, v: &[u8]) { let _ = std::str::from_utf8_unchecked(v); } // This is not measured either pub fn bur() { println!("bur"); } } <file_sep>/metered/src/common/in_flight.rs //! A module providing the `InFlight` metric. use crate::{ atomic::AtomicInt, clear::Clear, metric::{Gauge, Metric}, }; use aspect::{Advice, Enter, OnResult}; use serde::Serialize; use std::ops::Deref; /// A metric providing an in-flight gauge, showing how many calls are currently /// active for an expression. /// /// This is a light-weight metric. /// /// This makes sense mostly in a multi-threaded situation where several threads /// may call the same method constantly, and we want to monitor how many are /// active at a given time. /// /// The [`Throughput`] metric shows an alternative view /// of the same picture, by reporting how many transactions per seconds are /// processed by an expression. /// /// By default, `InFlight` uses a lock-free `u64` [`Gauge`], which makes sense /// in multithread scenarios. Non-threaded applications can gain performance by /// using a `std::cell:Cell<u64>` instead. #[derive(Clone, Default, Debug, Serialize)] pub struct InFlight<G: Gauge = AtomicInt<u64>>(pub G); impl<G: Gauge, R> Metric<R> for InFlight<G> {} impl<G: Gauge> Enter for InFlight<G> { type E = (); fn enter(&self) { self.0.incr(); } } impl<G: Gauge, R> OnResult<R> for InFlight<G> { fn leave_scope(&self, _: ()) -> Advice { self.0.decr(); Advice::Return } } impl<G: Gauge> Clear for InFlight<G> { fn clear(&self) { // Do nothing: an InFlight metric // would get in an inconsistent state if cleared } } impl<G: Gauge> Deref for InFlight<G> { type Target = G; fn deref(&self) -> &Self::Target { &self.0 } } <file_sep>/metered/src/common/response_time.rs //! A module providing the `ResponseTime` metric. use crate::{ clear::Clear, hdr_histogram::AtomicHdrHistogram, metric::{Histogram, Metric}, time_source::{Instant, StdInstant}, }; use aspect::{Advice, Enter, OnResult}; use serde::{Serialize, Serializer}; use std::ops::Deref; /// A metric measuring the response time of an expression, that is the duration /// the expression needed to complete. /// /// Because it retrieves the current time before calling the expression, /// computes the elapsed duration and registers it to an histogram, this is a /// rather heavy-weight metric better applied at entry-points. /// /// By default, `ResponseTime` uses an atomic hdr histogram and a synchronized /// time source, which work better in multithread scenarios. Non-threaded /// applications can gain performance by using unsynchronized structures /// instead. #[derive(Clone)] pub struct ResponseTime<H: Histogram = AtomicHdrHistogram, T: Instant = StdInstant>( pub H, std::marker::PhantomData<T>, ); impl<H: Histogram, T: Instant> Default for ResponseTime<H, T> { fn default() -> Self { // A HdrHistogram measuring latencies from 1ms to 5minutes // All recordings will be saturating, that is, a value higher than 5 minutes // will be replace by 5 minutes... ResponseTime(H::with_bound(5 * 60 * 1000), std::marker::PhantomData) } } impl<H: Histogram, T: Instant, R> Metric<R> for ResponseTime<H, T> {} impl<H: Histogram, T: Instant> Enter for ResponseTime<H, T> { type E = T; fn enter(&self) -> T { T::now() } } impl<H: Histogram, T: Instant, R> OnResult<R> for ResponseTime<H, T> { fn leave_scope(&self, enter: T) -> Advice { let elapsed = enter.elapsed_time(); self.0.record(elapsed); Advice::Return } } impl<H: Histogram, T: Instant> Clear for ResponseTime<H, T> { fn clear(&self) { self.0.clear(); } } impl<H: Histogram + Serialize, T: Instant> Serialize for ResponseTime<H, T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { Serialize::serialize(&self.0, serializer) } } use std::{fmt, fmt::Debug}; impl<H: Histogram + Debug, T: Instant> Debug for ResponseTime<H, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &self.0) } } impl<H: Histogram, T: Instant> Deref for ResponseTime<H, T> { type Target = H; fn deref(&self) -> &Self::Target { &self.0 } } <file_sep>/metered/src/common/error_count.rs //! A module providing the `ErrorCount` metric. use crate::{ atomic::AtomicInt, clear::Clear, metric::{Counter, Metric}, }; use aspect::{Advice, Enter, OnResult}; use serde::Serialize; use std::ops::Deref; /// A metric counting how many times an expression typed std `Result` as /// returned an `Err` variant. /// /// This is a light-weight metric. /// /// By default, `ErrorCount` uses a lock-free `u64` `Counter`, which makes sense /// in multithread scenarios. Non-threaded applications can gain performance by /// using a `std::cell:Cell<u64>` instead. #[derive(Clone, Default, Debug, Serialize)] pub struct ErrorCount<C: Counter = AtomicInt<u64>>(pub C); impl<C: Counter, T, E> Metric<Result<T, E>> for ErrorCount<C> {} impl<C: Counter> Enter for ErrorCount<C> { type E = (); fn enter(&self) {} } impl<C: Counter, T, E> OnResult<Result<T, E>> for ErrorCount<C> { fn on_result(&self, _: (), r: &Result<T, E>) -> Advice { if r.is_err() { self.0.incr(); } Advice::Return } } impl<C: Counter> Clear for ErrorCount<C> { fn clear(&self) { self.0.clear() } } impl<C: Counter> Deref for ErrorCount<C> { type Target = C; fn deref(&self) -> &Self::Target { &self.0 } } <file_sep>/metered/src/common/throughput/tx_per_sec.rs use super::RecordThroughput; use crate::{ clear::Clear, hdr_histogram::HdrHistogram, time_source::{Instant, StdInstant}, }; use serde::{Serialize, Serializer}; /// Non-thread safe implementation of `RecordThroughput`. Use as /// `RefCell<TxPerSec<T>>`. pub struct TxPerSec<T: Instant = StdInstant> { /// The inner histogram pub hdr_histogram: HdrHistogram, last: Option<T>, count: u64, time_source: std::marker::PhantomData<T>, } impl<T: Instant> Default for TxPerSec<T> { fn default() -> Self { TxPerSec { // Bound at 100K TPS, higher values will be saturated... // TODO: make this configurable :) hdr_histogram: HdrHistogram::with_bound(100_000), last: None, count: 0, time_source: std::marker::PhantomData, } } } impl<T: Instant> RecordThroughput for std::cell::RefCell<TxPerSec<T>> { #[inline] fn on_result(&self) { self.borrow_mut().on_result() } } impl<T: Instant> Clear for std::cell::RefCell<TxPerSec<T>> { fn clear(&self) { self.borrow_mut().clear(); } } impl<T: Instant> TxPerSec<T> { pub(crate) fn on_result(&mut self) { // Record previous count if the 1-sec window has closed if let Some(ref last) = self.last { let elapsed = last.elapsed_time(); if elapsed > T::ONE_SEC { self.hdr_histogram.record(self.count); self.count = 0; self.last = Some(T::now()); } } else { // Start a new window self.last = Some(T::now()); }; self.count += 1; } pub(crate) fn clear(&mut self) { self.hdr_histogram.clear(); self.last = None; self.count = 0; } } impl<T: Instant> Serialize for TxPerSec<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { Serialize::serialize(&self.hdr_histogram, serializer) } } use std::{fmt, fmt::Debug}; impl<T: Instant> Debug for TxPerSec<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &self.hdr_histogram) } } <file_sep>/metered-macro/src/lib.rs //! Procedural macros for Metered, a metric library for Rust. //! //! Please check the Metered crate for more documentation. #![deny(warnings)] // The `quote!` macro requires deep recursion. #![recursion_limit = "512"] #[macro_use] extern crate syn; #[macro_use] extern crate quote; mod error_count; mod error_count_opts; mod measure_opts; mod metered; mod metered_opts; use proc_macro::TokenStream; /// A procedural macro that generates a metric registry for an `impl` block. /// /// ``` /// use metered::{metered, Throughput, HitCount}; /// /// #[derive(Default, Debug)] /// pub struct Biz { /// metrics: BizMetrics, /// } /// /// #[metered::metered(registry = BizMetrics)] /// impl Biz { /// #[measure([HitCount, Throughput])] /// pub fn biz(&self) { /// let delay = std::time::Duration::from_millis(rand::random::<u64>() % 200); /// std::thread::sleep(delay); /// } /// } /// # /// # let biz = Biz::default(); /// # biz.biz(); /// # assert_eq!(biz.metrics.biz.hit_count.0.get(), 1); /// ``` /// /// ### The `metered` attribute /// /// `#[metered(registry = YourRegistryName, registry_expr = /// self.wrapper.my_registry)]` /// /// `registry` is mandatory and must be a valid Rust ident. /// /// `registry_expr` defaults to `self.metrics`, alternate values must be a valid /// Rust expression. /// /// ### The `measure` attribute /// /// Single metric: /// /// `#[measure(path::to::MyMetric<u64>)]` /// /// or: /// /// `#[measure(type = path::to::MyMetric<u64>)]` /// /// Multiple metrics: /// /// `#[measure([path::to::MyMetric<u64>, path::AnotherMetric])]` /// /// or /// /// `#[measure(type = [path::to::MyMetric<u64>, path::AnotherMetric])]` /// /// The `type` keyword is allowed because other keywords are planned for future /// extra attributes (e.g, instantation options). /// /// When `measure` attribute is applied to an `impl` block, it applies for every /// method that has a `measure` attribute. If a method does not need extra /// measure infos, it is possible to annotate it with simply `#[measure]` and /// the `impl` block's `measure` configuration will be applied. /// /// The `measure` keyword can be added several times on an `impl` block or /// method, which will add to the list of metrics applied. Adding the same /// metric several time will lead in a name clash. #[proc_macro_attribute] pub fn metered(attrs: TokenStream, item: TokenStream) -> TokenStream { metered::metered(attrs, item).unwrap_or_else(|e| TokenStream::from(e.to_compile_error())) } /// A procedural macro that generates a new metric that measures the amount /// of times each variant of an error has been thrown, to be used as /// crate-specific replacement for `metered::ErrorCount`. /// /// ``` /// # use metered_macro::{metered, error_count}; /// # use thiserror::Error; /// # /// #[error_count(name = LibErrorCount, visibility = pub)] /// #[derive(Debug, Error)] /// pub enum LibError { /// # #[error("read error")] /// ReadError, /// # #[error("init error")] /// InitError, /// } /// /// #[error_count(name = ErrorCount, visibility = pub)] /// #[derive(Debug, Error)] /// pub enum Error { /// # #[error("error from lib: {0}")] /// MyLibrary(#[from] #[nested] LibError), /// } /// /// #[derive(Default, Debug)] /// pub struct Baz { /// metrics: BazMetrics, /// } /// /// #[metered(registry = BazMetrics)] /// impl Baz { /// #[measure(ErrorCount)] /// pub fn biz(&self) -> Result<(), Error> { /// Err(LibError::InitError.into()) /// } /// } /// /// let baz = Baz::default(); /// baz.biz(); /// assert_eq!(baz.metrics.biz.error_count.my_library.read_error.get(), 0); /// assert_eq!(baz.metrics.biz.error_count.my_library.init_error.get(), 1); /// ``` /// /// - `name` is required and must be a valid Rust ident, this is the name of the /// generated struct containing a counter for each enum variant. /// - `visibility` specifies to visibility of the generated struct, it defaults /// to `pub(crate)`. /// - `skip_cleared` allows to make the serializer skip "cleared" entries, that /// is entries for which the `Clearable::is_cleared` function returns true /// (for counters, by default, whether they are 0). It defaults to whether the /// feature `error-count-skip-cleared-by-default` is enabled. By default, this /// feature is disabled, and no entry will be skipped. /// /// /// The `error_count` macro may only be applied to any enums that have a /// `std::error::Error` impl. The generated struct may then be included /// in `measure` attributes to measure the amount of errors returned of /// each variant defined in your error enum. #[proc_macro_attribute] pub fn error_count(attrs: TokenStream, item: TokenStream) -> TokenStream { error_count::error_count(attrs, item) .unwrap_or_else(|e| TokenStream::from(e.to_compile_error())) } <file_sep>/metered-macro/src/metered_opts.rs //! The module supporting `#[metered]` options use syn::{ parse::{Parse, ParseStream}, Result, }; use synattra::{types::KVOption, *}; use std::borrow::Cow; pub struct Metered<'a> { pub registry_ident: &'a syn::Ident, pub registry_name: String, pub registry_expr: Cow<'a, syn::Expr>, pub visibility: Cow<'a, syn::Visibility>, } pub struct MeteredKeyValAttribute { pub values: syn::punctuated::Punctuated<MeteredOption, Token![,]>, } impl MeteredKeyValAttribute { fn validate(&self, input: ParseStream<'_>) -> Result<()> { self.values .iter() .filter_map(|opt| { if let MeteredOption::Registry(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .ok_or_else(|| input.error("missing `registry` attribute."))?; let opt_types: std::collections::HashMap<_, _> = self .values .iter() .map(|opt| (std::mem::discriminant(opt), opt.as_str())) .collect(); for (opt_type, opt_name) in opt_types.iter() { let count = self .values .iter() .filter(|&opt| std::mem::discriminant(opt) == *opt_type) .count(); if count > 1 { let error = format!("`{}` attribute is defined more than once.", opt_name); return Err(input.error(error)); } } Ok(()) } pub fn to_metered(&self) -> Metered<'_> { let registry_ident = self .values .iter() .filter_map(|opt| { if let MeteredOption::Registry(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .expect("There should be a registry! This error cannot happen if the structure has been validated first!"); let registry_name = registry_ident.to_string(); let registry_expr = self .values .iter() .filter_map(|opt| { if let MeteredOption::RegistryExpr(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .map(|id| Cow::Borrowed(id)) .unwrap_or_else(|| Cow::Owned(syn::parse_str::<syn::Expr>("self.metrics").unwrap())); let visibility = self .values .iter() .filter_map(|opt| { if let MeteredOption::Visibility(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .map(|id| Cow::Borrowed(id)) .unwrap_or_else(|| { Cow::Owned(syn::parse_str::<syn::Visibility>("pub(crate)").unwrap()) }); Metered { registry_ident, registry_name, registry_expr, visibility, } } } impl Parse for MeteredKeyValAttribute { fn parse(input: ParseStream<'_>) -> Result<Self> { let this = MeteredKeyValAttribute { values: input.parse_terminated(MeteredOption::parse)?, }; this.validate(input)?; Ok(this) } } mod kw { syn::custom_keyword!(registry); syn::custom_keyword!(registry_expr); syn::custom_keyword!(visibility); } pub type MeteredRegistryOption = KVOption<kw::registry, syn::Ident>; pub type MeteredRegistryExprOption = KVOption<kw::registry_expr, syn::Expr>; pub type MeteredVisibilityOption = KVOption<kw::visibility, syn::Visibility>; #[allow(clippy::large_enum_variant)] pub enum MeteredOption { Registry(MeteredRegistryOption), RegistryExpr(MeteredRegistryExprOption), Visibility(MeteredVisibilityOption), } impl MeteredOption { pub fn as_str(&self) -> &str { use syn::token::Token; match self { MeteredOption::Registry(_) => <kw::registry>::display(), MeteredOption::RegistryExpr(_) => <kw::registry_expr>::display(), MeteredOption::Visibility(_) => <kw::visibility>::display(), } } } impl Parse for MeteredOption { fn parse(input: ParseStream<'_>) -> Result<Self> { if MeteredRegistryOption::peek(input) { Ok(input.parse_as(MeteredOption::Registry)?) } else if MeteredRegistryExprOption::peek(input) { Ok(input.parse_as(MeteredOption::RegistryExpr)?) } else if MeteredVisibilityOption::peek(input) { Ok(input.parse_as(MeteredOption::Visibility)?) } else { let err = format!("invalid metered option: {}", input); Err(input.error(err)) } } } <file_sep>/metered/src/metric.rs //! A module defining the [`Metric`] trait and common metric backends. use crate::clear::{Clear, Clearable}; /// Re-export `aspect-rs`'s types to avoid crates depending on it. pub use aspect::{Advice, Enter, OnResult, OnResultMut}; use serde::Serialize; use std::marker::PhantomData; /// A trait to implement to be used in the `measure!` macro /// /// Metrics wrap expressions to measure them. /// /// The return type, R, of the expression can be captured to perform special /// handling. pub trait Metric<R>: Default + OnResultMut<R> + Clear + Serialize {} // Needed to force `measure!` to work only with the [`Metric`] trait. #[doc(hidden)] pub fn on_result<R, A: Metric<R>>(metric: &A, _enter: <A as Enter>::E, _result: &mut R) -> Advice { metric.on_result(_enter, _result) } /// Handles a metric's lifecycle, guarding against early returns and panics. pub struct ExitGuard<'a, R, M: Metric<R>> { metric: &'a M, enter: Option<<M as Enter>::E>, _phantom: PhantomData<R>, } impl<'a, R, M: Metric<R>> ExitGuard<'a, R, M> { /// Enter a metric and create the guard for its exit. /// This calls [`aspect::Enter::enter`] on the metric internally. pub fn new(metric: &'a M) -> Self { Self { metric, enter: Some(metric.enter()), _phantom: PhantomData, } } /// If no unexpected exit occurred, record the expression's result. pub fn on_result(mut self, result: &mut R) { if let Some(enter) = self.enter.take() { self.metric.on_result(enter, result); } else { // OnResult called twice - we ignore } } } impl<'a, R, M: Metric<R>> Drop for ExitGuard<'a, R, M> { fn drop(&mut self) { if let Some(enter) = self.enter.take() { self.metric.leave_scope(enter); } else { // on_result was called, so the result was already recorded } } } /// A trait for Counters pub trait Counter: Default + Clear + Clearable + Serialize { /// Increment the counter fn incr(&self) { self.incr_by(1) } /// Increment the counter by count in one step /// /// Supplying a count larger than the underlying counter's remaining /// capacity will wrap like [`u8::wrapping_add`] and similar methods. fn incr_by(&self, count: usize); } /// A trait for Gauges pub trait Gauge: Default + Clear + Serialize { /// Increment the counter fn incr(&self) { self.incr_by(1) } /// Decrement the counter fn decr(&self) { self.decr_by(1) } /// Increment the gauge by count in one step /// /// Supplying a count larger than the underlying counter's remaining /// capacity will wrap like [`u8::wrapping_add`] and similar methods. fn incr_by(&self, count: usize); /// Decrement the gauge by count in one step /// /// Supplying a count larger than the underlying counter's current value /// will wrap like [`u8::wrapping_sub`] and similar methods. fn decr_by(&self, count: usize); } /// A trait for Histograms pub trait Histogram: Clear + Serialize { /// Build a new histogram with the given max bounds fn with_bound(max_value: u64) -> Self; /// Record a value to the histogram. /// /// It will saturate if the value is higher than the histogram's /// `max_value`. fn record(&self, value: u64); } <file_sep>/demos/src/biz.rs use metered::{metered, HitCount, Throughput}; #[derive(Default, Debug, serde::Serialize)] pub struct Biz { pub(crate) metrics: BizMetrics, } #[metered(registry = BizMetrics)] #[measure([HitCount, Throughput])] impl Biz { // This is measured with an Throughput metric (TPS) #[measure] pub fn biz(&self) { let delay = std::time::Duration::from_millis(rand::random::<u64>() % 200); std::thread::sleep(delay); } } <file_sep>/demos/src/main.rs use metered::clear::Clear; use metered::*; mod baz; use baz::Baz; mod biz; use biz::Biz; use std::collections::HashMap; #[derive(Default, Debug, serde::Serialize)] struct TestMetrics { hit_count: HitCount, error_count: ErrorCount, } fn test(should_fail: bool, metrics: &TestMetrics) -> Result<(), ()> { let hit_count = &metrics.hit_count; let error_count = &metrics.error_count; measure!(hit_count, { measure!(error_count, { println!("test !"); if should_fail { Err(()) } else { Ok(()) } }) }) } fn test_incr(metrics: &TestMetrics) -> Result<(), ()> { let hit_count = &metrics.hit_count; hit_count.incr_by(3); Ok(()) } fn sync_procmacro_demo(baz: &Baz) { for i in 1..=10 { baz.foo(); let _ = baz.bar(i % 3 == 0); } } async fn async_procmacro_demo(baz: Baz) { for i in 1..=5 { let _ = baz.baz(i % 3 == 0).await; let _ = baz.bazle(i % 3 == 0).await; } // Print the results! let serialized = serde_prometheus::to_string(&baz, None, HashMap::new()).unwrap(); println!("{}", serialized); } fn simple_api_demo() { let metrics = TestMetrics::default(); let _ = test(false, &metrics); let _ = test(true, &metrics); let _ = test_incr(&metrics); // Print the results! let serialized = serde_prometheus::to_string(&metrics, None, HashMap::new()).unwrap(); println!("{}", serialized); } use std::sync::Arc; use std::thread; fn test_biz() { println!("Running Biz throughput demo...(will take 20 seconds)"); let biz = Arc::new(Biz::default()); do_test_biz(&biz); println!("Clearing Biz metrics and running throughput demo again...(will take 20 seconds)"); biz.metrics.clear(); do_test_biz(&biz); } fn do_test_biz(biz: &Arc<Biz>) { let mut threads = Vec::new(); for _ in 0..5 { let biz = Arc::clone(&biz); let t = thread::spawn(move || { for _ in 0..200 { biz.biz(); } }); threads.push(t); } for t in threads { t.join().unwrap(); } println!("Running Biz throughput demo... done! Here are the metrics for that run:"); // Print the results! let serialized = serde_prometheus::to_string(&**biz, None, HashMap::new()).unwrap(); println!("{}", serialized); } fn main() { simple_api_demo(); test_biz(); let baz = Baz::default(); sync_procmacro_demo(&baz); let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async_procmacro_demo(baz)); } <file_sep>/metered/src/int_gauge.rs //! A module providing thread-safe and unsynchronized implementations for Gauges //! on various unsized integers. use crate::{atomic::AtomicInt, metric::Gauge, num_wrapper::NumWrapper}; use std::cell::Cell; macro_rules! impl_gauge_for { ($int:path) => { impl Gauge for Cell<$int> { fn incr_by(&self, count: usize) { let v = NumWrapper::<$int>::wrap(count); self.set(self.get().wrapping_add(v)); } fn decr_by(&self, count: usize) { let v = NumWrapper::<$int>::wrap(count); self.set(self.get().wrapping_sub(v)); } } impl Gauge for AtomicInt<$int> { fn incr_by(&self, count: usize) { let v = NumWrapper::<$int>::wrap(count); AtomicInt::<$int>::incr_by(&self, v); } fn decr_by(&self, count: usize) { let v = NumWrapper::<$int>::wrap(count); AtomicInt::<$int>::decr_by(&self, v); } } }; } impl_gauge_for!(u8); impl_gauge_for!(u16); impl_gauge_for!(u32); impl_gauge_for!(u64); impl_gauge_for!(u128); <file_sep>/metered-macro/src/measure_opts.rs //! The module supporting `#[measure]` options use syn::{ parse::{Parse, ParseStream}, Result, }; use synattra::{ types::{extra::InvokePath, KVOption, MultipleVal}, ParseStreamExt, }; pub struct MeasureRequest<'a> { pub tpe: &'a syn::TypePath, pub field_name: String, pub debug: Option<&'a InvokePath>, } impl<'a> MeasureRequest<'a> { pub fn ident(&self) -> syn::Ident { syn::Ident::new(&self.field_name, proc_macro2::Span::call_site()) } pub fn type_path(&self) -> &syn::TypePath { self.tpe } } pub enum MeasureRequestAttribute { Empty, NonEmpty(NonEmptyMeasureRequestAttribute), } impl MeasureRequestAttribute { pub fn to_requests(&self) -> Vec<MeasureRequest<'_>> { match self { MeasureRequestAttribute::Empty => Vec::new(), MeasureRequestAttribute::NonEmpty(req) => req.to_requests(), } } } impl Parse for MeasureRequestAttribute { fn parse(input: ParseStream<'_>) -> Result<Self> { if input.is_empty() { Ok(MeasureRequestAttribute::Empty) } else { Ok(MeasureRequestAttribute::NonEmpty( NonEmptyMeasureRequestAttribute::parse(input)?, )) } } } pub struct NonEmptyMeasureRequestAttribute { pub paren_token: syn::token::Paren, pub inner: Option<MeasureRequestAttributeInner>, } impl NonEmptyMeasureRequestAttribute { pub fn to_requests(&self) -> Vec<MeasureRequest<'_>> { if let Some(ref inner) = self.inner { inner.to_requests() } else { Vec::new() } } } impl Parse for NonEmptyMeasureRequestAttribute { fn parse(input: ParseStream<'_>) -> Result<Self> { let content; let paren_token = parenthesized!(content in input); let inner = if content.is_empty() { None } else { Some(content.parse()?) }; let this = NonEmptyMeasureRequestAttribute { paren_token, inner }; Ok(this) } } pub enum MeasureRequestAttributeInner { TypePath(MeasureRequestTypePathAttribute), KeyVal(MeasureRequestKeyValAttribute), } impl MeasureRequestAttributeInner { pub fn to_requests(&self) -> Vec<MeasureRequest<'_>> { match self { MeasureRequestAttributeInner::TypePath(type_path) => type_path.to_requests(), MeasureRequestAttributeInner::KeyVal(key_val) => key_val.to_requests(), } } } impl Parse for MeasureRequestAttributeInner { fn parse(input: ParseStream<'_>) -> Result<Self> { input .try_parse_as(MeasureRequestAttributeInner::TypePath) .or_else(|_| input.try_parse_as(MeasureRequestAttributeInner::KeyVal)) .map_err(|_| { let err = format!( "invalid format for measure attribute: {}", input.to_string() ); input.error(err) }) } } pub struct MeasureRequestTypePathAttribute { pub type_paths: MultipleVal<syn::TypePath>, } impl MeasureRequestTypePathAttribute { pub fn to_requests(&self) -> Vec<MeasureRequest<'_>> { let mut v = Vec::new(); for type_path in self.type_paths.iter() { let field_name = make_field_name(type_path); v.push(MeasureRequest { tpe: type_path, field_name, debug: None, }) } v } } impl Parse for MeasureRequestTypePathAttribute { fn parse(input: ParseStream<'_>) -> Result<Self> { Ok(MeasureRequestTypePathAttribute { type_paths: input.parse()?, }) } } pub struct MeasureRequestKeyValAttribute { pub values: syn::punctuated::Punctuated<MeasureOptions, Token![,]>, } impl MeasureRequestKeyValAttribute { fn validate(&self, input: ParseStream<'_>) -> Result<()> { self.values .iter() .filter_map(|opt| { if let MeasureOptions::Type(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .ok_or_else(|| { input.error( "missing `type` attribute with a path to a valid metered::Metric struct.", ) })?; let opt_types: std::collections::HashMap<_, _> = self .values .iter() .map(|opt| (std::mem::discriminant(opt), opt.as_str())) .collect(); for (opt_type, opt_name) in opt_types.iter() { let count = self .values .iter() .filter(|&opt| std::mem::discriminant(opt) == *opt_type) .count(); if count > 1 { let error = format!("`{}` attribute is defined more than once.", opt_name); return Err(input.error(error)); } } // self.values.iter(). Ok(()) } pub fn to_requests(&self) -> Vec<MeasureRequest<'_>> { let type_paths = self .values .iter() .filter_map(|opt| { if let MeasureOptions::Type(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .expect("There should be a type! This error cannot happen if the structure has been validated first!"); let debug = self .values .iter() .filter_map(|opt| { if let MeasureOptions::Debug(dbg) = opt { Some(&dbg.value) } else { None } }) .next(); let mut v = Vec::new(); for type_path in type_paths.iter() { let field_name = make_field_name(type_path); v.push(MeasureRequest { tpe: type_path, field_name, debug, }) } v } } fn make_field_name(type_path: &syn::TypePath) -> String { use heck::ToSnakeCase; type_path .path .segments .last() .unwrap() // never empty .ident .to_string() .to_snake_case() } impl Parse for MeasureRequestKeyValAttribute { fn parse(input: ParseStream<'_>) -> Result<Self> { let this = MeasureRequestKeyValAttribute { values: input.parse_terminated(MeasureOptions::parse)?, }; this.validate(input)?; Ok(this) } } mod kw { syn::custom_keyword!(debug); } pub type MeasureTypeOption = KVOption<syn::Token![type], MultipleVal<syn::TypePath>>; pub type MeasureDebugOption = KVOption<kw::debug, InvokePath>; pub enum MeasureOptions { Type(MeasureTypeOption), Debug(MeasureDebugOption), } impl MeasureOptions { pub fn as_str(&self) -> &str { use syn::token::Token; match self { MeasureOptions::Type(_) => <syn::Token![type]>::display(), MeasureOptions::Debug(_) => <kw::debug>::display(), } } } impl Parse for MeasureOptions { fn parse(input: ParseStream<'_>) -> Result<Self> { if MeasureTypeOption::peek(input) { Ok(input.parse_as(MeasureOptions::Type)?) } else if MeasureDebugOption::peek(input) { Ok(input.parse_as(MeasureOptions::Debug)?) } else { let err = format!("invalid measure option: {}", input.to_string()); Err(input.error(err)) } } } <file_sep>/metered/src/common/mod.rs //! A module providing common metrics. mod error_count; mod hit_count; mod in_flight; mod response_time; mod throughput; pub use error_count::ErrorCount; pub use hit_count::HitCount; pub use in_flight::InFlight; pub use response_time::ResponseTime; pub use throughput::{AtomicTxPerSec, RecordThroughput, Throughput, TxPerSec}; <file_sep>/metered/src/common/throughput/atomic_tps.rs use super::{tx_per_sec::TxPerSec, RecordThroughput}; use crate::{ clear::Clear, hdr_histogram::HdrHistogram, time_source::{Instant, StdInstant}, }; use parking_lot::Mutex; use serde::{Serialize, Serializer}; /// Thread-safe implementation of [`super::RecordThroughput`]. It uses a `Mutex` /// to wrap `TxPerSec`. pub struct AtomicTxPerSec<T: Instant = StdInstant> { /// The inner mutex protecting the `TxPerSec` value holding the histogram pub inner: Mutex<TxPerSec<T>>, } impl<T: Instant> AtomicTxPerSec<T> { /// Returns a cloned snapshot of the inner histogram. pub fn histogram(&self) -> HdrHistogram { self.inner.lock().hdr_histogram.clone() } } impl<T: Instant> RecordThroughput for AtomicTxPerSec<T> { #[inline] fn on_result(&self) { self.inner.lock().on_result() } } impl<T: Instant> Default for AtomicTxPerSec<T> { fn default() -> Self { AtomicTxPerSec { inner: Mutex::new(TxPerSec::default()), } } } impl<T: Instant> Clear for AtomicTxPerSec<T> { fn clear(&self) { self.inner.lock().clear(); } } impl<T: Instant> Serialize for AtomicTxPerSec<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let inner = self.inner.lock(); Serialize::serialize(&*inner, serializer) } } use std::{fmt, fmt::Debug}; impl<T: Instant> Debug for AtomicTxPerSec<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let inner = self.inner.lock(); write!(f, "{:?}", &*inner) } } <file_sep>/metered/src/time_source.rs //! A module for Time Sources. /// A trait for any time source providing time measurements in milliseconds. /// /// It is useful to let users provide an unsynchronized (`!Send`/`!Sync`) time /// source, unlike std's `Instant`. pub trait Instant { /// Creates a new Instant representing the current time. fn now() -> Self; /// Returns the elapsed time since an Instant was created. /// /// The unit depends on the Instant's resolution, as defined by the /// `ONE_SEC` constant. fn elapsed_time(&self) -> u64; /// One second in the instant units. const ONE_SEC: u64; } /// A new-type wrapper for std Instants and Metered's /// [Instant] trait that measures time in milliseconds. #[derive(Debug, Clone)] pub struct StdInstant(std::time::Instant); impl Instant for StdInstant { const ONE_SEC: u64 = 1_000; fn now() -> Self { StdInstant(std::time::Instant::now()) } fn elapsed_time(&self) -> u64 { let elapsed = self.0.elapsed(); elapsed.as_secs() * Self::ONE_SEC + u64::from(elapsed.subsec_millis()) } } /// A new-type wrapper for std Instants and Metered's /// [Instant] trait that measures time in microseconds. #[derive(Debug, Clone)] pub struct StdInstantMicros(std::time::Instant); impl Instant for StdInstantMicros { const ONE_SEC: u64 = 1_000_000; fn now() -> Self { StdInstantMicros(std::time::Instant::now()) } fn elapsed_time(&self) -> u64 { let elapsed = self.0.elapsed(); elapsed.as_secs() * Self::ONE_SEC + u64::from(elapsed.subsec_micros()) } } <file_sep>/demos/Cargo.toml [package] name = "metered-demo" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" #break out of workspace [workspace] [dependencies] hdrhistogram = "7.5" rand = "0.8" atomic = "0.5" tokio = { version = "1.19", features = [ "rt", "rt-multi-thread", "time" ] } serde = { version = "1.0", features = ["derive"] } serde_prometheus = "0.1" thiserror = "1.0" [dependencies.metered] version = "0.9" path = "../metered" features = [ # Enable to override the default and skip "cleared" entries from the `error_count` # even when the attribute is not specified. "error-count-skip-cleared-by-default" ] <file_sep>/rustfmt-unstable.toml edition = "2018" imports_granularity="Crate" normalize_comments = true unstable_features = true wrap_comments = true <file_sep>/README.md # metered-rs [![Build Status](https://travis-ci.org/magnet/metered-rs.svg?branch=master)](https://travis-ci.org/magnet/metered-rs) [![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)]( https://github.com/magnet/metered-rs) [![Cargo](https://img.shields.io/crates/v/metered.svg)]( https://crates.io/crates/metered) [![Documentation](https://docs.rs/metered/badge.svg)]( https://docs.rs/metered) [![Rust 1.31+](https://img.shields.io/badge/rust-1.31+-lightgray.svg)]( https://www.rust-lang.org) ## Fast, ergonomic metrics for Rust! Metered helps you measure the performance of your programs in production. Inspired by Coda Hale's Java metrics library, Metered makes live measurements easy by providing declarative and procedural macros to measure your program without altering your logic. Metered is built with the following principles in mind: * **high ergonomics but no magic**: measuring code should just be a matter of annotating code. Metered lets you build your own metric registries from bare metrics, or will generate one using procedural macros. It does not use shared globals or statics. * **constant, very low overhead**: good ergonomics should not come with an overhead; the only overhead is the one imposed by actual metric back-ends themselves (e.g, counters, gauges, histograms), and those provided in Metered do not allocate after initialization. Metered will generate metric registries as regular Rust `struct`s, so there is no lookup involved with finding a metric. Metered provides both unsynchronized and thread-safe metric back-ends so that single-threaded or share-nothing architectures don't pay for synchronization. Where possible, thread-safe metric back-ends provided by Metered use lock-free data-structures. * **extensible**: metrics are just regular types that implement the [`Metric`](https://docs.rs/metered/latest/metered/metric/trait.Metric.html) trait with a specific behavior. Metered's macros let you refer to any Rust type, resulting in user-extensible attributes! Many metrics are only meaningful if we get precise statistics. When it comes to low-latency, high-range histograms, there's nothing better than [Gil Tene's High Dynamic Range Histograms](http://hdrhistogram.org/) and Metered uses [the official Rust port](https://github.com/HdrHistogram/HdrHistogram_rust) by default for its histograms. ## Changelog * 0.9.0: * Wrapping int metrics instead of under/overflow * Provide methods to increment or decrement int metrics by more than 1, useful for batched computations * Add blanket implementations for `Clear` (contributed by [@plankton6](https://github.com/plankton6)) * Add len method to `HdrHistogram` (contributed by [@plankton6](https://github.com/plankton6)) * Code quality fixes and dependency updates * 0.8.0: * Update Metrics via `OnResultMut` rather than an `OnResult` to support metrics that require mutable access to the result - for instance to consume a `Stream` (contributed by [@w4](https://github.com/w4)) * 0.7.0: * Expose inner metric backend `Throughput` type (fixes issue #30) * Implement `Deref` for all top-level metrics * Expose inner metric backend `Throughput` type * Add `skip_cleared` option to `error_count` attribute (contributed by [@w4](https://github.com/w4)) * Introduce a new `Clearable` trait that exposes behavior for metrics that implement `Clear` (in an effort of backwards compatibility). Currently only implemented on counters. * Default behavior can be controlled by the a build-time feature, `error-count-skip-cleared-by-default` * 0.6.0: * Extend `error_count` macro to allow `nested` enum error variants to be reported, providing zero-cost error tracking for nested errors (contributed by [@w4](https://github.com/w4)) * 0.5.0: * Make inner metrics public (contributed by [@nemosupremo](https://github.com/nemosupremo)) * Provide `error_count` macro to generate a tailored `ErrorCount` metric counting variants for an error enum (contributed by [@w4](https://github.com/w4)) * Use `Drop` to automatically trigger metrics that don't rely on the result value (affects `InFlight`, `ResponseTime`, `Throughput`) * 0.4.0: * Add allow(missing_docs) to generated structs (This allows to use metered structs in Rust code with lint level warn(missing_docs) or even deny(missing_docs)) (contributed by [@reyk](https://github.com/reyk)) * Implement `Clear` for generated registries (contributed by [@eliaslevy](https://github.com/eliaslevy)) * Implement `Histogram` and `Clear` for `RefCell<HdrHistogram>` (contributed by [@eliaslevy](https://github.com/eliaslevy)) * Introduce an `Instant` with microsecond precision (contributed by [@eliaslevy](https://github.com/eliaslevy)) * API breaking change: `Instant.elapsed_millis` is renamed to `elapsed_time`, and a new associated constant, `ONE_SEC` is introduced to specify one second in the instant units. * Make `AtomicTxPerSec` and `TxPerSec` visible by reexporting (contributed by [@eliaslevy](https://github.com/eliaslevy)) * Add `StdInstant` as the default type parameter for `T: Instant` in `TxPerSec` (contributed by [@eliaslevy](https://github.com/eliaslevy)) * Modify HdrHistogram to work with serde_prometheus (contributed by [@w4](https://github.com/w4)) * To be used with [serde_prometheus](https://github.com/w4/serde_prometheus) and any HTTP server. * Bumped dependencies: * `indexmap`: 1.1 -> 1.3 * `hdrhistogram`: 6.3 -> 7.1 * `parking_lot`: 0.9 -> 0.10 * 0.3.0: * Fix to preserve span in `async` measured methods. * Update nightly sample for new syntax and Tokio 0.2-alpha (using std futures, will need Rust >= 1.39, nightly or not) * Updated dependencies to use `syn`, `proc-macro2` and `quote` 1.0 * 0.2.2: * Async support in `#measured` methods don't rely on async closures anymore, so client code will not require the `async_closure` feature gate. * Updated dependency versions * 0.2.1: * Under certain circumstances, Serde would serialize "nulls" for `PhantomData` markers in `ResponseTime` and `Throughput` metrics. They are now explicitely excluded. * 0.2.0: * Support for `.await` notation users (no more `await!()`) * 0.1.3: * Fix for early returns in `#[measure]`'ed methods * Removed usage of crate `AtomicRefCell` which sometimes panicked . * Support for custom registry visibility. * Support for `async` + `await!()` macro users. ## Using Metered Metered comes with a variety of useful metrics ready out-of-the-box: * `HitCount`: a counter tracking how much a piece of code was hit. * `ErrorCount`: a counter tracking how many errors were returned -- (works on any expression returning a std `Result`) * `InFlight`: a gauge tracking how many requests are active * `ResponseTime`: statistics backed by an HdrHistogram of the duration of an expression * `Throughput`: statistics backed by an HdrHistogram of how many times an expression is called per second. These metrics are usually applied to methods, using provided procedural macros that generate the boilerplate. To achieve higher performance, these stock metrics can be customized to use non-thread safe (`!Sync`/`!Send`) datastructures, but they default to thread-safe datastructures implemented using lock-free strategies where possible. This is an ergonomical choice to provide defaults that work in all situations. Metered is designed as a zero-overhead abstraction -- in the sense that the higher-level ergonomics should not cost over manually adding metrics. Notably, stock metrics will *not* allocate memory after they're initialized the first time. However, they are triggered at every method call and it can be interesting to use lighter metrics (e.g `HitCount`) in hot code paths and favour heavier metrics (`Throughput`, `ResponseTime`) in higher-level entry points. If a metric you need is missing, or if you want to customize a metric (for instance, to track how many times a specific error occurs, or react depending on your return type), it is possible to implement your own metrics simply by implementing the trait `metered::metric::Metric`. Metered does not use statics or shared global state. Instead, it lets you either build your own metric registry using the metrics you need, or can generate a metric registry for you using method attributes. Metered will generate one registry per `impl` block annotated with the `metered` attribute, under the name provided as the `registry` parameter. By default, Metered will expect the registry to be accessed as `self.metrics` but the expression can be overridden with the `registry_expr` attribute parameter. See the demos for more examples. Metered will generate metric registries that derive `Debug` and `serde::Serialize` to extract your metrics easily. Metered generates one sub-registry per method annotated with the `measure` attribute, hence organizing metrics hierarchically. This ensures access time to metrics in generated registries is always constant (and, when possible, cache-friendly), without any overhead other than the metric itself. Metered will happily measure any method, whether it is `async` or not, and the metrics will work as expected (e.g, `ResponseTime` will return the completion time across `await`'ed invocations). Right now, Metered does not provide bridges to external metric storage or monitoring systems. Such support is planned in separate modules (contributions welcome!). ## Required Rust version Metered works on `Rust` stable, starting 1.31.0. It does not use any nightly features. There may be a `nightly` feature flag at some point to use upcoming Rust features (such as `const fn`s), and similar features from crates Metered depends on, but this is low priority (contributions welcome). ## Example using procedural macros (recommended) ```rust use metered::{metered, Throughput, HitCount}; #[derive(Default, Debug, serde::Serialize)] pub struct Biz { metrics: BizMetrics, } #[metered(registry = BizMetrics)] impl Biz { #[measure([HitCount, Throughput])] pub fn biz(&self) { let delay = std::time::Duration::from_millis(rand::random::<u64>() % 200); std::thread::sleep(delay); } } ``` In the snippet above, we will measure the `HitCount` and `Throughput` of the `biz` method. This works by first annotating the `impl` block with the `metered` annotation and specifying the name Metered should give to the metric registry (here `BizMetrics`). Later, Metered will assume the expression to access that repository is `self.metrics`, hence we need a `metrics` field with the `BizMetrics` type in `Biz`. It would be possible to use another field name by specificying another registry expression, such as `#[metered(registry = BizMetrics, registry_expr = self.my_custom_metrics)]`. Then, we must annotate which methods we wish to measure using the `measure` attribute, specifying the metrics we wish to apply: the metrics here are simply types of structures implementing the `Metric` trait, and you can define your own. Since there is no magic, we must ensure `self.metrics` can be accessed, and this will only work on methods with a `&self` or `&mut self` receiver. Let's look at `biz`'s code a second: it's a blocking method that returns after between 0 and 200ms, using `rand::random`. Since `random` has a random distribution, we can expect the mean sleep time to be around 100ms. That would mean around 10 calls per second per thread. In the following test, we spawn 5 threads that each will call `biz()` 200 times. We thus can expect a hit count of 1000, that it will take around 20 seconds (which means 20 samples, since we collect one sample per second), and around 50 calls per second (10 per thread, with 5 threads). ```rust use std::thread; use std::sync::Arc; fn test_biz() { let biz = Arc::new(Biz::default()); let mut threads = Vec::new(); for _ in 0..5 { let biz = Arc::clone(&biz); let t = thread::spawn(move || { for _ in 0..200 { biz.biz(); } }); threads.push(t); } for t in threads { t.join().unwrap(); } // Print the results! let serialized = serde_yaml::to_string(&*biz).unwrap(); println!("{}", serialized); } ``` We can then use serde to serialize our type as YAML: ```yaml metrics: biz: hit_count: 1000 throughput: - samples: 20 min: 35 max: 58 mean: 49.75 stdev: 5.146600819958742 90%ile: 55 95%ile: 55 99%ile: 58 99.9%ile: 58 99.99%ile: 58 - ~ ``` We see we indead have a mean of 49.75 calls per second, which corresponds to our expectations. The Hdr Histogram backing these statistics is able to give much more than fixed percentiles, but this is a practical view when using text. For a better performance analysis, please watch <NAME>'s talks ;-). ## Macro Reference ### The `metered` attribute `#[metered(registry = YourRegistryName, registry_expr = self.wrapper.my_registry)]` `registry` is mandatory and must be a valid Rust ident. `registry_expr` defaults to `self.metrics`, alternate values must be a valid Rust expression. This setting lets you configure the expression which resolves to the registry. Please note that this triggers an immutable borrow of that expression. `visibility` defaults to `pub(crate)`, and must be a valid struct Rust visibility (e.g, `pub`, `<nothing>`, `pub(self)`, etc). This setting lets you alter the visibility of the generated registry `struct`s. The registry fields are always public and named after snake cased methods or metrics. ### The `measure` attribute Single metric: `#[measure(path::to::MyMetric<u64>)]` or: `#[measure(type = path::to::MyMetric<u64>)]` Multiple metrics: `#[measure([path::to::MyMetric<u64>, path::AnotherMetric])]` or `#[measure(type = [path::to::MyMetric<u64>, path::AnotherMetric])]` The `type` keyword is allowed because other keywords are planned for future extra attributes (e.g, instantation options). When `measure` attribute is applied to an `impl` block, it applies for every method that has a `measure` attribute. If a method does not need extra measure infos, it is possible to annotate it with simply `#[measure]` and the `impl` block's `measure` configuration will be applied. The `measure` keyword can be added several times on an `impl` block or method, which will add to the list of metrics applied. Adding the same metric several time will lead in a name clash. ### Design Metered's custom attribute parsing supports using reserved keywords and arbitrary Rust syntax. The code has been extracted to the [Synattra](https://github.com/magnet/synattra) project, which provides useful methods on top of the Syn parser for Attribute parsing. Metered's metrics can wrap any piece of code, regardless of whether they're `async` blocks or not, using hygienic macros to emulate an approach similar to aspect-oriented programming. That code has been extracted to the [Aspect-rs](https://github.com/magnet/aspect-rs) project! ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. <file_sep>/metered/src/common/hit_count.rs //! A module providing the `HitCount` metric. use crate::{ atomic::AtomicInt, clear::Clear, metric::{Counter, Metric}, }; use aspect::{Enter, OnResult}; use serde::Serialize; use std::ops::Deref; /// A metric counting how many times an expression as been hit, before it /// returns. /// /// This is a light-weight metric. /// /// By default, `HitCount` uses a lock-free `u64` `Counter`, which makes sense /// in multithread scenarios. Non-threaded applications can gain performance by /// using a `std::cell:Cell<u64>` instead. #[derive(Clone, Default, Debug, Serialize)] pub struct HitCount<C: Counter = AtomicInt<u64>>(pub C); impl<C: Counter, R> Metric<R> for HitCount<C> {} impl<C: Counter> Enter for HitCount<C> { type E = (); fn enter(&self) -> Self::E { self.0.incr(); } } impl<C: Counter, R> OnResult<R> for HitCount<C> {} impl<C: Counter> Clear for HitCount<C> { fn clear(&self) { self.0.clear() } } impl<C: Counter> Deref for HitCount<C> { type Target = C; fn deref(&self) -> &Self::Target { &self.0 } } <file_sep>/metered-macro/src/error_count.rs use crate::error_count_opts::ErrorCountKeyValAttribute; use heck::ToSnakeCase; use proc_macro::TokenStream; use syn::{Attribute, Field, Fields, Ident, ItemEnum}; pub fn error_count(attrs: TokenStream, item: TokenStream) -> syn::Result<TokenStream> { let attrs: ErrorCountKeyValAttribute = syn::parse(attrs)?; let attrs = attrs.to_error_count_opts(); let vis = attrs.visibility; let metrics_ident = attrs.name_ident; let mut input: ItemEnum = syn::parse(item)?; let nested_attrs = get_nested_attrs(&mut input)?; // get the type of the metric for each variant, most of the time this will be // `C`, but if `#[nested(Abc)]` is on a variant field, the type will instead // be set to `Abc` and incrs will be delegated there let metric_type = nested_attrs .iter() .map(|(_, v)| { if let Some((field, attr)) = v { let error_type = &field.ty; attr.parse_args::<proc_macro2::TokenStream>() .unwrap_or_else( |_| quote!(<#error_type as metered::ErrorBreakdown<C>>::ErrorCount), ) } else { quote!(C) } }) .collect::<Vec<_>>(); let ident = &input.ident; let variants = input.variants.iter().map(|v| &v.ident); let stringified_variants = input.variants.iter().map(|v| v.ident.to_string()); let snake_variants: Vec<Ident> = input .variants .iter() .map(|v| Ident::new(&v.ident.to_string().to_snake_case(), v.ident.span())) .collect(); // copy #[cfg(..)] attributes from the variant and apply them to the // corresponding error in our struct so we don't point to an invalid variant // in certain configurations. let cfg_attrs: Vec<Vec<&Attribute>> = input .variants .iter() .map(|v| v.attrs.iter().filter(|v| v.path.is_ident("cfg")).collect()) .collect(); // generate unbound arg params for each enum variant let variants_args = nested_attrs .iter() .map(|(fields, nested_attr)| match &fields { syn::Fields::Named(_) => { if let Some((field, _)) = nested_attr { let key = field.ident.as_ref().expect("field missing ident"); quote!({ #key, .. }) } else { quote!({ .. }) } } syn::Fields::Unnamed(_) => { let args = fields.iter().map(|field| { if field.attrs.iter().any(|attr| attr.path.is_ident("nested")) { quote!(nested) } else { quote!(_) } }); quote! { (#( #args, )*) } } syn::Fields::Unit => quote!(), }); // generate incr calls for each variant, if a field is marked with `#[nested]`, // the incr is instead delegated there let variant_incr_call = nested_attrs .iter() .zip(snake_variants.iter()) .map(|((_, nested_attr), ident)| { if let Some((field, attr)) = nested_attr { let inner_val_ident = field .ident .clone() .unwrap_or_else(|| Ident::new("nested", attr.bracket_token.span)); quote! {{ self.#ident.incr(#inner_val_ident); }} } else { quote!(self.#ident.incr()) } }); let skip_cleared = attrs.skip_cleared; let serializer = nested_attrs.iter().map(|(_, nested_attr)| { if skip_cleared && nested_attr.is_none() { quote!("metered::error_variant_serializer_skip_cleared") } else { quote!("metered::error_variant_serializer") } }); Ok(quote! { #input #[derive(serde::Serialize, Default, Debug)] #[allow(missing_docs)] #vis struct #metrics_ident<C: metered::metric::Counter = metered::atomic::AtomicInt<u64>> { #[serde(skip)] __phantom: std::marker::PhantomData<C>, #( #(#cfg_attrs)* #[serde(rename = #stringified_variants, serialize_with = #serializer)] pub #snake_variants: #metric_type, )* } impl<C: metered::metric::Counter> #metrics_ident<C> { pub fn incr(&self, err: &#ident) { match err { #( #(#cfg_attrs)* #ident::#variants #variants_args => #variant_incr_call, )* } } } impl<C: metered::metric::Counter> metered::clear::Clear for #metrics_ident<C> { fn clear(&self) { #( #(#cfg_attrs)* self.#snake_variants.clear(); )* } } impl<T, C: metered::metric::Counter> metered::metric::Metric<Result<T, #ident>> for #metrics_ident<C> {} impl<C: metered::metric::Counter> metered::metric::Enter for #metrics_ident<C> { type E = (); fn enter(&self) {} } impl<T, C: metered::metric::Counter> metered::metric::OnResult<Result<T, #ident>> for #metrics_ident<C> { fn on_result(&self, _: (), r: &Result<T, #ident>) -> metered::metric::Advice { if let Err(e) = r { self.incr(e); } metered::metric::Advice::Return } } impl<C: metered::metric::Counter> metered::ErrorBreakdown<C> for #ident { type ErrorCount = #metrics_ident<C>; } }.into()) } type FieldWithNestedAttribute = Option<(Field, Attribute)>; /// Gets all variants from the given `ItemEnum`, and returns `Some(Field, /// Attribute)` along with each variant if one of fields contained a `#[nested]` /// attribute. /// /// If a `#[nested]` attribute is found, then the attribute itself removed from /// `input` so that we don't get "unrecognised attribute" errors. fn get_nested_attrs(input: &mut ItemEnum) -> syn::Result<Vec<(Fields, FieldWithNestedAttribute)>> { let attrs = input .variants .iter_mut() .map(|v| { // clone fields before we do any mutation on it so consumers can figure out the // position of #[nested] fields. let fields = v.fields.clone(); let inner_fields = match &mut v.fields { syn::Fields::Named(v) => &mut v.named, syn::Fields::Unnamed(v) => &mut v.unnamed, _ => return Ok((fields, None)), }; // field containing the nested attribute, along with the attribute itself let mut nested_attr = None; for field in inner_fields { if let Some(pos) = field.attrs.iter().position(|a| a.path.is_ident("nested")) { let attr = field.attrs.remove(pos); // if we've already found a nested attribute on a field in the current variant, // throw an error if nested_attr.is_some() { return Err(syn::Error::new( attr.bracket_token.span, "Can't declare `#[nested]` on more than one field in a single variant", )); } nested_attr = Some((field.clone(), attr.clone())); } } Ok((fields, nested_attr)) }) .collect::<syn::Result<Vec<_>>>()?; Ok(attrs) } <file_sep>/metered-macro/Cargo.toml [package] name = "metered-macro" version = "0.9.0" authors = ["<NAME> <<EMAIL>>"] license = "Apache-2.0 OR MIT" readme = "../README.md" keywords = ["metrics", "macro"] repository = "https://github.com/magnet/metered-rs" description = """ Fast, ergonomic metrics for Rust! """ categories = ["rust-patterns", "development-tools::profiling", "data-structures", "algorithms", "asynchronous"] edition = "2018" [dependencies] syn = {version= "1.0", features = ["full"] } aspect-weave = "0.2" synattra = "0.2" quote = "1.0" proc-macro2 = "1.0" heck = "0.4" indexmap = "1.8" [dev-dependencies] serde = { version = "1.0", features = ["derive"] } metered = { path = "../metered" } thiserror = "1.0" rand = "0.8" [features] # When enabled, the error count macro will skip serializing cleared entries (e.g counters with value 0) # This can be overridden with the `skip_cleared` macro attribute error-count-skip-cleared-by-default = [] [lib] proc-macro = true<file_sep>/metered/src/lib.rs //! # Fast, ergonomic metrics for Rust! //! //! Metered helps you measure the performance of your programs in production. //! Inspired by <NAME>'s Java metrics library, Metered makes live //! measurements easy by providing measurement declarative and procedural //! macros, and a variety of useful metrics ready out-of-the-box: //! * [`HitCount`]: a counter tracking how much a piece of code was hit. //! * [`ErrorCount`]: a counter tracking how many errors were returned -- (works //! on any expression returning a std `Result`) //! * [`InFlight`]: a gauge tracking how many requests are active //! * [`ResponseTime`]: statistics backed by an HdrHistogram of the duration of //! an expression //! * [`Throughput`]: statistics backed by an HdrHistogram of how many times an //! expression is called per second. //! //! These metrics are usually applied to methods, using provided procedural //! macros that generate the boilerplate. //! //! To achieve higher performance, these stock metrics can be customized to use //! non-thread safe (`!Sync`/`!Send`) datastructures, but they default to //! thread-safe datastructures implemented using lock-free strategies where //! possible. This is an ergonomical choice to provide defaults that work in all //! situations. //! //! Metered is designed as a zero-overhead abstraction -- in the sense that the //! higher-level ergonomics should not cost over manually adding metrics. //! Notably, stock metrics will *not* allocate memory after they're initialized //! the first time. However, they are triggered at every method call and it can //! be interesting to use lighter metrics (e.g //! [`HitCount`]) in hot code paths and favour //! heavier metrics ([`Throughput`], //! [`ResponseTime`]) in higher-level entry //! points. //! //! If a metric you need is missing, or if you want to customize a metric (for //! instance, to track how many times a specific error occurs, or react //! depending on your return type), it is possible to implement your own metrics //! simply by implementing the [`Metric`] trait . //! //! Metered does not use statics or shared global state. Instead, it lets you //! either build your own metric registry using the metrics you need, or can //! generate a metric registry for you using method attributes. Metered will //! generate one registry per `impl` block annotated with the `metered` //! attribute, under the name provided as the `registry` parameter. By default, //! Metered will expect the registry to be accessed as `self.metrics` but the //! expression can be overridden with the `registry_expr` attribute parameter. //! See the demos for more examples. //! //! Metered will generate metric registries that derive [`std::fmt::Debug`] and //! [`serde::Serialize`] to extract your metrics easily. Metered generates one //! sub-registry per method annotated with the `measure` attribute, hence //! organizing metrics hierarchically. This ensures access time to metrics in //! generated registries is always constant (and, when possible, //! cache-friendly), without any overhead other than the metric itself. //! //! Metered will happily measure any method, whether it is `async` or not, and //! the metrics will work as expected (e.g, //! [`ResponseTime`] will return the completion //! time across `await`'ed invocations). //! //! Metered's serialized metrics can be used in conjunction with //! [`serde_prometheus`](https://github.com/w4/serde_prometheus) to publish //! metrics to Prometheus. //! //! ## Example using procedural macros (recommended) //! //! ``` //! # extern crate metered; //! # extern crate rand; //! //! use metered::{metered, Throughput, HitCount}; //! //! #[derive(Default, Debug)] //! pub struct Biz { //! metrics: BizMetrics, //! } //! //! #[metered::metered(registry = BizMetrics)] //! impl Biz { //! #[measure([HitCount, Throughput])] //! pub fn biz(&self) { //! let delay = std::time::Duration::from_millis(rand::random::<u64>() % 200); //! std::thread::sleep(delay); //! } //! } //! //! # fn main() { //! # } //! ``` //! //! In the snippet above, we will measure the //! [`HitCount`] and //! [`Throughput`] of the `biz` method. //! //! This works by first annotating the `impl` block with the `metered` //! annotation and specifying the name Metered should give to the metric //! registry (here `BizMetrics`). Later, Metered will assume the expression to //! access that repository is `self.metrics`, hence we need a `metrics` field //! with the `BizMetrics` type in `Biz`. It would be possible to use another //! field name by specificying another registry expression, such as //! `#[metered(registry = BizMetrics, registry_expr = self.my_custom_metrics)]`. //! //! Then, we must annotate which methods we wish to measure using the `measure` //! attribute, specifying the metrics we wish to apply: the metrics here are //! simply types of structures implementing the `Metric` trait, and you can //! define your own. Since there is no magic, we must ensure `self.metrics` can //! be accessed, and this will only work on methods with a `&self` or `&mut //! self` receiver. //! //! ## Example of manually using metrics //! //! ``` //! use metered::{measure, HitCount, ErrorCount}; //! //! #[derive(Default, Debug)] //! struct TestMetrics { //! hit_count: HitCount, //! error_count: ErrorCount, //! } //! //! fn test(should_fail: bool, metrics: &TestMetrics) -> Result<u32, &'static str> { //! let hit_count = &metrics.hit_count; //! let error_count = &metrics.error_count; //! measure!(hit_count, { //! measure!(error_count, { //! if should_fail { //! Err("Failed!") //! } else { //! Ok(42) //! } //! }) //! }) //! } //! ``` //! //! The code above shows how different metrics compose, and in general the kind //! of boilerplate generated by the `#[metered]` procedural macro. #![deny(missing_docs)] #![deny(warnings)] pub mod atomic; pub mod clear; pub mod common; pub mod hdr_histogram; pub mod int_counter; pub mod int_gauge; pub mod metric; pub(crate) mod num_wrapper; pub mod time_source; pub use common::{ErrorCount, HitCount, InFlight, ResponseTime, Throughput}; pub use metered_macro::{error_count, metered}; pub use metric::{Counter, Gauge, Histogram, Metric}; /// Re-export this type so 3rd-party crates don't need to depend on the /// `aspect-rs` crate. pub use aspect::Enter; /// The `measure!` macro takes a reference to a metric and an expression. /// /// It applies the metric and the expression is returned unchanged. #[macro_export] macro_rules! measure { ($metric:expr, $e:expr) => {{ let metric = $metric; let guard = $crate::metric::ExitGuard::new(metric); let mut result = $e; guard.on_result(&mut result); result }}; } /// Serializer for values within a struct generated by /// `metered::metered_error_variants` that adds an `error_kind` label when being /// serialized by `serde_prometheus`. pub fn error_variant_serializer<S: serde::Serializer, T: serde::Serialize>( value: &T, serializer: S, ) -> Result<S::Ok, S::Error> { serializer.serialize_newtype_struct("!|variant[::]==<", value) } /// Serializer for values within a struct generated by /// `metered::metered_error_variants` that adds an `error_kind` label when being /// serialized by `serde_prometheus`. If the `value` has been cleared. This /// operation is a no-op and the value wont be written to the `serializer`. pub fn error_variant_serializer_skip_cleared< S: serde::Serializer, T: serde::Serialize + clear::Clearable, >( value: &T, serializer: S, ) -> Result<S::Ok, S::Error> { if value.is_cleared() { serializer.serialize_none() } else { error_variant_serializer(value, serializer) } } /// Trait applied to error enums by `#[metered::error_count]` to identify /// generated error count structs. pub trait ErrorBreakdown<C: metric::Counter> { /// The generated error count struct. type ErrorCount; } <file_sep>/metered/src/int_counter.rs //! A module providing thread-safe and unsynchronized implementations for //! Counters on various unsized integers. use crate::{ atomic::AtomicInt, clear::{Clear, Clearable}, metric::Counter, num_wrapper::NumWrapper, }; use std::cell::Cell; macro_rules! impl_counter_for { ($int:path) => { impl Counter for Cell<$int> { fn incr_by(&self, count: usize) { let v = NumWrapper::<$int>::wrap(count); self.set(self.get().wrapping_add(v)); } } impl Clear for Cell<$int> { fn clear(&self) { self.set(0); } } impl Clearable for Cell<$int> { fn is_cleared(&self) -> bool { self.get() == 0 } } impl Counter for AtomicInt<$int> { fn incr_by(&self, count: usize) { let v = NumWrapper::<$int>::wrap(count); AtomicInt::<$int>::incr_by(&self, v); } } impl Clear for AtomicInt<$int> { fn clear(&self) { AtomicInt::<$int>::set(&self, 0); } } impl Clearable for AtomicInt<$int> { fn is_cleared(&self) -> bool { AtomicInt::<$int>::get(&self) == 0 } } }; } impl_counter_for!(u8); impl_counter_for!(u16); impl_counter_for!(u32); impl_counter_for!(u64); impl_counter_for!(u128); <file_sep>/metered-macro/src/error_count_opts.rs //! The module supporting `#[error_count]` options use syn::{ parse::{Parse, ParseStream}, Result, }; use synattra::{types::KVOption, *}; use std::borrow::Cow; pub struct ErrorCountOpts<'a> { pub name_ident: &'a syn::Ident, pub visibility: Cow<'a, syn::Visibility>, pub skip_cleared: bool, } pub struct ErrorCountKeyValAttribute { pub values: syn::punctuated::Punctuated<ErrorCountOption, Token![,]>, } impl ErrorCountKeyValAttribute { fn validate(&self, input: ParseStream<'_>) -> Result<()> { self.values .iter() .filter_map(|opt| { if let ErrorCountOption::Name(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .ok_or_else(|| input.error("missing `name` attribute."))?; let opt_types: std::collections::HashMap<_, _> = self .values .iter() .map(|opt| (std::mem::discriminant(opt), opt.as_str())) .collect(); for (opt_type, opt_name) in opt_types.iter() { let count = self .values .iter() .filter(|&opt| std::mem::discriminant(opt) == *opt_type) .count(); if count > 1 { let error = format!("`{}` attribute is defined more than once.", opt_name); return Err(input.error(error)); } } Ok(()) } pub fn to_error_count_opts(&self) -> ErrorCountOpts<'_> { let name_ident = self .values .iter() .filter_map(|opt| { if let ErrorCountOption::Name(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .expect("There should be a name! This error cannot happen if the structure has been validated first!"); let visibility = self .values .iter() .filter_map(|opt| { if let ErrorCountOption::Visibility(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .map(|id| Cow::Borrowed(id)) .unwrap_or_else(|| { Cow::Owned(syn::parse_str::<syn::Visibility>("pub(crate)").unwrap()) }); let skip_cleared = self .values .iter() .filter_map(|opt| { if let ErrorCountOption::SkipCleared(tpe) = opt { Some(&tpe.value) } else { None } }) .next() .map(|value| value.value) .unwrap_or(cfg!(feature = "error-count-skip-cleared-by-default")); ErrorCountOpts { name_ident, visibility, skip_cleared, } } } impl Parse for ErrorCountKeyValAttribute { fn parse(input: ParseStream<'_>) -> Result<Self> { let this = ErrorCountKeyValAttribute { values: input.parse_terminated(ErrorCountOption::parse)?, }; this.validate(input)?; Ok(this) } } mod kw { syn::custom_keyword!(name); syn::custom_keyword!(visibility); syn::custom_keyword!(skip_cleared); } pub type ErrorCountNameOption = KVOption<kw::name, syn::Ident>; pub type ErrorCountVisibilityOption = KVOption<kw::visibility, syn::Visibility>; pub type ErrorCountSkipClearedOption = KVOption<kw::skip_cleared, syn::LitBool>; #[allow(clippy::large_enum_variant)] pub enum ErrorCountOption { Name(ErrorCountNameOption), Visibility(ErrorCountVisibilityOption), SkipCleared(ErrorCountSkipClearedOption), } impl ErrorCountOption { pub fn as_str(&self) -> &str { use syn::token::Token; match self { ErrorCountOption::Name(_) => <kw::name>::display(), ErrorCountOption::Visibility(_) => <kw::visibility>::display(), ErrorCountOption::SkipCleared(_) => <kw::skip_cleared>::display(), } } } impl Parse for ErrorCountOption { fn parse(input: ParseStream<'_>) -> Result<Self> { if ErrorCountNameOption::peek(input) { Ok(input.parse_as(ErrorCountOption::Name)?) } else if ErrorCountVisibilityOption::peek(input) { Ok(input.parse_as(ErrorCountOption::Visibility)?) } else if ErrorCountSkipClearedOption::peek(input) { Ok(input.parse_as(ErrorCountOption::SkipCleared)?) } else { let err = format!("invalid error_count option: {}", input); Err(input.error(err)) } } } <file_sep>/metered-macro/src/metered.rs //! The module supporting #[metered] use proc_macro::TokenStream; use crate::{measure_opts::MeasureRequestAttribute, metered_opts::MeteredKeyValAttribute}; use aspect_weave::*; use std::rc::Rc; use synattra::ParseAttributes; pub fn metered(attrs: TokenStream, item: TokenStream) -> syn::Result<TokenStream> { let woven_impl_block = weave_impl_block::<MeteredWeave>(attrs, item)?; let impl_block = &woven_impl_block.woven_block; let metered = &woven_impl_block.main_attributes.to_metered(); let measured = &woven_impl_block.woven_fns; let registry_name = &metered.registry_name; let registry_ident = &metered.registry_ident; let visibility = &metered.visibility; let mut code = quote! {}; let mut reg_fields = quote! {}; let mut reg_clears = quote! {}; for (fun_name, _) in measured.iter() { use heck::ToUpperCamelCase; let fun_reg_name = format!( "{}{}", registry_name, fun_name.to_string().to_upper_camel_case() ); let fun_registry_ident = syn::Ident::new(&fun_reg_name, impl_block.impl_token.span); reg_fields = quote! { #reg_fields pub #fun_name : #fun_registry_ident, }; reg_clears = quote! { #reg_clears self.#fun_name.clear(); }; } code = quote! { #code #[derive(Debug, Default, serde::Serialize)] #[allow(missing_docs)] #visibility struct #registry_ident { #reg_fields } impl metered::clear::Clear for #registry_ident { fn clear(&self) { #reg_clears } } }; drop(reg_fields); for (fun_name, measure_request_attrs) in measured.iter() { use heck::ToUpperCamelCase; let fun_reg_name = format!( "{}{}", registry_name, fun_name.to_string().to_upper_camel_case() ); let fun_registry_ident = syn::Ident::new(&fun_reg_name, impl_block.impl_token.span); let mut fun_reg_fields = quote! {}; let mut fun_reg_clears = quote! {}; for measure_req_attr in measure_request_attrs.iter() { let metric_requests = measure_req_attr.to_requests(); for metric in metric_requests.iter() { let metric_field = metric.ident(); let metric_type = metric.type_path(); fun_reg_fields = quote! { #fun_reg_fields pub #metric_field : #metric_type, }; fun_reg_clears = quote! { #fun_reg_clears self.#metric_field.clear(); }; } } code = quote! { #code #[derive(Debug, Default, serde::Serialize)] #[allow(missing_docs)] #visibility struct #fun_registry_ident { #fun_reg_fields } impl metered::clear::Clear for #fun_registry_ident { fn clear(&self) { #fun_reg_clears } } }; } code = quote! { #impl_block #code }; let result: TokenStream = code.into(); // println!("Result {}", result.to_string()); Ok(result) } struct MeteredWeave; impl Weave for MeteredWeave { type MacroAttributes = MeteredKeyValAttribute; fn update_fn_block( item_fn: &syn::ImplItemMethod, main_attr: &Self::MacroAttributes, fn_attr: &[Rc<<Self as ParseAttributes>::Type>], ) -> syn::Result<syn::Block> { let metered = main_attr.to_metered(); let ident = &item_fn.sig.ident; let block = &item_fn.block; // We must alter the block to capture early returns // using a closure, and handle the async case. let outer_block = if item_fn.sig.asyncness.is_some() { // For versions before `.await` stabilization, // We cannot use the `await` keyword in the `quote!` macro // We'd like to simply be able to put this in the `quote!`: // // (move || async move #block)().await` let await_fut = syn::parse_str::<syn::Expr>("fut.await")?; quote! { { let fut = (move || async move #block)(); #await_fut } } } else { quote! { (move || #block)() } }; let r = measure_list(&metered.registry_expr, &ident, fn_attr, outer_block); let new_block = syn::parse2::<syn::Block>(r)?; Ok(new_block) } } impl ParseAttributes for MeteredWeave { type Type = MeasureRequestAttribute; // const fn fn_attr_name() -> &'static str { "measure" } } fn measure_list( registry_expr: &syn::Expr, fun_ident: &syn::Ident, measure_request_attrs: &[Rc<MeasureRequestAttribute>], mut inner: proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { // Recursive macro invocations for measure_req_attr in measure_request_attrs.iter() { let metric_requests = measure_req_attr.to_requests(); for metric in metric_requests.iter() { let metric_var = metric.ident(); inner = quote! { metered::measure! { #metric_var, #inner } }; } } // Let-bindings to avoid moving issues for measure_req_attr in measure_request_attrs.iter() { let metric_requests = measure_req_attr.to_requests(); for metric in metric_requests.iter() { let metric_var = syn::Ident::new(&metric.field_name, proc_macro2::Span::call_site()); inner = quote! { let #metric_var = &#registry_expr.#fun_ident.#metric_var; #inner }; } // // Use debug routine if enabled! // if let Some(opt) = metric.debug { // } } // Add final braces quote! { { #inner } } } <file_sep>/metered/src/clear.rs //! A module providing a Clear trait which signals metrics to clear their state //! if applicable. use std::sync::Arc; /// The `Clear` trait is used to signal metrics to clear their state if /// applicable /// /// While it is recommended all metrics should implement `Clear`, for instance /// to derive `Clear` on registries, some metrics may choose to do nothing. For /// instance, Gauges would be left in an inconsistent state if they were altered /// during clear. pub trait Clear { /// Requests to clear self. fn clear(&self); } impl<T: Clear> Clear for Arc<T> { fn clear(&self) { (&**self).clear(); } } impl<T: Clear> Clear for &T { fn clear(&self) { (*self).clear(); } } /// The `Clearable` trait is used to provide metadata around some types that can /// be cleared. pub trait Clearable { /// Returns true if self has been cleared and not yet been written to since. fn is_cleared(&self) -> bool; } <file_sep>/metered/src/atomic.rs //! A module providing new-type Atomic wrapper that implements Debug & //! Serialize. use serde::{Serialize, Serializer}; use std::{ fmt, fmt::{Debug, Display}, sync::atomic::Ordering, }; /// A new-type wrapper over `atomic::Atomic` that supports serde serialization /// and a cleaner debug output. /// /// All default operations on the wrapper type are using a relaxed memory /// ordering, which makes it suitable for counters and little else. #[derive(Default)] pub struct AtomicInt<T: Copy> { /// The inner atomic instance pub inner: atomic::Atomic<T>, } impl<T: Copy> AtomicInt<T> { /// Returns the current value pub fn get(&self) -> T { self.inner.load(Ordering::Relaxed) } } impl<T: Copy + Display> Debug for AtomicInt<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.get()) } } macro_rules! impl_blocks_for { ($int:path: $method_name:ident) => { impl AtomicInt<$int> { /// Increments self /// /// Returns the previous count pub fn incr(&self) -> $int { self.inner.fetch_add(1, Ordering::Relaxed) } /// Increments self by count /// /// Returns the previous count pub fn incr_by(&self, count: $int) -> $int { self.inner.fetch_add(count, Ordering::Relaxed) } /// Decrements self /// /// Returns the previous count pub fn decr(&self) -> $int { self.inner.fetch_sub(1, Ordering::Relaxed) } /// Decrements self by count /// /// Returns the previous count pub fn decr_by(&self, count: $int) -> $int { self.inner.fetch_sub(count, Ordering::Relaxed) } /// Sets self to a new value pub fn set(&self, v: $int) { self.inner.store(v, Ordering::Relaxed); } } impl Serialize for AtomicInt<$int> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.$method_name(self.get()) } } }; } impl_blocks_for!(u8: serialize_u8); impl_blocks_for!(u16: serialize_u16); impl_blocks_for!(u32: serialize_u32); impl_blocks_for!(u64: serialize_u64); impl_blocks_for!(u128: serialize_u128); #[cfg(test)] mod tests { // The `atomic` crate makes no explicit guarantees on wrapping on overflow // however `std` atomics that it uses underneath do. // // This test ensures `atomic`'s behavior does not deviate. #[test] fn test_atomic_wraps() { use super::*; let a = AtomicInt { inner: atomic::Atomic::<u8>::new(255u8), }; a.incr(); assert_eq!(a.get(), 0u8); a.decr(); assert_eq!(a.get(), 255u8); } } <file_sep>/metered/src/num_wrapper.rs use std::marker::PhantomData; /// Metered metrics wrap when the counters are at capacity instead of /// overflowing or underflowing. /// /// This struct provides wrapping logic where a metric can be incremented or /// decremented `N` times, where `N` is `usize`. /// /// This is the most logical default: /// * It is observable /// * Metered should never panic business code /// * While we could argue that gauges saturate at max capacity, doing /// so will unbalance the gauge when decrementing the count after a saturated /// add. Instead we guarantee that for all `N`, each `incr_by(N)` followed by a /// `decr_by(N)` results in the original value. /// /// Should we avoid calling `NumWrapper` with `count = 1`, i.e is the optimizer /// able to get rid of the wrapping computations? The Godbolt compiler explorer /// shows that starting `opt-level = 1`, the generated call is equivalent. /// Program below for future reference: /// ```rust /// pub fn wrap(count: usize) -> u8 { /// (count % (u8::MAX as usize + 1)) as u8 /// } /// /// pub fn naive(c: u8) -> u8 { /// c.wrapping_add(wrap(1)) /// } /// /// pub fn manual(c: u8) -> u8 { /// c.wrapping_add(1) /// } /// /// /// pub fn main(){ /// let m = manual(42); /// let n = naive(42); /// println!("{n} {m}"); /// } /// ``` pub(crate) struct NumWrapper<T>(PhantomData<T>); macro_rules! impl_num_wrapper_for_smaller_than_usize { ($int:path) => { impl NumWrapper<$int> { /// Wrap count wrapped over $int pub(crate) fn wrap(count: usize) -> $int { (count % (<$int>::MAX as usize + 1)) as $int } } }; } macro_rules! impl_num_wrapper_for_equal_or_larger_than_usize { ($int:path) => { impl NumWrapper<$int> { /// Return count as $int pub(crate) fn wrap(count: usize) -> $int { count as $int } } }; } cfg_if::cfg_if! { if #[cfg(target_pointer_width = "8")] { impl_num_wrapper_for_equal_or_larger_than_usize!(u8); impl_num_wrapper_for_equal_or_larger_than_usize!(u16); impl_num_wrapper_for_equal_or_larger_than_usize!(u32); impl_num_wrapper_for_equal_or_larger_than_usize!(u64); impl_num_wrapper_for_equal_or_larger_than_usize!(u128); } else if #[cfg(target_pointer_width = "16")] { impl_num_wrapper_for_smaller_than_usize!(u8); impl_num_wrapper_for_equal_or_larger_than_usize!(u16); impl_num_wrapper_for_equal_or_larger_than_usize!(u32); impl_num_wrapper_for_equal_or_larger_than_usize!(u64); impl_num_wrapper_for_equal_or_larger_than_usize!(u128); } else if #[cfg(target_pointer_width = "32")] { impl_num_wrapper_for_smaller_than_usize!(u8); impl_num_wrapper_for_smaller_than_usize!(u16); impl_num_wrapper_for_equal_or_larger_than_usize!(u32); impl_num_wrapper_for_equal_or_larger_than_usize!(u64); impl_num_wrapper_for_equal_or_larger_than_usize!(u128); } else if #[cfg(target_pointer_width = "64")] { impl_num_wrapper_for_smaller_than_usize!(u8); impl_num_wrapper_for_smaller_than_usize!(u16); impl_num_wrapper_for_smaller_than_usize!(u32); impl_num_wrapper_for_equal_or_larger_than_usize!(u64); impl_num_wrapper_for_equal_or_larger_than_usize!(u128); } else if #[cfg(target_pointer_width = "128")] { impl_num_wrapper_for_smaller_than_usize!(u8); impl_num_wrapper_for_smaller_than_usize!(u16); impl_num_wrapper_for_smaller_than_usize!(u32); impl_num_wrapper_for_smaller_than_usize!(u64); impl_num_wrapper_for_equal_or_larger_than_usize!(u128); } else { compile_error!("Unsupported architecture - unhandled pointer size."); } } #[cfg(test)] mod tests { use super::*; use proptest::prelude::*; // test with u8 for more wrapping - same model/properties applies to other ints. fn incr_by(cc: u8, count: usize) -> u8 { let v = NumWrapper::<u8>::wrap(count); cc.wrapping_add(v) } fn incr_by_naive(mut cc: u8, count: usize) -> u8 { for _ in 0..count { cc = cc.wrapping_add(1); } cc } fn decr_by(cc: u8, count: usize) -> u8 { let v = NumWrapper::<u8>::wrap(count); cc.wrapping_sub(v) } fn decr_by_naive(mut cc: u8, count: usize) -> u8 { for _ in 0..count { cc = cc.wrapping_sub(1); } cc } proptest! { #[test] fn test_wrapping_incr(x: u8, y in 0..4096usize) { // Tests if calling incr() Y times returns the same value // as the optimized version assert_eq!(incr_by_naive(x, y), incr_by(x, y)); } #[test] fn test_wrapping_decr(x: u8, y in 0..4096usize) { // Tests if calling decr() Y times returns the same value // as the optimized version assert_eq!(decr_by_naive(x, y), decr_by(x, y)); } #[test] fn test_wrapping_incr_decr_symmetric(x: u8, y: usize) { // reduce strategy space, usize takes too long // Tests if calling decr() Y times on incr() Y times returns // the original value assert_eq!(x, decr_by(incr_by(x, y), y)); } } } <file_sep>/metered/src/hdr_histogram.rs //! A module providing thread-safe and unsynchronized implementations for //! Histograms, based on HdrHistogram. use crate::{clear::Clear, metric::Histogram}; use parking_lot::Mutex; use serde::{Serialize, Serializer}; /// A thread-safe implementation of HdrHistogram pub struct AtomicHdrHistogram { inner: Mutex<HdrHistogram>, } impl AtomicHdrHistogram { /// Returns a cloned snapshot of the inner histogram. pub fn histogram(&self) -> HdrHistogram { self.inner.lock().clone() } } impl Histogram for AtomicHdrHistogram { fn with_bound(max_bound: u64) -> Self { let histo = HdrHistogram::with_bound(max_bound); let inner = Mutex::new(histo); AtomicHdrHistogram { inner } } fn record(&self, value: u64) { self.inner.lock().record(value); } } impl Clear for AtomicHdrHistogram { fn clear(&self) { self.inner.lock().clear(); } } impl Serialize for AtomicHdrHistogram { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { use std::ops::Deref; let inner = self.inner.lock(); let inner = inner.deref(); Serialize::serialize(inner, serializer) } } use std::{fmt, fmt::Debug}; impl Debug for AtomicHdrHistogram { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let histo = self.inner.lock(); write!(f, "AtomicHdrHistogram {{ {:?} }}", &*histo) } } /// An High-Dynamic Range Histogram /// /// HdrHistograms can record and analyze sampled data in low-latency applications. Read more about HDR Histograms on [http://hdrhistogram.org/](http://hdrhistogram.org/) /// /// This structure uses the `hdrhistogram` crate under the hood. #[derive(Clone)] pub struct HdrHistogram { histo: hdrhistogram::Histogram<u64>, } impl HdrHistogram { /// Instantiates a new HdrHistogram with a max_bound /// /// For instance, a max_bound of 60 * 60 * 1000 will allow to record /// durations varying from 1 millisecond to 1 hour. pub fn with_bound(max_bound: u64) -> Self { let histo = hdrhistogram::Histogram::<u64>::new_with_bounds(1, max_bound, 2) .expect("Could not instantiate HdrHistogram"); HdrHistogram { histo } } /// Records a value to the histogram /// /// This is a saturating record: if the value is higher than `max_bound`, /// max_bound will be recorded instead. pub fn record(&mut self, value: u64) { // All recordings will be saturating self.histo.saturating_record(value); } /// Clears the values of the histogram pub fn clear(&mut self) { self.histo.reset(); } /// Get the number of recorded values in the histogram. pub fn len(&self) -> u64 { self.histo.len() } /// Get the lowest recorded value level in the histogram. /// If the histogram has no recorded values, the value returned will be 0. pub fn min(&self) -> u64 { self.histo.min() } /// Get the highest recorded value level in the histogram. /// If the histogram has no recorded values, the value returned is /// undefined. pub fn max(&self) -> u64 { self.histo.max() } /// Get the computed mean value of all recorded values in the histogram. pub fn mean(&self) -> f64 { self.histo.mean() } /// Get the computed standard deviation of all recorded /// values in the histogram pub fn stdev(&self) -> f64 { self.histo.stdev() } /// Get the value at the 90% quantile. pub fn p90(&self) -> u64 { self.histo.value_at_quantile(0.9) } /// Get the value at the 95% quantile. pub fn p95(&self) -> u64 { self.histo.value_at_quantile(0.95) } /// Get the value at the 99% quantile. pub fn p99(&self) -> u64 { self.histo.value_at_quantile(0.99) } /// Get the value at the 99.9% quantile. pub fn p999(&self) -> u64 { self.histo.value_at_quantile(0.999) } /// Get the value at the 99.99% quantile. pub fn p9999(&self) -> u64 { self.histo.value_at_quantile(0.9999) } } impl Serialize for HdrHistogram { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let hdr = &self.histo; /// A percentile of this histogram - for supporting serializers this /// will ignore the key (such as `90%ile`) and instead add a /// dimension to the metrics (such as `quantile=0.9`). macro_rules! ile { ($e:expr) => { &MetricAlias(concat!("!|quantile=", $e), hdr.value_at_quantile($e)) }; } /// A 'qualified' metric name - for supporting serializers this will /// prepend the metric name to this key, outputting /// `response_time_count`, for example rather than just `count`. macro_rules! qual { ($e:expr) => { &MetricAlias("<|", $e) }; } use serde::ser::SerializeMap; let mut tup = serializer.serialize_map(Some(10))?; tup.serialize_entry("samples", qual!(hdr.len()))?; tup.serialize_entry("min", qual!(hdr.min()))?; tup.serialize_entry("max", qual!(hdr.max()))?; tup.serialize_entry("mean", qual!(hdr.mean()))?; tup.serialize_entry("stdev", qual!(hdr.stdev()))?; tup.serialize_entry("90%ile", ile!(0.9))?; tup.serialize_entry("95%ile", ile!(0.95))?; tup.serialize_entry("99%ile", ile!(0.99))?; tup.serialize_entry("99.9%ile", ile!(0.999))?; tup.serialize_entry("99.99%ile", ile!(0.9999))?; tup.end() } } /// This is a mocked 'newtype' (eg. `A(u64)`) that instead allows us to /// define our own type name that doesn't have to abide by Rust's constraints /// on type names. This allows us to do some manipulation of our metrics, /// allowing us to add dimensionality to our metrics via key=value pairs, or /// key manipulation on serializers that support it. struct MetricAlias<T: Serialize>(&'static str, T); impl<T: Serialize> Serialize for MetricAlias<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_newtype_struct(self.0, &self.1) } } impl Debug for HdrHistogram { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let hdr = &self.histo; let ile = |v| hdr.value_at_percentile(v); write!( f, "HdrHistogram {{ samples: {}, min: {}, max: {}, mean: {}, stdev: {}, 90%ile = {}, 95%ile = {}, 99%ile = {}, 99.9%ile = {}, 99.99%ile = {} }}", hdr.len(), hdr.min(), hdr.max(), hdr.mean(), hdr.stdev(), ile(90.0), ile(95.0), ile(99.0), ile(99.9), ile(99.99) ) } } use std::cell::RefCell; impl Histogram for RefCell<HdrHistogram> { fn with_bound(max_value: u64) -> Self { RefCell::new(HdrHistogram::with_bound(max_value)) } fn record(&self, value: u64) { self.borrow_mut().record(value); } } impl Clear for RefCell<HdrHistogram> { fn clear(&self) { self.borrow_mut().clear(); } } <file_sep>/metered/src/common/throughput/mod.rs //! A module providing the `Throughput` metric. use crate::{ clear::Clear, metric::Metric, time_source::{Instant, StdInstant}, }; use aspect::{Advice, Enter, OnResult}; use serde::{Serialize, Serializer}; use std::ops::Deref; mod atomic_tps; mod tx_per_sec; pub use atomic_tps::AtomicTxPerSec; pub use tx_per_sec::TxPerSec; /// A metric providing a transaction per second count backed by a histogram. /// /// Because it retrieves the current time before calling the expression, stores /// it to appropriately build time windows of 1 second and registers results to /// a histogram, this is a rather heavy-weight metric better applied at /// entry-points. /// /// By default, `Throughput` uses an atomic transaction count backend and a /// synchronized time source, which work better in multithread scenarios. /// Non-threaded applications can gain performance by using unsynchronized /// structures instead. #[derive(Clone)] pub struct Throughput<T: Instant = StdInstant, P: RecordThroughput = AtomicTxPerSec<T>>( pub P, std::marker::PhantomData<T>, ); /// Trait to record the throughput on a [`Throughput`] instance. pub trait RecordThroughput: Default { /// Called after the execution that the throughput metric is measuring. fn on_result(&self); } impl<P: RecordThroughput, T: Instant> Default for Throughput<T, P> { fn default() -> Self { Throughput(P::default(), std::marker::PhantomData) } } impl<P: RecordThroughput + Serialize + Clear, T: Instant, R> Metric<R> for Throughput<T, P> {} impl<P: RecordThroughput, T: Instant> Enter for Throughput<T, P> { type E = (); fn enter(&self) {} } impl<P: RecordThroughput + Clear, T: Instant> Clear for Throughput<T, P> { fn clear(&self) { self.0.clear(); } } impl<P: RecordThroughput + Serialize, T: Instant, R> OnResult<R> for Throughput<T, P> { fn leave_scope(&self, _enter: ()) -> Advice { self.0.on_result(); Advice::Return } } impl<P: RecordThroughput + Serialize, T: Instant> Serialize for Throughput<T, P> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { Serialize::serialize(&self.0, serializer) } } use std::{fmt, fmt::Debug}; impl<P: RecordThroughput + Debug, T: Instant> Debug for Throughput<T, P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &self.0) } } impl<P: RecordThroughput, T: Instant> Deref for Throughput<T, P> { type Target = P; fn deref(&self) -> &Self::Target { &self.0 } }
90cc089e6b3fa7b52db39d3c2ed2d51980817341
[ "TOML", "Rust", "Markdown" ]
31
TOML
magnet/metered-rs
cf749f78d28052be6aa5963a0e8b0df727bfbb1e
23b868f93900a4bbfe0eb394bb2ab6d092670a5a
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Thu Jun 6 14:15:41 2019 @author: Pups """ import turtle import math ########################################################################### # Q1 def pythagorian_pair(a,b): """ (int, int) -> bool Returns True if the two numbers (a and b) are a pythagorean pair """ c = math.sqrt(a**2 + b**2) return int(c) == c #for i in range(1,100): # for y in range(1,100): # if pythagorian_pair(i,y): # print("i...", i, " y...", y) ########################################################################## # Q2 def mh2kh(s): """ (number) - > number cjnverts "s" given in miles/hour into the equivalent speed in kilometers/hour """ return 1.609344 * s ########################################################################## # Q3 def in_out(xs, ys, side): """(number number number) - > None Prompts the user to enter a (x,y) coordinates and checks if it is conteined inside of the square defined by the parameters(xs, ys, side) where (xs, ys) is the bottom left corner of the square, side is the length of one side of the square . If it is conteined in the square the function will print True, otherwise it will print False""" x = float(input('Please enter x coordinate: ')) y = float(input('Please enter y coordinate: ')) check = y <= ys + side and x <= xs + side and x >= xs and y >= ys print(check) ########################################################################## # Q4 def safe(n): """ (int) => bool return False if "n" conteins the digit 9 or can be divided by 9 otherwise it returns True """ first = n // 10 last = n - (first*10) return first != 9 and last != n % 9 != 0 ########################################################################## # Q5 def quote_maker(quote, name, year): """ (string, string, int) -> string returns a string in the form : "in %s, a parson called %s said: "%s"" %(year, name, quote) """ return "in %s, a parson called %s said: \"%s\"" %(year, name, quote) ########################################################################## # Q6 def quote_displayer(): """ (None) => None Prompts the user to input a qoute, name and year and prints a string to the screen in the form: "in %s, a parson called %s said: "%s"" %(year, name, quote) """ quote = input('Give me a quote: ') name = input('Who said that? ') year = input('What year did she/he/THEM say that? ') print(quote_maker(quote, name, year)) ########################################################################## # Q7 def rps_winner(): """ (None) => None Prompts the user for a player 1 decision of rock, paper or scissors. Then asks the user for player 2 decision with the same choices. It then determines the winner and display it to the screen. """ print("What choice did player 1 make? ") choice1 = input('Type one of the following options: rock, paper, scissors: ') print("What choice did player 2 make? ") choice2 = input('Type one of the following options: rock, paper, scissors: ') player1Wins = ((choice1 == 'rock' and choice2 == 'scissors') or (choice1 == 'scissors' and choice2 == 'paper') or (choice1 == 'paper' and choice2 == 'scissors') or (choice1 == 'paper' and choice2 == 'rock')) tie = choice1 == choice2 player2Wins = not (player1Wins) and not (tie) print("Player 1 wins? That is", player1Wins) print("Tie? That is", tie) print("Player 2 wins? That is", player2Wins) ########################################################################## # Q8 def fun(x): """ (number) -> number Solves the equation 10^(4y) = x + 3 for y and returns the value of y """ return math.log10(x + 3)/4 ########################################################################## # Q9 def ascii_name_plaque(name): """ string > None Display to the screen a name plaque with the given name padded by 1 space inside a box of stars with underscores before and after the name """ newStr = "* __" + name + "__ *" stars = len (newStr) print("*" * stars) print("* " + (stars-3) * ' ' + "*") print(newStr) print("* " + (stars-3) * ' ' + "*") print("*" * stars) ########################################################################## # Q10 def draw_car(): t = turtle.Turtle() t.speed(50) t.pensize(3) t.penup() #Right Weel t.forward(200) t.pendown() t.begin_fill() t.color('grey') t.circle(5) t.color('black') t.right(90) t.penup() t.forward(25) t.pendown() t.left(90) t.circle(30) t.right(90) t.penup() t.forward(25) t.pendown() t.left(90) t.circle(55) t.penup() t.left(90) t.forward(55) mid = t.pos() t.color('grey') for x in range(5): t.penup() t.goto(mid) t.right(360/5) t.forward(5) t.pendown() t.forward(25) t.color('black') t.penup() t.goto(mid) t.right(90) t.backward(400) t.pendown() t.color('grey') t.circle(5) t.color('black') t.right(90) t.penup() t.forward(25) t.pendown() t.left(50) t.circle(30) t.right(90) t.penup() t.forward(25) t.pendown() t.left(90) t.circle(55) t.penup() t.left(90) t.forward(55) mid = t.pos() def cad_cashier(price, payment): """ Calculates the change in Canadian dollars the user should receive. """ change = float(payment - price) # Здача = Сумма - цена roundedChange = 0.05 * round(float(change)/0.05) return round(roundedChange,2) def split_tester(N, d): """str, str > bool thefunction splits the given string N into a sequence of d length integers It then returns True if the sequence is strictly increasing """ lastNum = -1 checkInc = True seq = '' d = int(d) for i in range(0,len(N), d): newNum = N[i:i+d] seq += newNum if int(newNum) < lastNum: checkInc = False lastNum = int(newNum) if i < len(N) - d: seq += ', ' print(seq) return checkInc def nonrepetitive(s): """str >bool returns True if the given string in nonrepetitive and False otherwise. A nonrepetitive string is one that does not contain any sobsting twice in a row. """ for i in range(len(s)): for x in range(i,len(s)-1): lookFor = s[i:x+1] lookIn = s[x+1:x+1+len(lookFor)] if lookFor == lookIn: return False return True def make_deck(n): """ (int) > list of int Returns a list of inegers representing the strange deck with num ranks.""" deck = [] for x in range(1,5): for j in range(1,n+1): deck.append(100*x+j) return deck ваитвар
66ee797e3ce99e1bd2760f37b90a5c64301ffb6f
[ "Python" ]
1
Python
Oleg-Derkach/001-CS
86c228dcedaf6f2e7075cd97abd374cb0e753f08
dd0eed792d2710c5c75e1ea958bdd0548cbd86e1
refs/heads/master
<repo_name>DvdKhl/BBCodeTransform<file_sep>/README.md # BBCodeTransform Demo page: http://dvdkhl.github.io/BBCodeTransform/ ## What does BBCodeTransform try to achieve? BBCodeTransform is a TypeScript/JavaScript BBCode to Html transformer that *does not depend any required external frameworks*. It aims to be easily extendable, giving various possibilities to add new bbcode tags and substitutions (e.g. smilies). **Usage:** Transforming BBCode into Html is simply done by creating an instance, specifying the BBCode Tags/Substitutions that should be used and then calling `.ToHtml(bbCodeSrc)` on the instance. The output will be a HTMLDivElement. **Tag Parameters:** Besides the traditional `[tagName=tagValue]` tags, BBCodeTransform also supports additional parameters in the form of `[tagName=tagValue paramName1=paramValue1 paramName2=paramValue2 ...]` allowing for more feature rich tags. **Custom Tags:** Custom BBCode Tags and Substitutions contain callbacks which are called after that item has been fully parsed. In case of tags, the callback parameters include the name, its value and possible attributes and as the second parameter the HTMLElements within. Since the HTMLElements are supplied and not a string, it is *easy to add TypeScript/JavaScript for more dynamic functionality (e.g. Image Overlays, Spoilerboxes, etc)*. **Rules:** Before the content of a tag is parsed *each tag is asked to set their parsing rules* which include `maySubstitute, mayParseNewTags, mayReplaceNewLinesWithBr` to more finely control the parsing behavior to allow the implementation of for example *code* tags. After the tag is fully processed the parsing rules are reverted to its previous state automatically. **Performance:** BBCodeTransform should be close to the fastest ones out there (No regex or string concatenation is used for parsing and substitutions are done using a trie) under the condition that you want Html Elements as output. If on the other hand you're only interested in the resulting *html string* and are not planning to add it to the Dom (e.g. setting `innerHTML`) other libraries may outperform it by orders of magnitude. *To put things into perspective:* Transforming and displaying 64kb of bbcode takes around 60ms with BBCodeTransform. While other parsers which output html as a string may take several hundred ms to do the same, but may take a lot less than 10ms if the string isn't added to the Dom. Still in most cases any implementation is fast enough so performance shouldn't be an issue. ## Usage #### Instance creation and setup ```typescript var transform = new BBCode.BBCodeTransform(); transform.SetTagDefinitions([ BBCode.Tags.B, BBCode.Tags.I, BBCode.Tags.S, BBCode.Tags.U, BBCode.Tags.Url, BBCode.Tags.Img, BBCode.Tags.Spoiler, BBCode.Tags.Pre ]); transform.SetSubstitutions([ { match: ":)", replacement: function () { var elem = document.createElement("span"); elem.className = "i_icon i_icon_smiley_happy"; elem.title = "happy"; return elem; } } ]); ``` Here we create an instance of BBCodeTransform and setting some BBCode Tags and one substitution. Using the `transform.SetTagDefinitions` function we can pass an array of `TagDefinitions` which will be used to transform the BBCode. Some predefined tags already come with BBCodeTransform and are used in the code above. The `transform.SetSubstitutions` can be used to pass an array of substitution rules which was mainly introduced to support smilies but can also be used for different purposes (e.g. replacing keywords with something else). After this setup a single call to `transform.ToHtml(bbCode)` will transform the bbcode and output an Html (Div) Element, ready to be added to the Dom. #### Custom BBCodeTags To create new Tags a new instance of BBCodeTagDefinition needs to be created: ```typescript constructor( name: string, //Name of the tag, used by the parser to identify tags isSelfClosing: boolean, //Should the parser expect a closing tag? (Similar to <br>) handle: (tag: BBCodeTag, items: any[]) => any, //Callback for custom tag transformation onTag?: (rules: BBCodeRules) => void //Used to set parsing rules ) class BBCodeTag { public Name: string; public Value: string; public Attributes: { [attributeName: string]: string } = {}; } //handle > items: Parsed Html Elements of the tag content class BBCodeRules { public maySubstitute; public mayParseNewTags; public mayReplaceNewLinesWithBr; } ``` Afterwards simply include the new instance in the array for `SetTagDefinitions`. **Examples:** ```typescript //Pre tag example: new BBCode.BBCodeTagDefinition( "pre", false, (tag, items) => { //console.log(items); var elem = document.createElement("pre"); for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; }, (rules) => { rules.maySubstitute = false; rules.mayParseNewTags = false; rules.mayReplaceNewLinesWithBr = false; } ) //Image tag example new BBCode.BBCodeTagDefinition("img", true, (tag, items) => { var imgElem = document.createElement("img"); imgElem.src = tag.Value; var title = tag.Attributes["title"]; if(title) imgElem.title = title; var width = tag.Attributes["width"]; if(width) imgElem.width = parseInt(width); var height = tag.Attributes["height"]; if(height) imgElem.width = parseInt(height); var containerElem = document.createElement("div"); containerElem.appendChild(imgElem); var overlayElem: HTMLDivElement; imgElem.onclick = () => { if(overlayElem) { containerElem.removeChild(overlayElem); overlayElem = null; } else { var overlayImageElem = document.createElement("img"); overlayImageElem.src = tag.Value; overlayElem = document.createElement("div"); overlayElem.appendChild(overlayImageElem); overlayElem.classList.add("image-overlay"); containerElem.appendChild(overlayElem); overlayElem.onclick = imgElem.onclick; } }; return containerElem; }) ``` #### Adding Substitutions (Smilies) To add substitutions you simple need to create an array of the fowllowing format: `{match: "matchString", replacement: function() { /*Code returning an HTML Element*/ }}` If an exact match with the value of "match" is found the callback is called which must return an HTML Element. The HTML Element is then used to replace the matched text. #### AngularJs If AngularJs is available, BBCodeTransform will register a module with a directive called `bbcodeDocument`, which allows for simple binding between the BBCode and the view. #### TODO: - [ ] Maybe: Substitutions with parameters (e.g. Item{Id=100}) - [ ] More parsing rules <file_sep>/Transform/BBCodeTransform.ts ///<reference path="ThirdParty/DefinitelyTyped/angularjs/angular.d.ts" /> module BBCode { class Trie<T> { public root: TrieNode<T> = new TrieNode<T>(); public add(key: string, value: T) { var current = this.root; for(var i = 0; i < key.length; i++) { var char = key[i]; if(!(char in current.nodes)) { var node = new TrieNode<T>(); current.nodes[char] = node; } current = current.nodes[char]; } current.value = value; } } class TrieNode<T> { public value: T = null; public nodes: { [char: string]: TrieNode<T> } = {}; } export class BBCodeTransform { private substitutions: Trie<() => any>; private preprocessor: (source: string) => string; private tagDefinitions: { [name: string]: BBCodeTagDefinition } private noValueParameterPrefix: string = "#"; private source: string; private position: number; private tagStack: BBCodeTagDefinition[]; private rules = new BBCodeRules(); public SetPreprocessor(preprocessor: (source: string) => string) { this.preprocessor = preprocessor; } public SetTagDefinitions(tagDefinitions: BBCodeTagDefinition[]) { this.tagDefinitions = {}; for(var i = 0; i < tagDefinitions.length; i++) { this.tagDefinitions[tagDefinitions[i].Name] = tagDefinitions[i]; } } public SetSubstitutions(substitutions: { match: string; replacement: () => any }[]) { this.substitutions = new Trie<() => any>(); for(var i = 0; i < substitutions.length; i++) { this.substitutions.add(substitutions[i].match, substitutions[i].replacement); } } public ToHtml(source: string) { this.substitutions = this.substitutions || new Trie<() => any>(); this.tagDefinitions = this.tagDefinitions || {}; this.tagStack = []; this.position = 0; this.source = source; if(this.preprocessor) this.source = this.preprocessor(this.source); var items = this.parse(); this.parseText(this.position, this.source.length, items); var elem = document.createElement("div"); for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; } private parse(): any[] { var items = []; var textStartPosition = this.position; var backtrackPosition = this.position; while(this.position < this.source.length) { if(this.source[this.position] == "[") { var textEndPosition = this.position; backtrackPosition = this.position + 1; if(this.source[this.position + 1] == "/") { this.position += 2; backtrackPosition = this.position; //Potential Closing Tag var name = this.parseName(); if(this.source[this.position] != "]") { //No closing tag: Backtrack //console.log("No closing tag backtracking to " + backtrackPosition); this.position = backtrackPosition; } else if(this.tagStack.length != 0 && name == this.tagStack[0].Name) { //Is matching closing tag //console.log("Closing tag: " + name); this.parseText(textStartPosition, textEndPosition, items); backtrackPosition = textStartPosition = ++this.position; this.tagStack.shift(); break; } else { //Is wrong closing tag: Backtrack //console.log("Wrong closing tag(" + name + ") Backtracking to " + backtrackPosition); this.position = backtrackPosition; } } else if(this.rules.mayParseNewTags) { //Potential Opening tag var tag = this.parseTag(); var tagDefinition = tag != null ? this.tagDefinitions[tag.Name] || null : null; if(tagDefinition != null) { //Is opening Tag //console.log("Opening tag: " + tag.Name); this.parseText(textStartPosition, textEndPosition, items); backtrackPosition = textStartPosition = this.position; var oldRules: BBCodeRules = this.rules.Clone(); tagDefinition.OnTag(this.rules); var tagItems: any[]; if(!tagDefinition.IsSelfClosing) { this.tagStack.unshift(tagDefinition); tagItems = this.parse(); } this.rules = oldRules; var tagElem = tagDefinition.Handle(tag, tagItems || []); if(tagElem != null) { items.push(tagElem); backtrackPosition = textStartPosition = this.position; } } else { //No opening Tag: Backtrack //console.log("No opening tag backtracking to " + backtrackPosition); this.position = backtrackPosition; } } else this.position++; } else if(this.rules.mayReplaceNewLinesWithBr && this.source[this.position] == "\n") { this.parseText(textStartPosition, this.position, items); items.push(document.createElement("br")); backtrackPosition = textStartPosition = textEndPosition = ++this.position; } else this.position++; } this.position = textStartPosition; //Reset position when parsing text and reaching end of string instead of end of tag return items; } private parseTag(): BBCodeTag { var tag = new BBCodeTag(); if(this.source[this.position] != "[") throw new Error("Internal BBCodeTransform.parseTag error: Tag didn't start with ["); this.position++, tag.Name = this.parseName(); if(tag.Name == null) return null; if(this.source[this.position] == "=") { this.position++; tag.Value = this.parseValue(); if(tag.Value == null) return null; } while(this.source[this.position] == " ") { this.position++; if(this.source[this.position] == this.noValueParameterPrefix) { this.position++; var name = this.parseName(); tag.Attributes[name] = null; } else { var name = this.parseName(); if(this.source[this.position++] != "=") return null; var value = this.parseValue(); tag.Attributes[name] = value; } } if(this.source[this.position] != "]") return null; this.position++; return tag; } private parseName(): string { var oldPosition = this.position; var charCode = this.source.charCodeAt(this.position); while((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) { charCode = this.source.charCodeAt(++this.position); } return this.source.substring(oldPosition, this.position); } private parseValue(): string { var oldPosition = this.position; var charCode = this.source.charCodeAt(this.position); while(++this.position < this.source.length && charCode != 32 && charCode != 93) { charCode = this.source.charCodeAt(this.position); } return this.source.substring(oldPosition, --this.position); } private parseText(start: number, length: number, items: any[]): void { if(!this.rules.maySubstitute) { items.push(document.createTextNode(this.source.substring(start, length))); return; } var position = start; var end = start; var node = this.substitutions.root; var prevNode = this.substitutions.root; while(position < length + 1) { //+ 1: Make sure we get subs at the end of the string (saves us the checking after the loop) node = node.nodes[this.source[position]] || null; if(!node) { if(prevNode && prevNode.value) { items.push(document.createTextNode(this.source.substring(start, end))); start = position; var elem = prevNode.value(); items.push(elem); } end = position; node = this.substitutions.root.nodes[this.source[position]] if(!node) { end++; node = this.substitutions.root; } } prevNode = node; position++; } if(start != length) items.push(document.createTextNode(this.source.substring(start, length))); } } export class BBCodeTag { public Name: string; public Value: string; public Attributes: { [attributeName: string]: string } = {}; } export class BBCodeRules { public maySubstitute = true; public mayParseNewTags = true; public mayReplaceNewLinesWithBr = true; public Clone() { var rules = new BBCodeRules(); rules.maySubstitute = this.maySubstitute; rules.mayParseNewTags = this.mayParseNewTags; rules.mayReplaceNewLinesWithBr = this.mayReplaceNewLinesWithBr; return rules; } } export class BBCodeTagDefinition { private name: string; private isSelfClosing: boolean; public static Decline = {}; //TODO get Name(): string { return this.name; } get IsSelfClosing(): boolean { return this.isSelfClosing; } private onTag: (rules: BBCodeRules) => void; public OnTag(rules: BBCodeRules) { if(this.onTag) this.onTag(rules); } private handle: (tag: BBCodeTag, items: any[]) => any; public Handle(tag: BBCodeTag, items: any[]) { return this.handle(tag, items); } constructor(name: string, isSelfClosing: boolean, handle: (tag: BBCodeTag, items: any[]) => any, onTag?: (rules: BBCodeRules) => void) { this.name = name; this.isSelfClosing = isSelfClosing; this.handle = handle; this.onTag = onTag || null; } } export class Tags { static Pre = new BBCode.BBCodeTagDefinition( "pre", false, (tag, items) => { //console.log(items); var elem = document.createElement("pre"); for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; }, (rules) => { rules.maySubstitute = false; rules.mayParseNewTags = false; rules.mayReplaceNewLinesWithBr = false; } ); static B = new BBCode.BBCodeTagDefinition("b", false, (tag, items) => { //console.log(items); var elem = document.createElement("b"); for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; }); static I = new BBCode.BBCodeTagDefinition("i", false, (tag, items) => { //console.log(items); var elem = document.createElement("i"); for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; }); static U = new BBCode.BBCodeTagDefinition("u", false, (tag, items) => { //console.log(items); var elem = document.createElement("span"); elem.style.textDecoration = "underline"; for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; }); static S = new BBCode.BBCodeTagDefinition("s", false, (tag, items) => { //console.log(items); var elem = document.createElement("span"); elem.style.textDecoration = "line-through"; for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; }); static Url = new BBCode.BBCodeTagDefinition("url", false, (tag, items) => { //console.log(items); var elem = document.createElement("a"); elem.href = tag.Value; var title = tag.Attributes["title"]; if(title) elem.title = title; for(var i = 0; i < items.length; i++) elem.appendChild(items[i]); return elem; }); static Spoiler = new BBCode.BBCodeTagDefinition("spoiler", false, (tag, items) => { //console.log(items); var spanElem = document.createElement("span"); spanElem.classList.add("spoiler"); spanElem.classList.add("hide"); for(var i = 0; i < items.length; i++) spanElem.appendChild(items[i]); var inputElem = document.createElement("input"); inputElem.classList.add("button"); inputElem.type = "button"; inputElem.value = "Show Spoiler"; inputElem.onclick = () => { inputElem.value = spanElem.classList.toggle("hide") ? "Show Spoiler" : "Hide Spoiler"; }; var containerElem = document.createElement("div"); containerElem.classList.add("spoiler"); containerElem.appendChild(spanElem); containerElem.appendChild(inputElem); return containerElem; }); static Img = new BBCode.BBCodeTagDefinition("img", true, (tag, items) => { //console.log(items); var imgElem = document.createElement("img"); imgElem.src = tag.Value; var title = tag.Attributes["title"]; if(title) imgElem.title = title; var width = tag.Attributes["width"]; if(width) imgElem.width = parseInt(width); var height = tag.Attributes["height"]; if(height) imgElem.width = parseInt(height); var containerElem = document.createElement("div"); containerElem.appendChild(imgElem); var overlayElem: HTMLDivElement; imgElem.onclick = () => { if(overlayElem) { containerElem.removeChild(overlayElem); overlayElem = null; } else { var overlayImageElem = document.createElement("img"); overlayImageElem.src = tag.Value; overlayElem = document.createElement("div"); overlayElem.appendChild(overlayImageElem); overlayElem.classList.add("image-overlay"); containerElem.appendChild(overlayElem); overlayElem.onclick = imgElem.onclick; } }; return containerElem; }); } export function Register(angular: ng.IAngularStatic) { var bbCodeModule = angular.module("bbCode", []); bbCodeModule.directive('bbcodeDocument', function() { return { restrict: 'E', replace: true, scope: { source: "=", transform: "=", debug: "=" }, link: ($scope, element: JQuery, attr) => { var unregister = $scope.$watch('source', function(newValue) { element.empty(); if(!$scope.transform) return; $scope.source = $scope.source || ""; var start = window.performance.now(); var bbcodeElem = $scope.transform.ToHtml($scope.source); var elapsed = window.performance.now() - start; if($scope.debug == true) element.append("Elapsed: " + elapsed + "ms<br>"); element.append(bbcodeElem); }); } }; }); } } if(window["angular"]) BBCode.Register(angular);
c5de3b2da3864b5e1911f03ec27c420fbe444e84
[ "Markdown", "TypeScript" ]
2
Markdown
DvdKhl/BBCodeTransform
812417cdd31708661a401212d8a7aaa317d9d267
a504e7de30146c761bbdf1b98c38876cc14a99d7
refs/heads/master
<repo_name>allinbits/cosm<file_sep>/Makefile all: install mod: @go mod tidy build: mod @go get -u github.com/gobuffalo/packr/v2/packr2 @packr2 @go build -mod=readonly -o build/cosm main.go @packr2 clean @go mod tidy ui: @rm -rf ui/dist @which npm 1>/dev/null && cd ui && npm install 1>/dev/null && npm run build 1>/dev/null install: build ui @go install -mod=readonly ./... cli: build @go install -mod=readonly ./... .PHONY: all mod build ui install<file_sep>/cmd/serve.go package cmd import ( "fmt" "log" "net/http" "os" "os/exec" "time" "github.com/gobuffalo/packr/v2" "github.com/gorilla/mux" "github.com/radovskyb/watcher" "github.com/spf13/cobra" ) func startServe(verbose bool) (*exec.Cmd, *exec.Cmd) { appName, _ := getAppAndModule() fmt.Printf("\n📦 Installing dependencies...\n") cmdMod := exec.Command("/bin/sh", "-c", "go mod tidy") if verbose { cmdMod.Stdout = os.Stdout } if err := cmdMod.Run(); err != nil { log.Fatal("Error running go mod tidy. Please, check ./go.mod") } fmt.Printf("🚧 Building the application...\n") cmdMake := exec.Command("/bin/sh", "-c", "make") if verbose { cmdMake.Stdout = os.Stdout } if err := cmdMake.Run(); err != nil { log.Fatal("Error in building the application. Please, check ./Makefile") } fmt.Printf("💫 Initializing the chain...\n") cmdInit := exec.Command("/bin/sh", "-c", "sh init.sh") if verbose { cmdInit.Stdout = os.Stdout } if err := cmdInit.Run(); err != nil { log.Fatal("Error in initializing the chain. Please, check ./init.sh") } fmt.Printf("🎨 Created a web front-end: cd ui && npm i && npm run serve\n") fmt.Printf("🌍 Running a server at http://localhost:26657 (Tendermint)\n") cmdTendermint := exec.Command(fmt.Sprintf("%[1]vd", appName), "start") if verbose { cmdTendermint.Stdout = os.Stdout } if err := cmdTendermint.Start(); err != nil { log.Fatal(fmt.Sprintf("Error in running %[1]vd start", appName), err) } fmt.Printf("🌍 Running a server at http://localhost:1317 (LCD)\n") cmdREST := exec.Command(fmt.Sprintf("%[1]vcli", appName), "rest-server") if verbose { cmdREST.Stdout = os.Stdout } if err := cmdREST.Start(); err != nil { log.Fatal(fmt.Sprintf("Error in running %[1]vcli rest-server", appName)) } fmt.Printf("🔧 Running dev interface at http://localhost:12345\n\n") router := mux.NewRouter() devUI := packr.New("ui/dist", "../ui/dist") router.PathPrefix("/").Handler(http.FileServer(devUI)) go func() { http.ListenAndServe(":12345", router) }() return cmdTendermint, cmdREST } var serveCmd = &cobra.Command{ Use: "serve", Short: "Launches a reloading server", Args: cobra.ExactArgs(0), Run: func(cmd *cobra.Command, args []string) { verbose, _ := cmd.Flags().GetBool("verbose") cmdt, cmdr := startServe(verbose) w := watcher.New() w.SetMaxEvents(1) go func() { for { select { case _ = <-w.Event: cmdr.Process.Kill() cmdt.Process.Kill() cmdt, cmdr = startServe(verbose) case err := <-w.Error: log.Fatalln(err) case <-w.Closed: return } } }() if err := w.AddRecursive("."); err != nil { log.Fatalln(err) } if err := w.Ignore("./ui"); err != nil { log.Fatalln(err) } if err := w.Start(time.Millisecond * 100); err != nil { log.Fatalln(err) } }, } <file_sep>/go.mod module github.com/allinbits/cosm go 1.14 require ( github.com/gobuffalo/envy v1.9.0 // indirect github.com/gobuffalo/genny v0.6.0 github.com/gobuffalo/packr/v2 v2.8.0 github.com/gobuffalo/plush v3.8.3+incompatible github.com/gobuffalo/plushgen v0.1.2 github.com/gorilla/mux v1.7.4 github.com/karrick/godirwalk v1.15.6 // indirect github.com/radovskyb/watcher v1.0.7 github.com/rogpeppe/go-internal v1.6.0 // indirect github.com/sirupsen/logrus v1.6.0 // indirect github.com/spf13/cobra v1.0.0 github.com/spf13/pflag v1.0.5 // indirect golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a // indirect golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4 // indirect ) <file_sep>/templates/app/templates/init.sh.plush #!/bin/bash rm -r ~/.<%= AppName %>cli rm -r ~/.<%= AppName %>d <%= AppName %>d init mynode --chain-id <%= AppName %> <%= AppName %>cli config keyring-backend test <%= AppName %>cli keys add me <%= AppName %>cli keys add you <%= AppName %>d add-genesis-account $(<%= AppName %>cli keys show me -a) 1000<%= Denom %>,100000000stake <%= AppName %>d add-genesis-account $(<%= AppName %>cli keys show you -a) 1<%= Denom %> <%= AppName %>cli config chain-id <%= AppName %> <%= AppName %>cli config output json <%= AppName %>cli config indent true <%= AppName %>cli config trust-node true <%= AppName %>d gentx --name me --keyring-backend test <%= AppName %>d collect-gentxs<file_sep>/main.go package main import "github.com/allinbits/cosm/cmd" func main() { cmd.Execute() } <file_sep>/cmd/root.go package cmd import ( "fmt" "io/ioutil" "log" "os" "strings" "github.com/spf13/cobra" ) // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "cosmos", Short: "A tool for scaffolding out Cosmos applications", } // Execute ... func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func init() { rootCmd.AddCommand(appCmd) rootCmd.AddCommand(typedCmd) rootCmd.AddCommand(serveCmd) serveCmd.Flags().BoolP("verbose", "v", false, "Verbose output") appCmd.Flags().StringP("denom", "d", "token", "Token denomination") rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } func getAppAndModule() (string, string) { goModFile, err := ioutil.ReadFile("go.mod") if err != nil { log.Fatal(err) } moduleString := strings.Split(string(goModFile), "\n")[0] modulePath := strings.ReplaceAll(moduleString, "module ", "") var appName string if t := strings.Split(modulePath, "/"); len(t) > 0 { appName = t[len(t)-1] } return appName, modulePath } <file_sep>/cmd/app.go package cmd import ( "context" "fmt" "os" "strings" "github.com/allinbits/cosm/templates/app" "github.com/gobuffalo/genny" "github.com/spf13/cobra" ) var appCmd = &cobra.Command{ Use: "app [github.com/org/repo]", Short: "Generates an empty application", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { denom, _ := cmd.Flags().GetString("denom") var appName string if t := strings.Split(args[0], "/"); len(t) > 0 { appName = t[len(t)-1] } g, _ := app.New(&app.Options{ ModulePath: args[0], AppName: appName, Denom: denom, }) run := genny.WetRunner(context.Background()) run.With(g) pwd, _ := os.Getwd() run.Root = pwd + "/" + appName run.Run() fmt.Printf("\n⭐️ Successfully created a Cosmos app `%[1]v`.\n\n", appName) }, }
a0384f7859d7801eb10533eb4382578cd99615be
[ "Go", "Go Module", "Makefile", "Shell" ]
7
Makefile
allinbits/cosm
bf0f4c735bf4a7b09544e9052d01ce8cdf0429a4
6af1c9a6d8c342c13ed4ea22f1a7a89acf0168cd
refs/heads/master
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>no.rmz</groupId> <artifactId>blobee</artifactId> <packaging>jar</packaging> <version>1.4-SNAPSHOT</version> <name>Blobee</name> <url>https://github.com/la3lma/blobee</url> <description> An transport mechanism for the RPC interfaces that are defined in the open source version of Google's protobuffer library. </description> <scm> <connection>scm:git:git@github.com:la3lma/blobee.git</connection> <url>https://github.com/la3lma/blobee</url> </scm> <developers> <developer> <id>rmz</id> <name><NAME></name> <email><EMAIL></email> <url>http://rmzlablog.blobspot.no/</url> <roles> <role>architect</role> <role>developer</role> </roles> <timezone>+1</timezone> </developer> </developers> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> </license> </licenses> <parent> <groupId>org.sonatype.oss</groupId> <artifactId>oss-parent</artifactId> <version>7</version> </parent> <distributionManagement> <repository> <id>sonatype-nexus-staging</id> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url> </repository> <snapshotRepository> <id>sonatype-nexus-snapshots</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> </distributionManagement> <properties> <guice.version>3.0</guice.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <jetty.version>8.0.0.M2</jetty.version> <compileSource>1.7</compileSource> <compileTarget>1.7</compileTarget> <mockito.version>1.9.5-rc1</mockito.version> <findbugs.version>1.3.2</findbugs.version> <junit.version>4.11</junit.version> <guava.version>13.0.1</guava.version> <netty.version>3.6.2.Final</netty.version> <protobuf.version>2.3.0</protobuf.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>${mockito.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty</artifactId> <version>${netty.version}</version> </dependency> <dependency> <groupId>no.rmz</groupId> <artifactId>blobeeprototest</artifactId> <version>1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> <dependency> <groupId>net.sourceforge.findbugs</groupId> <artifactId>annotations</artifactId> <version>${findbugs.version}</version> </dependency> </dependencies> <!-- Profiles used to determine which protoc compiler binary we need to use --> <profiles> <profile> <id>profile-protoc-mac-x86_64</id> <activation> <os> <family>mac</family> <name>mac os x</name> <arch>x86_64</arch> </os> </activation> <properties> <protoc.executable>bin/protoc-mac_os_x-x86_64</protoc.executable> </properties> </profile> <profile> <id>profile-protoc-linux-x86</id> <activation> <os> <family>unix</family> <name>linux</name> </os> </activation> <properties> <protoc.executable>bin/protoc-linux-i386</protoc.executable> </properties> </profile> <profile> <id>profile-protoc-win32</id> <activation> <os> <family>Windows</family> </os> </activation> <properties> <protoc.executable>bin/protoc-${protobuf.version}-win32.exe</protoc.executable> </properties> </profile> </profiles> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.4</version> <configuration> <mavenExecutorId>forked-path</mavenExecutorId> </configuration> <executions> <execution> <id>default</id> <goals> <goal>perform</goal> </goals> <configuration> <pomFileName>blobee/pom.xml</pomFileName> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>generate-sources</id> <phase>generate-sources</phase> <configuration> <tasks> <mkdir dir="${project.build.directory}/generated-sources" /> <exec executable="${basedir}/${protoc.executable}"> <arg value="--java_out=${project.build.directory}/generated-sources" /> <arg value="--proto_path=${basedir}/src/main/protobuf" /> <arg value="${basedir}/src/main/protobuf/rpc.proto" /> </exec> </tasks> <sourceRoot>${project.build.directory}/generated-sources</sourceRoot> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-sources</source> </sources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.4</version> <configuration> <source>${compileSource}</source> <target>${compileTarget}</target> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <archive> <index>true</index> <manifest> <classpathPrefix>lib/</classpathPrefix> <addClasspath>true</addClasspath> <mainClass>no.rmz.App</mainClass> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.2</version> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <overWriteReleases>true</overWriteReleases> <overWriteSnapshots>true</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.5.1</version> <configuration> <instrumentation> <ignores> <ignore>com.example.boringcode.*</ignore> </ignores> <excludes> <exclude>no/rmz/rmatch/**/*Test.class</exclude> </excludes> </instrumentation> </configuration> <executions> <execution> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.9.1</version> <configuration> <configLocation>config/sun_checks.xml</configLocation> </configuration> </plugin> </plugins> </reporting> </project> <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>no.rmz</groupId> <artifactId>blobeeprototest</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>blobeeprototest</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <compileSource>1.7</compileSource> <compileTarget>1.7</compileTarget> </properties> <developers> <developer> <id>rmz</id> <name><NAME></name> <email><EMAIL></email> </developer> </developers> <!-- Profiles used to determine which protoc compiler binary we need to use --> <profiles> <profile> <id>profile-protoc-mac-x86_64</id> <activation> <os> <family>mac</family> <name>mac os x</name> <arch>x86_64</arch> </os> </activation> <properties> <protoc.executable>bin/protoc-mac_os_x-x86_64</protoc.executable> </properties> </profile> <profile> <id>profile-protoc-linux-x86</id> <activation> <os> <family>unix</family> <name>linux</name> </os> </activation> <properties> <protoc.executable>bin/protoc-linux-i386</protoc.executable> </properties> </profile> <profile> <id>profile-protoc-win32</id> <activation> <os> <family>Windows</family> </os> </activation> <properties> <protoc.executable>bin/protoc-2.3.0-win32.exe</protoc.executable> </properties> </profile> </profiles> <build> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>generate-sources</id> <phase>generate-sources</phase> <configuration> <tasks> <mkdir dir="${project.build.directory}/generated-sources" /> <exec executable="${basedir}/${protoc.executable}"> <arg value="--java_out=${project.build.directory}/generated-sources" /> <arg value="--proto_path=${basedir}/src/main/protobuf" /> <arg value="${basedir}/src/main/protobuf/testservice.proto" /> </exec> </tasks> <sourceRoot>${project.build.directory}/generated-sources</sourceRoot> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-sources</source> </sources> </configuration> </execution> </executions> </plugin> <!-- We want unit test output on the console --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.9</version> <configuration> <useFile>false</useFile> <argLine>-Dsmtp.server=disabled</argLine> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${compileSource}</source> <target>${compileTarget}</target> </configuration> </plugin> <!-- attach sources and javadoc to built artifact --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.1.2</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> <pluginManagement> <plugins> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. --> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <versionRange>[1.3,)</versionRange> <goals> <goal>run</goal> </goals> </pluginExecutionFilter> <action> <ignore /> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </pluginManagement> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>2.3.0</version> </dependency> </dependencies> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>2.4</version> <configuration> <!-- We want to turn off location finding, as it takes a long time --> <dependencyLocationsEnabled>false</dependencyLocationsEnabled> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.9</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> <version>2.3.2</version> <configuration> <findbugsXmlOutput>true</findbugsXmlOutput> <findbugsXmlOutputDirectory>target/site</findbugsXmlOutputDirectory> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.7</version> <configuration> <configLocation>checkstyle.xml</configLocation> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>2.5</version> <configuration> <linkXRef>true</linkXRef> <targetJdk>1.6</targetJdk> <excludes> <exclude>**/*Bean.java</exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.5.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.3</version> </plugin> </plugins> </reporting> </project> <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc.client; import no.rmz.blobee.rpc.methods.MethodSignatureResolver; import no.rmz.blobee.rpc.methods.ResolverImpl; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.protobuf.Message; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcChannel; import com.google.protobuf.RpcController; import com.google.protobuf.Service; import edu.umd.cs.findbugs.annotations.SuppressWarnings; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import no.rmz.blobee.controllers.RpcClientController; import no.rmz.blobee.controllers.RpcClientControllerImpl; import no.rmz.blobee.protobuf.MethodTypeException; import no.rmz.blobee.protobuf.TypeExctractor; import no.rmz.blobee.rpc.peer.RemoteExecutionContext; import no.rmz.blobee.rpc.peer.wireprotocol.OutgoingRpcAdapter; import no.rmz.blobee.rpc.peer.wireprotocol.WireFactory; import org.jboss.netty.channel.Channel; public final class RpcClientImpl implements RpcClient { private static final Logger log = Logger.getLogger(RpcClientImpl.class.getName()); private static final int MILLIS_TO_SLEEP_BETWEEN_ATTEMPTS = 20; private static final int NUM_OF_TIMES_BEFORE_FAILING = 200; private static final int MAX_CAPACITY_FOR_INPUT_BUFFER = 10000; private static final int TIME_TO_WAIT_WHEN_QUEUE_IS_EMPTY_IN_MILLIS = 50; public static final int MAXIMUM_TCP_PORT_NUMBER = 65535; private final int capacity; private final BlockingQueue<RpcClientSideInvocation> incoming; private volatile boolean running = false; // XXX Should this also be a concurrent hash? Yes. Also, a lot // (perhaps all) of the synchronization over invocations // should be removed. private final Map<Long, RpcClientSideInvocation> invocations = new TreeMap<>(); private OutgoingRpcAdapter wire; private long nextIndex; private Channel channel; private final Object mutationMonitor = new Object(); private final Object runLock = new Object(); private final MethodSignatureResolver resolver; @Override public void returnCall( final RemoteExecutionContext dc, final Message message) { checkNotNull(dc); checkNotNull(message); synchronized (invocations) { final long rpcIndex = dc.getRpcIndex(); final RpcClientSideInvocation invocation = invocations.get(rpcIndex); if (invocation == null) { log.log(Level.FINEST, "Attempt to return nonexistant invocation: " + rpcIndex + " with message message " + message); return; } // Deliver the result then disable the controller // so it can be reused. final RpcCallback<Message> done = invocation.getDone(); // XXX If we add a flag to the return value saying // "noReturnValue", then "done.run(message)" will // only be invoked if there is actually a return // value. This can be used to close down a sequence // of multiple return values. done.run(message); if (!dc.isMultiReturn()) { deactivateInvocation(dc.getRpcIndex()); } } } @Override public void terminateMultiSequence(long rpcIndex) { checkArgument(rpcIndex >= 0); synchronized (invocations) { final RpcClientSideInvocation invocation = invocations.get(rpcIndex); if (invocation == null) { log.log(Level.FINEST, "Attempt to terminate nonexistant multiinvocation sequence: " + rpcIndex); return; } deactivateInvocation(rpcIndex); } } private void deactivateInvocation(final Long index) { synchronized (invocations) { final RpcClientSideInvocation invocation = invocations.get(index); if (invocation == null) { throw new IllegalStateException( "Couldn't find call stub for invocation " + index); } invocations.remove(index); if (invocations.containsKey(index)) { log.info("Removal of index did not succeed for index " + index); } invocation.getController().setActive(false); } } private final Runnable incomingDispatcher = new Runnable() { @Override public void run() { while (running) { sendFirstAvailableOutgoingInvocation(); } try { runningLock.lock(); noLongerRunning.signal(); } finally { runningLock.unlock(); } } }; private void sendFirstAvailableOutgoingInvocation() { try { final RpcClientSideInvocation invocation = incoming.poll(TIME_TO_WAIT_WHEN_QUEUE_IS_EMPTY_IN_MILLIS, TimeUnit.MILLISECONDS); // If nothing there, then just return to the busy-waiting loop. if (invocation == null) { return; } // If the invocation is cancelled already, don't even bother // sending it over the wire, just forget about it. if (invocation.getController().isCanceled()) { return; } if (listener != null) { listener.listenToInvocation(invocation); } final Long currentIndex = nextIndex++; final RpcClientController rcci = (RpcClientController) invocation.getController(); // Avoid leaking memory for no-return invocations. if (!rcci.isNoReturn()) { synchronized (invocations) { invocations.put(currentIndex, invocation); } } rcci.setClientAndIndex(this, currentIndex); sendInvocation(invocation, currentIndex); } catch (InterruptedException ex) { log.warning("Something went south"); } } public RpcClientImpl( final int capacity) { this(capacity, new ResolverImpl()); } private final Lock runningLock; private final Condition noLongerRunning; public RpcClientImpl( final int capacity, final MethodSignatureResolver resolver) { checkArgument(0 < capacity && capacity < MAX_CAPACITY_FOR_INPUT_BUFFER); this.capacity = capacity; this.incoming = new ArrayBlockingQueue<>(capacity); this.resolver = checkNotNull(resolver); this.runningLock = new ReentrantLock(); this.noLongerRunning = runningLock.newCondition(); } public void setChannel(final Channel channel) { synchronized (mutationMonitor) { if (this.channel != null) { throw new IllegalStateException( "Can't set channel since channel is already set"); } this.channel = checkNotNull(channel); this.wire = WireFactory.getWireForChannel(channel); } } public void start( final Channel channel, final ChannelShutdownCleaner channelCleanupRunnable) { checkNotNull(channel); checkNotNull(channelCleanupRunnable); synchronized (runLock) { setChannel(channel); // This runnable will start, then just wait until // the channel stops, then the bootstrap will be instructed // to reease external resources, and with that the client // is completely halted. final Runnable channelCleanup = new Runnable() { @Override public void run() { // Wait until the connection is // closed or the connection attempt fails. channel.getCloseFuture().awaitUninterruptibly(); // Then do whatever cleanup is necessary channelCleanupRunnable.shutdownHook(); } }; running = true; final Thread thread = new Thread(channelCleanup, "client shutdown cleaner"); thread.start(); final Thread dispatcherThread = new Thread(incomingDispatcher, "Incoming dispatcher for client"); dispatcherThread.start(); } } @Override public RpcChannel newClientRpcChannel() { return new RpcChannel() { @Override public void callMethod( final MethodDescriptor method, final RpcController controller, final Message request, final Message responsePrototype, final RpcCallback<Message> done) { checkNotNull(method); checkNotNull(controller); checkNotNull(request); checkNotNull(responsePrototype); checkNotNull(done); // Binding the controller to this invocation. if (controller instanceof RpcClientController) { final RpcClientController ctrl = (RpcClientController) controller; if (ctrl.isActive()) { throw new IllegalStateException( "Attempt to activate already active controller"); } else { ctrl.setActive(running); } } final RpcClientSideInvocation invocation = new RpcClientSideInvocation( method, controller, request, responsePrototype, done); // XXX // Busy-wait to add to in-queue for (int i = 0; i < NUM_OF_TIMES_BEFORE_FAILING; i++) { if (incoming.offer(invocation)) { return; } try { Thread.sleep(MILLIS_TO_SLEEP_BETWEEN_ATTEMPTS); } catch (InterruptedException ex) { log.info("Ignoring interruption " + ex); } } throw new RuntimeException("Couldn't add to queue"); } }; } @Override public BlobeeRpcController newController() { return new RpcClientControllerImpl(); } @Override public void failInvocation(final long rpcIndex, final String errorMessage) { checkNotNull(errorMessage); checkArgument(rpcIndex >= 0); final RpcClientSideInvocation invocation; synchronized (invocations) { invocation = invocations.get(rpcIndex); } if (invocation == null) { log.log(Level.FINEST, "Attempt to fail nonexistant invocation: " + rpcIndex + " with error message " + errorMessage); return; } checkNotNull(invocation); invocation.getController().setFailed(errorMessage); deactivateInvocation(rpcIndex); } @Override public void cancelInvocation(final long rpcIndex) { checkArgument(rpcIndex >= 0); synchronized (invocations) { final RpcClientSideInvocation invocation = invocations.get(rpcIndex); if (invocation == null) { log.log(Level.FINEST, "Attempt to cancel nonexistant invocation: " + rpcIndex); return; } } wire.sendCancelMessage(rpcIndex); deactivateInvocation(rpcIndex); } @Override public RpcClient start() { return this; } private RpcClientSideInvocationListener listener; @Override public RpcClient addInvocationListener( final RpcClientSideInvocationListener listener) { checkNotNull(listener); this.listener = listener; return this; } @Override public MethodSignatureResolver getResolver() { return resolver; } @Override public RpcClient addProtobuferRpcInterface(final Object instance) { if (!( instance instanceof com.google.protobuf.Service )) { throw new IllegalArgumentException( "Expected a class extending com.google.protobuf.Service"); } final Service service = (Service) instance; final ServiceDescriptor descriptor = service.getDescriptorForType(); final List<MethodDescriptor> methods = descriptor.getMethods(); for (final MethodDescriptor md : methods) { try { final Message inputType = TypeExctractor.getReqestPrototype(service, md); final Message outputType = TypeExctractor.getResponsePrototype(service, md); // The lines above were made in desperation snce I couldn1t get // these two lines to work. If I made some stupid mistake, // and someone can get the two lines below to work, I can // remove the entire TypeExtractor class and be very happy // about that :-) // final MessageLite outputType = md.getOutputType().toProto().getDefaultInstance(); // final MessageLite inputType = md.getInputType().toProto().getDefaultInstance(); resolver.addTypes(md, inputType, outputType); } catch (MethodTypeException ex) { /// XXXX Something more severe should happen here Logger.getLogger( RpcClientImpl.class.getName()).log( Level.SEVERE, null, ex); } } return this; } @Override public RpcClient addInterface(final Class serviceDefinition) { checkNotNull(serviceDefinition); Method newReflectiveService = null; for (final Method m : serviceDefinition.getMethods()) { if (m.getName().equals("newReflectiveService")) { newReflectiveService = m; break; } } if (newReflectiveService == null) { throw new IllegalStateException( "class " + serviceDefinition + " is not a service defining class"); } final Object instance; try { instance = newReflectiveService.invoke(null, (Object) null); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException(ex); } addProtobuferRpcInterface(instance); return this; } @Override @SuppressWarnings("WA_AWAIT_NOT_IN_LOOP") public void stop() { running = false; try { runningLock.lock(); noLongerRunning.await(); } catch (InterruptedException ex) { throw new RuntimeException(ex); // XXXX } finally { runningLock.unlock(); } if (channel.isOpen() && channel.isBound()) { try { log.info("about to close stuff"); /// XXXX // For some reason this fails, and the catch below doesn't work. // channel.close(); } catch (Throwable e) { log.log(Level.SEVERE, "Something went wrong when closing channel: " + channel, e); } } } private void sendInvocation( final RpcClientSideInvocation invocation, final Long rpcIndex) { checkNotNull(invocation); checkArgument(rpcIndex >= 0); // Then creating the protobuf representation of // the invocation, in preparation of sending it // down the wire. final MethodDescriptor md = invocation.getMethod(); final String methodName = md.getFullName(); final String inputType = md.getInputType().getFullName(); final String outputType = md.getOutputType().getFullName(); final Message request = invocation.getRequest(); final RpcClientController controller = invocation.getController(); final boolean multiReturn = controller.isMultiReturn(); final boolean noReturn = controller.isNoReturn(); wire.sendInvocation( methodName, inputType, outputType, rpcIndex, request, multiReturn, noReturn); } } <file_sep>How hard can it be to write an RPC framework? ============================================= Well, the only way to find out is to try I guess, so that's what I'm doing. Call it a finger exercise, a design study, whatever. It's not something that useful for anyone for anything, but do feel free to take a look and if you find it interesting please tell me. If you send me a pull request i'll be ecstatic ;-) Btw, there is no license tagged on to anything here, but when I get around to it I'll open source this by tagging an Apache 2 license to everything. How to use the RPC library ========================== The blobee library is now in a pre-alpha state, but it's finished enough for me to ask for input from other developers. I know there are many strange things in the source code, so I'm actually not so interested in comments on that since I'm in the process of cleaning it up already. The user-facing API however is something I very much would like to have to get feedback about, so if feel free to give it try and please do send me feedback (to <EMAIL>). Even if you don't write your own servers and clients, please take a look at the example code below and comment on it. I really need for feedback from someone else now :-) * Clone it from github git clone git://github.com/la3lma/blobee.git * Compile mvn clean install * Write some code that uses it. You should include something like this in your pom.xml file. It will only work if you've compiled the library locally, since nothing has been uploaded to maven central yet. <dependency> <groupId>no.rmz</groupId> <artifactId>blobee</artifactId> <version>1-0.SNAPSHOT</version> </dependency> * Write some code. This is a test program from the project itself, but it should be able to serve as a template both for writing clients and servers. /** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcChannel; import com.google.protobuf.RpcController; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; import no.rmz.blobee.rpc.client.RpcClient; import no.rmz.blobee.rpc.server.RpcServer; import no.rmz.blobeeprototest.api.proto.Testservice; import no.rmz.blobeeprototest.api.proto.Testservice.RpcResult; import no.rmz.testtools.Net; /** * This really simple test sends messages over the loopback * wire a lot of times. The intention of the test is both to * get a rough idea of the performance (at present about 0.02ms per * roundtrip on my laptop), but also to smoke out any memory leaks. * * The idea is simple: Perform a very simple invocation a lot of * times. At present 100K, but it has proven to be * very convenient to try many different numbers (10K and 40K, 100K, 400K * 1M and 100M are favorites)in particular when smoking out blatant * performance and memory leaks. */ public final class ReallySimplePerformanceTest { /** * When things go long we log. */ private static final Logger log = Logger.getLogger( no.rmz.blobee.rpc.RpcPeerInvocationTest.class.getName()); /** * The number of iterations we should run during the test. */ private final static int ROUNDTRIPS = 1000000; /** * The host where we set up the server. */ private final static String HOST = "localhost"; /** * The port we set up the server on. It will be dynamically allocated * by finding a free port and then just use that. */ private int port; /** * The RpcChannel that is connected to the client and will be used * to invoke the service. */ private RpcChannel clientChannel; /** * The RpcClient that is used to sent messages over the channel. */ private RpcClient rpcClient; /** * The server accepting incoming requests. */ private RpcServer rpcServer; /** * This test is all about simplicity and speed, so we pre-compute both * the parameter and the response. This is the request parameter, and * it contains nothing in the way of payload. */ private Testservice.RpcParam request = Testservice.RpcParam.newBuilder().build(); /** * The message that is sent in the response. */ public final static String RETURN_VALUE = "Going home"; /** * A return value used to return results from the server serving the * RPC requests. It contains a short static string. */ final RpcResult RETURNVALUE = Testservice.RpcResult.newBuilder().setReturnvalue(RETURN_VALUE).build(); /** * An RPC service implementation is made by first subclassing * the abstract service class generated by protoc, in this case * Testservice.RpcService, and then wiring it up in a server context. * This is the implementation class, the wiring up happens further down. */ public final class TestService extends Testservice.RpcService { @Override public void invoke( final RpcController controller, final Testservice.RpcParam request, final RpcCallback<Testservice.RpcResult> done) { // We just return a pecomputed return value. done.run(RETURNVALUE); } } /** * This is where we set up the server and the client * and start them up. */ public void setUp() { try { // First we find a free port port = Net.getFreePort(); } catch (IOException ex) { throw new RuntimeException(ex); } // Then we set up a new server. // This is done using a "cascading" style, so the server is // actually created by the first line (newServer), // then one or more service implementations are added // (in this case one), and finally the service is started. rpcServer = RpcSetup.newServer( new InetSocketAddress(HOST, port)) .addImplementation( new TestService(), // An implementation instance Testservice.RpcService.Interface.class) // The service interface it implements. .start(); // finally start the whole thing. // Then we set up a client. The pattern is much // same as for servers, first we create the instance, // then we add a service implementation class that is handled by // the client, and then we start it. Starting the client will // involve connecting to the server at the other end. rpcClient = RpcSetup .newClient(new InetSocketAddress(HOST, port)) .addInterface(Testservice.RpcService.class) .start(); // Finally we get an RPC client that is actually used when // invoking the RPC service (this is the way the RPC interface // provided by the protoc compiler assumes we will use // RPC). clientChannel = rpcClient.newClientRpcChannel(); } /** * In this method we actually run the test. It sets up a callback * for the RPC, then invokes the service XXXX To be continued.... * @throws InterruptedException * @throws BrokenBarrierException */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("WA_AWAIT_NOT_IN_LOOP") public void testRpcInvocation() throws InterruptedException, BrokenBarrierException { // The test is done when we've counted down the // callbackCounter latch. final CountDownLatch callbackCounter = new CountDownLatch(ROUNDTRIPS); // The callback does the countdown final RpcCallback<Testservice.RpcResult> callback = new RpcCallback<Testservice.RpcResult>() { public void run(final Testservice.RpcResult response) { callbackCounter.countDown(); } }; // We create a new RPC service based on the client channel // we maede in the setup. final Testservice.RpcService myService = Testservice.RpcService.newStub(clientChannel); // We do a bit of timing final long startTime = System.currentTimeMillis(); // ... and let it rip. Nothing magical here: We create a new controller // per invocation(recycling is just too much hassle). for (int i = 0; i < ROUNDTRIPS; i++) { final RpcController clientController = rpcClient.newController(); myService.invoke(clientController, request, callback); } // Then we make an order of magnitude calculation about how // long the user should expect this to take and inform her // through the log. final int marginFactor = 2; final double expectedTime = 0.025 * ROUNDTRIPS * marginFactor; final long expectedMillis = (long) expectedTime; log.info("This shouldn't take more than " + expectedMillis + " millis (margin factor = " + marginFactor + ")"); // Now we wait. We won't pass this barrier until all the // invocations have returned to the callback callbackCounter.await(); // So now we know how long it took, stop the stopwatch. // and make some calculations. final long endTime = System.currentTimeMillis(); final long duration = endTime - startTime; final double millisPerRoundtrip = (double) duration / (double) ROUNDTRIPS; // Then tell the user about our results. log.info("Duration of " + ROUNDTRIPS + " iterations was " + duration + " milliseconds. " + millisPerRoundtrip + " milliseconds per roundtrip."); log.info("Latch count " + callbackCounter.getCount()); } /** * Ignores all input parameters, runs the test only according to * parameters defind in the class. * @param argv * @throws Exception */ public final static void main(final String argv[]) throws Exception { final ReallySimplePerformanceTest tst = new ReallySimplePerformanceTest(); tst.setUp(); tst.testRpcInvocation(); tst.rpcClient.stop(); tst.rpcServer.stop(); } } <file_sep>MAKE THE BASICS WORK ===================== o Write a better description on how to upload to sonatype/maven central. o Implement server runnig on the client side as default. o Crypto (at least document the protocol extension). o Use the invocation method generated by protoc instead of the reflection cruft I'm currently using. o Fix checkstyle objections (not all of them, but the worst ones). o When a connection is dropped, all connections on both client and server sides should be set to "cancelled" (or at least on the server side, the client side may chose to treat connection loss as an error situation instead). o Look, real hard, to figure out if some or all of the bogusness involving reflection to figure out the types of the stuff going back and forth over the wire can't be replaced by standard methods already produced by the protoc compilation. A lot of really bothersome code could be reduced to nothing if this worked out. o Think about how to extend the RPC controller to allow - Streaming returns (many return values). - Zeror returns (invocations that never ever return anything). With these two in place it will be dead simple to implement a pub/sub system. o Harmonize the way methods are described on the serving and client ends of a connection. o When resetting a client controller, it should also be so that the controller is not refered to by anything or anyone. o Get someone else to use the API and offer feedback. o Set up a demo server somewhere on the intertubes. o Write an implementation in something else that talks to this server written in one or more of: - C, because it's minimal. - Objective C, because it's so Apple. - Haskell because it's awsome. - Python because it is useful. o Generally increase neatness: -> Test coverage. -> Comments -> General ugliness -> Inner classes that shouldn't be inner classes. -> Collections of hashes that should be refactored into fewer hashes. o Make another test that is a bit more complex to make sure the implementation is actually minimally useful. o Figure out how to involve more people. - Design discussions. - Code review. - Developers. - Users. o Figure out what to do when cancelling invocations. Does it even make sense to return values for a cancelled invocation? I think not, but now it is possible. Discuss and fix. DISCUSS EXTENSIONS ================== The purpose of this discussion is to determine their impact on the current, minimal API design. o Discuss possible extensions with someone. Some possibilities are: o A listener interface that lets an application have a handle on which users/connections etc. is talking to it at any time. o Collect statistics (usage, timing). o Send an userid in the envelope. Assume that the client can do authentication, so that the server can perform authorization if it wants to. o Streaming results: An invocation can return multiple results spread out over time. (combined with the "drop ongoing calls" this is actually pretty cool). o Source quench: Let the server send a signal that indicates that too much traffic is coming in. QUALITY IMPROVEMENTS ==================== o Refactor a lot, add comments, dot "i"s cross "t"s. Javadoc everything, enhance test coverage, but don't add many new features. Consolidate, consolidate. o Make some performance tests. Nothing fancy, but they should be there from not very far into the future and forever, with historical record. -> Performance (as soon as a stable API is available (arguably it is today). Run from command line as an independent java app. -> Benchmark against java RMI. If we're in the same ballpark or faster we're pretty well set. INTERESTING NICE TO HAVES (may in fact be must haves): ====================================================== o Don't try to guarantee single delivery of messages. Implementors must handle duplicated calls. o Clearly defined threading model. o Support client-side load balancing o Late binding of RPC calls to tcp connections. o Automatic retries if desired. o Deal with clients starting before server. o Clearly defined wire-format. o Multiple compression formats o Sharing tcp connections between different RPC client-server objects. o Pluggable tracing and logging. o Pluggable security layer (for handshakes and encryption) <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc; import java.util.logging.Logger; import no.rmz.blobee.rpc.peer.RpcMessageListener; import no.rmz.blobee.serviceimpls.SampleServerImpl; import no.rmz.blobeeproto.api.proto.Rpc; import no.rmz.testtools.Receiver; import org.jboss.netty.channel.ChannelHandlerContext; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import static org.mockito.Mockito.*; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public final class RpcPeerStartupAndShutdownTest { private static final Logger log = Logger.getLogger( no.rmz.blobee.rpc.RpcPeerStartupAndShutdownTest.class.getName()); private static final String HOST = "localhost"; private static final Rpc.RpcControl HEARTBEAT_MESSAGE = Rpc.RpcControl.newBuilder() .setMessageType(Rpc.MessageType.HEARTBEAT).build(); private static final Rpc.RpcControl SHUTDOWN_MESSAGE = Rpc.RpcControl.newBuilder() .setMessageType(Rpc.MessageType.SHUTDOWN).build(); private ClientServerFixture csf; private void startClientAndServer(final RpcMessageListener ml) { csf = new ClientServerFixture(new SampleServerImpl(), ml); } @After public void shutDown() { csf.stop(); } @Mock Receiver<Rpc.RpcControl> heartbeatReceiver; @Mock Receiver<Rpc.RpcControl> shutdownReceiver; public void sleepHalfASec() { try { Thread.currentThread().sleep(500); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } @Test(timeout = 10000) public void testTransmissionOfHeartbeatsAtStartup() { final RpcMessageListener ml = new RpcMessageListener() { @Override public void receiveMessage( final Object message, final ChannelHandlerContext ctx) { if (message instanceof Rpc.RpcControl) { final Rpc.RpcControl msg = (Rpc.RpcControl) message; heartbeatReceiver.receive(msg); ctx.getChannel().close(); } } }; startClientAndServer(ml); sleepHalfASec(); verify(heartbeatReceiver, times(1)).receive(HEARTBEAT_MESSAGE); } @Test(timeout = 10000) public void testReactionToShutdown() { final RpcMessageListener ml = new RpcMessageListener() { @Override public void receiveMessage( final Object message, final ChannelHandlerContext ctx) { if (message instanceof Rpc.RpcControl) { final Rpc.RpcControl msg = (Rpc.RpcControl) message; if (msg.getMessageType() == Rpc.MessageType.HEARTBEAT) { heartbeatReceiver.receive(msg); ctx.getChannel().write(SHUTDOWN_MESSAGE); } else if (msg.getMessageType() == Rpc.MessageType.SHUTDOWN) { shutdownReceiver.receive(msg); } } } }; startClientAndServer(ml); // Need some time to let the startup transient settle. // XXX Should perhaps used a lock instead? sleepHalfASec(); verify(heartbeatReceiver).receive(HEARTBEAT_MESSAGE); // XXX This test is bogus, since it does not have the right // probes in the right places. It needs to be fixed. // verify(shutdownReceiver).receive(SHUTDOWN_MESSAGE); } } <file_sep>/* * Copyright 2013 rmz. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.rmz.blobee.rpc.client; import com.google.protobuf.RpcController; /** * An interface extending the standard RpcController interface in ways that are * necessary to make Blobee into an actually useful RPC implementation. */ public interface BlobeeRpcController extends RpcController { /** * Set this invocation to be multi-return, meaning that a procedure can * return more than one value. */ void setMultiReturn(); /** * True iff the invocation is multi-return. * * @return true if invocation is multi-return. */ boolean isMultiReturn(); /** * Set this invocation to be no-return, meaning that it is assumed that the * return-value callback will not be invoked. Indeed it will represent an * error situation to attempt to use the return callback. */ void setNoReturn(); /** * True iff the invocation is a no-return invocation. * * @return true if invocation is no-return. */ boolean isNoReturn(); } <file_sep>#!/bin/sh VERSION=blobee-1.3 (cd target jar cvf ${VERSION}-bundle.jar \ ${VERSION}.pom \ ${VERSION}.pom.asc \ ${VERSION}.jar \ ${VERSION}.jar.asc \ ${VERSION}-javadoc.jar \ ${VERSION}-javadoc.jar.asc \ ${VERSION}-sources.jar \ ${VERSION}-sources.jar.asc ) <file_sep>/** * Copyright 2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.rmz.testtools; import static com.google.common.base.Preconditions.checkArgument; import java.io.IOException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.List; /** * Testing utilities for networking. * * @author borud */ public final class Net { private Net() { } /** * Find a network port that is not in use. <p> The only way to implement * this sensibly without obvious race conditions would be if we could return * an opened listen socket. This way we would only run into trouble if we * were unable to find a port we can bind at all. <p> However, since most of * the code we need to test doesn't let us inject listen sockets this is * impractical. We could of course pass a socket back and have the client * code close it and then re-use it, but that would be burdening the * developer unduly. <p> This means that the goal of this code is to, with * some probability, locate a port number that appears to be free and hope * that the time window is narrow enough so other threads or processes * cannot grab it before we make use of it. * * @throws IOException if an IO error occurs * @return a port number which is probably free so we can bind it */ public static int getFreePort() throws IOException { final int[] port = getFreePorts(1); return port[0]; } /** * Get multiple ports. This is useful when you need more than one port * number before you start binding any of the ports. * * @param numPorts the number of port numbers we need. * @return an array of numPorts port numbers. * @throws IOException if an IO error occurs. */ public static int[] getFreePorts(final int numPorts) throws IOException { checkArgument(numPorts > 0); final List<ServerSocket> sockets = new ArrayList<>(numPorts); final int[] portNums = new int[numPorts]; try { for (int i = 0; i < numPorts; i++) { // Calling the constructor of ServerSocket with the port // number argument set to zero has defined semantics: it // allocates a free port. final ServerSocket ss = new ServerSocket(0); ss.setReuseAddress(true); sockets.add(ss); portNums[i] = ss.getLocalPort(); } return portNums; } finally { for (final ServerSocket socket : sockets) { socket.close(); } } } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc.peer.wireprotocol; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.protobuf.ByteString; import com.google.protobuf.Message; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import no.rmz.blobeeproto.api.proto.Rpc; import no.rmz.blobeeproto.api.proto.Rpc.RpcControl; import org.jboss.netty.channel.Channel; /** * An adapter that translates an API style programming into * a wire-format style. */ public final class OutgoingRpcAdapterImpl implements OutgoingRpcAdapter { private static final Logger log = Logger.getLogger(OutgoingRpcAdapterImpl.class.getName()); /** * A constant used when sending heartbeats. */ private static final Rpc.RpcControl HEARTBEAT = Rpc.RpcControl.newBuilder() .setMessageType(Rpc.MessageType.HEARTBEAT).build(); /** * The channel we are sending messages over. */ private final Channel channel; /** * Construct a new adapter that will send all its messages * to the parameter channel. * @param channel the channel to send all messages to. */ public OutgoingRpcAdapterImpl(final Channel channel) { this.channel = checkNotNull(channel); } /** * Conert a mesage to a bytestring that can then be packaged * as a payload field in an RpcControl instance. * @param msg The message to encode. * @return A ByteString representation of msg. */ public final static ByteString messageToByteString(final Message msg) { // XXX Can this be replaced with msg.toByteString(); checkNotNull(msg); final ByteArrayOutputStream baos = new ByteArrayOutputStream(msg.getSerializedSize()); try { msg.writeTo(baos); baos.close(); } catch (IOException ex) { log.log(Level.SEVERE, "Couldn't serialize payload", ex); } ByteString payload; payload = ByteString.copyFrom(baos.toByteArray()); checkNotNull(payload); return payload; } @Override public void sendInvocation( final String methodName, final String inputType, final String outputType, final Long rpcIndex, final Message rpParameter, final boolean multiReturn, final boolean noReturn) { checkNotNull(methodName); checkNotNull(inputType); checkNotNull(outputType); checkNotNull(rpParameter); checkArgument(rpcIndex >= 0); final ByteString payload = messageToByteString(rpParameter); final Rpc.MethodSignature ms = Rpc.MethodSignature.newBuilder() .setMethodName(methodName) .setInputType(inputType) .setOutputType(outputType) .build(); final Rpc.RpcControl rpcInvocationMessage = Rpc.RpcControl.newBuilder() .setMessageType(Rpc.MessageType.RPC_INV) .setRpcIndex(rpcIndex) .setMethodSignature(ms) .setMultiReturn(multiReturn) .setNoReturn(noReturn) .setPayload(payload) .build(); channel.write(rpcInvocationMessage); } @Override public void returnRpcResult( final long rpcIndex, final Rpc.MethodSignature methodSignature, final Message result, final boolean multiReturn) { final ByteString payload = messageToByteString(result); final Rpc.RpcControl returnValueMessage = Rpc.RpcControl.newBuilder() .setMessageType(Rpc.MessageType.RPC_RET) .setRpcIndex(rpcIndex) .setPayload(payload) .setMethodSignature(methodSignature) .setMultiReturn(multiReturn) .build(); channel.write(returnValueMessage); } @Override public void sendHeartbeat() { channel.write(HEARTBEAT); } @Override public void sendCancelMessage(final long rpcIndex) { final RpcControl cancelMessage = Rpc.RpcControl.newBuilder() .setMessageType(Rpc.MessageType.RPC_CANCEL) .setRpcIndex(rpcIndex) .build(); channel.write(cancelMessage); } @Override public void sendInvocationFailedMessage( final long rpcIndex, final String reason) { checkNotNull(reason); checkArgument(rpcIndex >= 0); final RpcControl failedMessage = RpcControl.newBuilder() .setMessageType(Rpc.MessageType.INVOCATION_FAILED) .setRpcIndex(rpcIndex) .setFailed(reason) .build(); channel.write(failedMessage); } @Override public void terminateMultiReturnSequence(long rpcIndex) { final RpcControl failedMessage = RpcControl.newBuilder() .setMessageType(Rpc.MessageType.TERMINATE_MULTI_SEQUENCE) .setRpcIndex(rpcIndex) .build(); } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc.methods; import com.google.protobuf.Descriptors; import com.google.protobuf.MessageLite; import no.rmz.blobeeproto.api.proto.Rpc.MethodSignature; /** * An interface used to resolve method signatures, and to store them when * they are extracted from the client implementation. */ public interface MethodSignatureResolver { /** * Given a method signature (which is a protobuf-serializable * description of an RPC invoked procedure), return the prototype * instance for the parameter type. This prototype can then * be used to deserialize an incoming protobuf packet for a method * invocation. * @param methodSignature A method signature describing which * procedure this request is all about. * @return The prototype for the parameter for the procedure. */ MessageLite getPrototypeForParameter( final MethodSignature methodSignature); /** * Given a method signature (which is a protobuf-serializable * description of an RPC invoked procedure), return the prototype * instance for the return type. This prototype can then * be used to deserialize an incoming protobuf packet for a * returning method invocation. * @param methodSignature A method signature describing which * procedure this request is all about. * @return The prototype for the return value for theprocedure. */ MessageLite getPrototypeForReturnValue( final MethodSignature methodSignature); /** * Add a description for a method in an RPC callable * procedure. * @param md The method. * @param inputType The prototype for the parameter. * @param outputType The prototype for the return value. */ void addTypes( final Descriptors.MethodDescriptor md, final MessageLite inputType, final MessageLite outputType); } <file_sep>package no.rmz.blobee.rpc.server; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import no.rmz.blobee.controllers.RpcServiceController; import org.jboss.netty.channel.ChannelHandlerContext; // XXX Use "table" from guava instead? public final class ControllerStorage { private final Map< RpcExecutionServiceImpl.ControllerCoordinate, RpcServiceController> map = new ConcurrentHashMap< >(); public void storeController( final ChannelHandlerContext ctx, final long rpcIdx, final RpcServiceController controller) { checkNotNull(ctx); checkArgument(rpcIdx >= 0); checkNotNull(controller); map.put(new RpcExecutionServiceImpl.ControllerCoordinate( ctx, rpcIdx), controller); } public RpcServiceController removeController( final ChannelHandlerContext ctx, final long rpcIdx) { return map.remove( new RpcExecutionServiceImpl.ControllerCoordinate(ctx, rpcIdx)); } public RpcServiceController getController( final ChannelHandlerContext ctx, final long rpcIdx) { final RpcServiceController result = map.get( new RpcExecutionServiceImpl.ControllerCoordinate( ctx, rpcIdx)); return result; } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc.server; /** * An RPC server interface. It is simply used to start and stop * the server. */ public interface RpcServer { /** * Start the RPC server. * @return Returns the server so that the start invocation can be used * in a "cascading" coding style. */ RpcServer start(); /** * Stop the service. */ void stop(); } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcChannel; import com.google.protobuf.RpcController; import edu.umd.cs.findbugs.annotations.SuppressWarnings; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; import no.rmz.blobee.rpc.client.RpcClient; import no.rmz.blobee.rpc.server.RpcServer; import no.rmz.blobee.rpc.server.RpcServerException; import no.rmz.blobeetestproto.api.proto.Testservice; import no.rmz.blobeetestproto.api.proto.Testservice.RpcResult; import no.rmz.testtools.Net; /** * This really simple test sends messages over the loopback * wire a lot of times. The intention of the test is both to * get a rough idea of the performance (at present about 0.02ms per * roundtrip on my laptop), but also to smoke out any memory leaks. * * The idea is simple: Perform a very simple invocation a lot of * times. At present 100K, but it has proven to be * very convenient to try many different numbers (10K and 40K, 100K, 400K * 1M and 100M are favorites)in particular when smoking out blatant * performance and memory leaks. */ public final class ReallySimplePerformanceTest { /** * When things go long we log. */ private static final Logger log = Logger.getLogger( no.rmz.blobee.rpc.RpcPeerInvocationTest.class.getName()); /** * The number of iterations we should run during the test. */ private static final int ROUNDTRIPS = 1000; /** * The host where we set up the server. */ private static final String HOST = "localhost"; /** * The port we set up the server on. It will be dynamically allocated * by finding a free port and then just use that. */ private int port; /** * The RpcChannel that is connected to the client and will be used * to invoke the service. */ private RpcChannel clientChannel; /** * The RpcClient that is used to sent messages over the channel. */ private RpcClient rpcClient; /** * The server accepting incoming requests. */ private RpcServer rpcServer; /** * This test is all about simplicity and speed, so we pre-compute both * the parameter and the response. This is the request parameter, and * it contains nothing in the way of payload. */ private Testservice.RpcParam request = Testservice.RpcParam.newBuilder().build(); /** * The message that is sent in the response. */ public static final String RETURN_VALUE = "Going home"; /** * A return value used to return results from the server serving the * RPC requests. It contains a short static string. */ private static final RpcResult RETURNVALUE = Testservice.RpcResult.newBuilder() .setReturnvalue(RETURN_VALUE).build(); /** * An RPC service implementation is made by first subclassing * the abstract service class generated by protoc, in this case * Testservice.RpcService, and then wiring it up in a server context. * This is the implementation class, the wiring up happens further down. */ public final class TestService extends Testservice.RpcService { @Override public void invoke( final RpcController controller, final Testservice.RpcParam request, final RpcCallback<Testservice.RpcResult> done) { // We just return a pecomputed return value. done.run(RETURNVALUE); } } /** * This is where we set up the server and the client * and start them up. */ public void setUp() throws RpcServerException { try { // First we find a free port port = Net.getFreePort(); } catch (IOException ex) { throw new RuntimeException(ex); } // Then we set up a new server. // This is done using a "cascading" style, so the server is // actually created by the first line (newServer), // then one or more service implementations are added // (in this case one), and finally the service is started. rpcServer = RpcSetup.newServer( new InetSocketAddress(HOST, port)) .addImplementation( new TestService(), // An implementation instance // The service interface it implements. Testservice.RpcService.Interface.class) .start(); // finally start the whole thing. // Then we set up a client. The pattern is much // same as for servers, first we create the instance, // then we add a service implementation class that is handled by // the client, and then we start it. Starting the client will // involve connecting to the server at the other end. rpcClient = RpcSetup .newClient(new InetSocketAddress(HOST, port)) .addInterface(Testservice.RpcService.class) .start(); // Finally we get an RPC client that is actually used when // invoking the RPC service (this is the way the RPC interface // provided by the protoc compiler assumes we will use // RPC). clientChannel = rpcClient.newClientRpcChannel(); } /** * In this method we actually run the test. It sets up a callback * for the RPC, then invokes the service XXXX To be continued.... * @throws InterruptedException * @throws BrokenBarrierException */ @SuppressWarnings({"WA_AWAIT_NOT_IN_LOOP", "DLS_DEAD_LOCAL_STORE" }) public void testRpcInvocation() throws InterruptedException, BrokenBarrierException { // The test is done when we've counted down the // callbackCounter latch. final CountDownLatch callbackCounter = new CountDownLatch(ROUNDTRIPS); // The callback does the countdown final RpcCallback<Testservice.RpcResult> callback = new RpcCallback<Testservice.RpcResult>() { @Override public void run(final Testservice.RpcResult response) { callbackCounter.countDown(); } }; // We create a new RPC service based on the client channel // we maede in the setup. final Testservice.RpcService myService = Testservice.RpcService.newStub(clientChannel); // We do a bit of timing final long startTime = System.currentTimeMillis(); // ... and let it rip. Nothing magical here: We create a new controller // per invocation(recycling is just too much hassle). for (int i = 0; i < ROUNDTRIPS; i++) { final RpcController clientController = rpcClient.newController(); myService.invoke(clientController, request, callback); } // Then we make an order of magnitude calculation about how // long the user should expect this to take and inform her // through the log. final int marginFactor = 2; final long expectedMillis = (long) (0.025 * ROUNDTRIPS * marginFactor); log.info("This shouldn't take more than " + expectedMillis + " millis (margin factor = " + marginFactor + ")"); // Now we wait. We won't pass this barrier until all the // invocations have returned to the callback callbackCounter.await(); // So now we know how long it took, stop the stopwatch. // and make some calculations. final long endTime = System.currentTimeMillis(); final long duration = endTime - startTime; final double millisPerRoundtrip = (double) duration / (double) ROUNDTRIPS; // Then tell the user about our results. log.info("Duration of " + ROUNDTRIPS + " iterations was " + duration + " milliseconds. " + millisPerRoundtrip + " milliseconds per roundtrip."); log.info("Latch count " + callbackCounter.getCount()); } /** * Ignores all input parameters, runs the test only according to * parameters defind in the class. * @param argv * @throws Exception */ public static void main(final String [] argv) throws Exception { final ReallySimplePerformanceTest tst = new ReallySimplePerformanceTest(); tst.setUp(); tst.testRpcInvocation(); tst.rpcClient.stop(); tst.rpcServer.stop(); } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.rmz.blobee.rpc.peer; import static com.google.common.base.Preconditions.checkNotNull; import no.rmz.blobee.rpc.client.RpcClientFactory; import no.rmz.blobee.rpc.methods.MethodSignatureResolver; import no.rmz.blobee.rpc.server.RpcExecutionService; import no.rmz.blobeeproto.api.proto.Rpc; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; /** * A factory for ChannelPipelines that willl accept incoming * RPC requests (and replies and control messages). */ public final class RpcPeerPipelineFactory implements ChannelPipelineFactory { /** * A name used to keep track of which pipeline factory this * is. */ private final String name; /** * For debugging purposes we can insert a listener * that can listen in to the messages that arrives at this * RpcPeer. */ private RpcMessageListener listener; /** * A service that is used to execute incoming requests for * remote procedure calls. */ private final RpcExecutionService executionService; // XXX Missing javadoc private final MethodSignatureResolver clientResolver; /** * An endpoint that can accept incoming requests for remote * procedure calls, and that can receive answers from our * peer at the other end of the wire when it has processed * the request. */ private final RpcClientFactory rcf; public RpcPeerPipelineFactory( final String name, final RpcExecutionService executor, final RpcClientFactory rcf) { this.name = checkNotNull(name); this.executionService = checkNotNull(executor); this.rcf = checkNotNull(rcf); this.clientResolver = rcf.getResolver(); } public RpcPeerPipelineFactory( final String name, final RpcExecutionService executor, final RpcClientFactory rcf, final RpcMessageListener listener) { this(name, executor, rcf); this.listener = listener; } // XXX Eventually this thing should get things like // compression, ssl, http, whatever, but for not it's just // the simplest possible pipeline I could get away with, and it's // complex enough already. @Override public ChannelPipeline getPipeline() throws Exception { final ProtobufDecoder protbufDecoder; protbufDecoder = new ProtobufDecoder( Rpc.RpcControl.getDefaultInstance()); final ChannelPipeline p = pipeline(); p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder()); p.addLast("protobufDecoder", protbufDecoder); p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender()); p.addLast("protobufEncoder", new ProtobufEncoder()); final RpcPeerHandler handler = new RpcPeerHandler( clientResolver, executionService, rcf); if (listener != null) { handler.setListener(listener); } p.addLast("handler", handler); return p; } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.rmz.blobee.rpc.peer; import static com.google.common.base.Preconditions.checkNotNull; import com.google.protobuf.Message; import no.rmz.blobee.controllers.RpcServiceController; import no.rmz.blobee.controllers.RpcServiceControllerImpl; import no.rmz.blobee.rpc.peer.wireprotocol.OutgoingRpcAdapter; import no.rmz.blobee.rpc.peer.wireprotocol.WireFactory; import no.rmz.blobeeproto.api.proto.Rpc.MethodSignature; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; /** * Keeps the state of an invocation on the server side of the * connection. This is a value object that contains enough * information to be able to return a result from an execution. */ public final class RemoteExecutionContext { private final MethodSignature methodSignature; private final long rpcIndex; private final RpcPeerHandler peerHandler; private final ChannelHandlerContext ctx; private final RpcDirection direction; private final RpcServiceController controller; private final OutgoingRpcAdapter wire; public RemoteExecutionContext( final RpcPeerHandler peerHandler, final ChannelHandlerContext ctx, final MethodSignature methodSignature, final long rpcIndex, final RpcDirection direction, final boolean multiReturn, final boolean noReturn) { this.ctx = checkNotNull(ctx); this.peerHandler = checkNotNull(peerHandler); this.methodSignature = checkNotNull(methodSignature); this.rpcIndex = checkNotNull(rpcIndex); this.direction = checkNotNull(direction); this.controller = new RpcServiceControllerImpl(this, multiReturn, noReturn); final Channel channel = this.getCtx().getChannel(); this.wire = WireFactory.getWireForChannel(channel); } public boolean isMultiReturn() { return controller.isMultiReturn(); } public RpcDirection getDirection() { return direction; } public MethodSignature getMethodSignature() { return methodSignature; } public long getRpcIndex() { return rpcIndex; } public void returnResult( final Message result) { final long rpcIndex = getRpcIndex(); final MethodSignature methodSignature = getMethodSignature(); wire.returnRpcResult(rpcIndex, methodSignature, result, controller.isMultiReturn()); } public ChannelHandlerContext getCtx() { return ctx; } public void startCancel() { controller.startCancel(); } public void terminateMultiReturnSequence() { wire.terminateMultiReturnSequence(rpcIndex); } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc; import static com.google.common.base.Preconditions.checkNotNull; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcChannel; import com.google.protobuf.RpcController; import edu.umd.cs.findbugs.annotations.SuppressWarnings; import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import no.rmz.blobee.rpc.client.BlobeeRpcController; import no.rmz.blobee.rpc.peer.RpcMessageListener; import no.rmz.blobee.rpc.server.IllegalReturnException; import no.rmz.blobeetestproto.api.proto.Testservice; import no.rmz.testtools.Conditions; import no.rmz.testtools.Receiver; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import static org.mockito.Mockito.*; import org.mockito.runners.MockitoJUnitRunner; /** * Test functionality to let a method return values more than one time. Can be * used to "subscribe" to results from a source. */ @RunWith(MockitoJUnitRunner.class) // XXX This is work in progress and the tests below break, // so I'm ignoring while debugging. No commits will break // existing tests that are not also work in progress. // @Ignore public final class MultipleReturnsTest { private static final Logger log = Logger.getLogger( no.rmz.blobee.rpc.MultipleReturnsTest.class.getName()); /** * Number of results that should be transmitted by the method. */ private final static int NO_OF_REPETITIONS = 50; private RpcChannel clientChannel; private Testservice.RpcParam request = Testservice.RpcParam.newBuilder().build(); private BlobeeRpcController clientController; private static final String FAILED_TEXT = "The computation failed"; private ClientServerFixture csf; private Lock lock; private Condition resultsReceived; private Condition resultsSent; private Condition doneRunFailed; @Mock private Receiver<String> callbackResponse; private void startClientAndServer(final RpcMessageListener ml) { csf = new ClientServerFixture(new ServiceTestItem(), ml); } private void startClientAndServer() { csf = new ClientServerFixture(new ServiceTestItem(), null); } @After public void shutDown() { csf.stop(); } /** * The service instance that we will use to communicate over the controller * channel. */ public final class ServiceTestItem extends Testservice.RpcService { public static final String RETURN_VALUE = "Going home"; private final Testservice.RpcResult result = Testservice.RpcResult .newBuilder().setReturnvalue(RETURN_VALUE).build(); @Override public void invoke( final RpcController controller, final Testservice.RpcParam request, final RpcCallback<Testservice.RpcResult> done) { checkNotNull(controller); checkNotNull(request); checkNotNull(done); try { // Return the result many times for (int i = 0; i < NO_OF_REPETITIONS; i++) { done.run(result); } } catch (IllegalReturnException e) { Conditions.signalCondition("done.run Failed.", lock, doneRunFailed); } catch (Exception e) { fail("Caught an unknown exception: " + e); } Conditions.signalCondition("resultsSent", lock, resultsSent); } } @Before public void setUp() { lock = new ReentrantLock(); resultsReceived = lock.newCondition(); resultsSent = lock.newCondition(); doneRunFailed = lock.newCondition(); startClientAndServer(); clientChannel = csf.getClient().newClientRpcChannel(); clientController = csf.getClient().newController(); } @Test(timeout = 3000) @SuppressWarnings("WA_AWAIT_NOT_IN_LOOP") public void testCorrectMultiReturn() throws InterruptedException { clientController.setMultiReturn(); final CountDownLatch countdownLatch = new CountDownLatch(NO_OF_REPETITIONS); final RpcCallback<Testservice.RpcResult> callback = new RpcCallback<Testservice.RpcResult>() { @Override public void run(final Testservice.RpcResult response) { callbackResponse.receive(response.getReturnvalue()); countdownLatch.countDown(); } }; final Testservice.RpcService myService = Testservice.RpcService.newStub(clientChannel); clientController.isMultiReturn(); myService.invoke(clientController, request, callback); Conditions.waitForCondition("resultsSent", lock, resultsSent); countdownLatch.await(); verify(callbackResponse, times(NO_OF_REPETITIONS)) .receive(ServiceTestItem.RETURN_VALUE); } @Test//(timeout = 3000) @SuppressWarnings("WA_AWAIT_NOT_IN_LOOP") public void testMultiReturnWithoutMultiSetInController() throws InterruptedException { final CountDownLatch countdownLatch = new CountDownLatch(NO_OF_REPETITIONS); final RpcCallback<Testservice.RpcResult> callback = new RpcCallback<Testservice.RpcResult>() { @Override public void run(final Testservice.RpcResult response) { callbackResponse.receive(response.getReturnvalue()); countdownLatch.countDown(); } }; final Testservice.RpcService myService = Testservice.RpcService.newStub(clientChannel); assertFalse(clientController.isMultiReturn()); myService.invoke(clientController, request, callback); Conditions.waitForCondition("done.run Failed", lock, doneRunFailed); verify(callbackResponse, times(1)) .receive(ServiceTestItem.RETURN_VALUE); assertEquals(countdownLatch.getCount(), NO_OF_REPETITIONS - 1); } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc.methods; import static com.google.common.base.Preconditions.checkNotNull; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.MessageLite; /** * Value object used to describe messages associated with * RPC APIs. */ public final class MethodDesc { private MethodDescriptor descriptor; private MessageLite parameterType; private MessageLite returnValueType; /** * Construct a new method descriptor. * @param descriptor The method descriptor, from protoc. * @param parameterType The * @param returnValueTupe */ public MethodDesc( final MethodDescriptor descriptor, final MessageLite parameterType, final MessageLite outputType) { this.descriptor = checkNotNull(descriptor); this.parameterType = checkNotNull(parameterType); this.returnValueType = checkNotNull(outputType); } public MethodDescriptor getDescriptor() { return descriptor; } public MessageLite getInputType() { return parameterType; } public MessageLite getOutputType() { return returnValueType; } } <file_sep>package no.rmz.testtools; import static com.google.common.base.Preconditions.checkNotNull; import edu.umd.cs.findbugs.annotations.SuppressWarnings; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.Assert.*; /** * Utility class for setting up conditions that are used to * ensure the required synchronization when setting up * tests that involves components running bits of pieces of * a test in different threads. */ public final class Conditions { private static final Logger log = Logger.getLogger(Conditions.class.getName()); /** * Utility class! No public constructor for you! */ private Conditions() { } @SuppressWarnings("WA_AWAIT_NOT_IN_LOOP") public static void waitForCondition( final String description, final Lock lock, final Condition condition) { checkNotNull(description); checkNotNull(lock); checkNotNull(condition); try { lock.lock(); log.log(Level.INFO, "Awaiting condition {0}", description); condition.await(); log.log(Level.INFO, "Just finished waiting for condition {0}", description); } catch (InterruptedException ex) { fail("Interrupted: " + ex); } finally { lock.unlock(); } } public static void signalCondition( final String description, final Lock lock, final Condition condition) { try { lock.lock(); log.log(Level.INFO, "Signalling condition {0}", description); condition.signal(); } finally { lock.unlock(); } } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc; import com.google.protobuf.Descriptors; import com.google.protobuf.Message; import java.util.List; import java.util.logging.Logger; import no.rmz.blobee.protobuf.MethodTypeException; import no.rmz.blobee.protobuf.TypeExctractor; import no.rmz.blobee.serviceimpls.SampleServerImpl; import no.rmz.blobeetestproto.api.proto.Testservice; import org.junit.Test; public final class TypeExtractorTest { private static final Logger log = Logger.getLogger( no.rmz.blobee.rpc.TypeExtractorTest.class.getName()); @Test(timeout = 10000) public void determineMethodTypesTest() throws MethodTypeException { final com.google.protobuf.Service service = new SampleServerImpl(); final Descriptors.ServiceDescriptor descriptor = service.getDescriptorForType(); final List<Descriptors.MethodDescriptor> methods = descriptor.getMethods(); // Since we know that SampleServerImpl has only one method. org.junit.Assert.assertEquals(1, methods.size()); Descriptors.MethodDescriptor md = methods.get(0); final Message inputType = TypeExctractor.getReqestPrototype(service, md); org.junit.Assert.assertNotNull(inputType); final Message outputType = TypeExctractor.getResponsePrototype(service, md); org.junit.Assert.assertNotNull(outputType); final String fullName = md.getFullName(); org.junit.Assert.assertEquals( "no.rmz.blobeetestproto.api.proto.RpcService.Invoke", fullName); org.junit.Assert.assertTrue( inputType instanceof Testservice.RpcParam); org.junit.Assert.assertTrue( outputType instanceof Testservice.RpcResult); } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.controllers; import com.google.protobuf.RpcController; import no.rmz.blobee.rpc.client.BlobeeRpcController; import no.rmz.blobee.rpc.client.RpcClientImpl; import no.rmz.blobee.rpc.client.RpcClientSideInvocation; /** * The extension of the RpcControllr we use when implementing * the Rpc. */ public interface RpcClientController extends BlobeeRpcController { /** * The index of the invocation. This is always associated to * a particular RpcClient. * @return */ long getIndex(); /** * True if the controller is associated with an RPC invocation * that is still ongoing. * @return True if the invocation is still ongoing. */ boolean isActive(); /** * Setting the value that is read by isActive. * @param active New value of active field. */ void setActive(final boolean active); /** * Bind the controller to a record keeping track of the client side * of an RPC invocation. * @param invocation The invocation that we want the * controller to be associated with. */ void bindToInvocation(final RpcClientSideInvocation invocation); /** * Associate the client with a client and an index. * @param rpcClient The client associated witht this controller. * @param rpcIndex The index associated with this controller. */ void setClientAndIndex(final RpcClientImpl rpcClient, final long rpcIndex); } <file_sep>package no.rmz.blobee.rpc.server; import static com.google.common.base.Preconditions.checkNotNull; import com.google.protobuf.Message; import com.google.protobuf.RpcCallback; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import no.rmz.blobee.controllers.RpcServiceController; import no.rmz.blobee.controllers.RpcServiceControllerImpl; import no.rmz.blobee.rpc.peer.RemoteExecutionContext; import org.jboss.netty.channel.ChannelHandlerContext; final class MethodInvokingRunnable implements Runnable { private final Object implementation; private final RemoteExecutionContext dc; private final ChannelHandlerContext ctx; private final Object parameter; private final RpcExecutionServiceImpl executor; private final boolean noReturn; private final boolean multiReturn; public MethodInvokingRunnable( final Object implementation, final RemoteExecutionContext dc, final ChannelHandlerContext ctx, final Object parameter, final ControllerStorage ctStor, final RpcExecutionServiceImpl executor, final boolean multiReturn, final boolean noReturn) { this.implementation = checkNotNull(implementation); this.dc = checkNotNull(dc); this.ctx = checkNotNull(ctx); this.parameter = checkNotNull(parameter); this.executor = checkNotNull(executor); this.multiReturn = multiReturn; this.noReturn = noReturn; } private final Object monitor = new Object(); private boolean hasReturnedOnce = false; @Override public void run() { final Method method = executor.getMethod(dc.getMethodSignature()); final RpcServiceController controller = new RpcServiceControllerImpl(dc, multiReturn, noReturn); executor.storeController(ctx, dc.getRpcIndex(), controller); final RpcCallback<Message> callbackAdapter = new RpcCallback<Message>() { @Override public void run(final Message response) { if (noReturn) { throw new IllegalReturnException( "Returning from a noReturn invocation", MethodInvokingRunnable.this, this); } else if (hasReturnedOnce && !multiReturn) { throw new IllegalReturnException( "Returning multi from a non-multi invocation", MethodInvokingRunnable.this, this); } else { hasReturnedOnce = true; } controller.invokeCancelledCallback(); dc.returnResult(response); } }; try { method.invoke(implementation, controller, parameter, callbackAdapter); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException(ex); } finally { if (multiReturn) { dc.terminateMultiReturnSequence(); } executor.removeController(ctx, dc.getRpcIndex()); } } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc.server; import static com.google.common.base.Preconditions.checkNotNull; import com.google.protobuf.Service; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger; import no.rmz.blobee.rpc.client.MultiChannelClientFactory; import no.rmz.blobee.rpc.peer.RpcMessageListener; import no.rmz.blobee.rpc.peer.RpcPeerPipelineFactory; import no.rmz.blobee.threads.ErrorLoggingThreadFactory; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * An implementation of an RpcServer that will listen for incoming * TCP connections on a given InetSocketAddress, and will then handle * incoming RPC connections on that TCP connection. */ public final class RpcServerImpl implements RpcServer { private static final Logger log = Logger.getLogger(RpcServerImpl.class.getName()); private final InetSocketAddress socket; private final RpcExecutionService executionService; private final RpcMessageListener listener; private final ServerBootstrap bootstrap; /** * A thread pool. */ private final ExecutorService bossExecutor; /** * Another thread pool. */ private final ExecutorService workerExcecutor; /** * Construct a new server implementation that will listen for * incoming client connections on the specified socket. * * The optional listener argument is used while debugging to listen * in on incoming messages. * * @param socket The socket to listen for. * @param listener An optional listener. IF non-null, this listener * will listen in on all the messages flowing into the server. */ public RpcServerImpl( final InetSocketAddress socket, final RpcMessageListener listener) { this(socket, new RpcExecutionServiceImpl( "Execution service for server listening on " + socket.toString()), listener); } /** * Construct a new server implementation that will listen for * incoming client connections on the specified socket. * * The execution service will be used to actually run the incoming * requests. * * The optional listener argument is used while debugging to listen * in on incoming messages. * * @param socket The socket to listen for. * @param executionService An execution service that will run incoming * requests. * @param listener An optional listener. IF non-null, this listener * will listen in on all the messages flowing into the server. */ public RpcServerImpl( final InetSocketAddress socket, final RpcExecutionService executionService, final RpcMessageListener listener) { this.socket = checkNotNull(socket); this.executionService = checkNotNull(executionService); this.listener = listener; // XXX Nullable bossExecutor = Executors.newCachedThreadPool( new ErrorLoggingThreadFactory( "RpcServerImpl bossExecutor", log)); workerExcecutor = Executors.newCachedThreadPool( new ErrorLoggingThreadFactory( "RpcServerImpl workerExcecutor", log)); this.bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( bossExecutor, workerExcecutor)); final String name = "RPC Server at " + socket.toString(); final RpcPeerPipelineFactory serverChannelPipelineFactory = new RpcPeerPipelineFactory( name, executionService, new MultiChannelClientFactory(), listener); // Set up the pipeline factory. bootstrap.setPipelineFactory(serverChannelPipelineFactory); } /** * Bind to bootstrap socket and start accepting incoming connections and * requests. * * @return this */ @Override public RpcServer start() { bootstrap.bind(socket); return this; } /** * Add a service to the server. * * @param service The implementation. * @param implementation The service being imolemented. * @return this RpcServerImpl */ public RpcServer addImplementation( final Service service, final Class implementation) throws RpcServerException { checkNotNull(service); checkNotNull(implementation); executionService.addImplementation(service, implementation); return this; } @Override public void stop() { bootstrap.shutdown(); bossExecutor.shutdownNow(); workerExcecutor.shutdownNow(); } } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package no.rmz.blobee.rpc.client; /** * Used for debugging only, used to listen in on invocations * that goes through the client side. */ public interface RpcClientSideInvocationListener { /** * When the client side sees an invocation, this method * lets a spy listen in on it. * @param invocation an invocation to spy on. */ void listenToInvocation(final RpcClientSideInvocation invocation); } <file_sep>/** * Copyright 2013 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.rmz.blobee.serviceimpls; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcController; import no.rmz.blobeetestproto.api.proto.Testservice.RpcParam; import no.rmz.blobeetestproto.api.proto.Testservice.RpcResult; import no.rmz.blobeetestproto.api.proto.Testservice.RpcService; /** * A really simple service used in several of the tests. */ public final class SampleServerImpl extends RpcService { public static final String RETURN_VALUE = "Going home"; private final RpcResult result = RpcResult.newBuilder().setReturnvalue(RETURN_VALUE).build(); @Override public void invoke( final RpcController controller, final RpcParam request, final RpcCallback<RpcResult> done) { done.run(result); } }
98bd7dfdf226dc98e3efa5abe6ce338f2396369e
[ "Markdown", "Maven POM", "Java", "Text", "Shell" ]
25
Maven POM
la3lma/blobee
c069a752967094b6970a2e766762ff61b9dacdd7
93f9abb44d5d8b1c1c6760f9f122e0b06f0b8523
refs/heads/master
<repo_name>lonedawg/paperboy<file_sep>/UsenetStreamReader.cs using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Runtime.InteropServices; namespace Paperboy { internal class UsenetStreamReader : TextReader { // =========================================================================== // = Private Constants // =========================================================================== private const Int32 BUFFER_SIZE = 1024; // =========================================================================== // = Private Fields // =========================================================================== private Byte[] _inputBuffer; private Char[] _decodedBuffer; private Int32 _decodedCount; private Int32 _currentDecodePosition; private Int32 _bufferSize; private Encoding _encoding; private Decoder _decoder; private Stream _baseStream; private Boolean _mayBlock; private StringBuilder _lineBuilder; private Boolean _foundCarriageReturn; // =========================================================================== // = Construction // =========================================================================== public UsenetStreamReader(Stream inStream, Encoding inEncoding) { _baseStream = inStream; _bufferSize = BUFFER_SIZE; _encoding = inEncoding; _decoder = inEncoding.GetDecoder(); _inputBuffer = new Byte[BUFFER_SIZE]; _decodedBuffer = new Char[inEncoding.GetMaxCharCount(BUFFER_SIZE)]; _decodedCount = 0; _currentDecodePosition = 0; } // =========================================================================== // = Overrides // =========================================================================== public override String ReadLine() { if (_currentDecodePosition >= _decodedCount && ReadBuffer() == 0) return null; var begin = _currentDecodePosition; var end = FindNextEndOfLineIndex(); if (end < _decodedCount && end >= begin) return new String(_decodedBuffer, begin, end - begin); if (_lineBuilder == null) _lineBuilder = new StringBuilder(); else _lineBuilder.Length = 0; while (true) { if (_foundCarriageReturn) _decodedCount--; _lineBuilder.Append(_decodedBuffer, begin, _decodedCount - begin); if (ReadBuffer() == 0) { if (_lineBuilder.Capacity > 32768) { var stringBuilder = _lineBuilder; _lineBuilder = null; return stringBuilder.ToString(0, stringBuilder.Length); } return _lineBuilder.ToString(0, _lineBuilder.Length); } begin = _currentDecodePosition; end = FindNextEndOfLineIndex(); if (end < _decodedCount && end >= begin) { _lineBuilder.Append(_decodedBuffer, begin, end - begin); if (_lineBuilder.Capacity > 32768) { var stringBuilder = _lineBuilder; _lineBuilder = null; return stringBuilder.ToString(0, stringBuilder.Length); } return _lineBuilder.ToString(0, _lineBuilder.Length); } } } public override String ReadToEnd() { var stringBuilder = new StringBuilder(); var size = _decodedBuffer.Length; var buffer = new Char[size]; int bytesRead; while ((bytesRead = Read(buffer, 0, size)) > 0) stringBuilder.Append(buffer, 0, bytesRead); return stringBuilder.ToString(); } public override Int32 Peek() { if (_currentDecodePosition >= _decodedCount && (_mayBlock || ReadBuffer() == 0)) return -1; return _decodedBuffer[_currentDecodePosition]; } public override Int32 Read() { if (_currentDecodePosition >= _decodedCount && ReadBuffer() == 0) return -1; return _decodedBuffer[_currentDecodePosition++]; } public override Int32 Read([In, Out] Char[] destinationBuffer, Int32 index, Int32 count) { int charsRead = 0; while (count > 0) { if (_currentDecodePosition >= _decodedCount && ReadBuffer() == 0) return charsRead > 0 ? charsRead : 0; var cch = Math.Min(_decodedCount - _currentDecodePosition, count); Array.Copy(_decodedBuffer, _currentDecodePosition, destinationBuffer, index, cch); _currentDecodePosition += cch; index += cch; count -= cch; charsRead += cch; } return charsRead; } public override void Close() { Dispose(true); } protected override void Dispose(Boolean disposing) { try { if (disposing && _baseStream != null) { _baseStream.Close(); } _inputBuffer = null; _decodedBuffer = null; _encoding = null; _decoder = null; _baseStream = null; } finally { base.Dispose(disposing); } } // =========================================================================== // = Private Methods // =========================================================================== private Int32 ReadBuffer() { _currentDecodePosition = 0; _decodedCount = 0; Int32 currentByteEncoded = 0; do { currentByteEncoded = _baseStream.Read(_inputBuffer, 0, _bufferSize); if (currentByteEncoded <= 0) return 0; _mayBlock = (currentByteEncoded < _bufferSize); _decodedCount += _decoder.GetChars(_inputBuffer, 0, currentByteEncoded, _decodedBuffer, 0); } while (_decodedCount == 0); return _decodedCount; } private Int32 FindNextEndOfLineIndex() { var curChar = '\0'; while (_currentDecodePosition < _decodedCount) { curChar = _decodedBuffer[_currentDecodePosition]; if (curChar == '\n' && _foundCarriageReturn) { _currentDecodePosition++; var res = _currentDecodePosition - 2; if (res < 0) res = 0; // If a new array starts with a \n and there was a \r at the end of the previous one, we get here. _foundCarriageReturn = false; return res; } _foundCarriageReturn = curChar == '\r'; _currentDecodePosition++; } return -1; } } } <file_sep>/UsenetClient.cs using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Paperboy { public class UsenetClient : IDisposable { // =========================================================================== // = Private Properties // =========================================================================== private String HostName { get; set; } private Int32 Port { get; set; } private String UserName { get; set; } private String Password { get; set; } private Boolean UseSsl { get; set; } // =========================================================================== // = Private Fields // =========================================================================== private static readonly Encoding _encoding = Encoding.GetEncoding("iso-8859-1"); private TcpClient _client; private TextWriter _writer; private TextReader _reader; private String _selectedGroup; // =========================================================================== // = Construction // =========================================================================== public UsenetClient(String inHostName, Int32 inPort, String inUserName, String inPassword, Boolean inUseSsl) { HostName = inHostName; Port = inPort; UserName = inUserName; Password = <PASSWORD>; UseSsl = inUseSsl; } // =========================================================================== // = Public Methods // =========================================================================== public IEnumerable<String> TryGetArticle(IEnumerable<String> inGroups, String inMessageId) { EnsureConnected(); EnsureGroupSelected(inGroups); var messageId = inMessageId; if (!messageId.StartsWith("<")) messageId = "<" + messageId; if (!messageId.EndsWith(">")) messageId = messageId + ">"; WriteCommand("ARTICLE {0}", messageId); if (ReadResponseCode() != ResponseCode.ArticleRetrieved) yield break; var readingHeader = true; while (true) { var line = _reader.ReadLine(); if (line == ".") yield break; if (line.StartsWith("..")) line = line.Substring(1); if (readingHeader) { if (line.Length == 0) readingHeader = false; } else yield return line; } } // =========================================================================== // = Private Methods // =========================================================================== private void EnsureConnected() { if (_client == null) Connect(); } private void Connect() { _client = new TcpClient(HostName, Port); var stream = (Stream)_client.GetStream(); if (UseSsl) { var sslStream = new SslStream(stream); sslStream.AuthenticateAsClient(HostName); stream = sslStream; } var writer = new StreamWriter(stream, _encoding); writer.AutoFlush = true; _writer = writer; _reader = new UsenetStreamReader(stream, _encoding); var response = ReadResponseCode(); if (response != ResponseCode.ServerReadyPostingAllowed && response != ResponseCode.ServerReadyNoPostingAllowed) throw new ApplicationException("Unexpected response code on connect."); Authenticate(); } private void Authenticate() { WriteCommand("AUTHINFO USER {0}", UserName); var userResponse = ReadResponseCode(); if (userResponse == ResponseCode.PasswordRequired) { WriteCommand("AUTHINFO PASS {0}", Password); var passwordResponse = ReadResponseCode(); if (passwordResponse != ResponseCode.AuthenticationAccepted) throw new ApplicationException("Authentication failed."); } } private void EnsureGroupSelected(IEnumerable<String> inGroups) { if (_selectedGroup != null && inGroups.Contains(_selectedGroup)) return; foreach (var group in inGroups) if (TrySelectGroup(group)) { _selectedGroup = group; return; } } private Boolean TrySelectGroup(String inGroup) { WriteCommand("GROUP {0}", inGroup); var response = ReadResponseCode(); if (response == ResponseCode.NoSuchNewsgroup) return false; if (response == ResponseCode.NewsgroupSelected) return true; throw new ApplicationException("Unexpected response to GROUP command: " + response); } private void WriteCommand(String inFormat, params Object[] inParams) { _writer.WriteLine(String.Format(inFormat, inParams)); } private String ReadResponse() { return _reader.ReadLine(); } private ResponseCode ReadResponseCode() { var response = _reader.ReadLine(); response = response.Substring(0, 3); return (ResponseCode)Convert.ToInt32(response); } // =========================================================================== // = IDisposable Implementation // =========================================================================== public void Dispose() { _writer.TryDispose(); _reader.TryDispose(); try { _client.Close(); } catch { } _client.TryDispose(); } } } <file_sep>/ResponseCode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Paperboy { internal enum ResponseCode { ServerReadyPostingAllowed = 200, ServerReadyNoPostingAllowed = 201, NewsgroupSelected = 211, NoSuchNewsgroup = 411, AuthenticationRequired = 480, PasswordRequired = 381, AuthenticationAccepted = 281, ArticleRetrieved = 220 } }
8717308bec53cc0069e26b4dbbee40403e219fd8
[ "C#" ]
3
C#
lonedawg/paperboy
9c759cf6f0e884a26305d1cc5c0d75191ce60b7f
d9d1139eb6cb12173e9db84239325cbf3ceaa121
refs/heads/master
<file_sep>numbers = [1, 2, 3, 4] removed_number = numbers.pop() print(numbers) print(removed_number) a = 10 n = 20 num_list = list(range(a, n)) print(num_list) print(num_list.pop()) print(num_list) # Given the following code, what would print to the console? random_list = [True, 1, 5.5, 3] popped_value = random_list.pop() print(random_list) # Given the following code, what would print to the console? random_list = ['True', 1, 5.5, 3] new_value = random_list.pop() print(new_value) """3 Pop Challenge It is common in mathematics to need to remove outliers from a data set. The .pop() method in conjunction with the .index() method can be a useful combination for accomplishing such a task. Complete the remove_outliers function below. This function takes one parameter called data and is a collection of observed data. This function should return the data list with the smallest value removed and the largest value removed. Notes: Do not modify the original list, make a copy first Do not modify the original order of the elements of the list Example: remove_outliers([55, 1, 23, 523, 68, 81, 99]) -> [55, 23, 68, 81, 99] """ data_lst = [55, 1, 23, 523, 68, 81, 99] def remove_outliers(data_lst): data_lst1 = data_lst.copy() data_lst1.pop(data_lst1.index(max(data_lst1))) data_lst1.pop(data_lst1.index(min(data_lst1))) return data_lst1 print(remove_outliers(data_lst))
f0baf44fb96ee7a511d4fe434b06ef4e964d6f69
[ "Python" ]
1
Python
deepikaasharma/The-Pop-Method
90fa54c9ef1bb263e9189deba1ecdd2008560823
b8f208fcd9b759876198627a604fafa8059a19ec
refs/heads/master
<repo_name>jmack17m/NPSCalc<file_sep>/www/js/app.js // Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' angular.module('starter', ['ionic']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { if(window.cordova && window.cordova.plugins.Keyboard) { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); // Don't remove this line unless you know what you are doing. It stops the viewport // from snapping when text inputs are focused. Ionic handles this internally for // a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); }) app.controller('appCtrl', function($scope){ $scope.pro = "Test"; }); /*function calculateNPS(){ var tot = document.getElementById('totInput').value; var pro = document.getElementById('proInput').value; var det = document.getElementById('detInput').value; var proPercent = pro/tot; var detPercent = det/tot; var npsResult = (proPercent - detPercent).toFixed(2) * 100; if (tot, pro, det === ""){ alert("Please fill in all fields"); }else{ updateGauge(); } function updateGauge (){ var myGauge = Gauges.getById("uib-justgage-2"); myGauge.value = npsResult; myGauge.refresh(myGauge.value); } }*/
ef5e5c990192cf4da3b24115fe99dcd7a0ab12fe
[ "JavaScript" ]
1
JavaScript
jmack17m/NPSCalc
ae43c6c9dbe03781e99f3dedcf0bdd532fca9551
eb444464c096f07910f667cf8cba087ced852c57
refs/heads/main
<file_sep>package com.dao; import com.dto.FacultyDetails; import com.dto.StudentDetails; import com.ts.db.HibernateTemplate; public class FacultyDAO { public int register(FacultyDetails user) { System.out.println(user); return HibernateTemplate.addObject(user); } public FacultyDetails getFacultyByPass(String userEmail,String userPassword) { return (FacultyDetails)HibernateTemplate.getObjectByFacultyPass(userEmail,userPassword); } public int update(FacultyDetails editUser) { System.out.println(editUser); return HibernateTemplate.updateObject(editUser); } } <file_sep>package com.dto; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @Entity public class StudentDetails { @Id@GeneratedValue private int studentId; private String studentName; private String studentEmail; private String studentPassword; private String studentNumber; private String studentSection; private String studentBranch; @OneToMany(mappedBy="studentDetails",fetch = FetchType.LAZY) private List<BookDetails> bookDetails = new ArrayList<BookDetails>(); public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentNumber() { return studentNumber; } public void setStudentNumber(String studentNumber) { this.studentNumber = studentNumber; } public String getStudentSection() { return studentSection; } public void setStudentSection(String studentSection) { this.studentSection = studentSection; } public String getStudentBranch() { return studentBranch; } public void setStudentBranch(String studentBranch) { this.studentBranch = studentBranch; } public String getStudentEmail() { return studentEmail; } public void setStudentEmail(String studentEmail) { this.studentEmail = studentEmail; } public String getStudentPassword() { return studentPassword; } public void setStudentPassword(String studentPassword) { this.studentPassword = studentPassword; } public List<BookDetails> getBookDetails() { return bookDetails; } public void setBookDetails(List<BookDetails> bookDetails) { this.bookDetails = bookDetails; } @Override public String toString() { return "StudentDetails [studentId=" + studentId + ", studentName=" + studentName + ", studentEmail=" + studentEmail + ", studentPassword=" + <PASSWORD>Password + ", studentNumber=" + studentNumber + ", studentSection=" + studentSection + ", studentBranch=" + studentBranch + ", bookDetails=" + bookDetails + "]"; } } <file_sep>package com.dto; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @Entity public class FacultyDetails { @Id@GeneratedValue private int facultyId; private String facultyName; private String facultyEmail; private String facultyPassword; private String facultyBranch; @OneToMany(mappedBy="facultyDetails",fetch = FetchType.LAZY) private List<BookDetails> bookDetails = new ArrayList<BookDetails>(); @OneToMany(mappedBy="facultyDetails",fetch = FetchType.LAZY) private List<ThesisDetails> thesisDetails = new ArrayList<ThesisDetails>(); public int getFacultyId() { return facultyId; } public void setFacultyId(int facultyId) { this.facultyId = facultyId; } public String getFacultyName() { return facultyName; } public void setFacultyName(String facultyName) { this.facultyName = facultyName; } public String getFacultyBranch() { return facultyBranch; } public void setFacultyBranch(String facultyBranch) { this.facultyBranch = facultyBranch; } public List<BookDetails> getBookDetails() { return bookDetails; } public void setBookDetails(List<BookDetails> bookDetails) { this.bookDetails = bookDetails; } public List<ThesisDetails> getThesisDetails() { return thesisDetails; } public void setThesisDetails(List<ThesisDetails> thesisDetails) { this.thesisDetails = thesisDetails; } public String getFacultyEmail() { return facultyEmail; } public void setFacultyEmail(String facultyEmail) { this.facultyEmail = facultyEmail; } public String getFacultyPassword() { return <PASSWORD>Password; } public void setFacultyPassword(String facultyPassword) { this.facultyPassword = <PASSWORD>; } @Override public String toString() { return "FacultyDetails [facultyId=" + facultyId + ", facultyName=" + facultyName + ", facultyEmail=" + facultyEmail + ", facultyPassword=" + <PASSWORD> + ", facultyBranch=" + facultyBranch + ", bookDetails=" + bookDetails + ", thesisDetails=" + thesisDetails + "]"; } } <file_sep>package com.dto; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @Entity public class ThesisDetails { @Id@GeneratedValue private int thesisId; private String thesisName; private String thesisAuthor; private String thesisSubject; private int thesisPublishingYear; @ManyToOne private FacultyDetails facultyDetails; public int getThesisId() { return thesisId; } public void setThesisId(int thesisId) { this.thesisId = thesisId; } public String getThesisName() { return thesisName; } public void setThesisName(String thesisName) { this.thesisName = thesisName; } public String getThesisAuthor() { return thesisAuthor; } public void setThesisAuthor(String thesisAuthor) { this.thesisAuthor = thesisAuthor; } public String getThesisSubject() { return thesisSubject; } public void setThesisSubject(String thesisSubject) { this.thesisSubject = thesisSubject; } public int getThesisPublishingYear() { return thesisPublishingYear; } public void setThesisPublishingYear(int thesisPublishingYear) { this.thesisPublishingYear = thesisPublishingYear; } public FacultyDetails getFacultyDetails() { return facultyDetails; } public void setFacultyDetails(FacultyDetails facultyDetails) { this.facultyDetails = facultyDetails; } @Override public String toString() { return "ThesisDetails [thesisId=" + thesisId + ", thesisName=" + thesisName + ", thesisAuthor=" + thesisAuthor + ", thesisSubject=" + thesisSubject + ", thesisPublishingYear=" + thesisPublishingYear + ", facultyDetails=" + facultyDetails + "]"; } } <file_sep>package com.dao; import com.dto.StudentDetails; import com.ts.db.HibernateTemplate; public class StudentDAO { public StudentDetails getStudentByPass(String userEmail,String userPassword) { return (StudentDetails)HibernateTemplate.getObjectByUserPass(userEmail,userPassword); } public StudentDetails getUserByEmail(String email) { return (StudentDetails)HibernateTemplate.getObjectByEmail(email); } public int register(StudentDetails user) { System.out.println(user); return HibernateTemplate.addObject(user); } public int update(StudentDetails editUser) { System.out.println(editUser); return HibernateTemplate.updateObject(editUser); } }
de6c79d3af2326466061b6d444ad0a403c492bd8
[ "Java" ]
5
Java
BhavyaAparna/LibraryManagementSystem
c945493055167f232cf0c9d40f782820d14e5de0
6f09f4b1e36435c37239e62acdb26a4a6758993c
refs/heads/master
<repo_name>yumendy/HIT_school_calender<file_sep>/main.py import datetime import json import sys class CalenderApp(object): def __init__(self, first_day='2017-02-27', week_num=18, events=None, beauty=False): if events is None: events = {} self.first_day = datetime.date(*tuple(map(int, first_day.split('-')))) self.week_num = week_num self.events = events self.beauty = beauty def get_a_date_obj(self, current_date): event = self.events.get(current_date.strftime("%Y-%m-%d"), None) if event is not None: event = event.encode('utf8') return { "date": current_date.strftime("%Y-%m-%d"), "weekday": current_date.isoweekday(), "events": event } def gen_json(self): weeks_list = [] current_date = self.first_day for week_no in xrange(1, self.week_num + 1): week = {'week_number': week_no, 'dates': []} for i in xrange(7): week['dates'].append(self.get_a_date_obj(current_date)) current_date += datetime.timedelta(days=1) weeks_list.append(week) return json.dumps({'weeks': weeks_list}, indent=4 if self.beauty else None, encoding='utf8') if __name__ == '__main__': arg_dict = None with open(sys.argv[1], 'rb') as fp: arg_dict = json.load(fp, encoding='utf8') app = CalenderApp(**arg_dict) with open('output.json', 'wb') as fp: fp.write(app.gen_json()) <file_sep>/readme.md # 哈尔滨工业大学校历生成工具 ### 简介 * 校历生成工具,根据提供的学期开始日期以及周数和事件,生成校历json数据,可作为校园开放平台接口供第三方服务调用。 * 同时实现了一个标准化日历的API server可以供提供订阅服务。 ### 使用方法 * 可以在命令行下直接通过命令调用,也可作为模块导入其他应用。 * 基于命令行使用: `python main.py input.json` * 基于模块导入使用: `from HIT_school_calender.main import CalenderApp` * API Server基于webpy实现。 * 基于命令行部署: `python CalenderAPIServer.py 8000` * 基于nginx + uwsgi部署: pass ### 参数 * first_day: 学期开始的第一天的日期,格式为"yyyy-mm-dd" * week_num: 需要生成的周数, 整形 * beauty: 输出json是否需要美化,布尔值 * events: 事件字典,键为日期,格式为"yyyy-mm-dd",值为事件描述,字符串 ### 调用说明 * 基于命令行的调用只需生成一个包含上述参数的json文件即可在命令行中调用,示例: ```json { "first_day": "2017-02-27", "week_num": 18, "beauty" : true, "events" : { "2017-02-25": "本科生和研究生老生到校注册", "2017-02-26": "本科生和研究生老生到校注册", "2017-02-27": "春季学期开始上课", "2017-02-28": "2017春博士新生报到", "2017-04-02": "清明节放假调休3天", "2017-04-03": "清明节放假调休3天", "2017-04-04": "清明节放假调休3天", "2017-04-29": "劳动节放假3天", "2017-04-30": "劳动节放假3天", "2017-05-01": "劳动节放假3天", "2017-05-26": "校运动会", "2017-05-27": "校运动会", "2017-05-28": "端午节放假调休3天", "2017-05-29": "端午节放假调休3天", "2017-05-30": "端午节放假调休3天", "2017-06-26": "期末考试", "2017-06-27": "期末考试", "2017-06-28": "期末考试", "2017-06-29": "期末考试", "2017-06-30": "期末考试" } } ``` * 基于模块导入使用 ```python first_day = "2017-02-27" week_num = 18 beauty = True events = { "2017-02-25": "本科生和研究生老生到校注册", "2017-02-26": "本科生和研究生老生到校注册", "2017-02-27": "春季学期开始上课", "2017-02-28": "2017春博士新生报到", "2017-04-02": "清明节放假调休3天", "2017-04-03": "清明节放假调休3天", "2017-04-04": "清明节放假调休3天", "2017-04-29": "劳动节放假3天", "2017-04-30": "劳动节放假3天", "2017-05-01": "劳动节放假3天", "2017-05-26": "校运动会", "2017-05-27": "校运动会", "2017-05-28": "端午节放假调休3天", "2017-05-29": "端午节放假调休3天", "2017-05-30": "端午节放假调休3天", "2017-06-26": "期末考试", "2017-06-27": "期末考试", "2017-06-28": "期末考试", "2017-06-29": "期末考试", "2017-06-30": "期末考试" } app = CalenderApp(first_day, week_num, events, beauty) result = app.gen_json() ``` * API Server访问 * 基于标准get请求,提供8位开始及结束日期 * http://server/?start=20170225&end=20170228 ### 返回结果 * 返回一个json对象,格式如下: ```json { "weeks": [ { "dates": [ { "date": "2017-02-27", "weekday": 1, "events": "\u6625\u5b63\u5b66\u671f\u5f00\u59cb\u4e0a\u8bfe" }, { "date": "2017-02-28", "weekday": 2, "events": "2017\u6625\u535a\u58eb\u65b0\u751f\u62a5\u5230" }, { "date": "2017-03-01", "weekday": 3, "events": null }, { "date": "2017-03-02", "weekday": 4, "events": null }, { "date": "2017-03-03", "weekday": 5, "events": null }, { "date": "2017-03-04", "weekday": 6, "events": null }, { "date": "2017-03-05", "weekday": 7, "events": null } ], "week_number": 1 } ] } ``` * 字段说明: * weeks: 周次列表,装有每周的信息 * week_number: 周次号,即本学期的第几周 * dates: 天列表,装有一周中每天的信息 * date: 日期,格式"yyyy-mm-dd" * weekday: 星期几,用1-7表示周一到周日 * events: 本日事件,字符串,无则为null,注意:此处为unicode编码,直接使用文本编辑器打开显示为编码,浏览器或程序读入后正常显示中文。 * API Server返回结果同为json格式,示例如下: ```json { "errcode": 0, "errmsg": "ok", "events": [ { "eventid": 364761512, "end": "2017-02-27 00:00", "description": "\u672c\u79d1\u751f\u548c\u7814\u7a76\u751f\u8001\u751f\u5230\u6821\u6ce8\u518c", "title": "\u672c\u79d1\u751f\u548c\u7814\u7a76\u751f\u8001\u751f\u5230\u6821\u6ce8\u518c", "url": "", "start": "2017-02-26 00:00", "address": "" }, { "eventid": 364761509, "end": "2017-02-26 00:00", "description": "\u672c\u79d1\u751f\u548c\u7814\u7a76\u751f\u8001\u751f\u5230\u6821\u6ce8\u518c", "title": "\u672c\u79d1\u751f\u548c\u7814\u7a76\u751f\u8001\u751f\u5230\u6821\u6ce8\u518c", "url": "", "start": "2017-02-25 00:00", "address": "" } ] } ``` * 字段说明 * errcode: 返回码 * errmsg: 对返回码的本文描述 * events: 日程事件数组 * eventid: 事件id * title: 事件标题 * description: 事件描述 * start: 开始时间 * end: 结束时间 * address: 事件地址 * url: 详情页面 ### 联系作者 * 版权所有:哈尔滨工业大学网络与信息中心 哈尔滨工业大学Pureweber开发组 * 作者: yumendy * Email:<EMAIL><file_sep>/CalenderAPIServer.py import json import datetime import web class Redirect(object): def GET(self, path): web.seeother('/' + path) class Event(object): def __init__(self, date, event): self.date = datetime.date(*tuple(map(int, date.split('-')))) self.event = event class APIServer(object): def __init__(self): self.event_list = [] with open('input.json') as fp: temp = json.load(fp) self.event_list = [Event(date, event) for date, event in temp['events'].iteritems()] def __query_event(self, start, end): start = datetime.date(*tuple(map(int, [start[:4], start[4:6], start[6:]]))) end = datetime.date(*tuple(map(int, [end[:4], end[4:6], end[6:]]))) return filter(lambda event: start <= event.date <= end, self.event_list) def __gen_json(self, event_list): result = { 'errcode': 0, 'errmsg': 'ok', 'events': [] } for event in event_list: ev = { 'eventid': abs(hash(event.date.strftime("%Y-%m-%d"))), 'title': event.event, 'description': event.event, 'start': event.date.strftime("%Y-%m-%d %H:%M"), 'end': (event.date + datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M"), 'address': '', 'url': '' } result['events'].append(ev) return json.dumps(result, indent=4) def query(self, start, end): return self.__gen_json(self.__query_event(start, end)) def GET(self): return self.query(web.input()['start'], web.input()['end']) if __name__ == '__main__': url = ( '/(.*)/', 'Redirect', '/', 'APIServer' ) app = web.application(url, globals()) app.run()
fb2f765241644921fdf8bb3cddf3984e3890cc79
[ "Markdown", "Python" ]
3
Python
yumendy/HIT_school_calender
98052d828e2c2fec20d1762c8d45912acef39dba
7805a3eb18ca375ba7f6198b2e0c9543adc83c10
refs/heads/master
<repo_name>dydcfg/tree<file_sep>/pytree.py #!/usr/bin/env python3 import subprocess import sys import os from os import listdir, walk from os.path import isdir, isfile, dirname, abspath # YOUR CODE GOES here MID_LEVEL_DIR = '│ ' MID_LEVEL_SPACE = " " LAST_LEVEL = '├── ' LAST_LEVEL_LAST_ITEM = '└── ' def addPrefix(prefix): s = "" for x in prefix: s = s + x return s def tree(dirPath, prefix=[]): if(len(prefix) == 0): print(dirPath) elements = sorted(listdir(dirPath)) nElement = len(elements) nDirs = 0 nFiles = 0 count = 0 for item in elements: count = count + 1 if not item.startswith('.'): s = addPrefix(prefix) if(isdir(dirPath + '/' + item)): nDirs = nDirs + 1 prefix.append(MID_LEVEL_DIR) if(count == nElement): prefix[-1] = MID_LEVEL_SPACE print(s + LAST_LEVEL_LAST_ITEM + item) else: print(s + LAST_LEVEL + item) x, y = tree(dirPath=dirPath + '/' + item, prefix=prefix) nDirs = nDirs + x nFiles = nFiles + y del prefix[-1] else: nFiles = nFiles + 1 if(count == nElement): print(s + LAST_LEVEL_LAST_ITEM + item) else: print(s + LAST_LEVEL + item) return nDirs, nFiles if __name__ == '__main__': # just for demo # subprocess.run(['tree'] + sys.argv[1:]) if len(sys.argv) == 2 and isdir(sys.argv[1]): nDirs, nFiles = tree(sys.argv[1]) else: nDirs, nFiles = tree(".") print("\n" + str(nDirs) + " directories, " + str(nFiles) + " files")
41db07c51626edb3a1224aeb51c528b8c56717f2
[ "Python" ]
1
Python
dydcfg/tree
aea1be5c34e4e10ffa25ea696647f2bb6542ae6f
3265391cad08dd8d7e452e34e08a9fc31db56da9
refs/heads/master
<repo_name>memfiz/tmux.conf<file_sep>/tmux.sh tmux has-session -t ct if [ $? != 0 ] #if [ $? == 0 ] then tmux new-session -s ct -n ct -d tmux send-keys -t ct 'cd ~/' C-m tmux send-keys -t ct 'vim' C-m tmux split-window -v -t ct tmux select-layout -t ct main-horizontal tmux send-keys -t ct:1.2 'cd ~/' C-m tmux new-window -n console -t ct tmux send-keys -t ct:2 'cd ~/' C-m tmux select-window -t ct:1 fi tmux attach -t ct
4a42fc6ba8e263231be98bf2800c6e941892dec6
[ "Shell" ]
1
Shell
memfiz/tmux.conf
e838cb977f6be1390b8810cdf470b077c7caf502
b33a2a394d89473d3a8fa7351de51bdf5385c51e
refs/heads/master
<repo_name>bekarice/simple-registration-for-woocommerce<file_sep>/sake.config.js module.exports = { deploy: { type: 'local' }, framework: false, multiPluginRepo: false, paths: { src: 'plugin' } } <file_sep>/readme.md ## Simple registration for WooCommerce Adds simple registration forms to WooCommerce. **Requires PHP 5.4+**. ### Description This plugin makes it easy to include a registration form for WooCommerce stores. Use the `[wc_registration_form]` shortcode to display the registration form on your site. You can optionally add a few attributes: - `button` = changes the text for the form submission button - `show_names` = override the global setting to show name fields (accepts "yes" or "no") - `require_names` = override the global setting to require name fields (accepts "yes" or "no") This makes it easy to create new users, which could be synced to additional apps, such as [Jilt](https://jilt.com/). Inspired by [WC Simple Registration](https://github.com/Astoundify/wc-simple-registration) from Astoundify. ### Development Be sure to follow WordPress development guidelines.
4bfc794a76c4c735a46a542ff610ca64edaa485d
[ "JavaScript", "Markdown" ]
2
JavaScript
bekarice/simple-registration-for-woocommerce
1748ee99c8982c269d3a3e1d8d41325058cd6db9
475cee71a26756fed59bc0806255c17814111943
refs/heads/master
<repo_name>utilcollect/demo<file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/CreditPayeeDirectCertMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.CreditPayeeDirectCert; public interface CreditPayeeDirectCertMapper { int deleteByPrimaryKey(Long nFundId); int insert(CreditPayeeDirectCert record); int insertSelective(CreditPayeeDirectCert record); CreditPayeeDirectCert selectByPrimaryKey(Long nFundId); int updateByPrimaryKeySelective(CreditPayeeDirectCert record); int updateByPrimaryKey(CreditPayeeDirectCert record); }<file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/HcUserInfoMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.HcUserInfo; public interface HcUserInfoMapper { int deleteByPrimaryKey(Long nUserId); int insert(HcUserInfo record); int insertSelective(HcUserInfo record); HcUserInfo selectByPrimaryKey(Long nUserId); int updateByPrimaryKeySelective(HcUserInfo record); int updateByPrimaryKey(HcUserInfo record); }<file_sep>/src/main/java/com/gezhiwei/demo/vo/PayRedPacketResVo.java package com.gezhiwei.demo.vo; /** * @ClassName: PayRedPacketResVo * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/23 19:11 * @modified By: */ public class PayRedPacketResVo { // 0 微信支付 2 抵扣券支付 private Integer type; private Long redPacketId; private DapH5SubPayRes dapH5SubPayRes; public Integer getType() { return type; } public PayRedPacketResVo setType(Integer type) { this.type = type; return this; } public Long getRedPacketId() { return redPacketId; } public PayRedPacketResVo setRedPacketId(Long redPacketId) { this.redPacketId = redPacketId; return this; } public DapH5SubPayRes getDapH5SubPayRes() { return dapH5SubPayRes; } public PayRedPacketResVo setDapH5SubPayRes(DapH5SubPayRes dapH5SubPayRes) { this.dapH5SubPayRes = dapH5SubPayRes; return this; } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/HcArea.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class HcArea { private Long nAreaId; private String sAreaCode; private String sAreaName; private String sAreaNameAbbr; private Integer nLevel; private String sCityCode; private String sCenter; private Long nParentId; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; public Long getnAreaId() { return nAreaId; } public void setnAreaId(Long nAreaId) { this.nAreaId = nAreaId; } public String getsAreaCode() { return sAreaCode; } public void setsAreaCode(String sAreaCode) { this.sAreaCode = sAreaCode == null ? null : sAreaCode.trim(); } public String getsAreaName() { return sAreaName; } public void setsAreaName(String sAreaName) { this.sAreaName = sAreaName == null ? null : sAreaName.trim(); } public String getsAreaNameAbbr() { return sAreaNameAbbr; } public void setsAreaNameAbbr(String sAreaNameAbbr) { this.sAreaNameAbbr = sAreaNameAbbr == null ? null : sAreaNameAbbr.trim(); } public Integer getnLevel() { return nLevel; } public void setnLevel(Integer nLevel) { this.nLevel = nLevel; } public String getsCityCode() { return sCityCode; } public void setsCityCode(String sCityCode) { this.sCityCode = sCityCode == null ? null : sCityCode.trim(); } public String getsCenter() { return sCenter; } public void setsCenter(String sCenter) { this.sCenter = sCenter == null ? null : sCenter.trim(); } public Long getnParentId() { return nParentId; } public void setnParentId(Long nParentId) { this.nParentId = nParentId; } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/vo/GrabRedPacketVo.java package com.gezhiwei.demo.vo; /** * @ClassName: GrabRedPacketVo * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/22 15:06 * @modified By: */ public class GrabRedPacketVo { // 0 未抢到 或者 过期 1 抢到红包 2 抢到锦鲤 3已经抢过 private Integer status; private DdhzRedPacketDetailInfoDTO ddhzRedPacketDetailInfoDTO; public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public DdhzRedPacketDetailInfoDTO getDdhzRedPacketDetailInfoDTO() { return ddhzRedPacketDetailInfoDTO; } public void setDdhzRedPacketDetailInfoDTO(DdhzRedPacketDetailInfoDTO ddhzRedPacketDetailInfoDTO) { this.ddhzRedPacketDetailInfoDTO = ddhzRedPacketDetailInfoDTO; } } <file_sep>/src/main/java/com/gezhiwei/demo/config/RoleEnum.java package com.gezhiwei.demo.config; /** * 角色枚举类 */ public enum RoleEnum { NO_ROLE(0, "未设置"), COMMUNITY_WORKER_MANAGER(1, "社工管理员"), COMMUNITY_WORKER(2, "社工"), VOLUNTEER(3, "志愿者"), HOSPITAL_LEADER(4, "医院领导"), ORGANIZATION(5, "机构"); private Integer code; private String desc; RoleEnum(int code, String desc) { this.code = code; this.desc = desc; } public Integer getCode() { return code; } public String getDesc() { return desc; } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/HcUserBaseInfo.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class HcUserBaseInfo { private Long nUserId; private String sLoginName; private String sMobileNumber; private String sThdPartId; private String sNickName; private String sRealName; private String sIdcardNumber; private String sPassword; private String sPayPassword; private Integer nStatus; private Date dRegisterTime; private Date dLastLoginTime; private String sPlatformVersion; private String sPlatformCode; private String sAppVersion; private String sPhoneName; private String sUuid; private Integer nAppVersionNum; private String sIpaddress; private String sThirdGroupId; private String sRemark; private String sFaceUrl; private Date dCertificationTime; private Integer nApproveStatus; private String sSignature; private Integer nSex; private Date dBirthDate; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; private String sOldMobileNumber; private String sQrCode; private String sQrCodeUrl; public Long getnUserId() { return nUserId; } public void setnUserId(Long nUserId) { this.nUserId = nUserId; } public String getsLoginName() { return sLoginName; } public void setsLoginName(String sLoginName) { this.sLoginName = sLoginName == null ? null : sLoginName.trim(); } public String getsMobileNumber() { return sMobileNumber; } public void setsMobileNumber(String sMobileNumber) { this.sMobileNumber = sMobileNumber == null ? null : sMobileNumber.trim(); } public String getsThdPartId() { return sThdPartId; } public void setsThdPartId(String sThdPartId) { this.sThdPartId = sThdPartId == null ? null : sThdPartId.trim(); } public String getsNickName() { return sNickName; } public void setsNickName(String sNickName) { this.sNickName = sNickName == null ? null : sNickName.trim(); } public String getsRealName() { return sRealName; } public void setsRealName(String sRealName) { this.sRealName = sRealName == null ? null : sRealName.trim(); } public String getsIdcardNumber() { return sIdcardNumber; } public void setsIdcardNumber(String sIdcardNumber) { this.sIdcardNumber = sIdcardNumber == null ? null : sIdcardNumber.trim(); } public String getsPassword() { return sPassword; } public void setsPassword(String sPassword) { this.sPassword = sPassword == null ? null : sPassword.trim(); } public String getsPayPassword() { return sPayPassword; } public void setsPayPassword(String sPayPassword) { this.sPayPassword = sPayPassword == null ? null : sPayPassword.trim(); } public Integer getnStatus() { return nStatus; } public void setnStatus(Integer nStatus) { this.nStatus = nStatus; } public Date getdRegisterTime() { return dRegisterTime; } public void setdRegisterTime(Date dRegisterTime) { this.dRegisterTime = dRegisterTime; } public Date getdLastLoginTime() { return dLastLoginTime; } public void setdLastLoginTime(Date dLastLoginTime) { this.dLastLoginTime = dLastLoginTime; } public String getsPlatformVersion() { return sPlatformVersion; } public void setsPlatformVersion(String sPlatformVersion) { this.sPlatformVersion = sPlatformVersion == null ? null : sPlatformVersion.trim(); } public String getsPlatformCode() { return sPlatformCode; } public void setsPlatformCode(String sPlatformCode) { this.sPlatformCode = sPlatformCode == null ? null : sPlatformCode.trim(); } public String getsAppVersion() { return sAppVersion; } public void setsAppVersion(String sAppVersion) { this.sAppVersion = sAppVersion == null ? null : sAppVersion.trim(); } public String getsPhoneName() { return sPhoneName; } public void setsPhoneName(String sPhoneName) { this.sPhoneName = sPhoneName == null ? null : sPhoneName.trim(); } public String getsUuid() { return sUuid; } public void setsUuid(String sUuid) { this.sUuid = sUuid == null ? null : sUuid.trim(); } public Integer getnAppVersionNum() { return nAppVersionNum; } public void setnAppVersionNum(Integer nAppVersionNum) { this.nAppVersionNum = nAppVersionNum; } public String getsIpaddress() { return sIpaddress; } public void setsIpaddress(String sIpaddress) { this.sIpaddress = sIpaddress == null ? null : sIpaddress.trim(); } public String getsThirdGroupId() { return sThirdGroupId; } public void setsThirdGroupId(String sThirdGroupId) { this.sThirdGroupId = sThirdGroupId == null ? null : sThirdGroupId.trim(); } public String getsRemark() { return sRemark; } public void setsRemark(String sRemark) { this.sRemark = sRemark == null ? null : sRemark.trim(); } public String getsFaceUrl() { return sFaceUrl; } public void setsFaceUrl(String sFaceUrl) { this.sFaceUrl = sFaceUrl == null ? null : sFaceUrl.trim(); } public Date getdCertificationTime() { return dCertificationTime; } public void setdCertificationTime(Date dCertificationTime) { this.dCertificationTime = dCertificationTime; } public Integer getnApproveStatus() { return nApproveStatus; } public void setnApproveStatus(Integer nApproveStatus) { this.nApproveStatus = nApproveStatus; } public String getsSignature() { return sSignature; } public void setsSignature(String sSignature) { this.sSignature = sSignature == null ? null : sSignature.trim(); } public Integer getnSex() { return nSex; } public void setnSex(Integer nSex) { this.nSex = nSex; } public Date getdBirthDate() { return dBirthDate; } public void setdBirthDate(Date dBirthDate) { this.dBirthDate = dBirthDate; } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } public String getsOldMobileNumber() { return sOldMobileNumber; } public void setsOldMobileNumber(String sOldMobileNumber) { this.sOldMobileNumber = sOldMobileNumber == null ? null : sOldMobileNumber.trim(); } public String getsQrCode() { return sQrCode; } public void setsQrCode(String sQrCode) { this.sQrCode = sQrCode == null ? null : sQrCode.trim(); } public String getsQrCodeUrl() { return sQrCodeUrl; } public void setsQrCodeUrl(String sQrCodeUrl) { this.sQrCodeUrl = sQrCodeUrl == null ? null : sQrCodeUrl.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/vo/DdhzRedPacketDetailDTO.java package com.gezhiwei.demo.vo; import com.alibaba.fastjson.annotation.JSONField; import java.util.Date; /** * Created by Wayne on 2019/1/15. */ public class DdhzRedPacketDetailDTO { //红包ID private Long redPacketId; //用户昵称 private String userName; //头像 private String face; //是否新注册用户:0-否,1-是 private Integer newUser; //是否锦鲤:0-否,1-是 private Integer vipHealth; //是否激活 private Integer status; //创建时间 @JSONField(format = "yyyy-MM-dd HH:mm") private Date createTime; public Long getRedPacketId() { return redPacketId; } public void setRedPacketId(Long redPacketId) { this.redPacketId = redPacketId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getFace() { return face; } public void setFace(String face) { this.face = face; } public Integer getNewUser() { return newUser; } public void setNewUser(Integer newUser) { this.newUser = newUser; } public Integer getVipHealth() { return vipHealth; } public void setVipHealth(Integer vipHealth) { this.vipHealth = vipHealth; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/CreditPayeeTypeMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.CreditPayeeType; public interface CreditPayeeTypeMapper { int deleteByPrimaryKey(Long nFundId); int insert(CreditPayeeType record); int insertSelective(CreditPayeeType record); CreditPayeeType selectByPrimaryKey(Long nFundId); int updateByPrimaryKeySelective(CreditPayeeType record); int updateByPrimaryKey(CreditPayeeType record); }<file_sep>/src/test/java/com/gezhiwei/demo/DaysTest.java package com.gezhiwei.demo; /** * @ClassName: DaysTest * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/9 21:06 * @modified By: */ public class DaysTest { } <file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/HcWorkerVolunteerRelationMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.HcWorkerVolunteerRelation; public interface HcWorkerVolunteerRelationMapper { int deleteByPrimaryKey(Long nId); int insert(HcWorkerVolunteerRelation record); int insertSelective(HcWorkerVolunteerRelation record); HcWorkerVolunteerRelation selectByPrimaryKey(Long nId); int updateByPrimaryKeySelective(HcWorkerVolunteerRelation record); int updateByPrimaryKey(HcWorkerVolunteerRelation record); }<file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/HcUserBaseInfoMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.HcUserBaseInfo; public interface HcUserBaseInfoMapper { int deleteByPrimaryKey(Long nUserId); int insert(HcUserBaseInfo record); int insertSelective(HcUserBaseInfo record); HcUserBaseInfo selectByPrimaryKey(Long nUserId); int updateByPrimaryKeySelective(HcUserBaseInfo record); int updateByPrimaryKey(HcUserBaseInfo record); }<file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/CreditPayeeSelfCertMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.CreditPayeeSelfCert; public interface CreditPayeeSelfCertMapper { int deleteByPrimaryKey(Long nFundId); int insert(CreditPayeeSelfCert record); int insertSelective(CreditPayeeSelfCert record); CreditPayeeSelfCert selectByPrimaryKey(Long nFundId); int updateByPrimaryKeySelective(CreditPayeeSelfCert record); int updateByPrimaryKey(CreditPayeeSelfCert record); }<file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/HcFundStatusTimeMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.HcFundStatusTime; public interface HcFundStatusTimeMapper { int deleteByPrimaryKey(Integer nId); int insert(HcFundStatusTime record); int insertSelective(HcFundStatusTime record); HcFundStatusTime selectByPrimaryKey(Integer nId); int updateByPrimaryKeySelective(HcFundStatusTime record); int updateByPrimaryKey(HcFundStatusTime record); }<file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/CreditPayeeType.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class CreditPayeeType { private Long nFundId; private Integer type; private Integer nCompleteStatus; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; public Long getnFundId() { return nFundId; } public void setnFundId(Long nFundId) { this.nFundId = nFundId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getnCompleteStatus() { return nCompleteStatus; } public void setnCompleteStatus(Integer nCompleteStatus) { this.nCompleteStatus = nCompleteStatus; } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/vo/DdhzRedPacketDetailInfoDTO.java package com.gezhiwei.demo.vo; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * Created by Wayne on 2019/1/15. */ public class DdhzRedPacketDetailInfoDTO { //头像 private String face; //昵称 private String nickName; //文言 private String content; //状态:0-未中奖,1-普通红包,2-锦鲤 private Integer status; //保障期 private Integer month; //价值 private BigDecimal amount; //服务期 private Integer vipMonth; //价值 private BigDecimal vipAmount; //新用户个数 private Integer newUserCount; //预计收益 private BigDecimal pendingIncome; //已领取 private Integer open; //总数 private Integer total; //产生锦鲤个数 private Integer openVip; //锦鲤总个数 private Integer totalVip; //领取详情 private List<DdhzRedPacketDetailDTO> redPacketDetails = new ArrayList<>(); public String getFace() { return face; } public void setFace(String face) { this.face = face; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Integer getNewUserCount() { return newUserCount; } public void setNewUserCount(Integer newUserCount) { this.newUserCount = newUserCount; } public BigDecimal getPendingIncome() { return pendingIncome; } public void setPendingIncome(BigDecimal pendingIncome) { this.pendingIncome = pendingIncome; } public Integer getOpen() { return open; } public void setOpen(Integer open) { this.open = open; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Integer getOpenVip() { return openVip; } public void setOpenVip(Integer openVip) { this.openVip = openVip; } public Integer getTotalVip() { return totalVip; } public void setTotalVip(Integer totalVip) { this.totalVip = totalVip; } public List<DdhzRedPacketDetailDTO> getRedPacketDetails() { return redPacketDetails; } public void setRedPacketDetails(List<DdhzRedPacketDetailDTO> redPacketDetails) { this.redPacketDetails = redPacketDetails; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getMonth() { return month; } public void setMonth(Integer month) { this.month = month; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Integer getVipMonth() { return vipMonth; } public void setVipMonth(Integer vipMonth) { this.vipMonth = vipMonth; } public BigDecimal getVipAmount() { return vipAmount; } public void setVipAmount(BigDecimal vipAmount) { this.vipAmount = vipAmount; } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/CreditPayeeHospitalCert.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class CreditPayeeHospitalCert { private Long nFundId; private String sHosptialNo; private String sDepartNo; private String sBedNo; private String sBankAccountName; private String sBankCode; private String sBankName; private String sDepositBank; private String sBankAccount; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; public Long getnFundId() { return nFundId; } public void setnFundId(Long nFundId) { this.nFundId = nFundId; } public String getsHosptialNo() { return sHosptialNo; } public void setsHosptialNo(String sHosptialNo) { this.sHosptialNo = sHosptialNo == null ? null : sHosptialNo.trim(); } public String getsDepartNo() { return sDepartNo; } public void setsDepartNo(String sDepartNo) { this.sDepartNo = sDepartNo == null ? null : sDepartNo.trim(); } public String getsBedNo() { return sBedNo; } public void setsBedNo(String sBedNo) { this.sBedNo = sBedNo == null ? null : sBedNo.trim(); } public String getsBankAccountName() { return sBankAccountName; } public void setsBankAccountName(String sBankAccountName) { this.sBankAccountName = sBankAccountName == null ? null : sBankAccountName.trim(); } public String getsBankCode() { return sBankCode; } public void setsBankCode(String sBankCode) { this.sBankCode = sBankCode == null ? null : sBankCode.trim(); } public String getsBankName() { return sBankName; } public void setsBankName(String sBankName) { this.sBankName = sBankName == null ? null : sBankName.trim(); } public String getsDepositBank() { return sDepositBank; } public void setsDepositBank(String sDepositBank) { this.sDepositBank = sDepositBank == null ? null : sDepositBank.trim(); } public String getsBankAccount() { return sBankAccount; } public void setsBankAccount(String sBankAccount) { this.sBankAccount = sBankAccount == null ? null : sBankAccount.trim(); } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/vo/CreateRedPacketVo.java package com.gezhiwei.demo.vo; import java.math.BigDecimal; import java.util.List; /** * @ClassName: CreateRedPackageVo * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/14 19:05 * @modified By: */ public class CreateRedPacketVo { private Integer redPackageNum; private Integer packageId; private Integer vipHealthNum; private List<Long> voucherIds; private BigDecimal amount; private String content; public Integer getRedPackageNum() { return redPackageNum; } public CreateRedPacketVo setRedPackageNum(Integer redPackageNum) { this.redPackageNum = redPackageNum; return this; } public Integer getPackageId() { return packageId; } public CreateRedPacketVo setPackageId(Integer packageId) { this.packageId = packageId; return this; } public Integer getVipHealthNum() { return vipHealthNum; } public CreateRedPacketVo setVipHealthNum(Integer vipHealthNum) { this.vipHealthNum = vipHealthNum; return this; } public List<Long> getVoucherIds() { return voucherIds; } public CreateRedPacketVo setVoucherIds(List<Long> voucherIds) { this.voucherIds = voucherIds; return this; } public BigDecimal getAmount() { return amount; } public CreateRedPacketVo setAmount(BigDecimal amount) { this.amount = amount; return this; } public String getContent() { return content; } public CreateRedPacketVo setContent(String content) { this.content = content; return this; } } <file_sep>/src/test/java/com/gezhiwei/demo/CommonTest.java package com.gezhiwei.demo; import org.junit.Test; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * @ClassName: CommonTest * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/3 19:09 * @modified By: */ public class CommonTest { private static final int ONE_WEEK = 7; private static final int EIGHT_WEEKS = 8 * ONE_WEEK; @Test public void test() { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, 2018); calendar.set(Calendar.MONTH, Calendar.NOVEMBER); calendar.set(Calendar.DAY_OF_MONTH, 28); Date t1 = calendar.getTime(); calendar.add(Calendar.DAY_OF_WEEK, EIGHT_WEEKS); Date t2 = calendar.getTime(); System.out.println(sf.format(t1)); System.out.println(sf.format(t2)); } @Test public void test2(){ String sql = "select dup.n_plan_id as planId," + "dp.s_name as planName," + "sum(case where dup.n_status =1 then 1 else 0 end) as waitPeople," + "sum(case where dup.n_status =2 then 1 else 0 end) as effiectivePeople," + "sum(case where dup.n_status =3 then 1 else 0 end) as gracePeople," + "sum(case where dup.n_quit_reason_type =3 then 1 else 0 end) as achievePeople," + "sum(case where dup.n_status =4 then 1 else 0 end) as exitPeople," + "sum(dup.n_qtt_gold) as qttGold " + " from ddhz_user_plan dup " + "left join ddhz_plan dp on dp.n_id = dup.n_plan_id " + "where dup.s_source = 'qtt'"; System.out.println(sql); } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/HcHospital.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class HcHospital { private Long nId; private String sCode; private String sLogo; private Integer nLevel; private String sName; private String sPhone; private Long nProvinceId; private String sProvinceName; private Long nCityId; private String sCityName; private Long nAreaId; private String sAreaName; private String sAddress; private String sLicence; private String sComment; private Integer nStatus; private String sReason; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; private Date dApproveTime; public Long getnId() { return nId; } public void setnId(Long nId) { this.nId = nId; } public String getsCode() { return sCode; } public void setsCode(String sCode) { this.sCode = sCode == null ? null : sCode.trim(); } public String getsLogo() { return sLogo; } public void setsLogo(String sLogo) { this.sLogo = sLogo == null ? null : sLogo.trim(); } public Integer getnLevel() { return nLevel; } public void setnLevel(Integer nLevel) { this.nLevel = nLevel; } public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName == null ? null : sName.trim(); } public String getsPhone() { return sPhone; } public void setsPhone(String sPhone) { this.sPhone = sPhone == null ? null : sPhone.trim(); } public Long getnProvinceId() { return nProvinceId; } public void setnProvinceId(Long nProvinceId) { this.nProvinceId = nProvinceId; } public String getsProvinceName() { return sProvinceName; } public void setsProvinceName(String sProvinceName) { this.sProvinceName = sProvinceName == null ? null : sProvinceName.trim(); } public Long getnCityId() { return nCityId; } public void setnCityId(Long nCityId) { this.nCityId = nCityId; } public String getsCityName() { return sCityName; } public void setsCityName(String sCityName) { this.sCityName = sCityName == null ? null : sCityName.trim(); } public Long getnAreaId() { return nAreaId; } public void setnAreaId(Long nAreaId) { this.nAreaId = nAreaId; } public String getsAreaName() { return sAreaName; } public void setsAreaName(String sAreaName) { this.sAreaName = sAreaName == null ? null : sAreaName.trim(); } public String getsAddress() { return sAddress; } public void setsAddress(String sAddress) { this.sAddress = sAddress == null ? null : sAddress.trim(); } public String getsLicence() { return sLicence; } public void setsLicence(String sLicence) { this.sLicence = sLicence == null ? null : sLicence.trim(); } public String getsComment() { return sComment; } public void setsComment(String sComment) { this.sComment = sComment == null ? null : sComment.trim(); } public Integer getnStatus() { return nStatus; } public void setnStatus(Integer nStatus) { this.nStatus = nStatus; } public String getsReason() { return sReason; } public void setsReason(String sReason) { this.sReason = sReason == null ? null : sReason.trim(); } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } public Date getdApproveTime() { return dApproveTime; } public void setdApproveTime(Date dApproveTime) { this.dApproveTime = dApproveTime; } }<file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/HcUserThirdInfo.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class HcUserThirdInfo { private Long nId; private Long nUserId; private String sThirdId; private String sThirdName; private String sRegisterType; private Integer nIsAppAccount; private Date dRegisterTime; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; private String sSysCode; private String sThirdGroupId; private Integer nThdPartConcern; private String sChannelCategory; private String sChannelSubCategory; private Integer sChannelType; public Long getnId() { return nId; } public void setnId(Long nId) { this.nId = nId; } public Long getnUserId() { return nUserId; } public void setnUserId(Long nUserId) { this.nUserId = nUserId; } public String getsThirdId() { return sThirdId; } public void setsThirdId(String sThirdId) { this.sThirdId = sThirdId == null ? null : sThirdId.trim(); } public String getsThirdName() { return sThirdName; } public void setsThirdName(String sThirdName) { this.sThirdName = sThirdName == null ? null : sThirdName.trim(); } public String getsRegisterType() { return sRegisterType; } public void setsRegisterType(String sRegisterType) { this.sRegisterType = sRegisterType == null ? null : sRegisterType.trim(); } public Integer getnIsAppAccount() { return nIsAppAccount; } public void setnIsAppAccount(Integer nIsAppAccount) { this.nIsAppAccount = nIsAppAccount; } public Date getdRegisterTime() { return dRegisterTime; } public void setdRegisterTime(Date dRegisterTime) { this.dRegisterTime = dRegisterTime; } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } public String getsSysCode() { return sSysCode; } public void setsSysCode(String sSysCode) { this.sSysCode = sSysCode == null ? null : sSysCode.trim(); } public String getsThirdGroupId() { return sThirdGroupId; } public void setsThirdGroupId(String sThirdGroupId) { this.sThirdGroupId = sThirdGroupId == null ? null : sThirdGroupId.trim(); } public Integer getnThdPartConcern() { return nThdPartConcern; } public void setnThdPartConcern(Integer nThdPartConcern) { this.nThdPartConcern = nThdPartConcern; } public String getsChannelCategory() { return sChannelCategory; } public void setsChannelCategory(String sChannelCategory) { this.sChannelCategory = sChannelCategory == null ? null : sChannelCategory.trim(); } public String getsChannelSubCategory() { return sChannelSubCategory; } public void setsChannelSubCategory(String sChannelSubCategory) { this.sChannelSubCategory = sChannelSubCategory == null ? null : sChannelSubCategory.trim(); } public Integer getsChannelType() { return sChannelType; } public void setsChannelType(Integer sChannelType) { this.sChannelType = sChannelType; } }<file_sep>/src/test/java/com/gezhiwei/demo/OpenCV.java package com.gezhiwei.demo; import org.opencv.core.*; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; import java.io.File; import java.io.InputStream; /** * @ClassName: OpenCV * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/2/11 15:55 * @modified By: */ public class OpenCV { private static void loadLibraries() { try { InputStream in = null; File fileOut = null; String osName = System.getProperty("os.name"); String opencvpath = "C:\\opencv\\build\\java"; if (osName.startsWith("Windows")) { int bitness = Integer.parseInt(System.getProperty("sun.arch.data.model")); if (bitness == 32) { opencvpath = opencvpath + "\\x86\\"; } else if (bitness == 64) { opencvpath = opencvpath + "\\x64\\"; } else { opencvpath = opencvpath + "\\x86\\"; } } else if (osName.equals("Mac OS X")) { opencvpath = opencvpath + "Your path to .dylib"; } System.out.println(opencvpath); System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll"); } catch (Exception e) { throw new RuntimeException("Failed to load opencv native library", e); } } public static void main(String[] args) { loadLibraries(); System.out.println("sdf"); System.out.println("Hello, OpenCV"); // Load the native library. new OpenCV().run(); } public void run() { System.out.println("\nRunning DetectFaceDemo"); // Create a face detector from the cascade file in the resources // directory. String templateFilePath = "C:\\Users\\gezhiwei\\Downloads\\s\\mmexport1537330794444.jpg"; String originalFilePath = "C:\\Users\\gezhiwei\\Downloads\\s\\mmexport1537330798654.jpg"; String originalFilePath1 = "C:\\Users\\gezhiwei\\Downloads\\s\\mmexport1537330871815.jpg"; //读取图片文件 Mat image = Imgcodecs.imread(originalFilePath1); // Mat image = Imgcodecs.imread(originalFilePath); File ff = new File("E:\\open_sources\\opencv\\data\\haarcascades\\haarcascade_lowerbody.xml"); CascadeClassifier faceDetector = new CascadeClassifier(ff.getAbsolutePath()); // Mat image = Imgcodecs.imread(getClass().getResource("/lena.png").getPath()); // Detect faces in the image. // MatOfRect is a special container class for Rect. MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // Draw a bounding box around each face. for (Rect rect : faceDetections.toArray()) { Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } // Save the visualized detection. String filename = "onss.png"; System.out.println(String.format("Writing %s", filename)); Imgcodecs.imwrite(filename, image); } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/HcHospitalMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.HcHospital; public interface HcHospitalMapper { int deleteByPrimaryKey(Long nId); int insert(HcHospital record); int insertSelective(HcHospital record); HcHospital selectByPrimaryKey(Long nId); int updateByPrimaryKeySelective(HcHospital record); int updateByPrimaryKey(HcHospital record); }<file_sep>/src/main/java/com/gezhiwei/demo/vo/back/UserPacketPriVo.java package com.gezhiwei.demo.vo.back; import com.alibaba.fastjson.annotation.JSONField; import java.math.BigDecimal; import java.util.Date; /** * @ClassName: UserPacketPriVo * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/17 20:47 * @modified By: */ public class UserPacketPriVo { private Long userId; private String userRealName; private String mobile; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date createTime; private Long redPacketId; private Integer packetNum; private BigDecimal keepAmount; private Integer vipHealthNum; private BigDecimal totalAmount; private BigDecimal payAmount; private BigDecimal lessAmount; private BigDecimal payBackAmount; public Long getUserId() { return userId; } public UserPacketPriVo setUserId(Long userId) { this.userId = userId; return this; } public String getUserRealName() { return userRealName; } public UserPacketPriVo setUserRealName(String userRealName) { this.userRealName = userRealName; return this; } public String getMobile() { return mobile; } public UserPacketPriVo setMobile(String mobile) { this.mobile = mobile; return this; } public Date getCreateTime() { return createTime; } public UserPacketPriVo setCreateTime(Date createTime) { this.createTime = createTime; return this; } public Long getRedPacketId() { return redPacketId; } public UserPacketPriVo setRedPacketId(Long redPacketId) { this.redPacketId = redPacketId; return this; } public BigDecimal getKeepAmount() { return keepAmount; } public UserPacketPriVo setKeepAmount(BigDecimal keepAmount) { this.keepAmount = keepAmount; return this; } public Integer getPacketNum() { return packetNum; } public UserPacketPriVo setPacketNum(Integer packetNum) { this.packetNum = packetNum; return this; } public Integer getVipHealthNum() { return vipHealthNum; } public UserPacketPriVo setVipHealthNum(Integer vipHealthNum) { this.vipHealthNum = vipHealthNum; return this; } public BigDecimal getTotalAmount() { return totalAmount; } public UserPacketPriVo setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; return this; } public BigDecimal getPayAmount() { return payAmount; } public UserPacketPriVo setPayAmount(BigDecimal payAmount) { this.payAmount = payAmount; return this; } public BigDecimal getLessAmount() { return lessAmount; } public UserPacketPriVo setLessAmount(BigDecimal lessAmount) { this.lessAmount = lessAmount; return this; } public BigDecimal getPayBackAmount() { return payBackAmount; } public UserPacketPriVo setPayBackAmount(BigDecimal payBackAmount) { this.payBackAmount = payBackAmount; return this; } } <file_sep>/src/test/java/com/gezhiwei/demo/RedisClear.java package com.gezhiwei.demo; import com.gezhiwei.demo.config.JedisClusterFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; /** * @ClassName: RedisClear * @Author: 葛志伟(赛事) * @Description: * @Date: 2018/12/19 14:06 * @modified By: */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisClear { private static final List<String> KEY_LIST = new ArrayList<>(); static { KEY_LIST.add("ddhz:user:new:id"); KEY_LIST.add("ddhz:incr:red:packet:id"); KEY_LIST.add("ddc:user:new:id"); KEY_LIST.add("gezhiwei:new:user"); } @Autowired private JedisClusterFactory redisCluster; @Test public void addTestKey() { redisCluster.incr("gezhiwei:new:user"); int i = 10; for (int i1 = 0; i1 < i; i1++) { redisCluster.set("gezhiwei:new:nuser:" + i1, String.valueOf(i1)); } } @Test public void clearFullALl() { TreeSet<String> all = redisCluster.keysAll("gezhiwei:*"); for (String key : all) { if (KEY_LIST.contains(key)) { continue; } System.out.println(key); redisCluster.del(key); } } @Test public void clearALl() { TreeSet<String> all = redisCluster.keysAll("hc:*"); all.forEach(System.out::println); all.forEach(a -> redisCluster.del(a)); } @Test public void clearUserInfo() { TreeSet<String> strings = redisCluster.keysAll("user:info:userid"); for (String string : strings) { redisCluster.del(string); } System.out.println("ok"); } @Test public void clearFundStatistics1() { TreeSet<String> strings = redisCluster.keysAll("hc:fund:statistics:volunteer:count:*"); for (String string : strings) { redisCluster.del(string); } } @Test public void clearFundStatistics2() { TreeSet<String> strings = redisCluster.keysAll("hc:fund:statistics:work:count:*"); for (String string : strings) { redisCluster.del(string); } } @Test public void clearFundStatistics3() { TreeSet<String> strings = redisCluster.keysAll("hc:fund:statistics:manager:count:*"); for (String string : strings) { redisCluster.del(string); } } @Test public void test() { String hget = redisCluster.hget("hc:user:info:userid", "13"); System.out.println(hget); } @Test public void testClearListR() { String key = "gezhiwei:list:test"; redisCluster.del(key); } @Test public void testRedisOne() { List<String> list = new ArrayList<>(); list.add("1"); list.add("0"); list.add("1"); list.add("0"); list.add("1"); list.add("3"); list.add("5"); list.add("9"); String key = "<KEY>list:test"; redisCluster.lpush(key, list); } @Test public void testPOp() { String key = "gezhiwei:list:test"; String lpop = redisCluster.rpop(key); System.out.println(lpop); } @Test public void testPO1p() { String key = "gezhiwei:list:test"; String lpop = "a"; while (!StringUtils.isEmpty(lpop)) { lpop = redisCluster.rpop(key); System.out.println(lpop); } } @Test public void testPO2p() { String key = "gezhiwei:list:test"; String lpop = "a"; lpop = redisCluster.rpop(key); System.out.println(lpop); } @Test public void testExsit() { String key = "gezhiwei:list:test"; if (redisCluster.exists(key)) { System.out.println("cunzai"); } else { System.out.println("not cunzai"); } } @Test public void testlrange() { int redPacketId = 21; String key = String.format("ddhz:red:packet:grab:%s", redPacketId); List<String> lrange = redisCluster.lrange(key, 0, 1000); System.out.println(lrange); } @Test public void testlrange1() { int redPacketId = 21; String key = String.format("gezhiwei:list:test", redPacketId); List<String> lrange = redisCluster.lrange(key, 0, -1); Long llen = redisCluster.llen(key); System.out.println("cahgdu " + llen); for (String s : lrange) { System.out.println(s); } System.out.println(lrange); } @Test public void tewst3() { int userId = 0; Long i = 1000000L; for (int aLong = 0; aLong < i; aLong++) { String key = String.format("ddhz:order:user:voucher:by:user:id:%s", aLong); redisCluster.del(key); } } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/CreditDiagnosisCert.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class CreditDiagnosisCert { private Long nId; private Long nFundId; private String sDiseases; private String sHospitalName; private String sProvinceName; private String sCityName; private String sHospitalAddr; private Integer nDiagnose; private String sDiagnosisCertPic; private String sOtherImages; private Integer nCompleteStatus; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; public Long getnId() { return nId; } public void setnId(Long nId) { this.nId = nId; } public Long getnFundId() { return nFundId; } public void setnFundId(Long nFundId) { this.nFundId = nFundId; } public String getsDiseases() { return sDiseases; } public void setsDiseases(String sDiseases) { this.sDiseases = sDiseases == null ? null : sDiseases.trim(); } public String getsHospitalName() { return sHospitalName; } public void setsHospitalName(String sHospitalName) { this.sHospitalName = sHospitalName == null ? null : sHospitalName.trim(); } public String getsProvinceName() { return sProvinceName; } public void setsProvinceName(String sProvinceName) { this.sProvinceName = sProvinceName == null ? null : sProvinceName.trim(); } public String getsCityName() { return sCityName; } public void setsCityName(String sCityName) { this.sCityName = sCityName == null ? null : sCityName.trim(); } public String getsHospitalAddr() { return sHospitalAddr; } public void setsHospitalAddr(String sHospitalAddr) { this.sHospitalAddr = sHospitalAddr == null ? null : sHospitalAddr.trim(); } public Integer getnDiagnose() { return nDiagnose; } public void setnDiagnose(Integer nDiagnose) { this.nDiagnose = nDiagnose; } public String getsDiagnosisCertPic() { return sDiagnosisCertPic; } public void setsDiagnosisCertPic(String sDiagnosisCertPic) { this.sDiagnosisCertPic = sDiagnosisCertPic == null ? null : sDiagnosisCertPic.trim(); } public String getsOtherImages() { return sOtherImages; } public void setsOtherImages(String sOtherImages) { this.sOtherImages = sOtherImages == null ? null : sOtherImages.trim(); } public Integer getnCompleteStatus() { return nCompleteStatus; } public void setnCompleteStatus(Integer nCompleteStatus) { this.nCompleteStatus = nCompleteStatus; } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/vo/back/UserPacketGrabDetailVo.java package com.gezhiwei.demo.vo.back; import com.alibaba.fastjson.annotation.JSONField; import java.util.Date; /** * @ClassName: UserPacketGrabDetailVo * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/18 9:50 * @modified By: */ public class UserPacketGrabDetailVo { private Long userId; private String userRealName; private String mobile; /** * 领取时间 */ @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 老用户 新用户 0否1是 */ private Integer userStatus = 0; /** * 1 激活 0 未激活 */ private Integer userPlanStatus =1; private Long sourceUserId; private String sourceUserName; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date redCreateTime; public Long getUserId() { return userId; } public UserPacketGrabDetailVo setUserId(Long userId) { this.userId = userId; return this; } public String getUserRealName() { return userRealName; } public UserPacketGrabDetailVo setUserRealName(String userRealName) { this.userRealName = userRealName; return this; } public String getMobile() { return mobile; } public UserPacketGrabDetailVo setMobile(String mobile) { this.mobile = mobile; return this; } public Date getCreateTime() { return createTime; } public UserPacketGrabDetailVo setCreateTime(Date createTime) { this.createTime = createTime; return this; } public Integer getUserStatus() { return userStatus; } public UserPacketGrabDetailVo setUserStatus(Integer userStatus) { this.userStatus = userStatus; return this; } public Integer getUserPlanStatus() { return userPlanStatus; } public UserPacketGrabDetailVo setUserPlanStatus(Integer userPlanStatus) { this.userPlanStatus = userPlanStatus; return this; } public Long getSourceUserId() { return sourceUserId; } public UserPacketGrabDetailVo setSourceUserId(Long sourceUserId) { this.sourceUserId = sourceUserId; return this; } public String getSourceUserName() { return sourceUserName; } public UserPacketGrabDetailVo setSourceUserName(String sourceUserName) { this.sourceUserName = sourceUserName; return this; } public Date getRedCreateTime() { return redCreateTime; } public UserPacketGrabDetailVo setRedCreateTime(Date redCreateTime) { this.redCreateTime = redCreateTime; return this; } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/mapper/CreditDiagnosisCertMapper.java package com.gezhiwei.demo.dao.mapper; import com.gezhiwei.demo.dao.entity.CreditDiagnosisCert; public interface CreditDiagnosisCertMapper { int deleteByPrimaryKey(Long nId); int insert(CreditDiagnosisCert record); int insertSelective(CreditDiagnosisCert record); CreditDiagnosisCert selectByPrimaryKey(Long nId); int updateByPrimaryKeySelective(CreditDiagnosisCert record); int updateByPrimaryKey(CreditDiagnosisCert record); }<file_sep>/src/main/java/com/gezhiwei/demo/config/RedisConfig.java package com.gezhiwei.demo.config; import io.lettuce.core.dynamic.annotation.Value; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashSet; import java.util.Set; /** * @ClassName: RedisConfig * @Author: 葛志伟(赛事) * @Description: * @Date: 2018/12/19 14:20 * @modified By: */ @Configuration public class RedisConfig { @Bean(name = "enericObjectPoolConfig") public GenericObjectPoolConfig genericObjectPoolConfig() { GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); genericObjectPoolConfig.setMaxIdle(-1); genericObjectPoolConfig.setMaxTotal(1000); genericObjectPoolConfig.setMinIdle(10); genericObjectPoolConfig.setMaxIdle(100); return genericObjectPoolConfig; } @Bean(name = "redisCluster") @ConfigurationProperties(prefix = "spring.redis") public JedisClusterFactory redisCluster(){ JedisClusterFactory jedisClusterFactory = new JedisClusterFactory(); jedisClusterFactory.setConnectionTimeout(3000); jedisClusterFactory.setSoTimeout(3000); jedisClusterFactory.setMaxRedirections(5); jedisClusterFactory.setGenericObjectPoolConfig(genericObjectPoolConfig()); Set<String> value = new HashSet<>(); //dev // value.add("172.16.250.194:6405"); // value.add("172.16.250.5:6401"); // value.add("172.16.250.5:6402"); // value.add("172.16.251.94:6402"); // value.add("172.16.251.94:6403"); // value.add("172.16.250.194:6406"); //test value.add("172.16.250.194:6409"); value.add("172.16.250.5:6405"); value.add("172.16.250.5:6406"); value.add("172.16.251.94:6406"); value.add("172.16.251.94:6407"); value.add("172.16.250.194:6410"); jedisClusterFactory.setJedisClusterNodes(value); return jedisClusterFactory; } } <file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/CreditPayeeSelfCert.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class CreditPayeeSelfCert { private Long nFundId; private String sRealName; private String sIdCardNo; private String sMobile; private String sBankCode; private String sBankName; private String sDepositBank; private String sBankAccount; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; public Long getnFundId() { return nFundId; } public void setnFundId(Long nFundId) { this.nFundId = nFundId; } public String getsRealName() { return sRealName; } public void setsRealName(String sRealName) { this.sRealName = sRealName == null ? null : sRealName.trim(); } public String getsIdCardNo() { return sIdCardNo; } public void setsIdCardNo(String sIdCardNo) { this.sIdCardNo = sIdCardNo == null ? null : sIdCardNo.trim(); } public String getsMobile() { return sMobile; } public void setsMobile(String sMobile) { this.sMobile = sMobile == null ? null : sMobile.trim(); } public String getsBankCode() { return sBankCode; } public void setsBankCode(String sBankCode) { this.sBankCode = sBankCode == null ? null : sBankCode.trim(); } public String getsBankName() { return sBankName; } public void setsBankName(String sBankName) { this.sBankName = sBankName == null ? null : sBankName.trim(); } public String getsDepositBank() { return sDepositBank; } public void setsDepositBank(String sDepositBank) { this.sDepositBank = sDepositBank == null ? null : sDepositBank.trim(); } public String getsBankAccount() { return sBankAccount; } public void setsBankAccount(String sBankAccount) { this.sBankAccount = sBankAccount == null ? null : sBankAccount.trim(); } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/HcUserLoginRecord.java package com.gezhiwei.demo.dao.entity; import java.util.Date; public class HcUserLoginRecord { private Long nId; private Long nUserId; private Date dLoginTime; private String sCmdName; private String sPhoneType; private String sOsVersion; private String sAppVersion; private String sPhoneModel; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; public Long getnId() { return nId; } public void setnId(Long nId) { this.nId = nId; } public Long getnUserId() { return nUserId; } public void setnUserId(Long nUserId) { this.nUserId = nUserId; } public Date getdLoginTime() { return dLoginTime; } public void setdLoginTime(Date dLoginTime) { this.dLoginTime = dLoginTime; } public String getsCmdName() { return sCmdName; } public void setsCmdName(String sCmdName) { this.sCmdName = sCmdName == null ? null : sCmdName.trim(); } public String getsPhoneType() { return sPhoneType; } public void setsPhoneType(String sPhoneType) { this.sPhoneType = sPhoneType == null ? null : sPhoneType.trim(); } public String getsOsVersion() { return sOsVersion; } public void setsOsVersion(String sOsVersion) { this.sOsVersion = sOsVersion == null ? null : sOsVersion.trim(); } public String getsAppVersion() { return sAppVersion; } public void setsAppVersion(String sAppVersion) { this.sAppVersion = sAppVersion == null ? null : sAppVersion.trim(); } public String getsPhoneModel() { return sPhoneModel; } public void setsPhoneModel(String sPhoneModel) { this.sPhoneModel = sPhoneModel == null ? null : sPhoneModel.trim(); } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/dao/entity/HcFundCommit.java package com.gezhiwei.demo.dao.entity; import java.math.BigDecimal; import java.util.Date; public class HcFundCommit { private Long nId; private Long nFundId; private String sForWho; private String sPatientRealName; private String sDiseasesName; private Integer nPatientAge; private String sPatientAddress; private Date dFallIllDate; private String sHospitalNameNow; private BigDecimal nHadPayMoney; private String sCommitNickName; private String sCommitRealName; private Integer nCompleteStatus; private Integer nFundType; private Date dCreateTime; private String sCreatedBy; private Date dUpdateTime; private String sUpdatedBy; public Long getnId() { return nId; } public void setnId(Long nId) { this.nId = nId; } public Long getnFundId() { return nFundId; } public void setnFundId(Long nFundId) { this.nFundId = nFundId; } public String getsForWho() { return sForWho; } public void setsForWho(String sForWho) { this.sForWho = sForWho == null ? null : sForWho.trim(); } public String getsPatientRealName() { return sPatientRealName; } public void setsPatientRealName(String sPatientRealName) { this.sPatientRealName = sPatientRealName == null ? null : sPatientRealName.trim(); } public String getsDiseasesName() { return sDiseasesName; } public void setsDiseasesName(String sDiseasesName) { this.sDiseasesName = sDiseasesName == null ? null : sDiseasesName.trim(); } public Integer getnPatientAge() { return nPatientAge; } public void setnPatientAge(Integer nPatientAge) { this.nPatientAge = nPatientAge; } public String getsPatientAddress() { return sPatientAddress; } public void setsPatientAddress(String sPatientAddress) { this.sPatientAddress = sPatientAddress == null ? null : sPatientAddress.trim(); } public Date getdFallIllDate() { return dFallIllDate; } public void setdFallIllDate(Date dFallIllDate) { this.dFallIllDate = dFallIllDate; } public String getsHospitalNameNow() { return sHospitalNameNow; } public void setsHospitalNameNow(String sHospitalNameNow) { this.sHospitalNameNow = sHospitalNameNow == null ? null : sHospitalNameNow.trim(); } public BigDecimal getnHadPayMoney() { return nHadPayMoney; } public void setnHadPayMoney(BigDecimal nHadPayMoney) { this.nHadPayMoney = nHadPayMoney; } public String getsCommitNickName() { return sCommitNickName; } public void setsCommitNickName(String sCommitNickName) { this.sCommitNickName = sCommitNickName == null ? null : sCommitNickName.trim(); } public String getsCommitRealName() { return sCommitRealName; } public void setsCommitRealName(String sCommitRealName) { this.sCommitRealName = sCommitRealName == null ? null : sCommitRealName.trim(); } public Integer getnCompleteStatus() { return nCompleteStatus; } public void setnCompleteStatus(Integer nCompleteStatus) { this.nCompleteStatus = nCompleteStatus; } public Integer getnFundType() { return nFundType; } public void setnFundType(Integer nFundType) { this.nFundType = nFundType; } public Date getdCreateTime() { return dCreateTime; } public void setdCreateTime(Date dCreateTime) { this.dCreateTime = dCreateTime; } public String getsCreatedBy() { return sCreatedBy; } public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy == null ? null : sCreatedBy.trim(); } public Date getdUpdateTime() { return dUpdateTime; } public void setdUpdateTime(Date dUpdateTime) { this.dUpdateTime = dUpdateTime; } public String getsUpdatedBy() { return sUpdatedBy; } public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy == null ? null : sUpdatedBy.trim(); } }<file_sep>/src/main/java/com/gezhiwei/demo/vo/EnterRedPacketVo.java package com.gezhiwei.demo.vo; import java.math.BigDecimal; import java.util.List; import java.util.Map; /** * @ClassName: EnterRedPackageVo * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/14 18:48 * @modified By: */ public class EnterRedPacketVo { /** * 保障期数 */ private Map<String, String> guaranteePeriods; /** * 锦鲤说明 */ private String description; /** * 优惠券总金额 */ private BigDecimal amount; /** * 优惠券信息 */ private List<VoucherSelectorVo> selectorVos; public Map<String, String> getGuaranteePeriods() { return guaranteePeriods; } public EnterRedPacketVo setGuaranteePeriods(Map<String, String> guaranteePeriods) { this.guaranteePeriods = guaranteePeriods; return this; } public String getDescription() { return description; } public EnterRedPacketVo setDescription(String description) { this.description = description; return this; } public BigDecimal getAmount() { return amount; } public EnterRedPacketVo setAmount(BigDecimal amount) { this.amount = amount; return this; } public List<VoucherSelectorVo> getSelectorVos() { return selectorVos; } public EnterRedPacketVo setSelectorVos(List<VoucherSelectorVo> selectorVos) { this.selectorVos = selectorVos; return this; } } <file_sep>/src/main/java/com/gezhiwei/demo/vo/PayRedPacketVo.java package com.gezhiwei.demo.vo; /** * @ClassName: PayRedPacketVo * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/16 14:57 * @modified By: */ public class PayRedPacketVo { /** * 0 付款成功 * 1 付款失败 */ private Integer status; private Long redPacketId; public Integer getStatus() { return status; } public PayRedPacketVo setStatus(Integer status) { this.status = status; return this; } public Long getRedPacketId() { return redPacketId; } public PayRedPacketVo setRedPacketId(Long redPacketId) { this.redPacketId = redPacketId; return this; } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.gezhiwei</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>dataCreate</name> <description></description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <!--repositories--> <repositories> <repository> <id>public</id> <url>http://maven.gezhiwei.com/nexus/content/groups/public/</url> </repository> </repositories> <!--distribution--> <distributionManagement> <snapshotRepository> <id>snapshots</id> <url>http://maven.gezhiwei.com/nexus/content/repositories/snapshots/</url> </snapshotRepository> <repository> <id>releases</id> <url>http://maven.gezhiwei.com/nexus/content/repositories/releases/</url> </repository> </distributionManagement> <pluginRepositories> <pluginRepository> <id>public</id> <url>http://maven.gezhiwei.com/nexus/content/groups/public/</url> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <junit.version>4.12</junit.version> <slf4j.version>1.7.25</slf4j.version> <logback.version>1.1.7</logback.version> <mysql.connector.version>5.1.39</mysql.connector.version> <mybatis-spring.version>1.3.2</mybatis-spring.version> <metrics.version>4.0.0</metrics.version> </properties> <dependencies> <!--slf4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.0</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring.version}</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </exclusion> </exclusions> </dependency> <!--Mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-core</artifactId> <version>${metrics.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-jmx</artifactId> <version>${metrics.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>20.0</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.bytedeco.javacpp-presets/opencv-platform --> <dependency> <groupId>org.bytedeco.javacpp-presets</groupId> <artifactId>opencv-platform</artifactId> <version>4.0.1-1.4.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.tensorflow/tensorflow --> <dependency> <groupId>org.tensorflow</groupId> <artifactId>tensorflow</artifactId> <version>1.12.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <!--配置文件的位置--> <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <executions> <execution> <id>Generate MyBatis Artifacts</id> <goals> <goal>generate</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
7a4ed53e2595e6d76c1e5e12ea3e6ba99730ae0e
[ "Java", "Maven POM" ]
35
Java
utilcollect/demo
23127669371e58275c53939a045e9f8adc1a9fbb
32d07140a477b1ee13d8d961228ed14e4be35ee3
refs/heads/master
<file_sep>var i = 0,j = 0,x = 0; var f=0; var Obj = {"sys": [],"sup": [],"env": []}; document.getElementById('btn-1').addEventListener("click", function() { $('#adv-list').append('<li><h5>Advantage</h5>'+ '<input type="text" class="form-control" id="adv1">'+ '<h5>Disadvantage</h5>'+ '<input type="text" class="form-control" id="adv1">'+ '</li><br>'); }); $('#sys-0').change(function(){ Obj.sys.push(this.value); }); document.getElementById('btn-2').addEventListener("click", function() { i++; $('#str1-list').append('<li>'+ '<input id="sys-'+i+ '" type="text" class="form-control">'+ '</li><br>'); $('#sys-'+i).change(function(){ Obj.sys.push(this.value); }); }); $('#sup-0').change(function(){ Obj.sup.push(this.value); }); document.getElementById('btn-3').addEventListener("click", function() { j++; $('#str2-list').append('<li>'+ '<input id="sup-'+j+ '" type="text" class="form-control">'+ '</li><br>'); $('#sup-'+j).change(function(){ Obj.sup.push(this.value); }); }); $('#env-0').change(function(){ Obj.env.push(this.value); }); document.getElementById('btn-4').addEventListener("click", function() { x++; $('#str3-list').append('<li>'+ '<input id="env-'+x+ '" type="text" class="form-control">'+ '</li><br>'); $('#env-'+x).change(function(){ Obj.env.push(this.value); }); });
7c780a56f65d9beb6af1d8d2807e2dabe0f7aa10
[ "JavaScript" ]
1
JavaScript
nbogis/TRIZ
831f302de22ecc70ac4ae9585bcea8da4834388c
586de79010ec82c394571f65c8e33133a8ed5376
refs/heads/master
<repo_name>freedomzzzii/ReactNative<file_sep>/src/screens/Tutorial/Tutorial.js import React, { Component } from 'react'; import { View, Text, AsyncStorage } from 'react-native'; import Swiper from 'react-native-swiper'; import tutorial from './TutorialStyle'; import theme from '../../../_theme'; import { Layout1 } from '../../component/Layout/Layout'; import { InputIcon } from '../../helpers/Input/Input'; import Button from '../../helpers/Button/Button'; import { getItem, setItem } from '../../helpers/Storage/Storage'; const Tutorial1 = () => ( <Layout1> <View style={tutorial.style1}> <Text style={theme.text1}> ขอสินเชื่อง่ายๆ </Text> <Text style={theme.text1}> ใน 3 ขั้นตอน </Text> </View> </Layout1> ); const Tutorial2 = () => ( <Layout1> <View style={tutorial.style1}> <Text style={theme.text1}> 1 </Text> <Text style={theme.text1}> กรอกข้อมูลและส่ง </Text> <Text style={theme.text1}> เอกสารออนไลน์ </Text> </View> </Layout1> ); const Tutorial3 = () => ( <Layout1> <View style={tutorial.style1}> <Text style={theme.text1}> 2 </Text> <Text style={theme.text1}> พิมพ์เอกสาร </Text> <Text style={theme.text1}> ที่หน้าสาขา </Text> </View> </Layout1> ); const Tutorial4 = () => ( <Layout1> <View style={tutorial.style1}> <Text style={theme.text1}> 3 </Text> <Text style={theme.text1}> รับเงิน </Text> <Text style={theme.text1}> รวดเร็วทันใจ </Text> </View> </Layout1> ); export class Login extends Component { handleLogin = async () => { try { const firstTime = await getItem('firstTime'); if (!firstTime) { await setItem('firstTime', 'firstTime'); } await setItem('isLogin', 'isLogin'); } catch(error) { await setItem('firstTime', 'firstTime'); await setItem('isLogin', 'isLogin'); } } render() { const settingsIDCard = { iconName: 'ios-person', iconSize: 25, placeholder: 'เลขบัตรประชาชน', }; const settingsPhone = { iconName: 'ios-call', iconSize: 25, placeholder: 'หมายเลขโทรศัพท์', }; return( <Layout1> <View style={tutorial.style2}> <Text style={theme.text2}> เข้าสู่ระบบ </Text> <View style={tutorial.input}> <InputIcon settings={settingsIDCard} /> </View> <View style={tutorial.input}> <InputIcon settings={settingsPhone} /> </View> <View style={tutorial.button}> <Button color="green" text="ยืนยัน" handleClick={this.handleLogin} /> </View> </View> </Layout1> ); } } export default class Tutorial extends Component { render() { return( <Swiper showsButtons={false} loop={false}> <Tutorial1 /> <Tutorial2 /> <Tutorial3 /> <Tutorial4 /> <Login /> </Swiper> ); } } <file_sep>/src/screens/Tutorial/TutorialStyle.js import { StyleSheet } from 'react-native'; const tutorial = StyleSheet.create({ style1: { flex: 1, justifyContent: 'center', alignItems: 'center', position: 'absolute', }, style2: { flex: 1, justifyContent: 'center', alignItems: 'center', position: 'absolute', borderStyle: 'solid', borderColor: '#ced4da', borderWidth: 1, borderRadius: 5, width: '90%', paddingHorizontal: 20, paddingVertical: 30, }, input: { marginTop: 15, flex: 1, }, button: { flex: 1, width: '40%', marginTop: 25, }, }); export default tutorial; <file_sep>/src/component/Layout/Layout.js import React, { Component } from 'react'; import { View, Text, Image } from 'react-native'; import theme from '../../../_theme'; import layout from './LayoutStyle'; export class Layout1 extends Component { constructor(props) { super(props); this.state = {}; } render() { return( <View style={theme.style1}> <View style={layout.flex1}> <Image resizeMode="contain" style={layout.logo} source={require('../../assets/logo.png')} /> </View> {this.props.children} </View> ); } } <file_sep>/App.js import React, { Component } from 'react'; import { Button, Text, View, AsyncStorage, AppState } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; import { StackNavigator, createBottomTabNavigator } from 'react-navigation'; import Tutorial, { Login } from './src/screens/Tutorial/Tutorial'; import { getItem } from './src/helpers/Storage/Storage'; class HomeScreen extends Component { render() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Home!</Text> <Button title="Go to Settings" onPress={() => this.props.navigation.navigate('Settings')} /> <Button title="Go to Details" onPress={() => this.props.navigation.navigate('Details')} /> </View> ); } } class SettingsScreen extends React.Component { render() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Settings!</Text> <Button title="Go to Home" onPress={() => this.props.navigation.navigate('Home')} /> <Button title="Go to Details" onPress={() => this.props.navigation.navigate('Details')} /> </View> ); } } class DetailsScreen extends Component { constructor(props) { super(props); this.state = {}; } render() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Details!</Text> </View> ); } } const HomeStack = StackNavigator({ Home: { screen: HomeScreen }, Details: { screen: DetailsScreen }, }); const SettingsStack = StackNavigator({ Settings: { screen: SettingsScreen }, Details: { screen: DetailsScreen }, }); const RootNavigator = createBottomTabNavigator( { Home: { screen: HomeStack }, Settings: { screen: SettingsStack }, Tutorial, }, { navigationOptions: ({ navigation }) => ({ tabBarIcon: ({ focused, tintColor }) => { const { routeName } = navigation.state; let iconName; if (routeName === 'Home') { iconName = `ios-information-circle${focused ? '' : '-outline'}`; } else if (routeName === 'Settings') { iconName = `ios-options${focused ? '' : '-outline'}`; } return <Icon name={iconName} size={25} color={tintColor} />; }, }), tabBarOptions: { activeTintColor: 'tomato', inactiveTintColor: 'gray', }, } ); class App extends Component { constructor(props) { super(props); this.state = { firstTime: false, appState: AppState.currentState, isLogin: false, }; } async componentWillMount() { try { const firstTime = await getItem('firstTime'); const isLogin = await getItem('isLogin'); this.setState({ firstTime, isLogin }); } catch (error) { this.setState({ firstTime: true }); } } componentDidMount() { AppState.addEventListener('change', this._handleAppStateChange); } componentWillUnmount() { AppState.removeEventListener('change', this._handleAppStateChange); } _handleAppStateChange = (nextAppState) => { if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') { console.log('App has come to the foreground!') } this.setState({ appState: nextAppState }); } render() { const { firstTime, isLogin } = this.state; console.log('appState>>>', this.state.appState); if (!firstTime) { return(<Tutorial />); } else if (!isLogin) { return(<Login />); } return(<RootNavigator />); } } export default App;
03ea8c918f266b3761cee4f806bf0df473f70e78
[ "JavaScript" ]
4
JavaScript
freedomzzzii/ReactNative
182f46ebc1cebf37267f9b0b5d8ed7a015538278
3c195e64c2ac7c56ea97ad9fc5f721827d6923be
refs/heads/master
<repo_name>RisingStack/opentracing-infrastructure-graph<file_sep>/README.md # opentracing-infrastructure-graph Visualizing infrastructure topology via OpenTracing instrumentation. This application uses the following libraries to extract the topology metrics to [Prometheus](https://prometheus.io/) via [OpenTracing](http://opentracing.io/): - [opentracing-metrics-tracer](https://github.com/RisingStack/opentracing-metrics-tracer) - [opentracing-auto](https://github.com/RisingStack/opentracing-auto) ## Requirements - Docker ### Run Prometheus Modify: `/prometheus-data/prometheus.yml`, replace `192.168.0.10` with your own host machine's IP. Host machine IP address: `ifconfig | grep 'inet 192'| awk '{ print $2}'` ```sh docker run -p 9090:9090 -v "$(pwd)/prometheus-data":/prometheus-data prom/prometheus -config.file=/prometheus-data/prometheus.yml ``` Open Prometheus: [http://http://localhost:9090](http://http://localhost:9090/graph) ## Getting started It will start three web servers and simulate a service call chain: `server1` calls `server2` and `server3` parallel. ``` npm start curl http://localhost:3001 ``` ## Metrics between services `parent_service="unknown"` label means that the request initiator is not instrumented *(Prometheus scraper, curl, etc)*. ![parent_service labels](img/labels.png) ### Throughput Prometheus query: ``` sum(rate(operation_duration_seconds_count{name="http_server"}[1m])) by (service, parent_service) * 60 ``` ![Throughput between services](img/throuhput.png) ### 95th response time Prometheus query: ``` histogram_quantile(0.95, sum(rate(operation_duration_seconds_bucket{name="http_server"}[1m])) by (le, service, parent_service)) * 1000 ``` ![95th response time between services](img/response_time_95th.png) ## Infrastructure topology Data comes from Prometheus. Uses [vizceral](https://github.com/Netflix/vizceral). ``` npm run start-client open http://localhost:8080 ``` ![Infrastructure topology](img/topology.png) ## Future - add databases - show latency <file_sep>/services/server3.js 'use strict' const MetricsTracer = require('@risingstack/opentracing-metrics-tracer') const prometheusReporter = new MetricsTracer.PrometheusReporter() const metricsTracer = new MetricsTracer('my-server-2', [prometheusReporter]) // Auto instrumentation const Instrument = require('@risingstack/opentracing-auto') new Instrument({ tracers: [metricsTracer] }) // Web server const express = require('express') const app = express() const port = process.env.PORT || 3003 app.get('/', async (req, res) => { res.json({ status: 'ok' }) }) app.get('/metrics', (req, res) => { res.set('Content-Type', MetricsTracer.PrometheusReporter.Prometheus.register.contentType) res.end(prometheusReporter.metrics()) }) app.listen(port, (err) => { console.log(err || `Server 1 is listening on ${port}`) }) <file_sep>/client/components/Topology.js import React, { Component } from 'react' import Vizceral from 'vizceral-react' import superagent from 'superagent' import 'vizceral-react/dist/vizceral.css' import './Topology.css' const PROMETHEUS_QUERY = 'sum(rate(operation_duration_seconds_count{name="http_server"}[1m]))' + ' by (service, parent_service) * 60' const ROOT_NODE = { name: 'INTERNET' } const UPDATE_INTERVAL = 10000 class Topology extends Component { constructor () { super() this.updateInterval = setInterval(() => this.update(), UPDATE_INTERVAL) this.state = { traffic: { layout: 'ltrTree', maxVolume: 10000, updated: Date.now(), name: 'Infrastructure', renderer: 'region', nodes: [ ROOT_NODE ], connections: [] } } this.update() } componentWillUnmount () { clearInterval(this.updateInterval) } update () { const epoch = Math.round(Date.now() / 1000) const uri = 'http://localhost:9090/api/v1/query' + `?query=${PROMETHEUS_QUERY}&start=${epoch - 60}&end=${epoch}` superagent.get(uri) .then(({ body }) => { const { traffic } = this.state const nodes = new Set() traffic.updated = Date.now() traffic.nodes = [ROOT_NODE] traffic.connections = [] body.data.result.forEach((result) => { // Add node if (!nodes.has(result.metric.service)) { traffic.nodes.push({ name: result.metric.service }) nodes.add(result.metric.service) } // Add edge traffic.connections.push({ source: result.metric.parent_service === 'unknown' ? ROOT_NODE.name : result.metric.parent_service, target: result.metric.service, metrics: { normal: Math.round(Number(result.value[1]) || 0), danger: 0, warning: 0 } }) }) this.setState({ traffic }) }) .catch((err) => { console.error(err) }) } render () { const { traffic } = this.state return ( <div className="vizceral-container"> <Vizceral traffic={traffic} showLabels allowDraggingOfNodes /> </div> ) } } export default Topology
94ba450363b38d7e9d23ec5cfb70f2ea677cc379
[ "Markdown", "JavaScript" ]
3
Markdown
RisingStack/opentracing-infrastructure-graph
99c2379b1da5f526c36a4a0034a4fa3b07fa9fa4
31f659e138d2d04f0703e13a643b888f7dda51d6
refs/heads/master
<file_sep>package com.cerebri.mueller.location.dao; import com.cerebri.mueller.location.model.Location; import java.util.List; public interface LocationDAO { public void saveOrUpdate(Location location); public void delete(int locationId); public Location get(int locationId); public List<Location> list(); public List<Location> list(double latitude , double longitude); }
1c2e675af9c93bdb27983d1dc51ceb6138d7684e
[ "Java" ]
1
Java
pranireddy9/location-rest-portlet
6dd6e2bd633039a627ae0e17719b26f695ab43c7
f1f9d84268188cbe3057148948ac747efe0ba699
refs/heads/master
<repo_name>ishmandoo/ar_art<file_sep>/server.js var express = require('express') var app = express(); var https = require('https'); var http = require('http'); var fs = require('fs'); var path = require('path'); var numeric = require('numeric'); app.all('*', ensureSecure); function ensureSecure(req, res, next){ if(req.secure){ return next(); }; res.redirect('https://' + req.hostname + req.url); } app.get('/', function (req, res) { res.sendFile(path.join(__dirname + '/public/client.html')); }) app.use("/public", express.static(__dirname + '/public')) app.use("/images", express.static(__dirname + '/images')) app.use("/bower_components", express.static(__dirname + '/bower_components')) // This line is from the Node.js HTTPS documentation. if(process.env.NODE_ENV == 'prod'){ var options = { key: fs.readFileSync('/etc/letsencrypt/live/spaceadventure.zone/privkey.pem'), cert: fs.readFileSync('/etc/letsencrypt/live/spaceadventure.zone/fullchain.pem') }; } else{ var options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') }; } // Create an HTTP service. var httpServer = http.createServer(app); // Create an HTTPS service identical to the HTTP service. var httpsServer = https.createServer(options, app); httpServer.listen(80); httpsServer.listen(443); var io = require('socket.io')(httpsServer); objects = { 0: [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, ] } io.on('connection', function(socket){ console.log("a client connected ", socket.id); objects[socket.id] = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, ]; socket.on("new pos", function(pos) { objects[socket.id] = pos; }) socket.on('disconnect', function () { io.emit('user disconnected', socket.id) delete objects[socket.id]; }) setInterval(function () { console.log(objects); updatePlanetPositions(); socket.emit('update', objects); }, 100); }); function unpackVec(v){ var vecs = []; for(var vecnum = 0; vecnum < v.length/3 ; vecnum++){ var vec = []; for(var index = 0; index < 3; index ++){ vec.push(v[3*vecnum + index]); } vecs.push(vec); } return vecs; } function packVec(v){ var y = []; for(var i = 0; i<v.length; i++){ for(var index = 0; index < 3; index ++){ y.push(v[i][index]); } } return y; } function derivatives(t, y){ var pos = unpackVec(y.slice(0, y.length/2)); var xdot = y.slice(y.length/2); var force = numeric.rep([pos.length,3],0) for(var i =0 ; i < pos.length; i++){ for(var j = 0; j < i; j++){ var dr = numeric.sub(pos[i],pos[j]); var denom = -0.1 / Math.pow(numeric.norm2(dr) , 3/2); force[i] = numeric.add(force[i], numeric.mul(denom, dr) ); } // central force var denom = -5.0 / Math.pow(numeric.norm2(pos[i]) , 3/2); force[i] = numeric.add(force[i], numeric.mul(denom, pos[i]) ); } var acc = packVec(force) var retval = xdot.concat(acc); return retval; } var time; var nPlanets = 1; //var state = numeric.mul(5,numeric.random([nPlanets * 3 ])).concat(numeric.mul(1,numeric.random([nPlanets * 3 ]))); var state = [10, 0, 0, 0, 0, 1]; var origin = [-10.6, 3, 5]; var R = 6; function updatePlanetPositionsIntegrator() { var now = new Date().getTime(); var dt = (now - (time || now)) / 1000; time = now; sol = numeric.dopri(0, dt, state, derivatives) state = sol.y[sol.y.length-1] var pos = unpackVec(state.slice(0, state.length/2)); for(var i = 0; i < nPlanets; i++){ objects[i] = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, pos[i][0] + origin[0], pos[i][1] + origin[1], pos[i][2] + origin[2], 1, ]; } } function updatePlanetPositions() { var now = new Date().getTime(); time = now; for(var i = 0; i < nPlanets; i++){ objects[i] = [ Math.cos(time/500), 0, -Math.sin(time/500), 0, 0, 1, 0, 0, Math.sin(time/500), 0, Math.cos(time/500), 0, R * Math.sin(time/1000) + origin[0], origin[1], R * Math.cos(time/1000) + origin[2], 1, ]; } }
337c17c07ff3f9574ecfbe53697c76149ca35ae0
[ "JavaScript" ]
1
JavaScript
ishmandoo/ar_art
a396b26b6a1716a95c6c71a946931eda9657ef8a
00b2c96c5017313e7ac94cc6dd7eded2c4ea59cb
refs/heads/master
<repo_name>mbuescher/Exam-December<file_sep>/README.md # Exam-December Practice code for the December exam in AP Computer Science <file_sep>/User.java /** * A User for a system. Contains username and password fields, * along with various methods for accessing them and for logging * in and out. */ import java.util.Scanner; public class User { String username, password; boolean loggedIn; /** * Constructor takes a username and password and creates a new user. * Default is that the user is not logged in. * @param uname the new username * @param passwd the new password */ public User (String uname, String passwd) { username = uname; password = <PASSWORD>; loggedIn = false; } // ----------------------------------------- // Accessor Methods // ----------------------------------------- public String getUsername() { return username; } public boolean getLogin() { return loggedIn; } // No accessor for password! // --------------------------------------------- // login and logout methods // --------------------------------------------- /** * Checks the username and password. Successful login if they match. * @param un the username * @param pw the password * @return whether the login was successful */ public boolean login (String un, String pw) { if (username.equals(un) && password.equals(pw)) loggedIn = true; else loggedIn = false; return loggedIn; } /** * Logs the user out. No check or validation. * @return false always, because the user is no longer logged in. */ public boolean logout () { loggedIn = false; return loggedIn; } } <file_sep>/QuestionType_Arith1.java /************************************************* * Practice questions for APCS: Convert Binary byte to Decimal * Bonus: You should also be able to understand and modify the code. * * @author <NAME> * @version December 1, 2016 */ import java.util.Scanner; import java.lang.Math; public class QuestionType_Arith1 { // stored as a string to handle leading zeros private String questionString, answerString; /** Constructor sets the question using a separate method; * That way this can be re-used for similar types of questions. * setQuestion() later fills it in with spcefic information. */ public void QuestionType_Arith1 () { setQuestion (); } // -------------------------------------------------------------- // Accessor Methods // -------------------------------------------------------------- /** Returns the question as a String. * @return the question as a String. */ public String getQuestion () { return questionString; } /** Returns the answer to the question. * @return the answer to the question. */ public String getAnswer () { return answerString; } /* ------------------------------------------------------------------ * Sets the question string and answer string based on a random choice * of one of several question types. Private methods set the details. */ public void setQuestion () { final int NUM_TYPES = 7; int qType = (int)(Math.random() * NUM_TYPES); switch (qType) { case 0: setIntAdd(); break; case 1: setIntDiv(); break; case 2: setIntMod(); break; case 3: setAddIntReal(); break; case 4: setOrdOp1(); break; case 5: setOrdOp2(); break; case 6: setOrdOp3(); break; } } // ------------------------------------------------------------ // Different question types // ------------------------------------------------------------ // Integer Addition private void setIntAdd () { int a = (int)(Math.random() * 50) - 25; int b = (int)(Math.random() * 50) - 25; questionString = a + " + " + b + " = ??? "; answerString = "" + (a + b); } // Integer Division: divide private void setIntDiv () { int a = (int)(Math.random() * 120) - 50; int b = (int)(Math.random() * 10) + 1; questionString = a + " / " + b + " = ??? "; answerString = "" + (a / b); } // Integer division: Mod private void setIntMod () { int a = (int)(Math.random() * 100); int b = (int)(Math.random() * 10) + 1; questionString = a + " % " + b + " = ??? "; answerString = "" + (a % b); } // Add integer and double private void setAddIntReal () { int a = (int)(Math.random() * 50) - 15; double b = (int)(Math.random() * 101)/10.0 + 1; questionString = a + " + " + b + " = ??? "; answerString = "" + (a + b); } // Order of Operations - first of many private void setOrdOp1 () { int a = (int)(Math.random() * 10) + 1; int b = (int)(Math.random() * 10) + 1; int c = (int)(Math.random() * 10) + 1; questionString = a + " + " + b + " * " + c + " = ??? "; answerString = "" + (a + b * c); } // Order of Operations - version 2 private void setOrdOp2 () { int a = (int)(Math.random() * 80) + 1; int b = (int)(Math.random() * 10) + 1; int c = (int)(Math.random() * 10) + 1; questionString = a + " / " + b + " * " + c + " = ??? "; answerString = "" + (a / b * c); } // Order of Operations - version 3 private void setOrdOp3 () { int a = (int)(Math.random() * 20) + 1; int b = (int)(Math.random() * 80) + 1; int c = (int)(Math.random() * 10) + 1; questionString = a + " + " + b + " % " + c + " = ??? "; answerString = "" + (a + b % c); } // --------------------------------------------------------------- // --------------------------------------------------------------- /** * Short program to test the class. * */ public static void main (String[] args) { Scanner keyboard = new Scanner (System.in); String user = " "; QuestionType_Arith1 question = new QuestionType_Arith1(); while (user.toLowerCase().charAt(0) != 'q') { question.setQuestion(); System.out.println (question.getQuestion()); System.out.print ("Any character for Answer and next question, \'q\' to quit. : "); user = keyboard.nextLine() + " "; System.out.println (question.getAnswer()); } System.out.println ("Thank you and come again."); keyboard.close(); } }<file_sep>/DiceFun.java public class DiceFun { public static void rollThemB (int n) { int roll, threes = 0; for (int i = 1; i <= n; i++) { roll = (int)(Math.random() *6) + 1; System.out.print (roll + ", "); if (roll == 3) threes++; } System.out.println ("\nThere were " + threes + " threes!"); } public static void rollThemC (int n) { int roll, doubles = 0, prev = 0; for (int i = 1; i <= n; i++) { roll = (int)(Math.random() *6) + 1; System.out.print (roll + ", "); if (prev == roll) doubles++; prev = roll; } System.out.println ("\nThere were " + doubles + " repeats!"); } public static void rollThemD (int n) { int roll, longRun = 0, currentRun = 1, prev = 0; for (int i = 1; i <= n; i++) { roll = (int)(Math.random() *6) + 1; System.out.print (roll + ", "); // if there's a match, add to the current run. // if not a match, reset the current run. if (prev == roll) currentRun++; else currentRun = 1; // if the current run is the longest, update that. if (currentRun > longRun) longRun = currentRun; // previous roll is now the current roll, ready for the next roll. prev = roll; } System.out.println ("\nLongest run: " + longRun + " in a row!"); } public static void main (String[] args) { rollThemD(30); } }<file_sep>/QuestionType_Bin2Dec.java /************************************************* * Practice questions for APCS: Convert Binary byte to Decimal * Bonus: You should also be able to understand and modify the code. * * @author <NAME> * @version December 1, 2016 */ import java.util.Scanner; import java.lang.Math; public class QuestionType_Bin2Dec { // stored as a string to handle leading zeros private String binary; /** Constructor sets the question using a separate method; * That way this can be re-used for similar types of questions. * setQuestion() later fills it in with spcefic information. */ public void QuestionType_Bin2Dec () { binary = setQuestion(); } /***************************************** * Returns the binary representation of a number. * @return an integer made up of ones and zeros. */ public String getBinary () { return binary; } /* ------------------------------------------------------------------ * Gets a random binary number with 8 bits (one byte). * It is stored internaly as a String to show leading zeros. * @return a String of 8 characters, '0' or '1', representing a binary number */ public String setQuestion () { String ans = ""; for (int i = 0; i < 8; i++) { if (Math.random() > 0.5) ans = ans + "1"; else ans = ans + "0"; } binary = ans; return ans; } /** ------------------------------------------------------------ * Gives the decimal representation of the Binary number stored in the question. * @return a decimal equivalent. */ public int convertBin2Dec () { int placeVal = 128; // leftmost digit in a byte is 128's place int ans = 0; for (int i = 0; i < 8; i++) { if (binary.charAt(i) == '1') ans += placeVal; // add the place value if it's a 1 placeVal = placeVal / 2; } return ans; } /** * Short program to test the class. * */ public static void main (String[] args) { Scanner keyboard = new Scanner (System.in); String user = " "; QuestionType_Bin2Dec question = new QuestionType_Bin2Dec(); while (user.toLowerCase().charAt(0) != 'q') { question.setQuestion(); System.out.println ("Convert to decimal: " + question.getBinary()); System.out.print ("Any character for Answer and next question, \'q\' to quit. : "); user = keyboard.nextLine() + " "; System.out.println ("Decimal equivalent: " + question.convertBin2Dec()); } System.out.println ("Thank you and come again."); keyboard.close(); } }
15bcc8fabf4df253e7b1568fc1f2610999167ca2
[ "Markdown", "Java" ]
5
Markdown
mbuescher/Exam-December
c11b29260fc3306c8320a95df8ce84c9b0c28d23
3fc81db94bf584ef3ae79fae95decf0b9323eeea
refs/heads/master
<repo_name>mingabire809/Python-Work<file_sep>/index.py #number_of_place = 30 #number_of_person = 0 #nairobi_mombasa = 8500 #nairobi_kigali = 10000 #nairobi_entebbe = 9000 #nairobi_bujumbura = 11500 #nairobi_juba = 12500 #nairobi_goma = 13500 number_of_place = 30 number_of_person = 0 class bus: def destination(self): nairobi_mombasa = 8500 nairobi_kigali = 10000 nairobi_entebbe = 9000 nairobi_bujumbura = 11500 nairobi_juba = 12500 nairobi_goma = 13500 class person(): #number_of_person = 0 def registration(self): nairobi_mombasa ='Your fare from Nairobi to Mombasa is 8500' nairobi_kigali = 'Your fare from Nairobi to Kigali is 10000' nairobi_entebbe = 'Your fare from Nairobi to Entebbe is 9000' nairobi_bujumbura = 'Your fare from Nairobi to Bujumbura is 11500' nairobi_juba = 'Your fare from Nairobi to Juba is 12500' nairobi_goma = 'Your fare from Nairobi to Goma is 13500' name = input("Enter your Name: ") print("\t") print("1. Nairobi to Mombasa") print("2. Nairobi to Kigali") print("3. Nairobi to Entebbe") print("4. Nairobi to Bujumbura") print("5. Nairobi to Juba") print("6. Nairobi to Goma") print("\t") #print("Select your direction: ") direction = input("Select your direction: ") while(number_of_person <= number_of_place): if(direction == '1'): print(name +" "+ nairobi_mombasa) number_of_person = number_of_person + 5 # fees = nairobi_mombasa elif(direction == '2'): print(name +" "+ nairobi_kigali) number_of_person = number_of_person + 5 #fees = nairobi_kigali elif(direction == '3'): print(name +" "+ nairobi_entebbe) number_of_person = number_of_person + 5 #fees = nairobi_entebbe elif(direction == '4'): print(name +" "+ nairobi_bujumbura) number_of_person = number_of_person + 5 #fees = nairobi_bujumbura elif(direction == '5'): print(name +" "+ nairobi_juba) number_of_person = number_of_person + 5 #fees = nairobi_juba elif(direction == '6'): print(name +" "+ nairobi_goma) number_of_person = number_of_person + 5 #fees = nairobi_goma else: print("destination not available") while(number_of_person <= number_of_place): print("Do you wish to continue to register passenger") print("Y or N") decision = input("Select decision: ") if(decision == "Y"): p = person() p.registration() else: print("The bus will leave with" + number_of_place + "person") break <file_sep>/Track/delete.py import mysql.connector mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>", database = "pythons" ) my_cursor = mydb.cursor() delete = "DELETE FROM employee WHERE name='me'" my_cursor.execute(delete) mydb.commit()<file_sep>/Track/networking/Neural/neural.py import sys import phonenumbers from phonenumbers import geocoder import folium import opencage.geocoder Key = "<KEY>" number = input("Phone Number: ") ch_number = phonenumbers.parse(number, "CH") location = geocoder.description_for_number(ch_number, "en") print(location) from phonenumbers import carrier service_number = phonenumbers.parse(number, "RO") print(carrier.name_for_number(service_number,"en")) samNumber = phonenumbers.parse(number) from opencage.geocoder import OpenCageGeocoder geocoder = OpenCageGeocoder(Key) query = str(location) results = geocoder.geocode(query) #print(results) lat = results[0]['geometry']['lat'] lng = results[0]['geometry']['lng'] print(lat,lng) myMap = folium.Map(location = [lat, lng], zoom_start = 9) folium.Marker([lat, lng], popup = location).add_to((myMap)) myMap.save('myLocation.html')<file_sep>/Track/creatdb.py import mysql.connector mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>", ) my_cursor = mydb.cursor() my_cursor.execute(" CREATE DATABASE Pythons ") my_cursor.execute('SHOW DATABASES') for db in my_cursor:print(db) if(mydb): print("Successful") else: print("unsuccessful")<file_sep>/Track/networking/Neural/test.py import numpy as np import pandas as pd from keras.preprocessing.image import ImageDataGenerator,load_img from keras.utils import to_categorical from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import random import os <file_sep>/Track/table.py import mysql.connector mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>", database = "pythons" ) my_cursor = mydb.cursor() #my_cursor.execute("CREATE TABLE employee(name VARCHAR(200), sal INT(20))") my_cursor.execute("Show tables") for tb in my_cursor: print(tb)<file_sep>/Track/readtable.py import mysql.connector mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>", database = "pythons" ) my_cursor = mydb.cursor() my_cursor.execute("Select * from employee") result = my_cursor.fetchall() for row in result: print(row) <file_sep>/Track/networking/packagecontent.py #import smtplib #from email import encoders #from email.mime.text import MIMEText #from email.mime.base import MIMEBase #from email.mime.multipart import MIMEMultipart #server = smtplib.SMTP('smtp.gmail.com',25) #server.ehlo() #server.login('<EMAIL>','<PASSWORD>') #msg = MIMEMultipart() #msg['From'] = 'mail' #msg['To'] = '<EMAIL>' #msg['Subject'] = 'Just A Test' #server.send_message('<EMAIL>','<EMAIL>','testing with python') import math import socket import threading import os import re contentmath = dir(math) contentsocket = dir(socket) contentthreading = dir(threading) #print(contentsocket) #print("\t") #print(contentmath) #print("\t") #print(contentthreading) #fo = open("test.txt") #print(fo.name) #print(fo.closed) #print(fo.mode) #os.rename('test.txt','testname.txt') try: fo = open("testname.txt","wb") fo.write("Python is amazing") #fo.close except: print("Error in writting in the file") else: print("Content written successfully") fo.close() state = "Dogs are better than cats" searchObj = re.search(r'(.*) are (.*?) .*', state,re.M|re.I) if searchObj: print("searchObj.group() : ",searchObj.group()) print("searchObj.group(1) : ",searchObj.group(1)) print("searchObj.group(2) : ",searchObj.group(2)) else: print("Nothing found") <file_sep>/Track/networking/Neural/game.py from calendar import week import tkinter as tk from tkinter import filedialog, Text import os from tkinter import * from typing import Sized from tkcalendar import * import random root = tk.Tk() root.title("Bus Reservation System") #root.iconbitmap('C:\Users\ZEBRA\Downloads\carbackground.jpg') apps = [] if os.path.isfile('save.txt'): with open('save.txt','r') as f: tempApps = f.read() tempApps = tempApps.split(',') apps = [x for x in tempApps if x.strip()] print(tempApps) def addApp(): for widget in frame.winfo_children(): widget.destroy() filename = filedialog.askopenfilename(initialdir = "/", title = "Select File", filetypes = (("executable","*.exe"),("a;; files", "*.*"))) apps.append(filename) print(filename) for app in apps: label = tk.Label(frame, text = app, bg="gray") label.pack() def runApps(): for app in apps: os.startfile(app) def submit(): username = entry.get() print(username) def delete(): entry.delete(0, END) #delete the line of text def backspace(): entry.delete(len(entry.get())-1, END) #delete last character canvas = tk.Canvas(root, height=600, width= 700, bg= "#263D42") #Entry widget #mytext = Text(root,width = 60, height = 20) #mytext.pack(pady = 20) #entry.insert(0, 'Python') # entry.config(show='*') for password especially canvas.pack() frame = tk.Frame(root, bg= 'white') frame.place(relwidth= 0.8, relheight= 0.8, relx=0.1, rely= 0.1) label1 = Label(frame, text= 'Full Name') label1.place(x=20,y=20) mytext = Text(frame,width = 30, height = 1,) mytext.pack(pady = 20) destination = Label(frame,text="Destination") destination.place(x=20,y=70) variable = StringVar(frame) variable.set("Choose the destination") destinations = OptionMenu(frame,variable,'Nairobi','Mombasa','Kigali',"Bujumbura",'Juba','Kampala','Dar es Salam') destinations.pack() print(variable) direction = tk.Label(frame,text=destinations.__str__()) direction.pack() label2 = Label(frame,text= 'Date of travelling') label2.place(x= 20, y=120) label3 = Label(frame,text="Test") label3.place(x=250,y= 130) cal = Calendar(frame) cal.pack() dates = cal.get_date() des = destinations print(dates) entry = Entry() entry.config(font=("Ink Free",20)) entry.config(bg="gray") entry.config(fg="white") entry.config(width= 12) entry.pack() openFile = tk.Button(root, text= 'Open File', padx=10, pady=5, fg='white',bg="#263D42", command= addApp) openFile.pack() runApps = tk.Button(root, text= 'Run Apps', padx=10, pady=5, fg='white',bg="#263D42",command=runApps) runApps.pack() submit = tk.Button(root, text = 'Submit', command= submit) submit.pack(side = RIGHT) delete = tk.Button(root, text = 'delete', command= delete) delete.pack(side = LEFT) backspace = tk.Button(root, text = 'backspace', command= backspace) backspace.pack(side = LEFT) root.mainloop() with open('save.txt','w') as f: for app in apps: f.write(app + ',') <file_sep>/Track/guessing.py import random import sys def guess(x): number = 0 while number == 0: random_number = random.randint(1,x) guess = 0 while guess != random_number: guess = int(input(f'Guess a number between 1 and {x}: ')) if guess < random_number: print("Too Low") elif guess > random_number: print('Too High') print(f'JackPot!!!!!\ The Number {random_number} is right') #guess(int(input('Choose your Number limit: '))) def computer_guess(x): low = 1 high = x feedback = '' chance = 3 while feedback != 'c': guess = random.randint(low, high) feedback = input(f'Is {guess} too high (H), too low (L) or correct(C): ') if feedback == 'h': high = guess - 1 chance = chance - 1 print(f'{chance} try remaing') elif feedback == 'l': low = guess + 1 chance = chance - 1 print(f'{chance} try remaing') if chance == 0: print('Your chances are exausted') sys.exit() print(f'Congratulations!!! , {guess} is correct') computer_guess(100)<file_sep>/Track/networking/database.py import mysql.connector mydb = mysql.connector.connect(host = 'localhost', user = 'root', password = '<PASSWORD>') print(mydb)<file_sep>/Track/insert.py import mysql.connector mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>", database = "pythons" ) my_cursor = mydb.cursor() form = "Insert into employee(name,sal) values(%s,%s)" link = 'my link' money = 22000 employees = [('Me',250000),('You',250000),('Him',250000),('Us',750000),('You',580000),('Them',745000),(link,money),] my_cursor.executemany(form, employees) mydb.commit()<file_sep>/Track/bus/busdatabase.py import mysql.connector mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>", database = "Bus" ) my_cursor = mydb.cursor() #my_cursor.execute("CREATE TABLE reservation(reference INT, name VARCHAR(200), destination VARCHAR(200), date DATETIME DEFAULT CURRENT_TIMESTAMP)") #my_cursor.execute("ALTER TABLE reservation ADD COLUMN reference INT AFTER name;") #my_cursor.execute('ALTER TABLE reservation ADD COLUMN bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP;') #my_cursor.execute('ALTER TABLE reservation Modify date varchar(20);') #my_cursor.execute("CREATE TABLE Nairobi(reference INT, name VARCHAR(200), date varchar(20), bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP)") #my_cursor.execute("CREATE TABLE Bujumbura(reference INT, name VARCHAR(200), date varchar(20), bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP)") #my_cursor.execute("CREATE TABLE Mombasa(reference INT, name VARCHAR(200), date varchar(20), bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP)") #my_cursor.execute("CREATE TABLE Kigali(reference INT, name VARCHAR(200), date varchar(20), bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP)") my_cursor.execute("CREATE TABLE Kampala(reference INT, name VARCHAR(200), date varchar(20), bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP)") #my_cursor.execute("CREATE TABLE Juba(reference INT, name VARCHAR(200), date varchar(20), bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP)") #my_cursor.execute("CREATE TABLE Dar_es_Salam(reference INT, name VARCHAR(200), date varchar(20), bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP)") #my_cursor.execute('ALTER TABLE reservation ADD COLUMN bookingdate DATETIME DEFAULT CURRENT_TIMESTAMP;')<file_sep>/Track/track.py for x in range(6): print("X") a = 6 while(a == 6): print("a") break while True: print(a) a = a +1 if(a==10): break b = 10 print(b==90)<file_sep>/server.py import socket import threading HEADER = 64 PORT = 5050 #SERVER = "10.5.0.107" SERVER = socket.gethostbyname(socket.gethostname()) # to get the ip address #print(SERVER) #print(socket.gethostname()) #name of the computer on the network ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn ,addr): print(f"[NEW CONNECTION] {addr} connected.") connected = True while connected: msg_lenght = conn.recv(HEADER).decode(FORMAT) if msg_lenght: msg_lenght = int(msg_lenght) msg = conn.recv(msg_lenght).decode(FORMAT) if msg ==DISCONNECT_MESSAGE: connected = False print(f"[{addr}] {msg}") conn.close() def start(): server.listen() print(f"[LISTENING] Server is listening on {SERVER}") while True: conn, addr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}") print("[STARTING] server is starting ...") start() <file_sep>/Track/update.py import mysql.connector mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>", database = "pythons" ) my_cursor = mydb.cursor() update = "UPDATE employee SET sal=1000000 WHERE name='me'" my_cursor.execute(update) mydb.commit()<file_sep>/Track/networking/cgi.py print ("Content-type:text/html\r\n\r\n") print ('<html>') print ('<head>') print ('<title>Hello World - First CGI Program</title>') print ('</head>') print ('<body>') print ('<h2>Hello World! This is my first CGI program</h2>') print ('</body>') print ('</html>') import os print ("Content-type: text/html\r\n\r\n") print ("<font size=+1>Environment</font><\br>") for param in os.environ.keys(): print ("<b>%20s</b>: %s<\br>" % (param, os.environ[param])) import cgi, cgitb form = cgi.FieldStorage() first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print ("Content-type:text/html\r\n\r\n") print ("<html>") print ("<head>") print ("<title>Hello - Second CGI Program</title>") print ("</head>") print ("<body>") print ("<h2>Hello %s %s</h2>" % (first_name, last_name)) print ("</body>") print ("</html>")<file_sep>/Track/bus/reservation.py import mysql.connector import sys import random from calendar import week import tkinter as tk from tkinter import filedialog, Text import os from tkinter import * from typing import Sized from tkcalendar import * from tkinter import messagebox from tkinter import ttk import calendar import datetime import tkinter import tkcalendar mydb = mysql.connector.connect( host="localhost",user="root",passwd="<PASSWORD>",database = "Bus" ) bus = tk.Tk() bus.geometry('900x750') intro = Label(bus,text='Bus Management',font=('Arial',25)) intro.pack() my_cursor = mydb.cursor() place = 0 def intro(): for widget in bus.winfo_children(): widget.destroy() #intro = Label(bus,text='Dashboard',font=('Arial',25)) #intro.pack() intro = Label(bus,text='Dashboard',font=('Arial',25)) intro.pack() frame = tk.Frame(bus,bg='white') frame.place(relwidth= 0.8, relheight= 0.8, relx=0.1, rely= 0.1) #intro = Label(frame,text='Dashboard',font=('Arial',25)) #intro.pack() label1 = Label(frame, text= 'Full Name',font=('Arial',10)) label1.place(x=40,y=20) global mytext mytext = Text(frame,width = 30, height = 1,) mytext.pack(pady = 20) label2 = Label(frame,text="Destination",font=('Arial',10)) label2.place(x=40,y=70) global variable variable = StringVar(frame) variable.set("Choose the destination") destinations = OptionMenu(frame,variable,'Nairobi','Mombasa','Kigali',"Bujumbura",'Juba','Kampala','Dar es Salam') destinations.pack() label3 = Label(frame,text= 'Date of travelling',font=('Arial',10)) label3.place(x= 40, y=120) global cal cal = Calendar(frame) cal.pack() confirm = tk.Button(frame,text='register',bg = 'gray',command=registration) confirm.pack(side=BOTTOM) retrieve = tk.Button(frame,text='show client',bg='gray',command=display) retrieve.pack(side=RIGHT) def registration(): registration_number = random.randint(1,1000) name = mytext.get(1.0,END) destination = variable.get() date = cal.get_date() dates = datetime.date.today() form = "Insert into reservation(name,reference,destination,date,bookingdate) values(%s,%s,%s,%s,%s)" data = [(name,registration_number,destination,date,dates),] my_cursor.executemany(form, data) mydb.commit() if(destination == 'Nairobi'): forms = "Insert into nairobi(reference,name,date,bookingdate) values(%s,%s,%s,%s)" datas = [(registration_number,name,date,dates)] my_cursor.executemany(forms,datas) mydb.commit() elif(destination == 'Mombasa'): forms = "Insert into mombasa(reference,name,date,bookingdate) values(%s,%s,%s,%s)" datas = [(registration_number,name,date,dates)] my_cursor.executemany(forms,datas) mydb.commit() elif(destination == 'Kigali'): forms = "Insert into kigali(reference,name,date,bookingdate) values(%s,%s,%s,%s)" datas = [(registration_number,name,date,dates)] my_cursor.executemany(forms,datas) mydb.commit() elif(destination == 'Bujumbura'): forms = "Insert into bujumbura(reference,name,date,bookingdate) values(%s,%s,%s,%s)" datas = [(registration_number,name,date,dates)] my_cursor.executemany(forms,datas) mydb.commit() elif(destination == 'Juba'): forms = "Insert into juba(reference,name,date,bookingdate) values(%s,%s,%s,%s)" datas = [(registration_number,name,date,dates)] my_cursor.executemany(forms,datas) mydb.commit() elif(destination == 'Kampala'): forms = "Insert into kampala(reference,name,date,bookingdate) values(%s,%s,%s,%s)" datas = [(registration_number,name,date,dates)] my_cursor.executemany(forms,datas) mydb.commit() else: forms = "Insert into dar_es_salam(reference,name,date,bookingdate) values(%s,%s,%s,%s)" datas = [(registration_number,name,date,dates)] my_cursor.executemany(forms,datas) mydb.commit() try: messagebox.showinfo("Status",f"Client {name} with reference number {registration_number} and destination to {destination} registered successfully!") mytext.delete(1.0,END) except: messagebox.showerror("Error","Error While registering data!!") def display(): for widget in bus.winfo_children(): widget.destroy() intro = Label(bus,text='Customer Records',font=('Arial',25)) intro.pack() frame1 = tk.Frame(bus,bg='white') frame1.place(relwidth= 0.8, relheight= 0.8, relx=0.1, rely= 0.1) variables = StringVar(frame1) variables.set("Choose the destination") destinations = OptionMenu(frame1,variables,'Nairobi','Mombasa','Kigali',"Bujumbura",'Juba','Kampala','Dar es Salam','all') destinations.pack() global canvas canvas = tk.Canvas(frame1, height=600, width= 700, bg= "#263D42") canvas.pack() tree = ttk.Treeview(frame1) tree['columns'] = ('Full Name','Reference','Date','Booking Date') tree.column("#0",width=120,minwidth=25) tree.column("<NAME>", anchor=W, width= 120) tree.column("Reference", anchor= CENTER,width=80) tree.column("Date", anchor=W,width= 80) tree.column("Booking Date",anchor=W,width=120) tree.heading('#0',text="Label",anchor = W) tree.heading('Full Name',text='Customer name',anchor = W) tree.heading('Reference',text='Reference Number',anchor = CENTER) tree.heading('Date',text='Departure Date',anchor = W) tree.heading('Booking Date',text='Booking date',anchor = W) def show(): destinations = variables.get() if(destinations == 'Nairobi'): my_cursor.execute("Select * from nairobi") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Reference', 'Full Name', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) for i,(reference,full_name,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(reference,full_name,date,booking_date)) elif(destinations == 'Mombasa'): my_cursor.execute("Select * from mombasa") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Reference', 'Full Name', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) count = 0 for i,(reference,full_name,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(reference,full_name,date,booking_date)) elif(destinations == 'Kigali'): my_cursor.execute("Select * from kigali") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Reference', 'Full Name', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) count = 0 for i,(reference,full_name,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(reference,full_name,date,booking_date)) elif(destinations == 'Bujumbura'): my_cursor.execute("Select * from bujumbura") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() #i = 0 label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Reference', 'Full Name', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) count = 0 for i,(reference,full_name,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(reference,full_name,date,booking_date)) elif(destinations == 'Juba'): my_cursor.execute("Select * from juba") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Reference', 'Full Name', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) count = 0 for i,(reference,full_name,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(reference,full_name,date,booking_date)) elif(destinations == 'Kampala'): my_cursor.execute("Select * from kampala") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Reference', 'Full Name', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) count = 0 for i,(reference,full_name,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(reference,full_name,date,booking_date)) elif(destinations == 'Dar es Salam'): my_cursor.execute("Select * from dar_es_salam") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Reference', 'Full Name', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) count = 0 for i,(reference,full_name,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(reference,full_name,date,booking_date)) elif(destinations == 'all'): my_cursor.execute("Select * from reservation") result = my_cursor.fetchall() for widget in canvas.winfo_children(): widget.destroy() i = 0 label = tk.Label(canvas, text=f"{destinations} Records", font=("Arial",20)).grid(row=0, columnspan=3) cols = ('Full Name','Reference','destination', 'date','booking date') listBox = ttk.Treeview(canvas, columns=cols, show='headings') for col in cols: listBox.heading(col, text=col) listBox.grid(row=1, column=0, columnspan=2) count = 0 for i,(full_name,reference,destination,date,booking_date) in enumerate(result,start=1): listBox.insert("","end",values=(full_name,reference,destination,date,booking_date)) else: messagebox.showerror("Error","No destination selected!!") confirm = tk.Button(bus,text='Display Client',command=show) confirm.place(x=350,y=680) dashboard = tk.Button(bus, text="Dasboard", command= clearing) dashboard.place(x=500,y=680) def clear_data(): for widget in frame1.winfo_children(): widget.destroy() display() clears = tk.Button(bus,text='Clear',command=clear_data) clears.place(x=450,y=680) def clearing(): for widgets in bus.winfo_children(): widgets.destroy() intro() intro()
5d5c30d4691e68dfe7ab6913ccafbce349526ada
[ "Python" ]
18
Python
mingabire809/Python-Work
fc148dfef6008b6f1b1b4bcbc133535e61c64f80
ab1455a50f3620ec642b568dbb5147bf3dbbffe9
refs/heads/master
<file_sep># python pokespam.py from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep login_timer = 40 # how long you have before it tries to spam spam_timer = 10 # how many seconds between each spam message will be message_text = "Gimme really shitty ivs pokemans" driver = webdriver.Chrome() driver.get("http://discord.com/login") sleep(login_timer) # You have 40 seconds to login and get to the right channel before it spams whatever you want to spam below # I originally had a counter here, so that I could see how much it counted up. # I replaced it, but left it here commented out if anyone wants to still use it. i = 1 while i: message = driver.find_element_by_xpath('//*[@id="app-mount"]/div[2]/div/div[2]/div/div/div/div[2]/div[2]/div/main/form/div/div/div/div/div[3]/div[2]/div') message.send_keys(message_text) # message.send_keys(str(i)) message.send_keys(Keys.ENTER) sleep(spam_timer) # i += 1 <file_sep># simple-discord-spam ##Requirements - Python - selenium - chromedriver You can install python pretty easily. After you have python, open up terminal/command prompt/powershell and run: `pip install selenium` or you can run: `pip install -r requirements` To install chromedriver, go to https://chromedriver.chromium.org/downloads and download the appropriate release for your version of Chrome. Once you have that, add it to your environment variables. Here's a link if you are having trouble: https://zwbetz.com/download-chromedriver-binary-and-add-to-your-path-for-automated-functional-testing/ ##How to Use When you are ready, just open up terminal/command prompt/powershell and navigate to the folder you saved this into. Then run the command: `python pokespam.py` I've set it so that once it pulls up the login page, you have 40 seconds to login and get to the channel you want to spam. You can change this time limit and other settings by modifying the python script.
419d855b0747c2681d360f44cdf13da95608f0fd
[ "Markdown", "Python" ]
2
Python
Chibbluffy/simple-discord-spam
c282d8cd946d43bae560e2bdef2aa03e0b360543
0b94f0d1dadddc20209930bcf8ea884be63372a6
refs/heads/master
<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "8f40c3f9156b544f8715680af481c226", "url": "/index.html" }, { "revision": "62c42abeb814f47561d0", "url": "/static/css/main.c31a1cb3.chunk.css" }, { "revision": "3f0192330eb126bd71a0", "url": "/static/js/2.a017127b.chunk.js" }, { "revision": "68c0d7c329e910a59df2bd84fb7bd14d", "url": "/static/js/2.a017127b.chunk.js.LICENSE.txt" }, { "revision": "62c42abeb814f47561d0", "url": "/static/js/main.b49448b1.chunk.js" }, { "revision": "245ce8cad78fa7db9511", "url": "/static/js/runtime-main.c590a1be.js" } ]);<file_sep>import React, { useState } from 'react'; import { TextField, CircularProgress } from '@material-ui/core'; import Autocomplete from '@material-ui/lab/Autocomplete'; const CitySearch = (props) => { const [cities, setCitiesList] = useState([]) const [open, setOpen] = useState({value: false}); const [loading, setLoading] = useState({value: false}) const getCities = async () => { const res = await fetch('./API/cityList.json'); const data = await res.json() setCitiesList(data); setLoading({value: false}); } return ( <> <Autocomplete options={cities} getOptionLabel={option => option.city} open={open.value} style={{ width: 300 }} renderInput={params => <TextField {...params} label="City Search" variant="outlined" name="city" InputProps={{ ...params.InputProps, endAdornment: ( <> {loading.value ? <CircularProgress color="inherit" size={20} /> : null} {params.InputProps.endAdornment} </> ), }} />} loading={loading.value} onOpen={() => { setOpen({value: true}); setLoading({value: true}); getCities() }} onClose={() => { setOpen({value: false}); setCitiesList([]) }} onChange={(e, value)=> props.findCity(value)} /> </> ) } export default CitySearch; <file_sep>import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Box, Typography } from '@material-ui/core'; const useStyles = makeStyles(theme => ({ root: { maxWidth: 400, height: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center' }, title: { fontSize: 150, color: 'white', textAlign: 'center' }, text: { fontSize: 20, color: 'white', fontWeight: 500, }, city: { color: 'white' } })); const DisplayToday = ({city}) => { const classes = useStyles(); console.log(city.value) const [weather, setWeather] = useState({value: null}) console.log(weather) useEffect(()=> { console.log('usee effect fired') const getWeather = async() => { let cityID = city.value.id; const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?id=${cityID}&appid=667259d3e642f1444ef8a44dc01be273`); const data = await res.json(); setWeather({value: data}) } if(city.value) { getWeather() } },[city.value]) const getCelsius = (kelvin) => Math.round(kelvin - 273.15) + "°c"; const getKPH = (miles) => Math.round(miles * 1.609); let image; if(weather.value) { image = `https://openweathermap.org/themes/openweathermap/assets/vendor/owm/img/widgets/${weather.value.weather[0].icon}.png` } return weather.value ? ( <Box> <Typography variant="h1" component="h2" color="textSecondary" className={classes.title} > {getCelsius(weather.value.main.temp)} </Typography> <Box display='flex' flexDirection = 'column' justifyContent="space-around" alignItems="center" className={classes.text} > <Box display='flex' justifyContent="space-around" alignItems = 'center' > <Typography variant="h4" component="h2" color="textSecondary" className={classes.city} > {weather.value.name}: </Typography> <img src={image} alt="weather icon" /></Box> <Box>Wind: {getKPH(weather.value.wind.speed)}km/h</Box> <Box>Humidity: {weather.value.main.humidity} %</Box> <Box>Pressure: {weather.value.main.pressure} hPa</Box> </Box> </Box> ) : null } export default DisplayToday;<file_sep>import React from 'react'; import Today from './Today'; import { Container } from '@material-ui/core'; const Main = () => { return ( <main> <Container> <Today /> </Container> </main> ) } export default Main;<file_sep>import React, { useState, useContext } from 'react'; import { Context } from './../../Context/Context'; import { logOutUser } from './../../Context/userActions'; import fb from './../../config/fbConfig'; import { Link, useHistory } from 'react-router-dom'; import { makeStyles } from '@material-ui/core/styles'; import { Box, Button, AppBar, Toolbar, Typography, IconButton, SwipeableDrawer, MenuList, MenuItem, } from '@material-ui/core'; import MenuIcon from '@material-ui/icons/Menu'; import DashboardIcon from '@material-ui/icons/Dashboard'; import AccountCircleIcon from '@material-ui/icons/AccountCircle'; import AccountBoxIcon from '@material-ui/icons/AccountBox'; import ExitToAppIcon from '@material-ui/icons/ExitToApp'; const useStyles = makeStyles(theme => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), fontSize: 26 }, title: { flexGrow: 1, }, linksList: { width: 200, }, buttons: { fontWeight: 500, fontSize: 14 } })); const Navbar = () => { const classes = useStyles(); const [state, setState] = useState({ menuOpen: false }); const { user, dispatch } = useContext(Context); const history = useHistory(); const signedInLinks = [{ name: 'Main', icon: 'DashboardIcon', path: '/' },{ name: 'Profile', icon: 'AccountCircleIcon', path: '/profile' }] const signedOutLinks = [{ name: 'Sign Up', icon: 'AccountBoxIcon', path: '/signup' },{ name: 'Log In', icon: 'AccountCircleIcon', path: '/login' }] const getIconHandler = icon => { switch(icon){ case 'Main': return(<DashboardIcon className={classes.menuButton}/>); case 'Profile': case 'Log In': return (<AccountCircleIcon className={classes.menuButton}/>) case 'Log Out': return (<ExitToAppIcon className={classes.menuButton}/>) case 'Sign Up': return (<AccountBoxIcon className={classes.menuButton}/>) default: return(<DashboardIcon className={classes.menuButton}/>); } } const logOut = () => { fb.auth().signOut().then(()=>{ dispatch(logOutUser()); history.push("/"); }).catch(err=>{ console.log(err.message) }) } const toggleDrawer = (open) => event => { if (event && event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) { return; } setState({ ...state, menuOpen: open }); }; const sideList = () => ( <div role="presentation" onClick={toggleDrawer(false)} onKeyDown={toggleDrawer(false)} > <MenuList className={classes.linksList}> {user.value ? signedInLinks.map((link, index)=>( <MenuItem button component={Link} to={link.path} key={index}> {getIconHandler(link.name)} <Box fontSize={16} ml={1}>{link.name}</Box> </MenuItem> )) : signedOutLinks.map((link, index)=>( <MenuItem button component={Link} to={link.path} key={index}> {getIconHandler(link.name)} <Box fontSize={16} ml={1}>{link.name}</Box> </MenuItem> ))} </MenuList> </div> ); return ( <div className={classes.root}> {/* App bar start */} <AppBar position="fixed" color="primary" > <Toolbar> <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu" onClick={toggleDrawer(true)}> <MenuIcon /> </IconButton> <Typography variant="h6" className={classes.title}> <Button color="primary" variant="contained" component={Link} to="/" className={classes.buttons}> Weather </Button> </Typography> {user.value ? <Button color="inherit" onClick={()=> logOut()} >Logout </Button> : null} </Toolbar> </AppBar> {/* App bar end */} {/* Drawer start */} <SwipeableDrawer open={state.menuOpen} onClose={toggleDrawer(false)} onOpen={toggleDrawer(true)} > {sideList()} </SwipeableDrawer> {/* Drawer end */} </div> ); } export default Navbar;<file_sep>import React, { useState, useContext } from 'react'; import { Context } from './../../Context/Context'; import { LoadingStatus } from './../../Context/userActions'; import { addUser } from './../../Context/userActions'; import { makeStyles } from '@material-ui/core/styles'; import { Link, useHistory } from 'react-router-dom'; import fb from './../../config/fbConfig'; import { motion } from 'framer-motion'; import { Container, Box, TextField, InputAdornment, Typography, Button, CircularProgress } from '@material-ui/core'; import EmailIcon from '@material-ui/icons/Email'; import VisibilityOffIcon from '@material-ui/icons/VisibilityOff'; const useStyles = makeStyles(theme => ({ root: { maxWidth: 400, height: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }, fonts: { fontWeight: '600', textDecoration: 'underline', textAlign: 'center' }, cursor: { cursor: 'pointer' } })); const LogIn = () => { const classes = useStyles(); const [fieldsState, setFieldsState] = useState({ email: null, password: <PASSWORD> }) const [errorState, setErrorState] = useState({ value: null }) const [showPassword, setShowPassword] = useState({show: false}); const {dispatch, user} = useContext(Context); const history = useHistory(); const showPass = () => { const showP = showPassword.show; setShowPassword({show: !showP}) } const inputFieldHandler = (e) => { const currentState = {...fieldsState}; currentState[e.target.name] = e.target.value; setFieldsState(currentState) } const submitFormHandler = (e) => { e.preventDefault() const email = fieldsState.email; const password = fieldsState.password; if(email && password) { dispatch(LoadingStatus()) fb.auth().signInWithEmailAndPassword(email, password) .then(cred => { dispatch(addUser(cred)) setFieldsState({ email: null, password: null }) console.log(user) setErrorState({value: null}) history.push("/"); }).catch(err=> { setErrorState({value: err.message}) }) } else { setErrorState({value: 'Fill in all fields!'}) } } return user.isLoading ? ( <Container className={classes.root} > <CircularProgress variant="indeterminate" color="secondary" size="80px" /> </Container> ) : ( <motion.div initial={{ scale: 0 }} animate={{ scale: 1 }} exit={{ scale: 0 }} > <Container className={classes.root} > <Typography variant="h4" component="h2" color="textSecondary" > Log In: </Typography> <form> <TextField fullWidth margin = "normal" placeholder = 'Enter email...' id="email" name="email" label="Email" helperText="" variant="outlined" InputProps={{ startAdornment: ( <InputAdornment position="start"> <EmailIcon color="primary" /> </InputAdornment> ), }} onInput={(e)=> inputFieldHandler(e)} /> <TextField autoComplete="true" fullWidth margin = "normal" placeholder = 'Enter password...' id="password" name="password" label="Password" helperText="" variant="outlined" type={showPassword.show ? "text" : "password"} InputProps={{ startAdornment: ( <InputAdornment position="start"> <VisibilityOffIcon className={classes.cursor} color="primary" onClick={()=> showPass()} /> </InputAdornment> ), }} onInput={(e)=> inputFieldHandler(e)} /> {errorState ? (<Typography color="error" className={classes.fonts}>{errorState.value}</Typography>) : null } <Box display='flex' justifyContent="space-around" alignItems="center" mt={3} > <Button variant="contained" color="primary" onClick={(e)=> submitFormHandler(e)} > Log In </Button> <Button variant="contained" color="secondary" component={Link} to='/signup'> Sign Up </Button> </Box> </form> </Container> </motion.div> ) } export default LogIn;<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "8752ac5ffb66744e869748c23993cb36", "url": "/index.html" }, { "revision": "ce36bb8c180f3a3d3542", "url": "/static/css/main.c31a1cb3.chunk.css" }, { "revision": "b4bc54bf502063d98180", "url": "/static/js/2.a1b5d246.chunk.js" }, { "revision": "68c0d7c329e910a59df2bd84fb7bd14d", "url": "/static/js/2.a1b5d246.chunk.js.LICENSE.txt" }, { "revision": "ce36bb8c180f3a3d3542", "url": "/static/js/main.af4b070c.chunk.js" }, { "revision": "245ce8cad78fa7db9511", "url": "/static/js/runtime-main.c590a1be.js" } ]);<file_sep>export const ADD_USER = 'ADD_USER'; export const LOG_OUT = 'LOG_OUT'; export const LOADING = 'LOADING'; export const addUser = (data) => { return { type: ADD_USER, payload: data } } export const logOutUser = () => { return { type: LOG_OUT, } } export const LoadingStatus = () => { return { type: LOADING } }<file_sep>import React, { createContext, useReducer } from 'react'; import UserReducer from './userReducer'; export const Context = createContext(); const initialUserState = { value: null, isLoading: false }; const Provider = (props) => { const [user, dispatch] = useReducer(UserReducer, initialUserState); return ( <Context.Provider value={{user, dispatch}}> {props.children} </Context.Provider> ) } export default Provider;<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "d32baf3a3e1117ba4a1712ca2e15eab3", "url": "/index.html" }, { "revision": "23660c6bc1206a57e1da", "url": "/static/css/main.c31a1cb3.chunk.css" }, { "revision": "3f0192330eb126bd71a0", "url": "/static/js/2.a017127b.chunk.js" }, { "revision": "68c0d7c329e910a59df2bd84fb7bd14d", "url": "/static/js/2.a017127b.chunk.js.LICENSE.txt" }, { "revision": "23660c6bc1206a57e1da", "url": "/static/js/main.ddc8d1d7.chunk.js" }, { "revision": "245ce8cad78fa7db9511", "url": "/static/js/runtime-main.c590a1be.js" } ]);
4c217d9cbe6bf1b7c8771dbe7112a6441770030b
[ "JavaScript" ]
10
JavaScript
igormarcikic/weather-demo
db30f74efec42366c80bb5d6f36724da559d3362
81b604b5497356bae775729ac9891fbbcade37ac
refs/heads/master
<repo_name>anandbadanahatti19/shop<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { CommonComponent } from './common/common.component'; import { HeaderComponent } from './common/header/header.component'; import { FooterComponent } from './common/footer/footer.component'; import { HomeComponent } from './home/home.component'; import { PartnersComponent } from './partners/partners.component'; import { OffersAndDealsComponent } from './offers-and-deals/offers-and-deals.component'; import { ProductsSearchComponent } from './products-search/products-search.component'; import { LayoutComponent } from './common/layout/layout.component'; import { MenuSearchComponent } from './common/menu-search/menu-search.component'; import { FilterComponent } from './common/filter/filter.component'; @NgModule({ declarations: [ AppComponent, CommonComponent, HeaderComponent, FooterComponent, HomeComponent, PartnersComponent, OffersAndDealsComponent, ProductsSearchComponent, LayoutComponent, MenuSearchComponent, FilterComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
027b2c0a97731abf8ca80e1749fde6019bdbc034
[ "TypeScript" ]
1
TypeScript
anandbadanahatti19/shop
f3b52b2d04b34bb32a9b08a7eefcfdbb884dab4e
65071c9a8dca586af6b851e216babb550c27863e
refs/heads/master
<repo_name>ssatiz/InfluxFinalTask<file_sep>/task/src/main/java/com/influx/task/view/CustomGridView.kt package com.influx.task.view import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.influx.task.R import com.influx.task.model.DargChildInfo import com.influx.task.other.CommUtil import java.util.ArrayList /** * 类: CustomGridView * * * 描述: TODO * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:07:44 * * */ class CustomGridView : LinearLayout { private var mContext: Context? = null private val mPlayList = ArrayList<DargChildInfo>() private var viewHeight: Int = 0 private var viewWidth: Int = 0 private var mParentView: LinearLayout? = null private var rowNum: Int = 0 private var verticalViewWidth: Int = 0 var childClickListener: CustomChildClickListener? = null interface CustomChildClickListener { fun onChildClicked(chilidInfo: DargChildInfo) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { initView(context) } private fun initView(context: Context) { this.mContext = context verticalViewWidth = CommUtil.dip2px(mContext!!, 1f) val root = View.inflate(mContext, R.layout.gridview_child_layoutview, null) val textView = root.findViewById<View>(R.id.gridview_child_name_tv) as TextView val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) textView.measure(widthSpec, heightSpec) viewHeight = textView.measuredHeight viewWidth = (mContext!!.resources.displayMetrics.widthPixels - CommUtil.dip2px(mContext!!, 2f)) / CustomGroup.COLUMNUM } constructor(context: Context) : super(context) { initView(context) } /** * 方法: refreshDataSet * * * 描述: 刷新页面 * * * 参数: @param playList * * * 返回: void * * * 异常 * * * 作者: 梅雄新 <EMAIL> * * * 时间: 2014年11月15日 上午10:46:06 * * */ fun refreshDataSet(playList: ArrayList<DargChildInfo>) { mPlayList.clear() mPlayList.addAll(playList) notifyDataSetChange(false) } /** * 方法: notifyDataSetChange * * * 描述: 刷新UI * * * 参数: @param needAnim * * * 返回: void * * */ fun notifyDataSetChange(needAnim: Boolean) { removeAllViews() rowNum = mPlayList.size / CustomGroup.COLUMNUM + if (mPlayList.size % CustomGroup.COLUMNUM > 0) 1 else 0 val rowParam = LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) val verticalParams = LinearLayout.LayoutParams(verticalViewWidth, LinearLayout.LayoutParams.FILL_PARENT) val horizontalParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, verticalViewWidth) for (rowIndex in 0 until rowNum) { val llContainer = LinearLayout(mContext) llContainer.orientation = LinearLayout.HORIZONTAL val itemParam = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) itemParam.width = viewWidth for (columnIndex in 0 until CustomGroup.COLUMNUM) { val itemInfoIndex = rowIndex * CustomGroup.COLUMNUM + columnIndex var isValidateView = true if (itemInfoIndex >= mPlayList.size) { isValidateView = false } val root = View.inflate(mContext, R.layout.gridview_child_layoutview, null) val textView = root.findViewById<View>(R.id.gridview_child_name_tv) as TextView if (isValidateView) { val tempChilid = mPlayList[itemInfoIndex] textView.text = tempChilid.name textView.setOnClickListener { if (childClickListener != null) { childClickListener!!.onChildClicked(tempChilid) } } } llContainer.addView(root, itemParam) if (columnIndex != CustomGroup.COLUMNUM - 1) { val view = View(mContext) view.setBackgroundResource(R.drawable.ver_line) llContainer.addView(view, verticalParams) } } addView(llContainer, rowParam) val view = View(mContext) view.setBackgroundResource(R.drawable.hor_line) addView(view, horizontalParams) Log.e("animator", "" + height + "--" + rowNum * viewHeight) if (needAnim) { createHeightAnimator(mParentView, this@CustomGridView.height, rowNum * viewHeight) } } } /** * 方法: createHeightAnimator * * * 描述: TODO * * * 参数: @param view * 参数: @param start * 参数: @param end * * * 返回: void * * */ fun createHeightAnimator(view: View?, start: Int, end: Int) { val animator = ValueAnimator.ofInt(start, end) animator.addUpdateListener { valueAnimator -> val value = valueAnimator.animatedValue as Int val layoutParams = view!!.layoutParams layoutParams.height = value view.layoutParams = layoutParams } animator.duration = 200 animator.start() } /** * 方法: setParentView * * * 描述: TODO * * * 参数: @param llBtm * * * 返回: void * * */ fun setParentView(llBtm: LinearLayout) { this.mParentView = llBtm } } <file_sep>/task/src/main/java/com/influx/task/view/CustomBehindView.kt package com.influx.task.view import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.graphics.Bitmap import android.graphics.Rect import android.os.Handler import android.view.* import android.view.ViewTreeObserver.OnPreDrawListener import android.view.animation.AccelerateDecelerateInterpolator import android.widget.* import com.influx.task.R import com.influx.task.model.DragIconInfo import com.influx.task.other.DragGridAdapter import java.util.ArrayList import java.util.LinkedList /** * * 类: CustomBehindView * * * 描述: TODO * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:08:40 * * */ class CustomBehindView(private val mContext: Context, private val mCustomGroup: CustomGroup) : GridView(mContext) { /*** DragGridView的item长按响应的时间, 默认是1000毫秒,也可以自行设置 */ private var dragResponseMS: Long = 100 /** 是否可以拖拽,默认不可以 */ private var isDrag = false private var mDownX: Int = 0 private var mDownY: Int = 0 private var moveX: Int = 0 private var moveY: Int = 0 /** 正在拖拽的position */ private var mDragPosition: Int = 0 /*** 刚开始拖拽的item对应的View */ private var mStartDragItemView: View? = null /** 用于拖拽的镜像,这里直接用一个ImageView */ private var mDragImageView: ImageView? = null private val mWindowManager: WindowManager /** item镜像的布局参数 */ private var mWindowLayoutParams: WindowManager.LayoutParams? = null /** 我们拖拽的item对应的Bitmap */ private var mDragBitmap: Bitmap? = null /** 按下的点到所在item的上边缘的距离 */ private var mPoint2ItemTop: Int = 0 /** 按下的点到所在item的左边缘的距离 */ private var mPoint2ItemLeft: Int = 0 /** DragGridView距离屏幕顶部的偏移量 */ private var mOffset2Top: Int = 0 /** DragGridView距离屏幕左边的偏移量 */ private var mOffset2Left: Int = 0 /** 状态栏的高度 */ private val mStatusHeight: Int /** DragGridView自动向下滚动的边界值 */ private var mDownScrollBorder: Int = 0 /** DragGridView自动向上滚动的边界值 */ private var mUpScrollBorder: Int = 0 private var mAnimationEnd = true private var mNumColumns = GridView.AUTO_FIT private var mDragAdapter: DragGridAdapter? = null /** * * 方法: getEditList * * * 描述: TODO * * * 参数: @return * * * 返回: ArrayList<DragIconInfo> </DragIconInfo> * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:00:24 */ val editList = ArrayList<DragIconInfo>() private val mHandler = Handler() private val mLongClickRunnable = Runnable { isDrag = true mStartDragItemView!!.visibility = View.INVISIBLE createDragImage(mDragBitmap, mDownX, mDownY) } private var isFirstLongDrag: Boolean = false private var hasFirstCalculate = false /** * 当moveY的值大于向上滚动的边界值,触发GridView自动向上滚动 当moveY的值小于向下滚动的边界值,触发GridView自动向下滚动 * 否则不进行滚动 */ @SuppressLint("NewApi") private val mScrollRunnable = object : Runnable { override fun run() { val scrollY: Int if (firstVisiblePosition == 0 || lastVisiblePosition == count - 1) { mHandler.removeCallbacks(this) } if (moveY > mUpScrollBorder) { scrollY = speed mHandler.postDelayed(this, 25) } else if (moveY < mDownScrollBorder) { scrollY = -speed mHandler.postDelayed(this, 25) } else { scrollY = 0 mHandler.removeCallbacks(this) } smoothScrollBy(scrollY, 10) } } private var parentView: CustomBehindParent? = null /** * * 方法: isModifyedOrder * * * 描述: 是否修改 * * * 参数: @return * * * 返回: boolean * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:35:20 */ val isModifyedOrder: Boolean get() = mDragAdapter!!.isHasModifyedOrder init { this.numColumns = CustomGroup.COLUMNUM mWindowManager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager mStatusHeight = getStatusHeight(mContext) // 获取状态栏的高度 } override fun setAdapter(adapter: ListAdapter) { super.setAdapter(adapter) if (adapter is DragGridAdapter) { mDragAdapter = adapter } else { throw IllegalStateException("the adapter must be implements DragGridAdapter") } } override fun setNumColumns(numColumns: Int) { super.setNumColumns(numColumns) this.mNumColumns = numColumns } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE shr 2, View.MeasureSpec.AT_MOST) super.onMeasure(widthMeasureSpec, expandSpec) } /** * 设置响应拖拽的毫秒数,默认是1000毫秒 * * @param dragResponseMS */ fun setDragResponseMS(dragResponseMS: Long) { this.dragResponseMS = dragResponseMS } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { when (ev.action) { MotionEvent.ACTION_DOWN -> { mDownX = ev.x.toInt() mDownY = ev.y.toInt() val tempPosit = pointToPosition(mDownX, mDownY) if (tempPosit == AdapterView.INVALID_POSITION) { return true } if (mCustomGroup.isEditModel && tempPosit != mDragPosition) { mCustomGroup.setEditModel(false, 0) return true } mHandler.postDelayed(mLongClickRunnable, dragResponseMS) mStartDragItemView = getChildAt(mDragPosition - firstVisiblePosition) mPoint2ItemTop = mDownY - mStartDragItemView!!.top mPoint2ItemLeft = mDownX - mStartDragItemView!!.left mOffset2Top = (ev.rawY - mDownY).toInt() mOffset2Left = (ev.rawX - mDownX).toInt() mDownScrollBorder = height / 5 mUpScrollBorder = height * 4 / 5 mStartDragItemView!!.isDrawingCacheEnabled = true mDragBitmap = Bitmap.createBitmap(mStartDragItemView!!.drawingCache) mStartDragItemView!!.destroyDrawingCache() } MotionEvent.ACTION_MOVE -> { val moveX = ev.x.toInt() val moveY = ev.y.toInt() if (isFirstLongDrag && !hasFirstCalculate) { mStartDragItemView = getChildAt(mDragPosition - firstVisiblePosition) mPoint2ItemTop = moveY - mStartDragItemView!!.top mPoint2ItemLeft = moveX - mStartDragItemView!!.left mOffset2Top = (ev.rawY - moveY).toInt() mOffset2Left = (ev.rawX - moveX).toInt() hasFirstCalculate = true } if (!isTouchInItem(mStartDragItemView, moveX, moveY)) { mHandler.removeCallbacks(mLongClickRunnable) } } MotionEvent.ACTION_UP -> { mHandler.removeCallbacks(mLongClickRunnable) mHandler.removeCallbacks(mScrollRunnable) } } return super.dispatchTouchEvent(ev) } fun drawWindowView(position: Int, event: MotionEvent) { mHandler.postDelayed({ mDragPosition = position if (mDragPosition != AdapterView.INVALID_POSITION) { isFirstLongDrag = true mDragAdapter!!.setModifyPosition(mDragPosition) mDownX = event.x.toInt() mDownY = event.y.toInt() mStartDragItemView = getChildAt(mDragPosition - firstVisiblePosition) createFirstDragImage() } }, 100) } private fun createFirstDragImage() { removeDragImage() isDrag = true val ivDelet = mStartDragItemView!!.findViewById<View>(R.id.delet_iv) as ImageView val llContainer = mStartDragItemView!!.findViewById<View>(R.id.edit_ll) as LinearLayout if (ivDelet != null) { ivDelet.visibility = View.VISIBLE } llContainer.setBackgroundColor(mContext.resources.getColor(R.color.item_bg)) mStartDragItemView!!.isDrawingCacheEnabled = true mDragBitmap = Bitmap.createBitmap(mStartDragItemView!!.drawingCache) mStartDragItemView!!.destroyDrawingCache() llContainer.setBackgroundColor(mContext.resources.getColor(R.color.white)) mWindowLayoutParams = WindowManager.LayoutParams() mWindowLayoutParams!!.format = 1 mWindowLayoutParams!!.gravity = Gravity.TOP or Gravity.LEFT val location = IntArray(2) mStartDragItemView!!.getLocationOnScreen(location) mWindowLayoutParams!!.x = location[0]// (x-mLastX-xtox)+dragItemView.getLeft()+8; mWindowLayoutParams!!.y = location[1] - mStatusHeight mWindowLayoutParams!!.height = WindowManager.LayoutParams.WRAP_CONTENT mWindowLayoutParams!!.width = WindowManager.LayoutParams.WRAP_CONTENT mWindowLayoutParams!!.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE mDragImageView = ImageView(context) mDragImageView!!.setBackgroundColor(mContext.resources.getColor(R.color.item_bg)) mDragImageView!!.setImageBitmap(mDragBitmap) mWindowManager.addView(mDragImageView, mWindowLayoutParams) mStartDragItemView!!.visibility = View.INVISIBLE// 隐藏该item } private fun isTouchInItem(dragView: View?, x: Int, y: Int): Boolean { if (dragView == null) { return false } val leftOffset = dragView.left val topOffset = dragView.top if (x < leftOffset || x > leftOffset + dragView.width) { return false } return !(y < topOffset || y > topOffset + dragView.height) } override fun onTouchEvent(ev: MotionEvent): Boolean { if (isDrag && mDragImageView != null) { when (ev.action) { MotionEvent.ACTION_MOVE -> { // LogUtil.d("CustomBehindView onTouchEvent", "ACTION_MOVE"); moveX = ev.x.toInt() moveY = ev.y.toInt() // 拖动item onDragItem(moveX, moveY) } MotionEvent.ACTION_UP -> { val dropx = ev.x.toInt() val dropy = ev.y.toInt() onStopDrag(dropx, dropy) isDrag = false isFirstLongDrag = false hasFirstCalculate = false } } return true } return super.onTouchEvent(ev) } /** * * 方法: cancleEditModel * * * 描述: 是否修改了 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:19:25 */ fun cancleEditModel() { removeDragImage() mCustomGroup.setEditModel(false, 0) } /**、 * * 方法: createDragImage * * * 描述: TODO * * * 参数: @param bitmap * 参数: @param downX 按下的点相对父控件的X坐标 * 参数: @param downY 按下的点相对父控件的Y坐标 * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:19:39 */ private fun createDragImage(bitmap: Bitmap?, downX: Int, downY: Int) { mWindowLayoutParams = WindowManager.LayoutParams() mWindowLayoutParams!!.format = 1 mWindowLayoutParams!!.gravity = Gravity.TOP or Gravity.LEFT mWindowLayoutParams!!.x = downX - mPoint2ItemLeft + mOffset2Left mWindowLayoutParams!!.y = downY - mPoint2ItemTop + mOffset2Top - mStatusHeight mWindowLayoutParams!!.width = WindowManager.LayoutParams.WRAP_CONTENT mWindowLayoutParams!!.height = WindowManager.LayoutParams.WRAP_CONTENT mWindowLayoutParams!!.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE mDragImageView = ImageView(context) mDragImageView!!.setBackgroundColor(mContext.resources.getColor(R.color.item_bg)) mDragImageView!!.setImageBitmap(bitmap) mWindowManager.addView(mDragImageView, mWindowLayoutParams) } /** * * 方法: removeDragImage * * * 描述: 从界面上面移除拖动镜像 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:19:52 */ private fun removeDragImage() { if (mDragImageView != null) { mWindowManager.removeView(mDragImageView) mDragImageView = null } } /** * * 方法: onDragItem * * * 描述: 拖动item,在里面实现了item镜像的位置更新,item的相互交换以及GridView的自行滚动 * * * 参数: @param moveX * 参数: @param moveY * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:20:08 */ private fun onDragItem(moveX: Int, moveY: Int) { mWindowLayoutParams!!.x = moveX - mPoint2ItemLeft + mOffset2Left mWindowLayoutParams!!.y = moveY - mPoint2ItemTop + mOffset2Top - mStatusHeight mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams) // 更新镜像的位置 onSwapItem(moveX, moveY) // GridView自动滚动 mHandler.post(mScrollRunnable) } /** * 交换item,并且控制item之间的显示与隐藏效果 * * @param moveX * @param moveY */ private fun onSwapItem(moveX: Int, moveY: Int) { // 获取我们手指移动到的那个item的position val tempPosition = pointToPosition(moveX, moveY) // 假如tempPosition 改变了并且tempPosition不等于-1,则进行交换 if (tempPosition != mDragPosition && tempPosition != AdapterView.INVALID_POSITION && mAnimationEnd) { if (tempPosition != editList.size - 1) { mDragAdapter!!.reorderItems(mDragPosition, tempPosition) mDragAdapter!!.setHideItem(tempPosition) val observer = viewTreeObserver observer.addOnPreDrawListener(object : OnPreDrawListener { override fun onPreDraw(): Boolean { observer.removeOnPreDrawListener(this) animateReorder(mDragPosition, tempPosition) mDragPosition = tempPosition return true } }) } } } private fun createTranslationAnimations( view: View, startX: Float, endX: Float, startY: Float, endY: Float ): AnimatorSet { val animX = ObjectAnimator.ofFloat(view, "translationX", startX, endX) val animY = ObjectAnimator.ofFloat(view, "translationY", startY, endY) val animSetXY = AnimatorSet() animSetXY.playTogether(animX, animY) return animSetXY } private fun animateReorder(oldPosition: Int, newPosition: Int) { val isForward = newPosition > oldPosition val resultList = LinkedList<Animator>() if (isForward) { for (pos in oldPosition until newPosition) { val view = getChildAt(pos - firstVisiblePosition) println(pos) if ((pos + 1) % mNumColumns == 0) { resultList.add( createTranslationAnimations( view, (-view.width * (mNumColumns - 1)).toFloat(), 0f, view.height.toFloat(), 0f ) ) } else { resultList.add(createTranslationAnimations(view, view.width.toFloat(), 0f, 0f, 0f)) } } } else { for (pos in oldPosition downTo newPosition + 1) { val view = getChildAt(pos - firstVisiblePosition) if ((pos + mNumColumns) % mNumColumns == 0) { resultList.add( createTranslationAnimations( view, (view.width * (mNumColumns - 1)).toFloat(), 0f, (-view.height).toFloat(), 0f ) ) } else { resultList.add(createTranslationAnimations(view, (-view.width).toFloat(), 0f, 0f, 0f)) } } } val resultSet = AnimatorSet() resultSet.playTogether(resultList) resultSet.duration = 300 resultSet.interpolator = AccelerateDecelerateInterpolator() resultSet.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { mAnimationEnd = false } override fun onAnimationEnd(animation: Animator) { mAnimationEnd = true } }) resultSet.start() } /** * * 方法: onStopDrag * * * 描述: 停止拖拽我们将之前隐藏的item显示出来,并将镜像移除 * * * 参数: @param dropx * 参数: @param dropy * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:20:35 */ private fun onStopDrag(dropx: Int, dropy: Int) { val view = getChildAt(mDragPosition - firstVisiblePosition) if (view != null) { view.visibility = View.VISIBLE } mDragAdapter!!.setHideItem(-1) removeDragImage() } /** * * 方法: getStatusHeight * * * 描述: 得到标题栏高度 * * * 参数: @param context * 参数: @return * * * 返回: int * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:20:46 */ private fun getStatusHeight(context: Context): Int { var statusHeight = 0 val localRect = Rect() (context as Activity).window.decorView.getWindowVisibleDisplayFrame(localRect) statusHeight = localRect.top if (0 == statusHeight) { val localClass: Class<*> try { localClass = Class.forName("com.android.internal.R\$dimen") val localObject = localClass.newInstance() val i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString()) statusHeight = context.getResources().getDimensionPixelSize(i5) } catch (e: Exception) { e.printStackTrace() } } return statusHeight } /** * * 方法: refreshIconInfoList * * * 描述: TODO * * * 参数: @param iconInfoList * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:00:14 */ fun refreshIconInfoList(iconInfoList: ArrayList<DragIconInfo>) { editList.clear() editList.addAll(iconInfoList) mDragAdapter = DragGridAdapter(mContext, editList, this) this.adapter = mDragAdapter!! mDragAdapter!!.notifyDataSetChanged() } /** * * 方法: notifyDataSetChange * * * 描述: 刷新数据 * * * 参数: @param iconInfoList * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:00:42 */ fun notifyDataSetChange(iconInfoList: ArrayList<DragIconInfo>) { editList.clear() editList.addAll(iconInfoList) mDragAdapter!!.resetModifyPosition() mDragAdapter!!.notifyDataSetChanged() } /** * * 方法: deletInfo * * * 描述: 删除 * * * 参数: @param position * 参数: @param iconInfo * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:56:47 */ fun deletInfo(position: Int, iconInfo: DragIconInfo) { deletAnimation(position) mCustomGroup.deletHomePageInfo(iconInfo) } /** * * 方法: deletAnimation * * * 描述: 删除动画 * * * 参数: @param position * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:21:37 */ private fun deletAnimation(position: Int) { val view = getChildAt(position) view.isDrawingCacheEnabled = true val mDragBitmap = Bitmap.createBitmap(view.drawingCache) view.destroyDrawingCache() val animView = ImageView(mContext) animView.setImageBitmap(mDragBitmap) val ivlp = AbsListView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.WRAP_CONTENT) parentView!!.addView(animView, ivlp) val aimPosit = editList.size - 1 val animatorSet = createTranslationAnim(position, aimPosit, view, animView) animatorSet.interpolator = AccelerateDecelerateInterpolator() animatorSet.duration = 500 animatorSet.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { view.visibility = View.INVISIBLE } override fun onAnimationEnd(animation: Animator) { animView.visibility = View.GONE animView.clearAnimation() parentView!!.removeView(animView) mDragAdapter!!.reorderItems(position, aimPosit) mDragAdapter!!.deleteItem(aimPosit) //mDragAdapter.setHideItem(aimPosit); val observer = viewTreeObserver observer.addOnPreDrawListener(object : OnPreDrawListener { override fun onPreDraw(): Boolean { observer.removeOnPreDrawListener(this) animateReorder(position, aimPosit) return true } }) } }) animatorSet.start() } /** * * 方法: createTranslationAnim * * * 描述: TODO * * * 参数: @param position * 参数: @param aimPosit * 参数: @param view * 参数: @param animView * 参数: @return * * * 返回: AnimatorSet * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:49:23 */ private fun createTranslationAnim(position: Int, aimPosit: Int, view: View, animView: ImageView): AnimatorSet { val startx = view.left val starty = view.top val aimView = getChildAt(aimPosit) val endx = aimView.left val endy = aimView.top val animX = ObjectAnimator.ofFloat(animView, "translationX", startx.toFloat(), endx.toFloat()) val animY = ObjectAnimator.ofFloat(animView, "translationY", starty.toFloat(), endy.toFloat()) val scaleX = ObjectAnimator.ofFloat(animView, "scaleX", 1f, 0.5f) val scaleY = ObjectAnimator.ofFloat(animView, "scaleY", 1f, 0.5f) val alpaAnim = ObjectAnimator.ofFloat(animView, "alpha", 1f, 0.0f) val animSetXY = AnimatorSet() animSetXY.playTogether(animX, animY, scaleX, scaleY, alpaAnim) return animSetXY } fun setDeletAnimView(customBehindParent: CustomBehindParent) { this.parentView = customBehindParent } /** * * 方法: cancleModifyedOrderState * * * 描述: TODO * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:35:10 */ fun cancleModifyedOrderState() { mDragAdapter!!.isHasModifyedOrder = false } /** * * 方法: resetHidePosition * * * 描述: TODO * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:35:05 */ fun resetHidePosition() { mDragAdapter!!.setHideItem(-1) } /** * * 方法: isValideEvent * * * 描述: 标记是否是在这个view里面的点击事件 防止事件冲突 * * * 参数: @param ev * 参数: @param scrolly * 参数: @return * * * 返回: boolean * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:34:01 */ fun isValideEvent(ev: MotionEvent, scrolly: Int): Boolean { val left = (parent.parent as View).left val top = (parent.parent as View).top val x_ = ev.x.toInt() val y_ = ev.y.toInt() val tempx = x_ - left val tempy = y_ - top + scrolly val position = pointToPosition(tempx, tempy) val rect = Rect() getHitRect(rect) return position != AdapterView.INVALID_POSITION } /** * * 方法: clearDragView * * * 描述: 清除拖动 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:28:13 */ fun clearDragView() { removeDragImage() } companion object { /** DragGridView自动滚动的速度 */ private val speed = 20 } } <file_sep>/task/src/main/java/com/influx/task/other/DragGridAdapter.kt package com.influx.task.other import android.content.Context import android.os.Handler import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import android.widget.* import com.influx.task.R import com.influx.task.model.DragIconInfo import com.influx.task.view.CustomBehindView import java.util.ArrayList import java.util.Collections /** * * 类: DragGridAdapter * * * 描述: TODO * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:02:40 * * */ class DragGridAdapter( private val mContext: Context, private val mIconInfoList: ArrayList<DragIconInfo>, private val mCustomBehindView: CustomBehindView ) : BaseAdapter() { private val INVALID_POSIT = -100 private var mHidePosition = INVALID_POSIT private var modifyPosition = INVALID_POSIT private val mHandler = Handler() var isHasModifyedOrder = false fun setModifyPosition(position: Int) { modifyPosition = position } override fun getCount(): Int { return mIconInfoList.size } override fun getItem(position: Int): Any { return mIconInfoList[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView var viewHold: ViewHold? = null if (convertView == null) { viewHold = ViewHold() convertView = View.inflate(mContext, R.layout.gridview_behind_itemview, null) viewHold.llContainer = convertView!!.findViewById<View>(R.id.edit_ll) as LinearLayout viewHold.ivIcon = convertView.findViewById<View>(R.id.icon_iv) as ImageView viewHold.tvName = convertView.findViewById<View>(R.id.name_tv) as TextView viewHold.ivDelet = convertView.findViewById<View>(R.id.delet_iv) as ImageButton convertView.tag = viewHold } else { viewHold = convertView.tag as ViewHold } val iconInfo = mIconInfoList[position] viewHold.ivIcon!!.setImageResource(iconInfo.resIconId) viewHold.tvName!!.text = iconInfo.name viewHold.ivDelet!!.setOnClickListener { modifyPosition = INVALID_POSIT mCustomBehindView.deletInfo(position, iconInfo) } if (modifyPosition == position) { viewHold.llContainer!!.setBackgroundColor(mContext.resources.getColor(R.color.item_bg)) viewHold.ivDelet!!.visibility = View.VISIBLE } else { viewHold.llContainer!!.setBackgroundColor(mContext.resources.getColor(R.color.white)) viewHold.ivDelet!!.visibility = View.GONE } convertView.setOnClickListener { if (position != modifyPosition) { modifyPosition = INVALID_POSIT mCustomBehindView.cancleEditModel() } } if (position == mHidePosition) { convertView.visibility = View.INVISIBLE } else { convertView.visibility = View.VISIBLE } return convertView } /** * * 方法: reorderItems * * * 描述: TODO * * * 参数: @param oldPosition * 参数: @param newPosition * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:02:53 */ fun reorderItems(oldPosition: Int, newPosition: Int) { val temp = mIconInfoList[oldPosition] if (oldPosition < newPosition) { for (i in oldPosition until newPosition) { Collections.swap(mIconInfoList, i, i + 1) } } else if (oldPosition > newPosition) { for (i in oldPosition downTo newPosition + 1) { Collections.swap(mIconInfoList, i, i - 1) } } mIconInfoList[newPosition] = temp modifyPosition = newPosition isHasModifyedOrder = true } /** * * 方法: setHideItem * * * 描述: 拖动的时候会隐藏某个 * * * 参数: @param hidePosition * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:03:05 */ fun setHideItem(hidePosition: Int) { this.mHidePosition = hidePosition notifyDataSetChanged() } fun deleteItem(deletPosit: Int) { mIconInfoList.removeAt(deletPosit) notifyDataSetChanged() mHandler.postDelayed({ isHasModifyedOrder = true mCustomBehindView.cancleEditModel() }, 500) } internal inner class ViewHold { var llContainer: LinearLayout? = null var ivIcon: ImageView? = null var ivDelet: ImageView? = null var tvName: TextView? = null } /** * * 方法: resetModifyPosition * * * 描述: TODO * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:03:16 */ fun resetModifyPosition() { modifyPosition = INVALID_POSIT } } <file_sep>/taskfinal/src/main/java/com/influx/taskfinal/adapter/SeatAdapter.kt package com.influx.taskfinal.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.influx.taskfinal.R class SeatAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>(){ override fun onCreateViewHolder(parent: ViewGroup, position: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.seat, parent, false) return SeatViewHolder(view) } override fun getItemCount(): Int { return 120 } override fun onBindViewHolder(p0: RecyclerView.ViewHolder, p1: Int) { } class SeatViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){ fun onBind(){ } } }<file_sep>/task/src/main/java/com/influx/task/view/CustomGroup.kt package com.influx.task.view import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.Toast import com.influx.task.R import com.influx.task.model.DargChildInfo import com.influx.task.model.DragIconInfo import java.util.* /** * * 类: CustomGroup * * * 描述: TODO * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:54:26 * * */ class CustomGroup @JvmOverloads constructor(private val mContext: Context, attrs: AttributeSet? = null) : ViewGroup(mContext, attrs) { private val mCustomAboveView: CustomAboveView private val mCustomBehindParent: CustomBehindParent var isEditModel = false private set //所有以的list private val allInfoList = ArrayList<DragIconInfo>() /**显示的带more的list */ private val homePageInfoList = ArrayList<DragIconInfo>() /**可展开的list */ private var expandInfoList = ArrayList<DragIconInfo>() /**不可展开的list */ private var onlyInfoList = ArrayList<DragIconInfo>() var editModelListener: InfoEditModelListener? = null interface InfoEditModelListener { fun onModleChanged(isEditModel: Boolean) } init { val upParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) mCustomAboveView = CustomAboveView(mContext, this) addView(mCustomAboveView, upParams) val downParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) mCustomBehindParent = CustomBehindParent(mContext, this) addView(mCustomBehindParent, downParams) initData() } /** * * 方法: initData * * * 描述: 初始化监听和数据 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:29:40 */ private fun initData() { setCustomViewClickListener(object : CustomAboveView.CustomAboveViewClickListener { override fun onSingleClicked(iconInfo: DragIconInfo) { dispatchSingle(iconInfo) } override fun onChildClicked() { dispatchChild() } }) initIconInfo() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var widthMeasure = 0 var heightMeasure = 0 if (isEditModel) { mCustomBehindParent.measure(widthMeasureSpec, heightMeasureSpec) widthMeasure = mCustomBehindParent.measuredWidth heightMeasure = mCustomBehindParent.measuredHeight } else { mCustomAboveView.measure(widthMeasureSpec, heightMeasureSpec) widthMeasure = mCustomAboveView.measuredWidth heightMeasure = mCustomAboveView.measuredHeight } setMeasuredDimension(widthMeasure, heightMeasure) } /** * 方法: onLayout * * * 描述: TODO * * * @param changed * @param l * @param t * @param r * @param b * * * @see ViewGroup.onLayout */ override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { if (isEditModel) { val behindHeight = mCustomBehindParent.measuredHeight mCustomBehindParent.layout(l, 0, r, behindHeight + t) } else { val aboveHeight = mCustomAboveView.measuredHeight mCustomAboveView.layout(l, 0, r, aboveHeight + t) } } /** * * 方法: initIconInfo * * * 描述: 初始化数据 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:33:14 */ private fun initIconInfo() { allInfoList.clear() allInfoList.addAll(initAllOriginalInfo()) getPageInfoList() refreshIconInfo() } /** * * 方法: initAllOriginalInfo * * * 描述: 初始化Icon info * * * 参数: @return * * * 返回: ArrayList<DragIconInfo> </DragIconInfo> * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:33:48 */ private fun initAllOriginalInfo(): ArrayList<DragIconInfo> { val iconInfoList = ArrayList<DragIconInfo>() val childList = initChildList() iconInfoList.add(DragIconInfo(1, "Expand 1", R.mipmap.ic_launcher, DragIconInfo.CATEGORY_EXPAND, childList)) iconInfoList.add(DragIconInfo(2, "Expand 2", R.mipmap.ic_launcher, DragIconInfo.CATEGORY_EXPAND, childList)) iconInfoList.add(DragIconInfo(3, "Expand 3", R.mipmap.ic_launcher, DragIconInfo.CATEGORY_EXPAND, childList)) iconInfoList.add(DragIconInfo(4, "Expand 4", R.mipmap.ic_launcher, DragIconInfo.CATEGORY_EXPAND, childList)) iconInfoList.add(DragIconInfo(5, "Expand 5", R.mipmap.ic_launcher, DragIconInfo.CATEGORY_EXPAND, childList)) iconInfoList.add(DragIconInfo(6, "Expand 6", R.mipmap.ic_launcher, DragIconInfo.CATEGORY_EXPAND, childList)) return iconInfoList } /** * * 方法: initChildList * * * 描述: 初始化child list * * * 参数: @return * * * 返回: ArrayList<DargChildInfo> </DargChildInfo> * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:36:12 */ private fun initChildList(): ArrayList<DargChildInfo> { val childList = ArrayList<DargChildInfo>() childList.add(DargChildInfo(1, "Item1")) return childList } /** * * 方法: getPageInfoList * * * 描述: 初始化显示 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:37:33 */ private fun getPageInfoList() { homePageInfoList.clear() var count = 0 for (info in allInfoList) { if (count < 9) { homePageInfoList.add(info) count++ } else { break } } } /** * * 方法: refreshIconInfo * * * 描述: 刷新信息 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:38:11 */ private fun refreshIconInfo() { judeHomeInfoValid() val moreInfo = getMoreInfoList(allInfoList, homePageInfoList) expandInfoList = getInfoByType(moreInfo, DragIconInfo.CATEGORY_EXPAND) onlyInfoList = getInfoByType(moreInfo, DragIconInfo.CATEGORY_ONLY) setIconInfoList(homePageInfoList) } /** * * 方法: judeHomeInfoValid * * * 描述: 判断下显示里面是否包含更多 或者看下是否是最后一个 固定更多的位置 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:38:37 */ private fun judeHomeInfoValid() { var hasMoreInfo = false var posit = 0 for (index in homePageInfoList.indices) { val tempInfo = homePageInfoList[index] if (tempInfo.id == CustomAboveView.MORE) { hasMoreInfo = true posit = index break } } if (!hasMoreInfo) { //没有更多 增加 homePageInfoList.add(DragIconInfo(CustomAboveView.MORE, "更多", R.mipmap.ic_launcher, 0, ArrayList())) } else { if (posit != homePageInfoList.size - 1) { //不是最后一个 val moreInfo = homePageInfoList.removeAt(posit) homePageInfoList.add(moreInfo) } } } /** * * 方法: getInfoByType * * * 描述: TODO * * * 参数: @param moreInfo * 参数: @param categorySpt * 参数: @return * * * 返回: ArrayList<DragIconInfo> </DragIconInfo> * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:50:25 */ private fun getInfoByType(moreInfo: ArrayList<DragIconInfo>, categorySpt: Int): ArrayList<DragIconInfo> { val typeList = ArrayList<DragIconInfo>() for (info in moreInfo) { if (info.category == categorySpt) { typeList.add(info) } } return typeList } fun setCustomViewClickListener(gridViewClickListener: CustomAboveView.CustomAboveViewClickListener) { mCustomAboveView.gridViewClickListener = gridViewClickListener } /** * * 方法: setIconInfoList * * * 描述: 设置信息 * * * 参数: @param iconInfoList * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:45:55 */ fun setIconInfoList(iconInfoList: ArrayList<DragIconInfo>) { mCustomAboveView.refreshIconInfoList(iconInfoList) mCustomBehindParent.refreshIconInfoList(iconInfoList) } fun cancleEidtModel() { setEditModel(false, 0) } fun setEditModel(isEditModel: Boolean, position: Int) { this.isEditModel = isEditModel if (isEditModel) { mCustomAboveView.setViewCollaps() mCustomAboveView.visibility = View.GONE mCustomBehindParent.notifyDataSetChange(mCustomAboveView.iconInfoList) mCustomBehindParent.visibility = View.VISIBLE mCustomBehindParent.drawWindowView(position, mCustomAboveView.firstEvent!!) } else { homePageInfoList.clear() homePageInfoList.addAll(mCustomBehindParent.editList) mCustomAboveView.refreshIconInfoList(homePageInfoList) mCustomAboveView.visibility = View.VISIBLE mCustomBehindParent.visibility = View.GONE if (mCustomBehindParent.isModifyedOrder) { mCustomBehindParent.cancleModifyOrderState() } mCustomBehindParent.resetHidePosition() } if (editModelListener != null) { editModelListener!!.onModleChanged(isEditModel) } } fun sendEventBehind(ev: MotionEvent) { mCustomBehindParent.childDispatchTouchEvent(ev) } /** * * 方法: getMoreInfoList * * * 描述: TODO * * * 参数: @param allInfoList * 参数: @param homePageInfoList * 参数: @return * * * 返回: ArrayList<DragIconInfo> </DragIconInfo> * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:57:06 */ private fun getMoreInfoList( allInfoList: ArrayList<DragIconInfo>, homePageInfoList: ArrayList<DragIconInfo> ): ArrayList<DragIconInfo> { val moreInfoList = ArrayList<DragIconInfo>() moreInfoList.addAll(allInfoList) moreInfoList.removeAll(homePageInfoList) return moreInfoList } /** * * 方法: deletHomePageInfo * * * 描述: TODO * * * 参数: @param dragIconInfo * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:56:19 */ fun deletHomePageInfo(dragIconInfo: DragIconInfo) { homePageInfoList.remove(dragIconInfo) mCustomAboveView.refreshIconInfoList(homePageInfoList) val category = dragIconInfo.category when (category) { DragIconInfo.CATEGORY_ONLY -> onlyInfoList.add(dragIconInfo) DragIconInfo.CATEGORY_EXPAND -> expandInfoList.add(dragIconInfo) else -> { } } allInfoList.remove(dragIconInfo) allInfoList.add(dragIconInfo) } /** * * 方法: dispatchChild * * * 描述: 点击child * * * 参数: @param childInfo * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:30:58 */ protected fun dispatchChild() { Toast.makeText(mContext, "Test", Toast.LENGTH_SHORT).show() // mCustomAboveView.showPreviewView() } /** * * 方法: dispatchSingle * * * 描述: 没child的点击 * * * 参数: @param dragInfo * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:30:40 */ fun dispatchSingle(dragInfo: DragIconInfo?) { if (dragInfo == null) { return } Toast.makeText(mContext, "点击了icon" + dragInfo.name!!, Toast.LENGTH_SHORT).show() } fun isValideEvent(ev: MotionEvent, scrolly: Int): Boolean { return mCustomBehindParent.isValideEvent(ev, scrolly) } fun clearEditDragView() { mCustomBehindParent.clearDragView() } companion object { val COLUMNUM = 3 val CHILD_COLUMNUM = 1 } } <file_sep>/app/src/main/java/com/influx/influxtask/MainActivity.kt package com.influx.influxtask import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import com.influx.influxtask.widget.ExpandableGridView class MainActivity : AppCompatActivity(), ExpandableGridView.OnExpandItemClickListener { var countryGridView: ExpandableGridView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) initComponent() } private fun initComponent() { val countryData = arrayOf("7:15 AM", "6:15 AM", "8:15 AM", "3:15 AM", "10:15 PM", "3:15 PM", "11:15 PM", "12:15 AM") countryGridView = findViewById(R.id.country_grid) val countryAdapter = ArrayAdapter(baseContext, R.layout.grid_item, R.id.grid_item, countryData) countryGridView?.adapter = countryAdapter countryGridView?.onItemClickListener = AdapterView.OnItemClickListener { _, view, _, id -> countryGridView?.expandGridViewAtView(view) } countryGridView?.setOnExpandItemClickListener(this) } override fun onItemClick(position: Int, clickPositionData: Any) { Toast.makeText(this, clickPositionData.toString() + " clicked", Toast.LENGTH_LONG).show() } override fun onPreviewClick() { Toast.makeText(this, " onPreviewClick", Toast.LENGTH_LONG).show() //Thread.sleep(1000) countryGridView?.showPreviewView() } override fun onBuyTicketClick() { Toast.makeText(this, " onBuyTicketClick", Toast.LENGTH_LONG).show() } } <file_sep>/taskfinal/src/main/java/com/influx/taskfinal/MainActivity.kt package com.influx.taskfinal import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.LayoutInflater import android.widget.Toast import com.google.gson.Gson import com.influx.taskfinal.data.DatesItem import com.influx.taskfinal.data.Info import com.influx.taskfinal.widget.ExpandableGridClickListner import com.influx.taskfinal.widget.ExpandableGridView import kotlinx.android.synthetic.main.activity_main2.* import kotlinx.android.synthetic.main.lnr_container.view.* import org.json.JSONObject import java.io.IOException import java.nio.charset.Charset class MainActivity : AppCompatActivity(), ExpandableGridClickListner { val bookingTimeArray = arrayOf("7:15 AM", "6:15 AM", "8:15 AM", "3:15 AM", "10:15 PM", "3:15 PM", "11:15 PM", "12:15 AM") val bookingTime = ArrayList<Info>() // var gridView: ExpandableGridView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) // gridView = ExpandableGridView(this) // // container.addView(gridView) init() } private fun init() { // gridView?.setExpandableClickListner(this) // gridView?.refreshIconInfoList(generateData()) val infos = generateData() for (i in 0 until infos.size){ val viewMovies = LayoutInflater.from(this).inflate(R.layout.lnr_container, container, false) viewMovies.lblMovieName.text = infos[i].timing.moviewName val gridView = ExpandableGridView(this) gridView.setExpandableClickListner(this) val timings = infos[i].timing.timings!! for (i in 0 until timings.size){ timings[i].expand = 1 } gridView.refreshIconInfoList(timings) viewMovies.lnrExpand.addView(gridView) container.addView(viewMovies) } } private fun generateData(): ArrayList<Info> { // for ((i, array) in bookingTimeArray.withIndex()) { // bookingTime.add(Info(i, array, 1)) // } val testData = JSONObject(loadJSONFromAsset()) if (testData.has("result")){ val resultObj = testData.getJSONObject("result") if (resultObj.has("dates")){ val datesArrays = resultObj.getJSONArray("dates") val dateObj = Gson().fromJson(datesArrays.getJSONObject(0).toString(), DatesItem::class.java) dateObj.timings?.let { for (i in 0 until it.size){ val timing = it[i] bookingTime.add(Info(i, timing, 1)) } } } } // bookingTime.add(Info(bookingTime.size, MoviewItem("No Show Available", listOf()), 0)) return bookingTime } override fun onParentClick(value: String) { Toast.makeText(this, value, Toast.LENGTH_SHORT).show() } override fun onPreviewClick() { Toast.makeText(this, "onPreviewClick", Toast.LENGTH_SHORT).show() //gridView?.showPreviewView() } override fun onBuyTicketClick() { Toast.makeText(this, "onBuyTicketClick", Toast.LENGTH_SHORT).show() } fun loadJSONFromAsset(): String? { var json: String? = null try { val inputStream = assets.open("test_data.json") val size = inputStream.available() val buffer = ByteArray(size) inputStream.read(buffer) inputStream.close() json = String(buffer, Charset.forName("UTF-8")) } catch (ex: IOException) { ex.printStackTrace() return null } return json } } <file_sep>/app/src/main/java/com/influx/influxtask/widget/ExpandableGridView.kt package com.influx.influxtask.widget import android.content.Context import android.graphics.* import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.PathShape import android.util.AttributeSet import android.view.* import android.widget.* import com.influx.influxtask.R class ExpandableGridView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : GridView(context, attrs, defStyle) { private var mLayoutParams: WindowManager.LayoutParams? = null private var mCoverView: LinearLayout? = null private var mParentViewGroup: ViewGroup? = null private var hasScrolled = false private var scrollYY = 0 private var mListener: OnExpandItemClickListener? = null private lateinit var superChild: LinearLayout /** * Set listener for sub grid view item. When sub grid view item is clicked, it will invoke * the listener's onItemClick function. * * @param listener */ fun setOnExpandItemClickListener(listener: OnExpandItemClickListener) { mListener = listener } /** * Expand the grid view under the clicked item. * @param clickedView The clicked item. * @param expandGridAdapter Adapter set to sub grid view. */ fun expandGridViewAtView(clickedView: View) { mCoverView = LinearLayout(context) mCoverView!!.orientation = LinearLayout.VERTICAL val imageViewUp = ImageView(context) val imageViewDown = ImageView(context) val middleView = ScrollView(context) val touchBottom = clickedView.bottom if (touchBottom > measuredHeight - paddingBottom - verticalSpacing) { hasScrolled = true scrollYY = touchBottom - measuredHeight + paddingBottom + verticalSpacing / 2 scrollBy(0, scrollYY) } this.isDrawingCacheEnabled = true val bitmap = Bitmap.createBitmap(this.drawingCache) this.destroyDrawingCache() var heightUp = 1 var heightDown = 1 val middleViewHeight = clickedView.height + 20 val bottomPos = bitmap.height - touchBottom - verticalSpacing / 2 - middleViewHeight var upY = 0 var downY = touchBottom if (bottomPos <= 0) { heightUp = touchBottom + verticalSpacing / 2 - middleViewHeight upY = middleViewHeight heightDown = bitmap.height - heightUp - middleViewHeight if (heightDown < 0) { heightUp += heightDown heightDown = paddingBottom heightUp -= heightDown } downY = upY + heightUp } else { heightUp = touchBottom + verticalSpacing / 2 heightDown = bottomPos } val bitmapUp = Bitmap.createBitmap(bitmap, 0, upY, bitmap.width, heightUp) val bitmapDown = Bitmap.createBitmap(bitmap, 0, downY, bitmap.width, heightDown) imageViewUp.setImageBitmap(bitmapUp) imageViewUp.setOnClickListener { collapseGridView() } imageViewDown.setImageBitmap(bitmapDown) imageViewDown.setOnClickListener { collapseGridView() } val linearLayout = LinearLayout(context) // The below code is for adding the layout for expandable val inflater = LayoutInflater.from(context) val previewLayout = inflater.inflate(R.layout.preview_layout, null, false) val btn = previewLayout.findViewById<RelativeLayout>(R.id.btnOpenPanel) val btnBuy = previewLayout.findViewById<Button>(R.id.btnBuyTickets) superChild = previewLayout.findViewById(R.id.super_child) btn.setOnClickListener { mListener?.onPreviewClick() } btnBuy.setOnClickListener { mListener?.onBuyTicketClick() } linearLayout.addView(previewLayout) middleView.addView(linearLayout) val touchX = clickedView.left + columnWidth / 2 val touchY = heightUp val canvas = Canvas(bitmapUp) val path = Path() path.moveTo((touchX - 15).toFloat(), touchY.toFloat()) path.lineTo((touchX + 15).toFloat(), touchY.toFloat()) path.lineTo(touchX.toFloat(), (touchY - 15).toFloat()) path.lineTo((touchX - 15).toFloat(), touchY.toFloat()) val circle = ShapeDrawable(PathShape(path, width.toFloat(), height.toFloat())) circle.paint.color = Color.WHITE circle.setBounds(0, 0, width, height) circle.draw(canvas) // val params = ViewGroup.LayoutParams(width, middleViewHeight) val params = ViewGroup.LayoutParams(width, LayoutParams.WRAP_CONTENT) middleView.layoutParams = params middleView.setBackgroundColor(Color.WHITE) mCoverView!!.addView(imageViewUp) mCoverView!!.addView(middleView) mCoverView!!.addView(imageViewDown) mParentViewGroup = parent as ViewGroup mLayoutParams = WindowManager.LayoutParams() mLayoutParams!!.format = PixelFormat.TRANSLUCENT mLayoutParams!!.gravity = Gravity.TOP or Gravity.LEFT mLayoutParams!!.x = left mLayoutParams!!.y = top mLayoutParams!!.width = WindowManager.LayoutParams.WRAP_CONTENT mLayoutParams!!.height = WindowManager.LayoutParams.WRAP_CONTENT mLayoutParams!!.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE mParentViewGroup!!.addView(mCoverView, 0, mLayoutParams) mCoverView!!.bringToFront() } fun showPreviewView() { superChild.visibility = View.VISIBLE } /** * Collapse the grid view and remove the cover layer */ fun collapseGridView() { if (mParentViewGroup != null && mCoverView != null) { mCoverView!!.removeAllViews() mParentViewGroup!!.removeView(mCoverView) mLayoutParams = null mCoverView = null mParentViewGroup = null } if (hasScrolled) { scrollBy(0, -scrollYY) hasScrolled = false scrollYY = 0 } } /** * Sub item click listener interface */ interface OnExpandItemClickListener { fun onItemClick(position: Int, clickPositionData: Any) fun onPreviewClick() fun onBuyTicketClick() } } <file_sep>/taskfinal/src/main/java/com/influx/taskfinal/data/Info.kt package com.influx.taskfinal.data /** * Created by Gowtham on 15/11/18. * Copyright Indyzen Inc, 2018. */ data class Info(val id: Int, val timing: MoviewItem,val expand:Int)<file_sep>/task/src/main/java/com/influx/task/model/DragIconInfo.kt package com.influx.task.model import java.util.ArrayList /** * 类: DragIconInfo * * * 描述: 拖动显示的view和icon * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:08:23 * * */ class DragIconInfo { var id: Int = 0 var name: String? = null var resIconId: Int = 0 /** * 类型 */ var category: Int = 0 /** * 展开的child */ var childList = ArrayList<DargChildInfo>() constructor() { // TODO Auto-generated constructor stub } constructor( id: Int, name: String, resIconId: Int, category: Int, childList: ArrayList<DargChildInfo> ) : super() { this.id = id this.name = name this.resIconId = resIconId this.category = category this.childList = childList } companion object { /** * 可展开的 */ val CATEGORY_EXPAND = 100 /** * 不可展开的 */ val CATEGORY_ONLY = 300 } } <file_sep>/task/src/main/java/com/influx/task/view/CustomBehindParent.kt package com.influx.task.view import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.view.MotionEvent import android.widget.RelativeLayout import com.influx.task.R import com.influx.task.model.DragIconInfo import java.util.ArrayList /** * * 类: CustomBehindParent * * * 描述: TODO * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:51:29 * * */ class CustomBehindParent(private val mContext: Context, customGroup: CustomGroup) : RelativeLayout(mContext) { private val mCustomBehindEditView: CustomBehindView /** * * 方法: getEditList * * * 描述: TODO * * * 参数: @return * * * 返回: ArrayList<DragIconInfo> </DragIconInfo> * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:51:39 */ val editList: ArrayList<DragIconInfo> get() = mCustomBehindEditView.editList val isModifyedOrder: Boolean get() = mCustomBehindEditView.isModifyedOrder init { mCustomBehindEditView = CustomBehindView(mContext, customGroup) mCustomBehindEditView.horizontalSpacing = 1 mCustomBehindEditView.verticalSpacing = 1 mCustomBehindEditView.selector = ColorDrawable(Color.TRANSPARENT) mCustomBehindEditView.setBackgroundColor(mContext.resources.getColor(R.color.gap_line)) val lp = RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT ) addView(mCustomBehindEditView, lp) mCustomBehindEditView.setDeletAnimView(this) } /** * * 方法: refreshIconInfoList * * * 描述: TODO * * * 参数: @param iconInfoList * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:46:38 */ fun refreshIconInfoList(iconInfoList: ArrayList<DragIconInfo>) { mCustomBehindEditView.refreshIconInfoList(iconInfoList) } /** * * 方法: notifyDataSetChange * * * 描述: TODO * * * 参数: @param iconInfoList * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:51:15 */ fun notifyDataSetChange(iconInfoList: ArrayList<DragIconInfo>) { mCustomBehindEditView.notifyDataSetChange(iconInfoList) } /** * * 方法: drawWindowView * * * 描述: TODO * * * 参数: @param position * 参数: @param event * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:51:42 */ fun drawWindowView(position: Int, event: MotionEvent) { mCustomBehindEditView.drawWindowView(position, event) } /** * * 方法: childDispatchTouchEvent * * * 描述: TODO * * * 参数: @param ev * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:51:48 */ fun childDispatchTouchEvent(ev: MotionEvent) { mCustomBehindEditView.dispatchTouchEvent(ev) } fun cancleModifyOrderState() { mCustomBehindEditView.cancleModifyedOrderState() } /** * * 方法: resetHidePosition * * * 描述: TODO * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:51:51 */ fun resetHidePosition() { mCustomBehindEditView.resetHidePosition() } /** * * 方法: isValideEvent * * * 描述: TODO * * * 参数: @param ev * 参数: @param scrolly * 参数: @return * * * 返回: boolean * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午4:50:55 */ fun isValideEvent(ev: MotionEvent, scrolly: Int): Boolean { return mCustomBehindEditView.isValideEvent(ev, scrolly) } /** * * 方法: clearDragView * * * 描述: TODO * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:51:55 */ fun clearDragView() { mCustomBehindEditView.clearDragView() } } <file_sep>/task/src/main/java/com/influx/task/view/CustomAboveView.kt package com.influx.task.view import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.view.MotionEvent import android.view.View import android.view.animation.TranslateAnimation import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import com.influx.task.R import com.influx.task.model.DragIconInfo import java.util.* /** * * 类: CustomAboveView * * * 描述: TODO * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:01:18 * * */ @SuppressLint("ViewConstructor") class CustomAboveView(private val mContext: Context, private val mCustomGroup: CustomGroup) : LinearLayout(mContext, null) { var iconInfoList = ArrayList<DragIconInfo>() private var mItemViewClickListener: ItemViewClickListener? = null private val verticalViewWidth = 1 var gridViewClickListener: CustomAboveViewClickListener? = null var firstEvent: MotionEvent? = null // private lateinit var gridViewNoScroll: CustomGridView1 private var mChildClickListener: CustomGridView1.CustomChildClickListener? = null interface CustomAboveViewClickListener { /** * * 方法: onSingleClicked * * * 描述: TODO * * * 参数: @param iconInfo * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:30:13 */ fun onSingleClicked(iconInfo: DragIconInfo) /** * * 方法: onChildClicked * * * 描述: TODO * * * 参数: @param childInfo * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:30:10 */ fun onChildClicked() } init { orientation = LinearLayout.VERTICAL initData() } /** * * 方法: initData * * * 描述: TODO * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:02:12 */ private fun initData() { mChildClickListener = object : CustomGridView1.CustomChildClickListener { override fun onPreviewClicked() { return if (gridViewClickListener == null) { } else { gridViewClickListener!!.onChildClicked() } } override fun onBuyTicketClicked() { return if (gridViewClickListener == null) { } else { gridViewClickListener!!.onChildClicked() } } // override fun onChildClicked(chilidInfo: DargChildInfo) { // return if (gridViewClickListener == null) { // } else { // gridViewClickListener!!.onChildClicked(chilidInfo) // } // } } } /** * * 方法: refreshIconInfoList * * * 描述: TODO * * * 参数: @param iconInfoList * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午6:46:22 */ fun refreshIconInfoList(iconInfoList: ArrayList<DragIconInfo>) { this.iconInfoList.clear() this.iconInfoList.addAll(iconInfoList) refreshViewUI() } /** * * 方法: refreshViewUI * * * 描述: 刷新UI * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel w<EMAIL> * * * 时间: 2015年8月25日 下午7:02:17 */ private fun refreshViewUI() { removeAllViews() val rowNum = iconInfoList.size / CustomGroup.COLUMNUM + if (iconInfoList.size % CustomGroup.COLUMNUM > 0) 1 else 0 val rowParam = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) val verticalParams = LinearLayout.LayoutParams(verticalViewWidth, LinearLayout.LayoutParams.FILL_PARENT) val horizontalParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, verticalViewWidth) for (rowIndex in 0 until rowNum) { val rowView = View.inflate(mContext, R.layout.gridview_above_rowview, null) val llRowContainer = rowView.findViewById<View>(R.id.gridview_rowcontainer_ll) as LinearLayout val ivOpenFlag = rowView.findViewById<View>(R.id.gridview_rowopenflag_iv) as ImageView val llBtm = rowView.findViewById<View>(R.id.gridview_rowbtm_ll) as LinearLayout val gridViewNoScroll = rowView.findViewById<View>(R.id.gridview_child_gridview) as CustomGridView1 if (mChildClickListener != null) { gridViewNoScroll.childClickListener = mChildClickListener } gridViewNoScroll.setParentView(llBtm) val itemParam = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) itemParam.weight = 1.0f val itemClickLitener = ItemViewClickListener(llBtm, ivOpenFlag, object : ItemViewClickInterface { override fun shoudInteruptViewAnimtion(listener: ItemViewClickListener, position: Int): Boolean { var isInterupt = false mCustomGroup.clearEditDragView() if (mItemViewClickListener != null && mItemViewClickListener != listener) { mItemViewClickListener!!.closeExpandView() } mItemViewClickListener = listener val iconInfo = iconInfoList[position] val childList = iconInfo.childList if (childList.size > 0) { gridViewNoScroll.refreshDataSet(childList) } else { setViewCollaps() isInterupt = true if (gridViewClickListener != null) { gridViewClickListener!!.onSingleClicked(iconInfo) } } return isInterupt } override fun viewUpdateData(position: Int) { gridViewNoScroll.notifyDataSetChange(true) } }) for (columnIndex in 0 until CustomGroup.COLUMNUM) { val itemView = View.inflate(mContext, R.layout.gridview_above_itemview, null) val ivIcon = itemView.findViewById<View>(R.id.icon_iv) as ImageView val tvName = itemView.findViewById<View>(R.id.name_tv) as TextView val itemInfoIndex = rowIndex * CustomGroup.COLUMNUM + columnIndex if (itemInfoIndex > iconInfoList.size - 1) { itemView.visibility = View.INVISIBLE } else { val iconInfo = iconInfoList[itemInfoIndex] ivIcon.setImageResource(iconInfo.resIconId) tvName.text = iconInfo.name itemView.id = itemInfoIndex itemView.tag = itemInfoIndex itemView.setOnClickListener(itemClickLitener) itemView.setOnLongClickListener { v -> if (iconInfo.id != MORE) { val position = v.tag as Int mCustomGroup.setEditModel(true, position) } true } } llRowContainer.addView(itemView, itemParam) val view = View(mContext) view.setBackgroundResource(R.color.gap_line) llRowContainer.addView(view, verticalParams) } val view = View(mContext) view.setBackgroundResource(R.color.gap_line) addView(view, horizontalParams) addView(rowView, rowParam) if (rowIndex == rowNum - 1) { val btmView = View(mContext) btmView.setBackgroundResource(R.color.gap_line) addView(btmView, horizontalParams) } } } fun showPreviewView() { // gridViewNoScroll.showPreviewView() } /** * * 方法: setViewCollaps * * * 描述: TODO * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:03:23 */ fun setViewCollaps() { if (mItemViewClickListener != null) { mItemViewClickListener!!.closeExpandView() } } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { this.firstEvent = ev if (mCustomGroup.isEditModel) { mCustomGroup.sendEventBehind(ev) } return super.dispatchTouchEvent(ev) } interface ItemViewClickInterface { fun shoudInteruptViewAnimtion(animUtil: ItemViewClickListener, position: Int): Boolean fun viewUpdateData(position: Int) } inner class ItemViewClickListener( val contentView: View, private val mViewFlag: View, private val animationListener: ItemViewClickInterface? ) : View.OnClickListener { private val INVALID_ID = -1000 private var mLastViewID = INVALID_ID private var startX: Int = 0 private var viewFlagWidth: Int = 0 private var itemViewWidth: Int = 0 override fun onClick(view: View) { val viewId = view.id var isTheSameView = false if (animationListener != null) { if (animationListener.shoudInteruptViewAnimtion(this, viewId)) { return } } if (mLastViewID == viewId) { isTheSameView = true } else { mViewFlag.visibility = View.VISIBLE viewFlagWidth = getViewFlagWidth() itemViewWidth = view.width val endX = view.left + itemViewWidth / 2 - viewFlagWidth / 2 if (mLastViewID == INVALID_ID) { startX = endX xAxismoveAnim(mViewFlag, startX, endX) } else { xAxismoveAnim(mViewFlag, startX, endX) } startX = endX } val isVisible = contentView.visibility == View.VISIBLE if (isVisible) { if (isTheSameView) { animateCollapsing(contentView) } else { animationListener?.viewUpdateData(viewId) } } else { if (isTheSameView) { mViewFlag.visibility = View.VISIBLE xAxismoveAnim(mViewFlag, startX, startX) } animateExpanding(contentView) } mLastViewID = viewId } private fun getViewFlagWidth(): Int { var viewWidth = mViewFlag.width if (viewWidth == 0) { val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) mViewFlag.measure(widthSpec, heightSpec) viewWidth = mViewFlag.measuredWidth } return viewWidth } /** * * 方法: xAxismoveAnim * * * 描述: x轴移动 * * * 参数: @param v * 参数: @param startX * 参数: @param toX * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:03:35 */ fun xAxismoveAnim(v: View, startX: Int, toX: Int) { moveAnim(v, startX, toX, 0, 0, 200) } /** * * 方法: moveAnim * * * 描述: 移动动画 * * * 参数: @param v * 参数: @param startX * 参数: @param toX * 参数: @param startY * 参数: @param toY * 参数: @param during * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:03:40 */ private fun moveAnim(v: View, startX: Int, toX: Int, startY: Int, toY: Int, during: Long) { val anim = TranslateAnimation(startX.toFloat(), toX.toFloat(), startY.toFloat(), toY.toFloat()) anim.duration = during anim.fillAfter = true v.startAnimation(anim) } /** * * 方法: closeExpandView * * * 描述: 收缩 * * * 参数: * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:03:49 */ fun closeExpandView() { val isVisible = contentView.visibility == View.VISIBLE if (isVisible) { animateCollapsing(contentView) } } /** * * 方法: animateCollapsing * * * 描述: 收缩动画 * * * 参数: @param view * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:04:01 */ fun animateCollapsing(view: View) { val origHeight = view.height val animator = createHeightAnimator(view, origHeight, 0) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animator: Animator) { view.visibility = View.GONE mViewFlag.clearAnimation() mViewFlag.visibility = View.GONE } }) animator.start() } /** * * 方法: animateExpanding * * * 描述: 动画展开 * * * 参数: @param view * * * 返回: void * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:04:22 */ fun animateExpanding(view: View) { view.visibility = View.VISIBLE val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) view.measure(widthSpec, heightSpec) val animator = createHeightAnimator(view, 0, view.measuredHeight) animator.start() } /** * * 方法: createHeightAnimator * * * 描述: TODO * * * 参数: @param view * 参数: @param start * 参数: @param end * 参数: @return * * * 返回: ValueAnimator * * * 异常 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:04:29 */ fun createHeightAnimator(view: View, start: Int, end: Int): ValueAnimator { val animator = ValueAnimator.ofInt(start, end) animator.addUpdateListener { valueAnimator -> val value = valueAnimator.getAnimatedValue() as Int val layoutParams = view.layoutParams layoutParams.height = value view.layoutParams = layoutParams } return animator } } companion object { val MORE = 99999 } } <file_sep>/task/src/main/java/com/influx/task/other/CommUtil.kt package com.influx.task.other import android.content.Context object CommUtil { fun dip2px(context: Context, dipValue: Float): Int { val scale = context.resources.displayMetrics.density return (dipValue * scale + 0.5f).toInt() } } <file_sep>/task/src/main/java/com/influx/task/model/DargChildInfo.kt package com.influx.task.model /** * * 类: DargChildInfo * * * 描述: 子item显示 * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午5:24:04 * * */ class DargChildInfo { var id: Int = 0 var name: String? = null constructor() { // TODO Auto-generated constructor stub } constructor(id: Int, name: String) : super() { this.id = id this.name = name } } <file_sep>/task/src/main/java/com/influx/task/view/CustomGridView1.kt package com.influx.task.view import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.View import android.widget.Button import android.widget.LinearLayout import android.widget.RelativeLayout import com.influx.task.R import com.influx.task.model.DargChildInfo import com.influx.task.other.CommUtil import java.util.* /** * 类: CustomGridView * * * 描述: TODO * * * 作者: wedcel <EMAIL> * * * 时间: 2015年8月25日 下午7:07:44 * * */ class CustomGridView1 : LinearLayout { private var mContext: Context? = null private val mPlayList = ArrayList<DargChildInfo>() private var viewHeight: Int = 0 private var viewWidth: Int = 0 private var mParentView: LinearLayout? = null private var rowNum: Int = 0 private var verticalViewWidth: Int = 0 var childClickListener: CustomChildClickListener? = null interface CustomChildClickListener { fun onPreviewClicked() fun onBuyTicketClicked() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { initView(context) } private fun initView(context: Context) { this.mContext = context verticalViewWidth = CommUtil.dip2px(mContext!!, 1f) val root = View.inflate(mContext, R.layout.preview_layout, null) val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) root.measure(widthSpec, heightSpec) viewHeight = root.measuredHeight viewWidth = (mContext!!.resources.displayMetrics.widthPixels - CommUtil.dip2px(mContext!!, 2f)) / CustomGroup.CHILD_COLUMNUM } constructor(context: Context) : super(context) { initView(context) } fun refreshDataSet(playList: ArrayList<DargChildInfo>) { mPlayList.clear() mPlayList.addAll(playList) notifyDataSetChange(false) } fun notifyDataSetChange(needAnim: Boolean) { removeAllViews() rowNum = mPlayList.size / CustomGroup.COLUMNUM + if (mPlayList.size % CustomGroup.COLUMNUM > 0) 1 else 0 val rowParam = LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) val verticalParams = LinearLayout.LayoutParams(verticalViewWidth, LinearLayout.LayoutParams.FILL_PARENT) val horizontalParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, verticalViewWidth) for (rowIndex in 0 until rowNum) { val llContainer = LinearLayout(mContext) llContainer.orientation = LinearLayout.HORIZONTAL val itemParam = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) itemParam.width = viewWidth for (columnIndex in 0 until CustomGroup.COLUMNUM) { val itemInfoIndex = rowIndex * CustomGroup.COLUMNUM + columnIndex var isValidateView = true if (itemInfoIndex >= mPlayList.size) { isValidateView = false } val root = View.inflate(mContext, R.layout.preview_layout, null) val previewButton = root.findViewById<View>(R.id.btnOpenPanel) as RelativeLayout val buyTicketsButton = root.findViewById<View>(R.id.btnBuyTickets) as Button val superChild = root.findViewById<View>(R.id.super_child) as LinearLayout if (isValidateView) { previewButton.setOnClickListener { if (childClickListener != null) { // childClickListener!!.onPreviewClicked() showPreviewView(root, superChild) } } buyTicketsButton.setOnClickListener { if (childClickListener != null) { childClickListener!!.onBuyTicketClicked() } } } llContainer.addView(root, itemParam) if (columnIndex != CustomGroup.COLUMNUM - 1) { val view = View(mContext) view.setBackgroundResource(R.drawable.ver_line) // llContainer.addView(view, verticalParams) } } addView(llContainer, rowParam) val view = View(mContext) view.setBackgroundResource(R.drawable.hor_line) // addView(view, horizontalParams) Log.e("animator", "" + height + "--" + rowNum * viewHeight) if (needAnim) { createHeightAnimator(mParentView, height, rowNum * viewHeight) } } } fun createHeightAnimator(view: View?, start: Int, end: Int) { val animator = ValueAnimator.ofInt(start, end) animator.addUpdateListener { valueAnimator -> val value = valueAnimator.animatedValue as Int val layoutParams = view!!.layoutParams layoutParams.height = value view.layoutParams = layoutParams } animator.duration = 200 animator.start() } fun createChildHeightAnimator(view: View?, start: Int, end: Int) { val animator = ValueAnimator.ofInt(start, end) animator.addUpdateListener { valueAnimator -> val value = valueAnimator.animatedValue as Int val layoutParams = view!!.layoutParams layoutParams.height = value view.layoutParams = layoutParams } animator.duration = 200 animator.start() } /** * 方法: setParentView * * * 描述: TODO * * * 参数: @param llBtm * * * 返回: void * * */ fun setParentView(llBtm: LinearLayout) { this.mParentView = llBtm } fun showPreviewView(root: View, superChild: LinearLayout) { superChild.visibility = View.VISIBLE Log.e("Child animator", "" + height + "--" + (root.measuredHeight * 2)) createChildHeightAnimator(mParentView, height, (root.measuredHeight * 2)) } } <file_sep>/taskfinal/src/main/java/com/influx/taskfinal/widget/ExpandableGridClickListner.kt package com.influx.taskfinal.widget /** * Created by Gowtham on 15/11/18. * Copyright Indyzen Inc, 2018. */ interface ExpandableGridClickListner { fun onParentClick(value: String) fun onPreviewClick() fun onBuyTicketClick() }
183d9ea9b776857e4c85a70dbcc1ad74e23b2163
[ "Kotlin" ]
16
Kotlin
ssatiz/InfluxFinalTask
1c9d866ecf0b1bc2f94671b3216224b0005cd297
8ba129a47de856de98b9c7b5dcbe2c1811db3fc3
refs/heads/master
<repo_name>BenjaminIsaac0111/Database-Security-Implementation-Examples<file_sep>/audit_seq.sql -------------------------------------------------------- -- File created - Thursday-March-01-2018 -------------------------------------------------------- -------------------------------------------------------- -- DDL for Sequence AUDIT_TRAIL -------------------------------------------------------- CREATE SEQUENCE "C3444086"."AUDIT_TRAIL" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 272 CACHE 20 NOORDER NOCYCLE NOKEEP NOSCALE GLOBAL ; <file_sep>/Placement_Restrictions.sql -------------------------------------------------------- -- File created - Thursday-March-01-2018 -------------------------------------------------------- -------------------------------------------------------- -- DDL for Trigger PLACEMENT_RESTRICTIONS -------------------------------------------------------- CREATE OR REPLACE EDITIONABLE TRIGGER "C3444086"."PLACEMENT_RESTRICTIONS" FOR INSERT OR UPDATE ON LDS_PLACEMENT COMPOUND TRIGGER username VARCHAR2(255); daily_insert_amount NUMBER; --Set the variable states up for comparisons. BEFORE STATEMENT IS BEGIN SELECT cst_name INTO username FROM lds_consultant WHERE cst_name = USER; SELECT COUNT(*) INTO daily_insert_amount FROM S_AUDIT_TRAIL WHERE ACTION = 'I' AND DATESTAMP = TO_CHAR(SYSDATE, 'MM/DD/YYYY') AND USER = USERNAME; END BEFORE STATEMENT; --Make sure that all parameters are met so that a user may modify the table. BEFORE EACH ROW IS BEGIN --Check user is a consultant else throw error. IF USER != username THEN RAISE_APPLICATION_ERROR(-20001, 'YOU SHALL NOT MODIFY! *strikes ground with keyboard*'); END IF; IF INSERTING THEN --Before Execution check the user has not inserted over 5 times today. IF daily_insert_amount <= 5 THEN DBMS_OUTPUT.put_line(username || ': Success!'); ELSE RAISE_APPLICATION_ERROR(-20002, 'You have reached your daily limit to insert new placements.(No more than 5)'); END IF; END IF; IF UPDATING AND :OLD.PLT_ACTUAL_END_DATE IS NULL THEN DBMS_OUTPUT.put_line(username || ': Success!'); ELSE RAISE_APPLICATION_ERROR(-20003, 'Not an open placement, modification denied.'); END IF; END BEFORE EACH ROW; END; / ALTER TRIGGER "C3444086"."PLACEMENT_RESTRICTIONS" ENABLE; <file_sep>/audit_table.sql -------------------------------------------------------- -- File created - Thursday-March-01-2018 -------------------------------------------------------- -------------------------------------------------------- -- DDL for Table S_AUDIT_TRAIL -------------------------------------------------------- CREATE TABLE "C3444086"."S_AUDIT_TRAIL" ( "ID" NUMBER, "DATESTAMP" DATE, "ACTION" VARCHAR2(255 BYTE), "USERNAME" VARCHAR2(20 BYTE), "EVENT" VARCHAR2(255 BYTE) ) SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- DDL for Index S_AUDIT_TRAIL_PK -------------------------------------------------------- CREATE UNIQUE INDEX "C3444086"."S_AUDIT_TRAIL_PK" ON "C3444086"."S_AUDIT_TRAIL" ("ID") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- Constraints for Table S_AUDIT_TRAIL -------------------------------------------------------- ALTER TABLE "C3444086"."S_AUDIT_TRAIL" MODIFY ("ID" NOT NULL ENABLE); ALTER TABLE "C3444086"."S_AUDIT_TRAIL" MODIFY ("DATESTAMP" NOT NULL ENABLE); ALTER TABLE "C3444086"."S_AUDIT_TRAIL" MODIFY ("ACTION" NOT NULL ENABLE); ALTER TABLE "C3444086"."S_AUDIT_TRAIL" MODIFY ("USERNAME" NOT NULL ENABLE); ALTER TABLE "C3444086"."S_AUDIT_TRAIL" ADD CONSTRAINT "S_AUDIT_TRAIL_PK" PRIMARY KEY ("ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT) TABLESPACE "USERS" ENABLE;
2daab99ec32b8eb55b115c8605c3479805b047c9
[ "SQL" ]
3
SQL
BenjaminIsaac0111/Database-Security-Implementation-Examples
53973cfb7b7a64232fcd608ad941ef8290b7492b
c95f1080bc6cb2f231a8776a4eac1a22bad03381
refs/heads/master
<file_sep>import os import io import logging import json from .utils import get_audio_duration, ensure_dir, download, get_annotator logger = logging.getLogger(__name__) def convert_to_asr_json_manifest( input_data, output_dir, data_key, project_dir, upload_dir, download_resources ): audio_dir_rel = 'audio' output_audio_dir = os.path.join(output_dir, audio_dir_rel) ensure_dir(output_dir), ensure_dir(output_audio_dir) output_file = os.path.join(output_dir, 'manifest.json') with io.open(output_file, mode='w') as fout: for item in input_data: audio_path = item['input'][data_key] try: audio_path = download( audio_path, output_audio_dir, project_dir=project_dir, upload_dir=upload_dir, return_relative_path=True, download_resources=download_resources, ) duration = get_audio_duration( os.path.join(output_audio_dir, os.path.basename(audio_path)) ) except: logger.info( 'Unable to download {image_path} or get audio duration. The item {item} will be skipped'.format( image_path=audio_path, item=item ), exc_info=True, ) continue for texts in iter(item['output'].values()): if len(texts) > 0 and 'text' in texts[0]: break transcript = texts[0]['text'][0] metadata = { 'audio_filepath': audio_path, 'duration': duration, 'text': transcript, 'annotator': get_annotator(item, default=''), } json.dump(metadata, fout) fout.write('\n') <file_sep>import os import json # better to use "imports ujson as json" for the best performance import uuid import logging from PIL import Image from label_studio_converter.utils import ExpandFullPath from label_studio_converter.imports.label_config import generate_label_config logger = logging.getLogger('root') def new_task(out_type, root_url, file_name): return { "data": {"image": os.path.join(root_url, file_name)}, # 'annotations' or 'predictions' out_type: [ { "result": [], "ground_truth": False, } ], } def create_bbox(annotation, categories, from_name, image_height, image_width, to_name): label = categories[int(annotation['category_id'])] x, y, width, height = annotation['bbox'] x, y, width, height = float(x), float(y), float(width), float(height) item = { "id": uuid.uuid4().hex[0:10], "type": "rectanglelabels", "value": { "x": x / image_width * 100.0, "y": y / image_height * 100.0, "width": width / image_width * 100.0, "height": height / image_height * 100.0, "rotation": 0, "rectanglelabels": [label], }, "to_name": to_name, "from_name": from_name, "image_rotation": 0, "original_width": image_width, "original_height": image_height, } return item def create_segmentation( annotation, categories, from_name, image_height, image_width, to_name ): label = categories[int(annotation['category_id'])] segmentation = annotation['segmentation'][0] points = [list(x) for x in zip(*[iter(segmentation)] * 2)] for i in range(len(points)): points[i][0] = points[i][0] / image_width * 100.0 points[i][1] = points[i][1] / image_height * 100.0 item = { "id": uuid.uuid4().hex[0:10], "type": "polygonlabels", "value": {"points": points, "polygonlabels": [label]}, "to_name": to_name, "from_name": from_name, "image_rotation": 0, "original_width": image_width, "original_height": image_height, } return item def create_keypoints( annotation, categories, from_name, to_name, image_height, image_width, point_width ): label = categories[int(annotation['category_id'])] points = annotation['keypoints'] items = [] for i in range(0, len(points), 3): x, y, v = points[i : i + 3] # x, y, visibility x, y, v = float(x), float(y), int(v) item = { "id": uuid.uuid4().hex[0:10], "type": "keypointlabels", "value": { "x": x / image_width * 100.0, "y": y / image_height * 100.0, "width": point_width, "keypointlabels": [label], }, "to_name": to_name, "from_name": from_name, "image_rotation": 0, "original_width": image_width, "original_height": image_height, } # visibility if v < 2: item['value']['hidden'] = True items.append(item) return items def convert_coco_to_ls( input_file, out_file, to_name='image', from_name='label', out_type="annotations", image_root_url='/data/local-files/?d=', use_super_categories=False, point_width=1.0, ): """Convert COCO labeling to Label Studio JSON :param input_file: file with COCO json :param out_file: output file with Label Studio JSON tasks :param to_name: object name from Label Studio labeling config :param from_name: control tag name from Label Studio labeling config :param out_type: annotation type - "annotations" or "predictions" :param image_root_url: root URL path where images will be hosted, e.g.: http://example.com/images :param use_super_categories: use super categories from categories if they are presented :param point_width: key point width """ tasks = {} # image_id => task logger.info('Reading COCO notes and categories from %s', input_file) with open(input_file, encoding='utf8') as f: coco = json.load(f) # build categories => labels dict new_categories = {} # list to dict conversion: [...] => {category_id: category_item} categories = {int(category['id']): category for category in coco['categories']} ids = sorted(categories.keys()) # sort labels by their origin ids for i in ids: name = categories[i]['name'] if use_super_categories and 'supercategory' in categories[i]: name = categories[i]['supercategory'] + ':' + name new_categories[i] = name # mapping: id => category name categories = new_categories # mapping: image id => image images = {item['id']: item for item in coco['images']} logger.info( f'Found {len(categories)} categories, {len(images)} images and {len(coco["annotations"])} annotations' ) # flags for labeling config composing segmentation = bbox = keypoints = rle = False segmentation_once = bbox_once = keypoints_once = rle_once = False rectangles_from_name, keypoints_from_name = ( from_name + '_rectangles', from_name + '_keypoints', ) segmentation_from_name = from_name + 'polygons' tags = {} # create tasks for image in coco['images']: image_id, image_file_name = image['id'], image['file_name'] tasks[image_id] = new_task(out_type, image_root_url, image_file_name) for i, annotation in enumerate(coco['annotations']): segmentation |= 'segmentation' in annotation bbox |= 'bbox' in annotation keypoints |= 'keypoints' in annotation rle |= ( annotation.get('iscrowd') == 1 ) # 0 - polygons are in segmentation, otherwise rle if rle and not rle_once: # not supported logger.error('RLE in segmentation is not yet supported in COCO') rle_once = True if keypoints and not keypoints_once: logger.warning('Keypoints are partially supported without skeletons') tags.update({keypoints_from_name: 'KeyPointLabels'}) keypoints_once = True if segmentation and not segmentation_once: # not supported logger.warning('Segmentation in COCO is experimental') tags.update({segmentation_from_name: 'PolygonLabels'}) segmentation_once = True if bbox and not bbox_once: tags.update({rectangles_from_name: 'RectangleLabels'}) bbox_once = True # read image sizes image_id = annotation['image_id'] image = images[image_id] image_file_name, image_width, image_height = ( image['file_name'], image['width'], image['height'], ) task = tasks[image_id] if 'bbox' in annotation: item = create_bbox( annotation, categories, rectangles_from_name, image_height, image_width, to_name, ) task[out_type][0]['result'].append(item) if 'segmentation' in annotation: item = create_segmentation( annotation, categories, segmentation_from_name, image_height, image_width, to_name, ) task[out_type][0]['result'].append(item) if 'keypoints' in annotation: items = create_keypoints( annotation, categories, keypoints_from_name, to_name, image_height, image_width, point_width, ) task[out_type][0]['result'] += items tasks[image_id] = task # generate and save labeling config label_config_file = out_file.replace('.json', '') + '.label_config.xml' generate_label_config(categories, tags, to_name, from_name, label_config_file) if len(tasks) > 0: tasks = [tasks[key] for key in sorted(tasks.keys())] logger.info('Saving Label Studio JSON to %s', out_file) with open(out_file, 'w') as out: json.dump(tasks, out) print( '\n' f' 1. Create a new project in Label Studio\n' f' 2. Use Labeling Config from "{label_config_file}"\n' f' 3. Setup serving for images [e.g. you can use Local Storage (or others):\n' f' https://labelstud.io/guide/storage.html#Local-storage]\n' f' 4. Import "{out_file}" to the project\n' ) else: logger.error('No labels converted') def add_parser(subparsers): coco = subparsers.add_parser('coco') coco.add_argument( '-i', '--input', dest='input', required=True, help='directory with COCO where images, labels, notes.json are located', action=ExpandFullPath, ) coco.add_argument( '-o', '--output', dest='output', help='output file with Label Studio JSON tasks', default='output.json', action=ExpandFullPath, ) coco.add_argument( '--to-name', dest='to_name', help='object name from Label Studio labeling config', default='image', ) coco.add_argument( '--from-name', dest='from_name', help='control tag name from Label Studio labeling config', default='label', ) coco.add_argument( '--out-type', dest='out_type', help='annotation type - "annotations" or "predictions"', default='annotations', ) coco.add_argument( '--image-root-url', dest='image_root_url', help='root URL path where images will be hosted, e.g.: http://example.com/images', default='/data/local-files/?d=', ) coco.add_argument( '--point-width', dest='point_width', help='key point width (size)', default=1.0, type=float, ) <file_sep>pandas>=0.24.0 requests>=2.22.0,<3 Pillow==9.3.0 nltk==3.6.7 label-studio-tools>=0.0.2 ujson ijson~=3.2.0.post0 <file_sep>""" This code allows to export Label Studio Export JSON to FUNSD format. It's only the basic converter, it converts every bbox as a separate word. Check this github issue for more details: https://github.com/heartexlabs/label-studio/issues/2634#issuecomment-1251648670 Usage: funsd.py export.json This command will export your LS OCR annotations to "./funsd/" directory. """ import os import json from collections import defaultdict def convert_annotation_to_fund(result): # collect all LS results and combine labels, text, coordinates into one record pre = defaultdict(dict) for item in result: o = pre[item['id']] labels = item.get('value', {}).get('labels', None) if labels: o['label'] = labels[0] text = item.get('value', {}).get('text', None) if text: o['text'] = text[0] if 'box' not in o: w, h = item['original_width'], item['original_height'] v = item.get('value') x1 = v['x'] / 100.0 * w y1 = v['y'] / 100.0 * h x2 = x1 + v['width'] / 100.0 * w y2 = y1 + v['height'] / 100.0 * h o['box'] = [x1, x2, y1, y2] # make FUNSD output output = [] counter = 0 for key in pre: counter += 1 output.append( { "id": counter, "box": pre[key]['box'], "text": pre[key]['text'], "label": pre[key]['label'], "words": [{"box": pre[key]['box'], "text": pre[key]['text']}], "linking": [], } ) return {'form': output} def ls_to_funsd_converter( ls_export_path='export.json', funsd_dir='funsd', data_key='ocr' ): with open(ls_export_path) as f: tasks = json.load(f) os.makedirs(funsd_dir, exist_ok=True) for task in tasks: for annotation in task['annotations']: output = convert_annotation_to_fund(annotation['result']) filename = task["data"][data_key] filename = os.path.basename(filename) filename = ( f'{funsd_dir}/task-{task["id"]}-annotation-{annotation["id"]}-' f'{filename}.json' ) with open(filename, 'w') as f: json.dump(output, f) if __name__ == '__main__': import sys print('Usage:', sys.argv[0], 'export.json') print('This command will export your LS OCR annotations to "./funsd/" directory') ls_to_funsd_converter(sys.argv[1]) <file_sep>""" Original RLE JS code from https://github.com/thi-ng/umbrella/blob/develop/packages/rle-pack/src/index.ts export const decode = (src: Uint8Array) => { const input = new BitInputStream(src); const num = input.read(32); const wordSize = input.read(5) + 1; const rleSizes = [0, 0, 0, 0].map(() => input.read(4) + 1); const out = arrayForWordSize(wordSize, num); let x, j; for (let i = 0; i < num; ) { x = input.readBit(); j = i + 1 + input.read(rleSizes[input.read(2)]); if (x) { out.fill(input.read(wordSize), i, j); i = j; } else { for (; i < j; i++) { out[i] = input.read(wordSize); } } } return out; }; const arrayForWordSize = (ws: number, n: number) => { return new (ws < 9 ? Uint8Array : ws < 17 ? Uint16Array : Uint32Array)(n); }; """ import os import uuid import numpy as np import logging from PIL import Image from collections import defaultdict from itertools import groupby logger = logging.getLogger(__name__) ### Brush Export ### class InputStream: def __init__(self, data): self.data = data self.i = 0 def read(self, size): out = self.data[self.i : self.i + size] self.i += size return int(out, 2) def access_bit(data, num): """from bytes array to bits by num position""" base = int(num // 8) shift = 7 - int(num % 8) return (data[base] & (1 << shift)) >> shift def bytes2bit(data): """get bit string from bytes data""" return ''.join([str(access_bit(data, i)) for i in range(len(data) * 8)]) def decode_rle(rle, print_params: bool = False): """from LS RLE to numpy uint8 3d image [width, height, channel] Args: print_params (bool, optional): If true, a RLE parameters print statement is suppressed """ input = InputStream(bytes2bit(rle)) num = input.read(32) word_size = input.read(5) + 1 rle_sizes = [input.read(4) + 1 for _ in range(4)] if print_params: print( 'RLE params:', num, 'values', word_size, 'word_size', rle_sizes, 'rle_sizes' ) i = 0 out = np.zeros(num, dtype=np.uint8) while i < num: x = input.read(1) j = i + 1 + input.read(rle_sizes[input.read(2)]) if x: val = input.read(word_size) out[i:j] = val i = j else: while i < j: val = input.read(word_size) out[i] = val i += 1 return out def decode_from_annotation(from_name, results): """from LS annotation to {"tag_name + label_name": [numpy uint8 image (width x height)]}""" layers = {} counters = defaultdict(int) for result in results: key = ( 'brushlabels' if result['type'].lower() == 'brushlabels' else ('labels' if result['type'].lower() == 'labels' else None) ) if key is None or 'rle' not in result: continue rle = result['rle'] width = result['original_width'] height = result['original_height'] labels = result[key] if key in result else ['no_label'] name = from_name + '-' + '-'.join(labels) # result count i = str(counters[name]) counters[name] += 1 name += '-' + i image = decode_rle(rle) layers[name] = np.reshape(image, [height, width, 4])[:, :, 3] return layers def save_brush_images_from_annotation( task_id, annotation_id, completed_by, from_name, results, out_dir, out_format='numpy', ): layers = decode_from_annotation(from_name, results) if isinstance(completed_by, dict): email = completed_by.get('email', '') else: email = str(completed_by) email = "".join( x for x in email if x.isalnum() or x == '@' or x == '.' ) # sanitize filename for name in layers: filename = os.path.join( out_dir, 'task-' + str(task_id) + '-annotation-' + str(annotation_id) + '-by-' + email + '-' + name, ) image = layers[name] logger.debug(f'Save image to {filename}') if out_format == 'numpy': np.save(filename, image) elif out_format == 'png': im = Image.fromarray(image) im.save(filename + '.png') else: raise Exception('Unknown output format for brush converter') def convert_task(item, out_dir, out_format='numpy'): """Task with multiple annotations to brush images, out_format = numpy | png""" for from_name, results in item['output'].items(): save_brush_images_from_annotation( item['id'], item['annotation_id'], item['completed_by'], from_name, results, out_dir, out_format, ) def convert_task_dir(items, out_dir, out_format='numpy'): """Directory with tasks and annotation to brush images, out_format = numpy | png""" for item in items: convert_task(item, out_dir, out_format) # convert_task_dir('/ls/test/completions', '/ls/test/completions/output', 'numpy') ### Brush Import ### def bits2byte(arr_str, n=8): """Convert bits back to byte :param arr_str: string with the bit array :type arr_str: str :param n: number of bits to separate the arr string into :type n: int :return rle: :type rle: list """ rle = [] numbers = [arr_str[i : i + n] for i in range(0, len(arr_str), n)] for i in numbers: rle.append(int(i, 2)) return rle # Shamelessly plagiarized from https://stackoverflow.com/a/32681075/6051733 def base_rle_encode(inarray): """run length encoding. Partial credit to R rle function. Multi datatype arrays catered for including non Numpy returns: tuple (runlengths, startpositions, values)""" ia = np.asarray(inarray) # force numpy n = len(ia) if n == 0: return None, None, None else: y = ia[1:] != ia[:-1] # pairwise unequal (string safe) i = np.append(np.where(y), n - 1) # must include last element posi z = np.diff(np.append(-1, i)) # run lengths p = np.cumsum(np.append(0, z))[:-1] # positions return z, p, ia[i] def encode_rle(arr, wordsize=8, rle_sizes=[3, 4, 8, 16]): """Encode a 1d array to rle :param arr: flattened np.array from a 4d image (R, G, B, alpha) :type arr: np.array :param wordsize: wordsize bits for decoding, default is 8 :type wordsize: int :param rle_sizes: list of ints which state how long a series is of the same number :type rle_sizes: list :return rle: run length encoded array :type rle: list """ # Set length of array in 32 bits num = len(arr) numbits = f'{num:032b}' # put in the wordsize in bits wordsizebits = f'{wordsize - 1:05b}' # put rle sizes in the bits rle_bits = ''.join([f'{x - 1:04b}' for x in rle_sizes]) # combine it into base string base_str = numbits + wordsizebits + rle_bits # start with creating the rle bite string out_str = '' for length_reeks, p, value in zip(*base_rle_encode(arr)): # TODO: A nice to have but --> this can be optimized but works if length_reeks == 1: # we state with the first 0 that it has a length of 1 out_str += '0' # We state now the index on the rle sizes out_str += '00' # the rle size value is 0 for an individual number out_str += '000' # put the value in a 8 bit string out_str += f'{value:08b}' state = 'single_val' elif length_reeks > 1: state = 'series' # rle size = 3 if length_reeks <= 8: # Starting with a 1 indicates that we have started a series out_str += '1' # index in rle size arr out_str += '00' # length of array to bits out_str += f'{length_reeks - 1:03b}' out_str += f'{value:08b}' # rle size = 4 elif 8 < length_reeks <= 16: # Starting with a 1 indicates that we have started a series out_str += '1' out_str += '01' # length of array to bits out_str += f'{length_reeks - 1:04b}' out_str += f'{value:08b}' # rle size = 8 elif 16 < length_reeks <= 256: # Starting with a 1 indicates that we have started a series out_str += '1' out_str += '10' # length of array to bits out_str += f'{length_reeks - 1:08b}' out_str += f'{value:08b}' # rle size = 16 or longer else: length_temp = length_reeks while length_temp > 2**16: # Starting with a 1 indicates that we have started a series out_str += '1' out_str += '11' out_str += f'{2 ** 16 - 1:016b}' out_str += f'{value:08b}' length_temp -= 2**16 # Starting with a 1 indicates that we have started a series out_str += '1' out_str += '11' # length of array to bits out_str += f'{length_temp - 1:016b}' out_str += f'{value:08b}' # make sure that we have an 8 fold lenght otherwise add 0's at the end nzfill = 8 - len(base_str + out_str) % 8 total_str = base_str + out_str total_str = total_str + nzfill * '0' rle = bits2byte(total_str) return rle def contour2rle(contours, contour_id, img_width, img_height): """ :param contours: list of contours :type contours: list :param contour_id: id of contour which you want to translate :type contour_id: int :param img_width: image shape width :type img_width: int :param img_height: image shape height :type img_height: int :return: list of ints in RLE format """ import cv2 # opencv mask_im = np.zeros((img_width, img_height, 4)) mask_contours = cv2.drawContours( mask_im, contours, contour_id, color=(0, 255, 0, 100), thickness=-1 ) rle_out = encode_rle(mask_contours.ravel().astype(int)) return rle_out def mask2rle(mask): """Convert mask to RLE :param mask: uint8 or int np.array mask with len(shape) == 2 like grayscale image :return: list of ints in RLE format """ assert len(mask.shape) == 2, 'mask must be 2D np.array' assert mask.dtype == np.uint8 or mask.dtype == int, 'mask must be uint8 or int' array = mask.ravel() array = np.repeat(array, 4) # must be 4 channels rle = encode_rle(array) return rle def image2rle(path): """Convert mask image (jpg, png) to RLE 1. Read image as grayscale 2. Flatten to 1d array 3. Threshold > 128 4. Encode :param path: path to image with mask (jpg, png), this image will be thresholded with values > 128 to obtain mask, so you can mark background as black and foreground as white :return: list of ints in RLE format """ with Image.open(path).convert('L') as image: mask = np.array((np.array(image) > 128) * 255, dtype=np.uint8) array = mask.ravel() array = np.repeat(array, 4) rle = encode_rle(array) return rle, image.size[0], image.size[1] def image2annotation( path, label_name, from_name, to_name, ground_truth=False, model_version=None, score=None, ): """Convert image with mask to brush RLE annotation :param path: path to image with mask (jpg, png), this image will be thresholded with values > 128 to obtain mask, so you can mark background as black and foreground as white :param label_name: label name from labeling config (<Label>) :param from_name: brush tag name (<BrushLabels>) :param to_name: image tag name (<Image>) :param ground_truth: ground truth annotation true/false :param model_version: any string, only for predictions :param score: model score as float, only for predictions :return: dict with Label Studio Annotation or Prediction (Pre-annotation) """ rle, width, height = image2rle(path) result = { "result": [ { "id": str(uuid.uuid4())[0:8], "type": "brushlabels", "value": {"rle": rle, "format": "rle", "brushlabels": [label_name]}, "origin": "manual", "to_name": to_name, "from_name": from_name, "image_rotation": 0, "original_width": width, "original_height": height, } ], } # prediction if model_version: result["model_version"] = model_version result["score"] = score # annotation else: result["ground_truth"] = ground_truth return result <file_sep>import os import json # better to use "imports ujson as json" for the best performance import uuid import logging from PIL import Image from typing import Optional, Tuple from urllib.request import ( pathname2url, ) # for converting "+","*", etc. in file paths to appropriate urls from label_studio_converter.utils import ExpandFullPath from label_studio_converter.imports.label_config import generate_label_config logger = logging.getLogger('root') def convert_yolo_to_ls( input_dir, out_file, to_name='image', from_name='label', out_type="annotations", image_root_url='/data/local-files/?d=', image_ext='.jpg,.jpeg,.png', image_dims: Optional[Tuple[int, int]] = None, ): """Convert YOLO labeling to Label Studio JSON :param input_dir: directory with YOLO where images, labels, notes.json are located :param out_file: output file with Label Studio JSON tasks :param to_name: object name from Label Studio labeling config :param from_name: control tag name from Label Studio labeling config :param out_type: annotation type - "annotations" or "predictions" :param image_root_url: root URL path where images will be hosted, e.g.: http://example.com/images :param image_ext: image extension/s - single string or comma separated list to search, eg. .jpeg or .jpg, .png and so on. :param image_dims: image dimensions - optional tuple of integers specifying the image width and height of *all* images in the dataset. Defaults to opening the image to determine it's width and height, which is slower. This should only be used in the special case where you dataset has uniform image dimesions. """ tasks = [] logger.info('Reading YOLO notes and categories from %s', input_dir) # build categories=>labels dict notes_file = os.path.join(input_dir, 'classes.txt') with open(notes_file) as f: lines = [line.strip() for line in f.readlines()] categories = {i: line for i, line in enumerate(lines)} logger.info(f'Found {len(categories)} categories') # generate and save labeling config label_config_file = out_file.replace('.json', '') + '.label_config.xml' generate_label_config( categories, {from_name: 'RectangleLabels'}, to_name, from_name, label_config_file, ) # define directories labels_dir = os.path.join(input_dir, 'labels') images_dir = os.path.join(input_dir, 'images') logger.info('Converting labels from %s', labels_dir) # build array out of provided comma separated image_extns (str -> array) image_ext = [x.strip() for x in image_ext.split(",")] logger.info(f'image extensions->, {image_ext}') # loop through images for f in os.listdir(images_dir): image_file_found_flag = False for ext in image_ext: if f.endswith(ext): image_file = f image_file_base = f[0 : -len(ext)] image_file_found_flag = True break if not image_file_found_flag: continue image_root_url += '' if image_root_url.endswith('/') else '/' task = { "data": { # eg. '../../foo+you.py' -> '../../foo%2Byou.py' "image": image_root_url + str(pathname2url(image_file)) } } # define coresponding label file and check existence label_file = os.path.join(labels_dir, image_file_base + '.txt') if os.path.exists(label_file): task[out_type] = [ { "result": [], "ground_truth": False, } ] # read image sizes if image_dims is None: # default to opening file if we aren't given image dims. slow! with Image.open(os.path.join(images_dir, image_file)) as im: image_width, image_height = im.size else: image_width, image_height = image_dims with open(label_file) as file: # convert all bounding boxes to Label Studio Results lines = file.readlines() for line in lines: label_id, x, y, width, height = line.split() x, y, width, height = ( float(x), float(y), float(width), float(height), ) item = { "id": uuid.uuid4().hex[0:10], "type": "rectanglelabels", "value": { "x": (x - width / 2) * 100, "y": (y - height / 2) * 100, "width": width * 100, "height": height * 100, "rotation": 0, "rectanglelabels": [categories[int(label_id)]], }, "to_name": to_name, "from_name": from_name, "image_rotation": 0, "original_width": image_width, "original_height": image_height, } task[out_type][0]['result'].append(item) tasks.append(task) if len(tasks) > 0: logger.info('Saving Label Studio JSON to %s', out_file) with open(out_file, 'w') as out: json.dump(tasks, out) print( '\n' f' 1. Create a new project in Label Studio\n' f' 2. Use Labeling Config from "{label_config_file}"\n' f' 3. Setup serving for images [e.g. you can use Local Storage (or others):\n' f' https://labelstud.io/guide/storage.html#Local-storage]\n' f' 4. Import "{out_file}" to the project\n' ) else: logger.error('No labels converted') def add_parser(subparsers): yolo = subparsers.add_parser('yolo') yolo.add_argument( '-i', '--input', dest='input', required=True, help='directory with YOLO where images, labels, notes.json are located', action=ExpandFullPath, ) yolo.add_argument( '-o', '--output', dest='output', help='output file with Label Studio JSON tasks', default='output.json', action=ExpandFullPath, ) yolo.add_argument( '--to-name', dest='to_name', help='object name from Label Studio labeling config', default='image', ) yolo.add_argument( '--from-name', dest='from_name', help='control tag name from Label Studio labeling config', default='label', ) yolo.add_argument( '--out-type', dest='out_type', help='annotation type - "annotations" or "predictions"', default='annotations', ) yolo.add_argument( '--image-root-url', dest='image_root_url', help='root URL path where images will be hosted, e.g.: http://example.com/images', default='/data/local-files/?d=', ) yolo.add_argument( '--image-ext', dest='image_ext', help='image extension to search: .jpeg or .jpg, .png', default='.jpg', ) yolo.add_argument( '--image-dims', dest='image_dims', type=int, nargs=2, help=( "optional tuple of integers specifying the image width and height of *all* " "images in the dataset. Defaults to opening the image to determine it's width " "and height, which is slower. This should only be used in the special " "case where you dataset has uniform image dimesions. e.g. `--image-dims 600 800` " "if all your images are of dimensions width=600, height=800" ), default=None, ) <file_sep>from label_studio_converter.imports.colors import COLORS LABELS = """ <{# TAG_NAME #} name="{# FROM_NAME #}" toName="image"> {# LABELS #} </{# TAG_NAME #}> """ LABELING_CONFIG = """<View> <Image name="{# TO_NAME #}" value="$image"/> {# BODY #}</View> """ def generate_label_config( categories, tags, to_name='image', from_name='label', filename=None ): labels = '' for key in sorted(categories.keys()): color = COLORS[int(key) % len(COLORS)] label = f' <Label value="{categories[key]}" background="rgba({color[0]}, {color[1]}, {color[2]}, 1)"/>\n' labels += label body = '' for from_name in tags: tag_body = ( str(LABELS) .replace('{# TAG_NAME #}', tags[from_name]) .replace('{# LABELS #}', labels) .replace('{# TO_NAME #}', to_name) .replace('{# FROM_NAME #}', from_name) ) body += f'\n <Header value="{tags[from_name]}"/>' + tag_body config = ( str(LABELING_CONFIG) .replace('{# BODY #}', body) .replace('{# TO_NAME #}', to_name) ) if filename: with open(filename, 'w') as f: f.write(config) return config <file_sep># try is used here to import this file in setup.py and don't break the setup process try: from .converter import Converter except ModuleNotFoundError as e: print(e) __version__ = '0.0.54rc0' <file_sep>from label_studio_converter import Converter import os import pytest import tempfile import shutil BASE_DIR = os.path.dirname(__file__) TEST_DATA_PATH = os.path.join(BASE_DIR, "data", "test_export_yolo") INPUT_JSON_PATH = os.path.join(BASE_DIR, TEST_DATA_PATH, "data.json") LABEL_CONFIG_PATH = os.path.join(BASE_DIR, TEST_DATA_PATH, "label_config.xml") INPUT_JSON_PATH_POLYGONS = os.path.join(BASE_DIR, TEST_DATA_PATH, "data_polygons.json") LABEL_CONFIG_PATH_POLYGONS = os.path.join( BASE_DIR, TEST_DATA_PATH, "label_config_polygons.xml" ) def check_equal_list_of_strings(list1, list2): # Check that both lists are not empty if not list1 or not list2: return False list1.sort() list2.sort() # Check that the lists have the same length if len(list1) != len(list2): return False # Check that the elements of the lists are equal for i in range(len(list1)): if list1[i] != list2[i]: return False return True def get_os_walk(root_path): list_file_paths = [] for root, dirs, files in os.walk(root_path): for f in files: list_file_paths += [os.path.join(root, f)] return list_file_paths @pytest.fixture def create_temp_folder(): # Create a temporary folder temp_dir = tempfile.mkdtemp() # Yield the temporary folder yield temp_dir # Remove the temporary folder after the test shutil.rmtree(temp_dir) def test_convert_to_yolo(create_temp_folder): """Check converstion label_studio json exported file to yolo with multiple labelers""" # Generates a temporary folder and return the absolute path # The temporary folder contains all the data generate by the following function # For debugging replace create_temp_folder with "./tmp" tmp_folder = create_temp_folder output_dir = tmp_folder output_image_dir = os.path.join(output_dir, "tmp_image") output_label_dir = os.path.join(output_dir, "tmp_label") project_dir = "." converter = Converter(LABEL_CONFIG_PATH, project_dir) converter.convert_to_yolo( INPUT_JSON_PATH, output_dir, output_image_dir=output_image_dir, output_label_dir=output_label_dir, is_dir=False, split_labelers=True, ) abs_path_label_dir = os.path.abspath(output_label_dir) expected_paths = [ os.path.join(abs_path_label_dir, "1", "image1.txt"), os.path.join(abs_path_label_dir, "1", "image2.txt"), os.path.join(abs_path_label_dir, "2", "image1.txt"), ] generated_paths = get_os_walk(abs_path_label_dir) # Check all files and subfolders have been generated. assert check_equal_list_of_strings( expected_paths, generated_paths ), f"Generated file: \n {generated_paths} \n does not match expected ones: \n {expected_paths}" # Check all the annotations have been converted to yolo for file in expected_paths: with open(file) as f: lines = f.readlines() assert ( len(lines) == 2 ), f"Expect different number of annotations in file {file}." def test_convert_polygons_to_yolo(create_temp_folder): """Check converstion label_studio json exported file to yolo with polygons""" # Generates a temporary folder and return the absolute path # The temporary folder contains all the data generate by the following function # For debugging replace create_temp_folder with "./tmp" tmp_folder = create_temp_folder output_dir = tmp_folder output_image_dir = os.path.join(output_dir, "tmp_image") output_label_dir = os.path.join(output_dir, "tmp_label") project_dir = "." converter = Converter(LABEL_CONFIG_PATH_POLYGONS, project_dir) converter.convert_to_yolo( INPUT_JSON_PATH_POLYGONS, output_dir, output_image_dir=output_image_dir, output_label_dir=output_label_dir, is_dir=False, split_labelers=False, ) abs_path_label_dir = os.path.abspath(output_label_dir) expected_paths = [os.path.join(abs_path_label_dir, "image2.txt")] generated_paths = get_os_walk(abs_path_label_dir) # Check all files and subfolders have been generated. assert check_equal_list_of_strings( expected_paths, generated_paths ), f"Generated file: \n {generated_paths} \n does not match expected ones: \n {expected_paths}" # Check all the annotations have been converted to yolo for file in expected_paths: with open(file) as f: lines = f.readlines() assert ( len(lines) == 1 ), f"Expect different number of annotations in file {file}." <file_sep>import os import io import logging import argparse from label_studio_converter.converter import Converter, Format, FormatNotSupportedError from label_studio_converter.exports.csv import ExportToCSV from label_studio_converter.utils import ExpandFullPath from label_studio_converter.imports import yolo as import_yolo, coco as import_coco logging.basicConfig(level=logging.INFO) def get_export_args(parser): parser.add_argument( '-i', '--input', dest='input', required=True, help='Directory or JSON file with annotations (e.g. "/<project_path>/annotations")', action=ExpandFullPath, ) parser.add_argument( '-c', '--config', dest='config', help='Project config (e.g. "/<project_path>/config.xml")', action=ExpandFullPath, ) parser.add_argument( '-o', '--output', dest='output', help='Output file or directory (will be created if not exists)', default=os.path.join(os.path.dirname(__file__), 'output'), action=ExpandFullPath, ) parser.add_argument( '-f', '--format', dest='format', metavar='FORMAT', help='Output format: ' + ', '.join(f.name for f in Format), type=Format.from_string, choices=list(Format), default=Format.JSON, ) parser.add_argument( '--csv-separator', dest='csv_separator', help='Separator used in CSV format', default=',', ) parser.add_argument( '--csv-no-header', dest='csv_no_header', help='Whether to omit header in CSV output file', action='store_true', ) parser.add_argument( '--image-dir', dest='image_dir', help='In case of image outputs (COCO, VOC, ...), specifies output image directory where downloaded images will ' 'be stored. (If not specified, local image paths left untouched)', ) parser.add_argument( '--project-dir', dest='project_dir', default=None, help='Label Studio project directory path', ) parser.add_argument( '--heartex-format', dest='heartex_format', action='store_true', default=True, help='Set this flag if your annotations are in one JSON file instead of multiple JSON files from directory', ) def get_all_args(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='command', help='Available commands') subparsers.required = False # Export parser_export = subparsers.add_parser( 'export', help='Converter from Label Studio JSON annotations to external formats', ) get_export_args(parser_export) # Import parser_import = subparsers.add_parser( 'import', help="Converter from external formats to Label Studio JSON annotations", ) import_format = parser_import.add_subparsers(dest='import_format') import_yolo.add_parser(import_format) import_coco.add_parser(import_format) return parser.parse_args() def export(args): c = Converter(args.config, project_dir=args.project_dir) if args.format == Format.JSON: c.convert_to_json(args.input, args.output) elif args.format == Format.CSV: header = not args.csv_no_header sep = args.csv_separator c.convert_to_csv( args.input, args.output, sep=sep, header=header, is_dir=not args.heartex_format, ) elif args.format == Format.CSV_OLD: header = not args.csv_no_header sep = args.csv_separator ExportToCSV(args.input).to_file( args.output, sep=sep, header=header, index=False ) elif args.format == Format.TSV: header = not args.csv_no_header sep = '\t' c.convert_to_csv( args.input, args.output, sep=sep, header=header, is_dir=not args.heartex_format, ) elif args.format == Format.CONLL2003: c.convert_to_conll2003(args.input, args.output, is_dir=not args.heartex_format) elif args.format == Format.COCO: c.convert_to_coco( args.input, args.output, output_image_dir=args.image_dir, is_dir=not args.heartex_format, ) elif args.format == Format.VOC: c.convert_to_voc( args.input, args.output, output_image_dir=args.image_dir, is_dir=not args.heartex_format, ) elif args.format == Format.YOLO: c.convert_to_yolo(args.input, args.output, is_dir=not args.heartex_format) else: raise FormatNotSupportedError() def imports(args): if args.import_format == 'yolo': import_yolo.convert_yolo_to_ls( input_dir=args.input, out_file=args.output, to_name=args.to_name, from_name=args.from_name, out_type=args.out_type, image_root_url=args.image_root_url, image_ext=args.image_ext, ) elif args.import_format == 'coco': import_coco.convert_coco_to_ls( input_file=args.input, out_file=args.output, to_name=args.to_name, from_name=args.from_name, out_type=args.out_type, image_root_url=args.image_root_url, point_width=args.point_width, ) else: raise FormatNotSupportedError() def main(): args = get_all_args() if args.command == 'export': export(args) elif args.command == 'import': imports(args) else: print('Please, use "import" or "export" or "-h" command') if __name__ == "__main__": main() <file_sep># Label Studio Converter [Website](https://labelstud.io/) • [Docs](https://labelstud.io/guide) • [Twitter](https://twitter.com/heartexlabs) • [Join Slack Community <img src="https://app.heartex.ai/docs/images/slack-mini.png" width="18px"/>](https://slack.labelstud.io) ## Table of Contents - [Introduction](#introduction) - [Examples](#examples) - [JSON](#json) - [CSV](#csv) - [CoNLL 2003](#conll-2003) - [COCO](#coco) - [Pascal VOC XML](#pascal-voc-xml) - [Contributing](#contributing) - [License](#license) ## Introduction Label Studio Format Converter helps you to encode labels into the format of your favorite machine learning library. ## Examples #### JSON **Running from the command line:** ```bash pip install -U label-studio-converter python label-studio-converter export -i exported_tasks.json -c examples/sentiment_analysis/config.xml -o output_dir -f CSV ``` **Running from python:** ```python from label_studio_converter import Converter c = Converter('examples/sentiment_analysis/config.xml') c.convert_to_json('examples/sentiment_analysis/completions/', 'tmp/output.json') ``` Getting output file: `tmp/output.json` ```json [ { "reviewText": "Good case, Excellent value.", "sentiment": "Positive" }, { "reviewText": "What a waste of money and time!", "sentiment": "Negative" }, { "reviewText": "The goose neck needs a little coaxing", "sentiment": "Neutral" } ] ``` Use cases: any tasks #### CSV Running from the command line: ```bash python label_studio_converter/cli.py --input examples/sentiment_analysis/completions/ --config examples/sentiment_analysis/config.xml --output output_dir --format CSV --csv-separator $'\t' ``` Running from python: ```python from label_studio_converter import Converter c = Converter('examples/sentiment_analysis/config.xml') c.convert_to_csv('examples/sentiment_analysis/completions/', 'output_dir', sep='\t', header=True) ``` Getting output file `tmp/output.tsv`: ```tsv reviewText sentiment Good case, Excellent value. Positive What a waste of money and time! Negative The goose neck needs a little coaxing Neutral ``` Use cases: any tasks #### CoNLL 2003 Running from the command line: ```bash python label_studio_converter/cli.py --input examples/named_entity/completions/ --config examples/named_entity/config.xml --output tmp/output.conll --format CONLL2003 ``` Running from python: ```python from label_studio_converter import Converter c = Converter('examples/named_entity/config.xml') c.convert_to_conll2003('examples/named_entity/completions/', 'tmp/output.conll') ``` Getting output file `tmp/output.conll` ```text -DOCSTART- -X- O Showers -X- _ O continued -X- _ O throughout -X- _ O the -X- _ O week -X- _ O in -X- _ O the -X- _ O Bahia -X- _ B-Location cocoa -X- _ O zone, -X- _ O ... ``` Use cases: text tagging #### COCO Running from the command line: ```bash python label_studio_converter/cli.py --input examples/image_bbox/completions/ --config examples/image_bbox/config.xml --output tmp/output.json --format COCO --image-dir tmp/images ``` Running from python: ```python from label_studio_converter import Converter c = Converter('examples/image_bbox/config.xml') c.convert_to_coco('examples/image_bbox/completions/', 'tmp/output.conll', output_image_dir='tmp/images') ``` Output images could be found in `tmp/images` Getting output file `tmp/output.json` ```json { "images": [ { "width": 800, "height": 501, "id": 0, "file_name": "tmp/images/62a623a0d3cef27a51d3689865e7b08a" } ], "categories": [ { "id": 0, "name": "Planet" }, { "id": 1, "name": "Moonwalker" } ], "annotations": [ { "id": 0, "image_id": 0, "category_id": 0, "segmentation": [], "bbox": [ 299, 6, 377, 260 ], "ignore": 0, "iscrowd": 0, "area": 98020 }, { "id": 1, "image_id": 0, "category_id": 1, "segmentation": [], "bbox": [ 288, 300, 132, 90 ], "ignore": 0, "iscrowd": 0, "area": 11880 } ], "info": { "year": 2019, "version": "1.0", "contributor": "Label Studio" } } ``` Use cases: image object detection #### Pascal VOC XML Running from the command line: ```bash python label_studio_converter/cli.py --input examples/image_bbox/completions/ --config examples/image_bbox/config.xml --output tmp/voc-annotations --format VOC --image-dir tmp/images ``` Running from python: ```python from label_studio_converter import Converter c = Converter('examples/image_bbox/config.xml') c.convert_to_voc('examples/image_bbox/completions/', 'tmp/output.conll', output_image_dir='tmp/images') ``` Output images can be found in `tmp/images` Corresponding annotations could be found in `tmp/voc-annotations/*.xml`: ```xml <?xml version="1.0" encoding="utf-8"?> <annotation> <folder>tmp/images</folder> <filename>62a623a0d3cef27a51d3689865e7b08a</filename> <source> <database>MyDatabase</database> <annotation>COCO2017</annotation> <image>flickr</image> <flickrid>NULL</flickrid> </source> <owner> <flickrid>NULL</flickrid> <name>Label Studio</name> </owner> <size> <width>800</width> <height>501</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>Planet</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>299</xmin> <ymin>6</ymin> <xmax>676</xmax> <ymax>266</ymax> </bndbox> </object> <object> <name>Moonwalker</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>288</xmin> <ymin>300</ymin> <xmax>420</xmax> <ymax>390</ymax> </bndbox> </object> </annotation> ``` Use cases: image object detection ### YOLO to Label Studio converter Usage: ``` label-studio-converter import yolo -i /yolo/root/directory -o ls-tasks.json ``` Help: ``` label-studio-converter import yolo -h usage: label-studio-converter import yolo [-h] -i INPUT [-o OUTPUT] [--to-name TO_NAME] [--from-name FROM_NAME] [--out-type OUT_TYPE] [--image-root-url IMAGE_ROOT_URL] [--image-ext IMAGE_EXT] optional arguments: -h, --help show this help message and exit -i INPUT, --input INPUT directory with YOLO where images, labels, notes.json are located -o OUTPUT, --output OUTPUT output file with Label Studio JSON tasks --to-name TO_NAME object name from Label Studio labeling config --from-name FROM_NAME control tag name from Label Studio labeling config --out-type OUT_TYPE annotation type - "annotations" or "predictions" --image-root-url IMAGE_ROOT_URL root URL path where images will be hosted, e.g.: http://example.com/images or s3://my-bucket --image-ext IMAGE_EXT image extension to search: .jpg, .png ``` YOLO export folder example: ``` yolo-folder images - 1.jpg - 2.jpg - ... labels - 1.txt - 2.txt classes.txt ``` classes.txt example ``` Airplane Car ``` ## Contributing We would love to get your help for creating converters to other models. Please feel free to create pull requests. - [Contributing Guideline](https://github.com/heartexlabs/label-studio/blob/develop/CONTRIBUTING.md) - [Code Of Conduct](https://github.com/heartexlabs/label-studio/blob/develop/CODE_OF_CONDUCT.md) ## License This software is licensed under the [Apache 2.0 LICENSE](/LICENSE) © [Heartex](https://www.heartex.com/). 2020 <img src="https://github.com/heartexlabs/label-studio/blob/master/images/opossum_looking.png?raw=true" title="Hey everyone!" height="140" width="140" /> <file_sep>import unittest import label_studio_converter.utils as utils class TestUtils(unittest.TestCase): def test_create_tokens_and_tags_with_eol_tag(self): s = 'I need a break\nplease' spans = [ { 'end': 14, 'labels': ['Person'], 'start': 9, 'text': 'break', 'type': 'Labels', } ] tokens, tags = utils.create_tokens_and_tags(s, spans) self.assertEqual(tokens[0], "I") self.assertEqual(tags[0], "O") self.assertEqual(tokens[1], "need") self.assertEqual(tags[1], "O") self.assertEqual(tokens[2], "a") self.assertEqual(tags[2], "O") self.assertEqual(tokens[3], "break") self.assertEqual(tags[3], "B-Person") self.assertEqual(tokens[4], "please") self.assertEqual(tags[4], "O") def test_create_tokens_and_tags_with_tab_tag(self): s = 'I need a tab\tplease' spans = [ { 'end': 12, 'labels': ['Person'], 'start': 9, 'text': 'tab', 'type': 'Labels', } ] tokens, tags = utils.create_tokens_and_tags(s, spans) self.assertEqual(tokens[0], "I") self.assertEqual(tags[0], "O") self.assertEqual(tokens[1], "need") self.assertEqual(tags[1], "O") self.assertEqual(tokens[2], "a") self.assertEqual(tags[2], "O") self.assertEqual(tokens[3], "tab") self.assertEqual(tags[3], "B-Person") self.assertEqual(tokens[4], "please") self.assertEqual(tags[4], "O") def test_create_tokens_and_tags_for_full_token(self): text = 'We gave <NAME> the ball.' spans = [{'end': 12, 'labels': ['Person'], 'start': 9, 'text': 'ane'}] tokens, tags = utils.create_tokens_and_tags(text, spans) self.assertEqual(tokens, ['We', 'gave', 'Jane', 'Smith', 'the', 'ball', '.']) self.assertEqual(tags, ['O', 'O', 'B-Person', 'O', 'O', 'O', 'O']) def test_create_tokens_and_tags_with_leading_space(self): text = 'We gave <NAME> the ball.' spans = [{'end': 18, 'labels': ['Person'], 'start': 7, 'text': ' <NAME>'}] tokens, tags = utils.create_tokens_and_tags(text, spans) self.assertEqual(tokens, ['We', 'gave', 'Jane', 'Smith', 'the', 'ball', '.']) self.assertEqual(tags, ['O', 'O', 'B-Person', 'I-Person', 'O', 'O', 'O']) def test_create_tokens_and_tags_with_trailing_space(self): text = 'We gave <NAME> the ball.' spans = [{'end': 19, 'labels': ['Person'], 'start': 8, 'text': '<NAME> '}] tokens, tags = utils.create_tokens_and_tags(text, spans) self.assertEqual(tokens, ['We', 'gave', 'Jane', 'Smith', 'the', 'ball', '.']) self.assertEqual(tags, ['O', 'O', 'B-Person', 'I-Person', 'O', 'O', 'O']) def test_create_tokens_and_tags_for_token_with_dollar_sign(self): text = 'A meal with $3.99 bill' spans = [{'end': 16, 'labels': ['Person'], 'start': 12, 'text': '$3.99'}] tokens, tags = utils.create_tokens_and_tags(text, spans) self.assertEqual(tokens, ['A', 'meal', 'with', '$', '3.99', 'bill']) self.assertEqual(tags, ['O', 'O', 'O', 'B-Person', 'I-Person', 'O']) def test_create_tokens_and_tags_for_token_with_slash_sign(self): text = 'A meal from Google/Facebook' spans = [ {'end': 17, 'labels': ['ORG'], 'start': 12, 'text': 'Google'}, {'end': 22, 'labels': ['ORG'], 'start': 19, 'text': 'Face'}, ] tokens, tags = utils.create_tokens_and_tags(text, spans) self.assertEqual(tokens, ['A', 'meal', 'from', 'Google', '/', 'Facebook']) self.assertEqual(tags, ['O', 'O', 'O', 'B-ORG', 'O', 'B-ORG']) def test_create_tokens_and_tags_for_token_with_ampersand_sign(self): text = "They're the world's most fear;some fighting team,Teenage Mut;ant Ninja Turtles (We're really hip!).They're heroes in the half-shell and they're green,Teenage Mutant Ninja Turtles (Hey, get a grip!),When the evil Shre&dder attacks These Turtle boys don't cut him no slack! Spli\/nter taught them to be ninja teens.. Teen#age Mutant Ninja Turtles (He's a radi@cal rat!), Leonardo leads, Donat#ello does machines, Teenage Mutant Ninja Turt;les (That's a fact, Jack!),Raphael is cool but rude (Gimme a break!), Michel;angelo is a party dude (Party!)" spans = [ {"start": 0, "end": 4, "text": "They", "labels": ["PER"]}, {"start": 12, "end": 17, "text": "world", "labels": ["PER"]}, {"start": 57, "end": 60, "text": "Mut", "labels": ["PER"]}, {"start": 212, "end": 216, "text": "Shre", "labels": ["PER"]}, {"start": 314, "end": 318, "text": "Teen", "labels": ["PER"]}, {"start": 272, "end": 276, "text": "Spli", "labels": ["PER"]}, ] tokens, tags = utils.create_tokens_and_tags(text, spans) self.assertEqual(tokens[52], 'Shre') self.assertEqual(tags[52], 'B-PER') self.assertEqual(tags[51], 'O') self.assertEqual(tags[53], 'O') def test_create_tokens_and_tags_for_token_with_hash_sign(self): text = "Mut;ant Ninja Turtles. Teen#age Mutant Ninja Turtles." spans = [ {"start": 0, "end": 3, "text": "Mut", "labels": ["PER"]}, {"start": 5, "end": 7, "text": "ant", "labels": ["ORG"]}, {"start": 24, "end": 27, "text": "Teen", "labels": ["PER"]}, {"start": 29, "end": 30, "text": "Shre", "labels": ["ORG"]}, ] tokens, tags = utils.create_tokens_and_tags(text, spans) self.assertEqual( tokens, [ 'Mut', ';', 'ant', 'Ninja', 'Turtles.', 'Teen', '#', 'age', 'Mutant', 'Ninja', 'Turtles', '.', ], ) self.assertEqual( tags, [ 'B-PER', 'O', 'B-ORG', 'O', 'O', 'B-PER', 'O', 'B-ORG', 'O', 'O', 'O', 'O', ], ) <file_sep>import json import os import glob import lxml.etree as ET from label_studio_converter.imports import yolo as import_yolo def test_base_import_yolo(): """Tests generated config and json files for yolo imports test_import_yolo_data folder assumes only images in the 'images' folder with corresponding labels existing in the 'labes' dir and a 'classes.txt' present. (currently 7 images -> 3 png, 2 jpg and 2 jpeg files) """ input_data_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),'data','test_import_yolo_data') out_json_file = os.path.join('/tmp','lsc-pytest','yolo_exp_test.json') image_ext = '.jpg,.jpeg,.png' #comma seperated string of extns. import_yolo.convert_yolo_to_ls( input_dir=input_data_dir, out_file=out_json_file, image_ext=image_ext ) #'yolo_exp_test.label_config.xml' and 'yolo_exp_test.json' must be generated. out_config_file = os.path.join('/tmp','lsc-pytest','yolo_exp_test.label_config.xml') assert os.path.exists(out_config_file) and os.path.exists(out_json_file), "> import failed! files not generated." #provided labels from classes.txt with open(os.path.join(input_data_dir,'classes.txt'), 'r') as f: labels = f.read()[:-1].split('\n') #[:-1] since last line in classes.txt is empty by convention #generated labels from config xml label_element = ET.parse(out_config_file).getroot()[2] lables_generated = [x.attrib['value'] for x in label_element.getchildren()] assert set(labels) == set(lables_generated), "> generated class labels do not match original labels" #total image files in the input folder img_files = glob.glob(os.path.join(input_data_dir,'images','*')) with open(out_json_file, 'r') as f: ls_data = json.loads(f.read()) assert len(ls_data) == len(img_files), "some file imports did not succeed!" def test_base_import_yolo_with_img_dims(): """Tests generated config and json files for yolo imports while importing unique image dims """ input_data_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),'data','test_import_yolo_data_unif_dims') out_json_file = os.path.join('/tmp','lsc-pytest','yolo_exp_test.json') image_ext = '.jpg,.jpeg,.png' # comma seperated string of extns. img_dims = (640, 329) # known width and height of dataset import_yolo.convert_yolo_to_ls( input_dir=input_data_dir, out_file=out_json_file, image_ext=image_ext ) # 'yolo_exp_test.label_config.xml' and 'yolo_exp_test.json' must be generated. out_config_file = os.path.join('/tmp','lsc-pytest','yolo_exp_test.label_config.xml') assert os.path.exists(out_config_file) and os.path.exists(out_json_file), "> import failed! files not generated." # provided labels from classes.txt with open(os.path.join(input_data_dir, 'classes.txt'), 'r') as f: labels = f.read()[:-1].split( '\n' ) # [:-1] since last line in classes.txt is empty by convention # generated labels from config xml label_element = ET.parse(out_config_file).getroot()[2] lables_generated = [x.attrib['value'] for x in label_element.getchildren()] assert set(labels) == set( lables_generated ), "> generated class labels do not match original labels" #total image files in the input folder img_files = glob.glob(os.path.join(input_data_dir,'images','*')) with open(out_json_file, 'r') as f: ls_data = json.loads(f.read()) assert len(ls_data) == len(img_files), "some file imports did not succeed!" if __name__ == '__main__': test_base_import_yolo() test_base_import_yolo_with_img_dims() <file_sep>import json import os from label_studio_converter import Converter from pandas import read_csv def test_csv_export(): # Test case 1, simple output, no JSON converter = Converter({}, '/tmp') output_dir = '/tmp/lsc-pytest' result_csv = output_dir + '/result.csv' input_data = os.path.abspath(os.path.dirname(__file__)) + '/data/test_export_csv/csv_test.json' sep = ',' converter.convert_to_csv(input_data, output_dir, sep=sep, header=True, is_dir=False) df = read_csv(result_csv, sep=sep) nulls = df.isnull().sum() if nulls.any() > 0: assert False, "There should be no empty values in result CSV" # Test case 2, complex fields with JSON input_data = os.path.abspath(os.path.dirname(__file__)) + '/data/test_export_csv/csv_test2.json' assert_csv = os.path.abspath(os.path.dirname(__file__)) + '/data/test_export_csv/csv_test2_result.csv' sep = '\t' converter.convert_to_csv(input_data, output_dir, sep=sep, header=True, is_dir=False) df = read_csv(result_csv, sep=sep) nulls = df.isnull().sum() assert sum(nulls) == 2, "There should be exactly two empty values in result CSV" # Ensure fields are valid JSON json.loads(df.iloc[0].writers) json.loads(df.iloc[0].iswcs_1) assert open(result_csv).read() == open(assert_csv).read() if __name__ == '__main__': test_csv_export() <file_sep>""" This file is deprecated and not used in label-studio-converter command """ import argparse import os import io from label_studio_converter.converter import Converter, Format class ExpandFullPath(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values))) def main(): parser = argparse.ArgumentParser( description='Converter from Label Studio output completions to various formats', formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( '-i', '--input', dest='input', required=True, help='Directory or JSON file with completions (e.g. "/<project_path>/completions")', action=ExpandFullPath, ) parser.add_argument( '-c', '--config', dest='config', required=True, help='Project config (e.g. "/<project_path>/config.xml")', action=ExpandFullPath, ) parser.add_argument( '-o', '--output', dest='output', help='Output file or directory (will be created if not exists)', default=os.path.join(os.path.dirname(__file__), 'output'), action=ExpandFullPath, ) parser.add_argument( '-f', '--format', dest='format', metavar='FORMAT', help='Output format: ' + ', '.join(f.name for f in Format), type=Format.from_string, choices=list(Format), default=Format.JSON, ) parser.add_argument( '--csv-separator', dest='csv_separator', help='Separator used in CSV format', default=',', ) parser.add_argument( '--csv-no-header', dest='csv_no_header', help='Whether to omit header in CSV output file', action='store_true', ) parser.add_argument( '--image-dir', dest='image_dir', help='In case of image outputs (COCO, VOC, ...), specifies output image directory where downloaded images will ' 'be stored. (If not specified, local image paths left untouched)', ) parser.add_argument( '--project-dir', dest='project_dir', default=None, help='Label Studio project directory path', ) parser.add_argument( '--heartex-format', dest='heartex_format', action='store_true', help='Set this flag if your completions are coming from Heartex platform instead of Label Studio', ) args = parser.parse_args() with io.open(args.config) as f: config_str = f.read() c = Converter(config_str, project_dir=args.project_dir) if args.format == Format.JSON: c.convert_to_json(args.input, args.output) elif args.format == Format.CSV: header = not args.csv_no_header sep = args.csv_separator c.convert_to_csv( args.input, args.output, sep=sep, header=header, is_dir=not args.heartex_format, ) elif args.format == Format.CONLL2003: c.convert_to_conll2003(args.input, args.output, is_dir=not args.heartex_format) elif args.format == Format.COCO: c.convert_to_coco( args.input, args.output, output_image_dir=args.image_dir, is_dir=not args.heartex_format, ) elif args.format == Format.VOC: c.convert_to_voc( args.input, args.output, output_image_dir=args.image_dir, is_dir=not args.heartex_format, ) elif args.format == Format.YOLO: c.convert_to_yolo(args.input, args.output, is_dir=not args.heartex_format) print('Congratulations! Now check:\n' + args.output) if __name__ == "__main__": main() <file_sep>import io import os import requests import hashlib import logging import urllib import numpy as np import wave import shutil import argparse import re import datetime from copy import deepcopy from operator import itemgetter from PIL import Image from urllib.parse import urlparse from nltk.tokenize.treebank import TreebankWordTokenizer from lxml import etree from collections import defaultdict from label_studio_tools.core.utils.params import get_env logger = logging.getLogger(__name__) _LABEL_TAGS = {'Label', 'Choice'} _NOT_CONTROL_TAGS = { 'Filter', } LOCAL_FILES_DOCUMENT_ROOT = get_env( 'LOCAL_FILES_DOCUMENT_ROOT', default=os.path.abspath(os.sep) ) TreebankWordTokenizer.PUNCTUATION = [ (re.compile(r"([:,])([^\d])"), r" \1 \2"), (re.compile(r"([:,])$"), r" \1 "), (re.compile(r"\.\.\."), r" ... "), (re.compile(r"[;@#$/%&]"), r" \g<0> "), ( re.compile(r'([^\.])(\.)([\]\)}>"\']*)\s*$'), r"\1 \2\3 ", ), # Handles the final period. (re.compile(r"[?!]"), r" \g<0> "), (re.compile(r"([^'])' "), r"\1 ' "), ] class ExpandFullPath(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values))) def tokenize(text): tok_start = 0 out = [] for tok in text.split(): if len(tok): out.append((tok, tok_start)) tok_start += len(tok) + 1 else: tok_start += 1 return out def create_tokens_and_tags(text, spans): # tokens_and_idx = tokenize(text) # This function doesn't work properly if text contains multiple whitespaces... token_index_tuples = [ token for token in TreebankWordTokenizer().span_tokenize(text) ] tokens_and_idx = [(text[start:end], start) for start, end in token_index_tuples] if spans and all( [ span.get('start') is not None and span.get('end') is not None for span in spans ] ): spans = list(sorted(spans, key=itemgetter('start'))) span = spans.pop(0) span_start = span['start'] span_end = span['end'] - 1 prefix = 'B-' tokens, tags = [], [] for token, token_start in tokens_and_idx: tokens.append(token) token_end = ( token_start + len(token) - 1 ) # "- 1" - This substraction is wrong. token already uses the index E.g. "Hello" is 0-4 token_start_ind = token_start # It seems like the token start is too early.. for whichever reason # if for some reason end of span is missed.. pop the new span (Which is quite probable due to this method) # Attention it seems like span['end'] is the index of first char afterwards. In case the whitespace is part of the # labell we need to subtract one. Otherwise next token won't trigger the span update.. only the token after next.. if token_start_ind > span_end: while spans: span = spans.pop(0) span_start = span['start'] span_end = span['end'] - 1 prefix = 'B-' if token_start <= span_end: break # Add tag "O" for spans that: # - are empty # - span start has passed over token_end # - do not have any label (None or empty list) if not span or token_end < span_start or not span.get('labels'): tags.append('O') elif span_start <= token_end and span_end >= token_start_ind: tags.append(prefix + span['labels'][0]) prefix = 'I-' else: tags.append('O') else: tokens = [token for token, _ in tokens_and_idx] tags = ['O'] * len(tokens) return tokens, tags def _get_upload_dir(project_dir=None, upload_dir=None): """Return either upload_dir, or path by LS_UPLOAD_DIR, or project_dir/upload""" if upload_dir: return upload_dir upload_dir = os.environ.get('LS_UPLOAD_DIR') if not upload_dir and project_dir: upload_dir = os.path.join(project_dir, 'upload') if not os.path.exists(upload_dir): upload_dir = None if not upload_dir: raise FileNotFoundError( "Can't find upload dir: either LS_UPLOAD_DIR or project should be passed to converter" ) return upload_dir def download( url, output_dir, filename=None, project_dir=None, return_relative_path=False, upload_dir=None, download_resources=True, ): is_local_file = url.startswith('/data/') and '?d=' in url is_uploaded_file = url.startswith('/data/upload') if is_uploaded_file: upload_dir = _get_upload_dir(project_dir, upload_dir) filename = urllib.parse.unquote(url.replace('/data/upload/', '')) filepath = os.path.join(upload_dir, filename) logger.debug( f'Copy {filepath} to {output_dir}'.format( filepath=filepath, output_dir=output_dir ) ) if download_resources: shutil.copy(filepath, output_dir) if return_relative_path: return os.path.join( os.path.basename(output_dir), os.path.basename(filename) ) return filepath if is_local_file: filename, dir_path = url.split('/data/', 1)[-1].split('?d=') dir_path = str(urllib.parse.unquote(dir_path)) filepath = os.path.join(LOCAL_FILES_DOCUMENT_ROOT, dir_path) if not os.path.exists(filepath): raise FileNotFoundError(filepath) if download_resources: shutil.copy(filepath, output_dir) return filepath if filename is None: basename, ext = os.path.splitext(os.path.basename(urlparse(url).path)) filename = f'{basename}{ext}' filepath = os.path.join(output_dir, filename) if os.path.exists(filepath): filename = ( basename + '_' + hashlib.md5( url.encode() + str(datetime.datetime.now().timestamp()).encode() ).hexdigest()[:4] + ext ) filepath = os.path.join(output_dir, filename) if not os.path.exists(filepath): logger.info('Download {url} to {filepath}'.format(url=url, filepath=filepath)) if download_resources: r = requests.get(url) r.raise_for_status() with io.open(filepath, mode='wb') as fout: fout.write(r.content) if return_relative_path: return os.path.join(os.path.basename(output_dir), os.path.basename(filename)) return filepath def get_image_size(image_path): return Image.open(image_path).size def get_image_size_and_channels(image_path): i = Image.open(image_path) w, h = i.size c = len(i.getbands()) return w, h, c def get_audio_duration(audio_path): with wave.open(audio_path, mode='r') as f: return f.getnframes() / float(f.getframerate()) def ensure_dir(dir_path): if not os.path.exists(dir_path): os.makedirs(dir_path) def parse_config(config_string): """ :param config_string: Label config string :return: structured config of the form: { "<ControlTag>.name": { "type": "ControlTag", "to_name": ["<ObjectTag1>.name", "<ObjectTag2>.name"], "inputs: [ {"type": "ObjectTag1", "value": "<ObjectTag1>.value"}, {"type": "ObjectTag2", "value": "<ObjectTag2>.value"} ], "labels": ["Label1", "Label2", "Label3"] // taken from "alias" if exists or "value" } """ if not config_string: return {} def _is_input_tag(tag): return tag.attrib.get('name') and tag.attrib.get('value') def _is_output_tag(tag): return ( tag.attrib.get('name') and tag.attrib.get('toName') and tag.tag not in _NOT_CONTROL_TAGS ) def _get_parent_output_tag_name(tag, outputs): # Find parental <Choices> tag for nested tags like <Choices><View><View><Choice>... parent = tag while True: parent = parent.getparent() if parent is None: return name = parent.attrib.get('name') if name in outputs: return name try: xml_tree = etree.fromstring(config_string) except etree.XMLSyntaxError as e: raise ValueError(str(e)) inputs, outputs, labels = {}, {}, defaultdict(dict) for tag in xml_tree.iter(): if _is_output_tag(tag): tag_info = {'type': tag.tag, 'to_name': tag.attrib['toName'].split(',')} # Grab conditionals if any conditionals = {} if tag.attrib.get('perRegion') == 'true': if tag.attrib.get('whenTagName'): conditionals = {'type': 'tag', 'name': tag.attrib['whenTagName']} elif tag.attrib.get('whenLabelValue'): conditionals = { 'type': 'label', 'name': tag.attrib['whenLabelValue'], } elif tag.attrib.get('whenChoiceValue'): conditionals = { 'type': 'choice', 'name': tag.attrib['whenChoiceValue'], } if conditionals: tag_info['conditionals'] = conditionals outputs[tag.attrib['name']] = tag_info elif _is_input_tag(tag): inputs[tag.attrib['name']] = { 'type': tag.tag, 'value': tag.attrib['value'].lstrip('$'), } if tag.tag not in _LABEL_TAGS: continue parent_name = _get_parent_output_tag_name(tag, outputs) if parent_name is not None: actual_value = tag.attrib.get('alias') or tag.attrib.get('value') if not actual_value: logger.debug( 'Inspecting tag {tag_name}... found no "value" or "alias" attributes.'.format( tag_name=etree.tostring(tag, encoding='unicode').strip()[:50] ) ) else: labels[parent_name][actual_value] = dict(tag.attrib) for output_tag, tag_info in outputs.items(): tag_info['inputs'] = [] for input_tag_name in tag_info['to_name']: if input_tag_name not in inputs: logger.debug( f'to_name={input_tag_name} is specified for output tag name={output_tag}, ' 'but we can\'t find it among input tags' ) continue tag_info['inputs'].append(inputs[input_tag_name]) tag_info['labels'] = list(labels[output_tag]) tag_info['labels_attrs'] = labels[output_tag] return outputs def get_polygon_area(x, y): """https://en.wikipedia.org/wiki/Shoelace_formula""" assert len(x) == len(y) return float(0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))) def get_polygon_bounding_box(x, y): assert len(x) == len(y) x1, y1, x2, y2 = min(x), min(y), max(x), max(y) return [x1, y1, x2 - x1, y2 - y1] def get_annotator(item, default=None, int_id=False): """Get annotator id or email from annotation""" annotator = item['completed_by'] if isinstance(annotator, dict): annotator = annotator.get('email', default) return annotator if isinstance(annotator, int) and int_id: return annotator return str(annotator) def get_json_root_type(filename): char = 'x' with open(filename, "r", encoding='utf-8') as f: # Read the file character by character while char != '': char = f.read(1) # Skip any whitespace if char.isspace(): continue # If the first non-whitespace character is '{', it's a dict if char == '{': return "dict" # If the first non-whitespace character is '[', it's an array if char == '[': return "list" # If neither, the JSON file is invalid return "invalid" # If the file is empty, return "empty" return "empty" def prettify_result(v): """ :param v: list of regions or results :return: label name as is if there is only 1 item in result `v`, else list of label names """ out = [] tag_type = None for i in v: j = deepcopy(i) tag_type = j.pop('type') if tag_type == 'Choices' and len(j['choices']) == 1: out.append(j['choices'][0]) elif tag_type == 'TextArea' and len(j['text']) == 1: out.append(j['text'][0]) else: out.append(j) return out[0] if tag_type in ('Choices', 'TextArea') and len(out) == 1 else out <file_sep># this csv converter is not used in GUI export, see convert_to_csv function import pandas as pd import os import json from copy import deepcopy class ExportToCSV(object): def __init__(self, tasks): if isinstance(tasks, str) and tasks.endswith('.json'): if not os.path.exists(tasks): raise Exception(f'Task file not found {tasks}') # input is a file with open(tasks) as f: self.tasks = json.load(f) else: # input is a JSON object self.tasks = tasks def _get_result_name(self, result): return result.get('from_name') def _minify_result(self, result): value = result['value'] name = self._get_result_name(result) if len(value) == 1: item = next(iter(value.values())) if len(item) == 0: return {name: None} if len(item) == 1: return {name: item[0]} else: return {name: item} else: return value def _get_annotation_results(self, annotation, minify, flat_regions): results = annotation['result'] if not flat_regions: yield {'result': results} for result in annotation['result']: if minify: yield self._minify_result(result) else: yield {self._get_result_name(result): result} def _get_annotator_id(self, annotation): annotator = annotation.get('completed_by', {}) if isinstance(annotator, int): return annotator elif isinstance(annotator, dict): return annotator.get('email') or annotator.get('id') def to_records(self, minify=True, flat_regions=True): records = [] for task in self.tasks: annotations = task.get('annotations') if annotations is None: # Temp legacy fix annotations = task['completions'] for annotation in annotations: record = { 'id': task['id'], 'annotation_id': annotation.get('id'), 'annotator': self._get_annotator_id(annotation), } record.update(task['data']) for result in self._get_annotation_results( annotation, minify, flat_regions ): rec = deepcopy(record) rec.update(result) records.append(rec) return records def to_dataframe(self, minify=True, flat_regions=True): return pd.DataFrame.from_records(self.to_records(minify, flat_regions)) def to_file(self, file, minify=True, flat_regions=True, **kwargs): return self.to_dataframe(minify, flat_regions).to_csv(file, **kwargs) <file_sep>""" Test for the brush.py module """ import unittest import urllib3 import json from label_studio_converter.brush import encode_rle, image2annotation def test_image2annotation(): """ Import from png to LS annotation with RLE values """ annotation = image2annotation( 'tests/test.png', label_name='Airplane', from_name='tag', to_name='image', model_version='v1', score=0.5, ) # prepare Label Studio Task task = { 'data': {'image': 'https://labelstud.io/images/test.jpg'}, 'predictions': [annotation], } """ You can import this `task.json` to the Label Studio project with this labeling config: <View> <Image name="image" value="$image" zoom="true"/> <BrushLabels name="tag" toName="image"> <Label value="Airplane" background="rgba(255, 0, 0, 0.7)"/> <Label value="Car" background="rgba(0, 0, 255, 0.7)"/> </BrushLabels> </View> """ json.dump(task, open('task.json', 'w')) assert True def test_rle_encoding(): """ Encode from color values of pixels to RLE, simple example """ test_arr = [1, 1, 1, 1, 2, 3, 5, 6, 7, 8, 4, 4, 4, 4, 4, 4, 4, 4] # color pixels in rgb format rle_test = encode_rle(test_arr) # rle encoded output that will be stored in LS annotations assert rle_test == [ 0, 0, 0, 18, 57, 27, 252, 96, 32, 1, 0, 6, 0, 40, 0, 192, 3, 128, 17, 56, 32, ] <file_sep>""" PathTrack BBoxes to Label Studio convert https://www.trace.ethz.ch/publications/2017/pathtrack/index.html """ import os import sys import json import uuid import logging from types import SimpleNamespace logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) try: import bs4 except ImportError: logger.info('To use PathTrack convert do "pip install bs4"') def get_labels(): return {i: 'Other' for i in range(0, 1000)} def get_info(path): with open(path) as f: b = bs4.BeautifulSoup(f.read()) return SimpleNamespace( fps=float(b.root.doc.fps.get_text()), original_width=int(b.root.doc.imw.get_text()), original_height=int(b.root.doc.imh.get_text()), frame_count=int(b.root.doc.num_frames.get_text()), ) def new_task(data, result, ground_truth=False, model_version=None, score=None): """ :param data: dict :param result: annotation results with regions :param ground_truth: only for annotations :param model_version: if not None, there will be prediction :param score: prediction score, used only if model_version is not None """ task = {"data": data} # add predictions or annotations if model_version: task["predictions"] = [ {"result": result, "model_version": model_version, "score": score} ] else: task["annotations"] = [{"result": result, "ground_truth": ground_truth}] return task def new_region(labels, info, from_name, to_name): region = { "id": uuid.uuid4().hex[0:10], "type": "videorectangle", "value": {"sequence": [], "framesCount": info.frame_count}, "origin": "manual", "to_name": to_name, "from_name": from_name, } if labels is not None: region['value']['labels'] = labels return region def new_keyframe(region, bbox, info): region['value']['sequence'].append( { "x": bbox.x / info.original_width * 100, "y": bbox.y / info.original_height * 100, "width": bbox.width / info.original_width * 100, "height": bbox.height / info.original_height * 100, "time": bbox.frame / info.fps, "frame": bbox.frame, "enabled": False, "rotation": 0, } ) return region def generator(path): with open(path) as f: lines = f.readlines() for line in lines: v = line.split() yield SimpleNamespace( frame=int(v[0]), bbox_id=int(v[1]), label_id=int(v[1]), x=int(v[2]), y=int(v[3]), width=int(v[4]), height=int(v[5]), ) def create_config( from_name='box', to_name='video', source_value='video', target_fps=None ): return f"""<View> <Header>Label the video:</Header> <Video name="{to_name}" value="${source_value}" framerate="{target_fps}"/> <VideoRectangle name="{from_name}" toName="{to_name}" /> <Labels name="videoLabels" toName="{to_name}" allowEmpty="true"> <Label value="Man" background="blue"/> <Label value="Woman" background="red"/> <Label value="Other" background="green"/> </Labels> </View> """ def convert_shot( input_url, label_file, info_file, from_name='box', to_name='video', source_value='video', target_fps=None, hop_keyframes=0, ): """Convert bounding boxes from PathTrack to Label Studio video format :param input_url: video file :param label_file: text file with annotations line by line :param info_file: info.xml with frame rate and other useful info :param from_name: control tag name from Label Studio labeling config :param to_name: object name from Label Studio labeling config :param source_value: source name for Video tag, e.g. $video :param target_fps: keep video with this fps only :param hop_keyframes: how many keyframes to skip """ logger.info('Converting of the shot is starting: %s', input_url) if not os.path.exists(label_file): return None info = get_info(info_file) if target_fps is not None and info.fps != target_fps: return None label_map = get_labels() regions = {} keyframe_count = 0 # convert all bounding boxes to Label Studio Results for v in generator(label_file): idx = v.label_id if idx in regions: region = regions[idx] else: labels = [label_map[idx]] if idx in label_map else None region = regions[idx] = new_region(labels, info, from_name, to_name) # enable previous lifespan if len(regions[idx]['value']['sequence']) > 0: regions[idx]['value']['sequence'][-1]['enabled'] = True regions[idx] = new_keyframe(region, bbox=v, info=info) keyframe_count += 1 # keep only each <hop> keyframe if hop_keyframes > 1: for r in regions: last = regions[r]['value']['sequence'][-1] regions[r]['value']['sequence'] = regions[r]['value']['sequence'][ 0:-1:hop_keyframes ] if regions[r]['value']['sequence'][-1] != last: regions[r]['value']['sequence'].append(last) logger.info( 'Shot with %i regions and %i keyframes created', len(regions), keyframe_count ) data = {source_value: input_url} return new_task(data, result=list(regions.values())) def convert_dataset( root_dir, root_url, from_name='box', to_name='video', source_value='video', target_fps=None, hop_keyframes=0, ): """Convert PathTrack dataset to Label Studio video labeling format :param root_dir: root dir with video folders, e.g.: 'pathtrack/train' or 'pathtrack/test' :param root_url: where the dataset is served by http/https :param to_name: object name from Label Studio labeling config :param from_name: control tag name from Label Studio labeling config :param source_value: source name for Video tag, e.g. $video :param target_fps: keep video with this fps only :param hop_keyframes: how many keyframes to skip """ logger.info('Convert dataset start: %s', root_dir) tasks = [] if not root_url.endswith('/'): root_url += '/' for d in os.listdir(root_dir): shot_dir = os.path.join(root_dir, d) if not os.path.isdir(shot_dir): continue input_url = root_url + d + '/video.mp4' label_file = os.path.join(shot_dir, 'gt/gt.txt') info_file = os.path.join(shot_dir, 'info.xml') task = convert_shot( input_url, label_file, info_file, from_name, to_name, source_value, target_fps, hop_keyframes, ) if task is None: continue tasks.append(task) fps_name = int(target_fps) path = os.path.join(root_dir, f'import-{fps_name}.json') logger.info('Saving Label Studio JSON: %s', path) with open(path, 'w') as f: json.dump(tasks, f) path = os.path.join(root_dir, f'config-{fps_name}.xml') logger.info('Saving Labeling Config: %s', path) config = create_config(from_name, to_name, source_value, target_fps) with open(path, 'w') as f: f.write(config) if __name__ == '__main__': # convert_dataset('../../tests', 'https://data.heartex.net/pathtrack/train/') # exit() print(f'Usage: {sys.argv[0]} root_url target_fps\n') url = ( sys.argv[1] if len(sys.argv) > 1 else 'https://data.heartex.net/pathtrack/train/' ) fps = float(sys.argv[2]) if len(sys.argv) > 2 else None hop = int(sys.argv[3]) if len(sys.argv) > 3 else 0 convert_dataset('./', url, target_fps=fps, hop_keyframes=hop) <file_sep>import os import csv import time import logging import ujson as json from copy import deepcopy, copy from label_studio_converter.utils import ensure_dir, get_annotator, prettify_result logger = logging.getLogger(__name__) logger.setLevel('DEBUG') def convert(item_iterator, input_data, output_dir, **kwargs): start_time = time.time() logger.debug('Convert CSV started') if str(output_dir).endswith('.csv'): output_file = output_dir else: ensure_dir(output_dir) output_file = os.path.join(output_dir, 'result.csv') # these keys are always presented keys = {'annotator', 'annotation_id', 'created_at', 'updated_at', 'lead_time'} # make 2 passes: the first pass is to get keys, otherwise we can't write csv without headers logger.debug('Prepare column names for CSV ...') for item in item_iterator(input_data): record = prepare_annotation_keys(item) keys.update(record) # the second pass is to write records to csv logger.debug( f'Prepare done in {time.time()-start_time:0.2f} sec. Write CSV rows now ...' ) with open(output_file, 'w', encoding='utf8') as outfile: writer = csv.DictWriter( outfile, fieldnames=sorted(list(keys)), quoting=csv.QUOTE_NONNUMERIC, delimiter=kwargs['sep'], ) writer.writeheader() for item in item_iterator(input_data): record = prepare_annotation(item) writer.writerow(record) logger.debug(f'CSV conversion finished in {time.time()-start_time:0.2f} sec') def prepare_annotation(item): record = {} if item.get('id') is not None: record['id'] = item['id'] for name, value in item['output'].items(): pretty_value = prettify_result(value) record[name] = ( pretty_value if isinstance(pretty_value, str) else json.dumps(pretty_value, ensure_ascii=False) ) for name, value in item['input'].items(): if isinstance(value, dict) or isinstance(value, list): # flat dicts and arrays from task.data to json strings record[name] = json.dumps(value, ensure_ascii=False) else: record[name] = value record['annotator'] = get_annotator(item) record['annotation_id'] = item['annotation_id'] record['created_at'] = item['created_at'] record['updated_at'] = item['updated_at'] record['lead_time'] = item['lead_time'] if 'agreement' in item: record['agreement'] = item['agreement'] return record def prepare_annotation_keys(item): record = set(item['input'].keys()) # we don't need deepcopy for keys if item.get('id') is not None: record.add('id') for name, value in item['output'].items(): record.add(name) if 'agreement' in item: record.add('agreement') return record <file_sep>pytest==6.2.2 pytest-cov==2.9.0 lxml>=4.8.0<file_sep>import os import io import math import logging import ujson as json import ijson import xml.dom import xml.dom.minidom from shutil import copy2 from enum import Enum from datetime import datetime from glob import glob from collections import defaultdict from operator import itemgetter from copy import deepcopy from PIL import Image from label_studio_converter.exports import csv2 from label_studio_converter.utils import ( parse_config, create_tokens_and_tags, download, get_image_size, get_image_size_and_channels, ensure_dir, get_polygon_area, get_polygon_bounding_box, get_annotator, get_json_root_type, prettify_result, ) from label_studio_converter import brush from label_studio_converter.audio import convert_to_asr_json_manifest logger = logging.getLogger(__name__) class FormatNotSupportedError(NotImplementedError): pass class Format(Enum): JSON = 1 JSON_MIN = 2 CSV = 3 TSV = 4 CONLL2003 = 5 COCO = 6 VOC = 7 BRUSH_TO_NUMPY = 8 BRUSH_TO_PNG = 9 ASR_MANIFEST = 10 YOLO = 11 CSV_OLD = 12 def __str__(self): return self.name @classmethod def from_string(cls, s): try: return Format[s] except KeyError: raise ValueError() class Converter(object): _FORMAT_INFO = { Format.JSON: { 'title': 'JSON', 'description': "List of items in raw JSON format stored in one JSON file. Use to export both the data " "and the annotations for a dataset. It's Label Studio Common Format", 'link': 'https://labelstud.io/guide/export.html#JSON', }, Format.JSON_MIN: { 'title': 'JSON-MIN', 'description': 'List of items where only "from_name", "to_name" values from the raw JSON format are ' 'exported. Use to export only the annotations for a dataset.', 'link': 'https://labelstud.io/guide/export.html#JSON-MIN', }, Format.CSV: { 'title': 'CSV', 'description': 'Results are stored as comma-separated values with the column names specified by the ' 'values of the "from_name" and "to_name" fields.', 'link': 'https://labelstud.io/guide/export.html#CSV', }, Format.TSV: { 'title': 'TSV', 'description': 'Results are stored in tab-separated tabular file with column names specified by ' '"from_name" "to_name" values', 'link': 'https://labelstud.io/guide/export.html#TSV', }, Format.CONLL2003: { 'title': 'CONLL2003', 'description': 'Popular format used for the CoNLL-2003 named entity recognition challenge.', 'link': 'https://labelstud.io/guide/export.html#CONLL2003', 'tags': ['sequence labeling', 'text tagging', 'named entity recognition'], }, Format.COCO: { 'title': 'COCO', 'description': 'Popular machine learning format used by the COCO dataset for object detection and image ' 'segmentation tasks with polygons and rectangles.', 'link': 'https://labelstud.io/guide/export.html#COCO', 'tags': ['image segmentation', 'object detection'], }, Format.VOC: { 'title': 'Pascal VOC XML', 'description': 'Popular XML format used for object detection and polygon image segmentation tasks.', 'link': 'https://labelstud.io/guide/export.html#Pascal-VOC-XML', 'tags': ['image segmentation', 'object detection'], }, Format.YOLO: { 'title': 'YOLO', 'description': 'Popular TXT format is created for each image file. Each txt file contains annotations for ' 'the corresponding image file, that is object class, object coordinates, height & width.', 'link': 'https://labelstud.io/guide/export.html#YOLO', 'tags': ['image segmentation', 'object detection'], }, Format.BRUSH_TO_NUMPY: { 'title': 'Brush labels to NumPy', 'description': 'Export your brush labels as NumPy 2d arrays. Each label outputs as one image.', 'link': 'https://labelstud.io/guide/export.html#Brush-labels-to-NumPy-amp-PNG', 'tags': ['image segmentation'], }, Format.BRUSH_TO_PNG: { 'title': 'Brush labels to PNG', 'description': 'Export your brush labels as PNG images. Each label outputs as one image.', 'link': 'https://labelstud.io/guide/export.html#Brush-labels-to-NumPy-amp-PNG', 'tags': ['image segmentation'], }, Format.ASR_MANIFEST: { 'title': 'ASR Manifest', 'description': 'Export audio transcription labels for automatic speech recognition as the JSON manifest ' 'format expected by NVIDIA NeMo models.', 'link': 'https://labelstud.io/guide/export.html#ASR-MANIFEST', 'tags': ['speech recognition'], }, } def all_formats(self): return self._FORMAT_INFO def __init__( self, config, project_dir, output_tags=None, upload_dir=None, download_resources=True, ): """Initialize Label Studio Converter for Exports :param config: string or dict: XML string with Label studio labeling config or path to this file or parsed_config :param project_dir: upload root directory for images, audio and other labeling files :param output_tags: it will be calculated automatically, contains label names :param upload_dir: upload root directory with files that were imported using LS GUI :param download_resources: if True, LS will try to download images, audio, etc and include them to export """ self.project_dir = project_dir self.upload_dir = upload_dir self.download_resources = download_resources self._schema = None if isinstance(config, dict): self._schema = config elif isinstance(config, str): if os.path.isfile(config): with io.open(config) as f: config_string = f.read() else: config_string = config self._schema = parse_config(config_string) if self._schema is None: logger.warning( 'Label config or schema for Converter is not provided, ' 'it might be critical for some export formats, now set schema to empty dict' ) self._schema = {} self._data_keys, self._output_tags = self._get_data_keys_and_output_tags( output_tags ) self._supported_formats = self._get_supported_formats() def convert(self, input_data, output_data, format, is_dir=True, **kwargs): if isinstance(format, str): format = Format.from_string(format) if format == Format.JSON: self.convert_to_json(input_data, output_data, is_dir=is_dir) elif format == Format.JSON_MIN: self.convert_to_json_min(input_data, output_data, is_dir=is_dir) elif format == Format.CSV: header = kwargs.get('csv_header', True) sep = kwargs.get('csv_separator', ',') self.convert_to_csv( input_data, output_data, sep=sep, header=header, is_dir=is_dir ) elif format == Format.TSV: header = kwargs.get('csv_header', True) sep = kwargs.get('csv_separator', '\t') self.convert_to_csv( input_data, output_data, sep=sep, header=header, is_dir=is_dir ) elif format == Format.CONLL2003: self.convert_to_conll2003(input_data, output_data, is_dir=is_dir) elif format == Format.COCO: image_dir = kwargs.get('image_dir') self.convert_to_coco( input_data, output_data, output_image_dir=image_dir, is_dir=is_dir ) elif format == Format.YOLO: image_dir = kwargs.get('image_dir') label_dir = kwargs.get('label_dir') self.convert_to_yolo( input_data, output_data, output_image_dir=image_dir, output_label_dir=label_dir, is_dir=is_dir, ) elif format == Format.VOC: image_dir = kwargs.get('image_dir') self.convert_to_voc( input_data, output_data, output_image_dir=image_dir, is_dir=is_dir ) elif format == Format.BRUSH_TO_NUMPY: items = ( self.iter_from_dir(input_data) if is_dir else self.iter_from_json_file(input_data) ) brush.convert_task_dir(items, output_data, out_format='numpy') elif format == Format.BRUSH_TO_PNG: items = ( self.iter_from_dir(input_data) if is_dir else self.iter_from_json_file(input_data) ) brush.convert_task_dir(items, output_data, out_format='png') elif format == Format.ASR_MANIFEST: items = ( self.iter_from_dir(input_data) if is_dir else self.iter_from_json_file(input_data) ) convert_to_asr_json_manifest( items, output_data, data_key=self._data_keys[0], project_dir=self.project_dir, upload_dir=self.upload_dir, download_resources=self.download_resources, ) def _get_data_keys_and_output_tags(self, output_tags=None): data_keys = set() output_tag_names = [] if output_tags is not None: for tag in output_tags: if tag not in self._schema: logger.debug( 'Specified tag "{tag}" not found in config schema: ' 'available options are {schema_keys}'.format( tag=tag, schema_keys=str(list(self._schema.keys())) ) ) for name, info in self._schema.items(): if output_tags is not None and name not in output_tags: continue data_keys |= set(map(itemgetter('value'), info['inputs'])) output_tag_names.append(name) return list(data_keys), output_tag_names def _get_supported_formats(self): if len(self._data_keys) > 1: return [ Format.JSON.name, Format.JSON_MIN.name, Format.CSV.name, Format.TSV.name, ] output_tag_types = set() input_tag_types = set() for info in self._schema.values(): output_tag_types.add(info['type']) for input_tag in info['inputs']: input_tag_types.add(input_tag['type']) all_formats = [f.name for f in Format] if not ('Text' in input_tag_types and 'Labels' in output_tag_types): all_formats.remove(Format.CONLL2003.name) if not ( 'Image' in input_tag_types and ( 'RectangleLabels' in output_tag_types or 'Rectangle' in output_tag_types and 'Labels' in output_tag_types ) ): all_formats.remove(Format.VOC.name) if not ( 'Image' in input_tag_types and ( 'RectangleLabels' in output_tag_types or 'PolygonLabels' in output_tag_types ) or 'Rectangle' in output_tag_types and 'Labels' in output_tag_types or 'PolygonLabels' in output_tag_types and 'Labels' in output_tag_types ): all_formats.remove(Format.COCO.name) all_formats.remove(Format.YOLO.name) if not ( 'Image' in input_tag_types and ( 'BrushLabels' in output_tag_types or 'brushlabels' in output_tag_types or 'Brush' in output_tag_types and 'Labels' in output_tag_types ) ): all_formats.remove(Format.BRUSH_TO_NUMPY.name) all_formats.remove(Format.BRUSH_TO_PNG.name) if not ( ('Audio' in input_tag_types or 'AudioPlus' in input_tag_types) and 'TextArea' in output_tag_types ): all_formats.remove(Format.ASR_MANIFEST.name) return all_formats @property def supported_formats(self): return self._supported_formats def iter_from_dir(self, input_dir): if not os.path.exists(input_dir): raise FileNotFoundError( '{input_dir} doesn\'t exist'.format(input_dir=input_dir) ) for json_file in glob(os.path.join(input_dir, '*.json')): for item in self.iter_from_json_file(json_file): if item: yield item def iter_from_json_file(self, json_file): """Extract annotation results from json file param json_file: path to task list or dict with annotations """ data_type = get_json_root_type(json_file) # one task if data_type == 'dict': data = json.load(json_file) for item in self.annotation_result_from_task(data): yield item # many tasks elif data_type == 'list': with io.open(json_file, 'rb') as f: logger.debug(f'ijson backend in use: {ijson.backend}') data = ijson.items( f, 'item', use_float=True ) # 'item' means to read array of dicts for task in data: for item in self.annotation_result_from_task(task): if item is not None: yield item def annotation_result_from_task(self, task): has_annotations = 'completions' in task or 'annotations' in task if not has_annotations: logger.warning( 'Each task dict item should contain "annotations" or "completions" [deprecated], ' 'where value is list of dicts' ) return None # get last not skipped completion and make result from it annotations = ( task['annotations'] if 'annotations' in task else task['completions'] ) # return task with empty annotations if not annotations: data = Converter.get_data(task, {}, {}) yield data # skip cancelled annotations cancelled = lambda x: not ( x.get('skipped', False) or x.get('was_cancelled', False) ) annotations = list(filter(cancelled, annotations)) if not annotations: return None # sort by creation time annotations = sorted( annotations, key=lambda x: x.get('created_at', 0), reverse=True ) for annotation in annotations: result = annotation['result'] outputs = defaultdict(list) # get results only as output for r in result: if 'from_name' in r and r['from_name'] in self._output_tags: v = deepcopy(r['value']) v['type'] = self._schema[r['from_name']]['type'] if 'original_width' in r: v['original_width'] = r['original_width'] if 'original_height' in r: v['original_height'] = r['original_height'] outputs[r['from_name']].append(v) data = Converter.get_data(task, outputs, annotation) if 'agreement' in task: data['agreement'] = task['agreement'] yield data @staticmethod def get_data(task, outputs, annotation): return { 'id': task['id'], 'input': task['data'], 'output': outputs or {}, 'completed_by': annotation.get('completed_by', {}), 'annotation_id': annotation.get('id'), 'created_at': annotation.get('created_at'), 'updated_at': annotation.get('updated_at'), 'lead_time': annotation.get('lead_time'), } def _check_format(self, fmt): pass def convert_to_json(self, input_data, output_dir, is_dir=True): self._check_format(Format.JSON) ensure_dir(output_dir) output_file = os.path.join(output_dir, 'result.json') records = [] if is_dir: for json_file in glob(os.path.join(input_data, '*.json')): with io.open(json_file, encoding='utf8') as f: records.append(json.load(f)) with io.open(output_file, mode='w', encoding='utf8') as fout: json.dump(records, fout, indent=2, ensure_ascii=False) else: copy2(input_data, output_file) def convert_to_json_min(self, input_data, output_dir, is_dir=True): self._check_format(Format.JSON_MIN) ensure_dir(output_dir) output_file = os.path.join(output_dir, 'result.json') records = [] item_iterator = self.iter_from_dir if is_dir else self.iter_from_json_file for item in item_iterator(input_data): record = deepcopy(item['input']) if item.get('id') is not None: record['id'] = item['id'] for name, value in item['output'].items(): record[name] = prettify_result(value) record['annotator'] = get_annotator(item, int_id=True) record['annotation_id'] = item['annotation_id'] record['created_at'] = item['created_at'] record['updated_at'] = item['updated_at'] record['lead_time'] = item['lead_time'] if 'agreement' in item: record['agreement'] = item['agreement'] records.append(record) with io.open(output_file, mode='w', encoding='utf8') as fout: json.dump(records, fout, indent=2, ensure_ascii=False) def convert_to_csv(self, input_data, output_dir, is_dir=True, **kwargs): self._check_format(Format.CSV) item_iterator = self.iter_from_dir if is_dir else self.iter_from_json_file return csv2.convert(item_iterator, input_data, output_dir, **kwargs) def convert_to_conll2003(self, input_data, output_dir, is_dir=True): self._check_format(Format.CONLL2003) ensure_dir(output_dir) output_file = os.path.join(output_dir, 'result.conll') data_key = self._data_keys[0] with io.open(output_file, 'w', encoding='utf8') as fout: fout.write('-DOCSTART- -X- O\n') item_iterator = self.iter_from_dir if is_dir else self.iter_from_json_file for item in item_iterator(input_data): filtered_output = list( filter( lambda x: x[0]['type'].lower() == 'labels', item['output'].values(), ) ) tokens, tags = create_tokens_and_tags( text=item['input'][data_key], spans=next(iter(filtered_output), None), ) for token, tag in zip(tokens, tags): fout.write('{token} -X- _ {tag}\n'.format(token=token, tag=tag)) fout.write('\n') def convert_to_coco( self, input_data, output_dir, output_image_dir=None, is_dir=True ): def add_image(images, width, height, image_id, image_path): images.append( { 'width': width, 'height': height, 'id': image_id, 'file_name': image_path, } ) return images self._check_format(Format.COCO) ensure_dir(output_dir) output_file = os.path.join(output_dir, 'result.json') if output_image_dir is not None: ensure_dir(output_image_dir) else: output_image_dir = os.path.join(output_dir, 'images') os.makedirs(output_image_dir, exist_ok=True) images, categories, annotations = [], [], [] categories, category_name_to_id = self._get_labels() data_key = self._data_keys[0] item_iterator = ( self.iter_from_dir(input_data) if is_dir else self.iter_from_json_file(input_data) ) for item_idx, item in enumerate(item_iterator): image_path = item['input'][data_key] image_id = len(images) width = None height = None # download all images of the dataset, including the ones without annotations if not os.path.exists(image_path): try: image_path = download( image_path, output_image_dir, project_dir=self.project_dir, return_relative_path=True, upload_dir=self.upload_dir, download_resources=self.download_resources, ) except: logger.info( 'Unable to download {image_path}. The image of {item} will be skipped'.format( image_path=image_path, item=item ), exc_info=True, ) # add image to final images list try: with Image.open(os.path.join(output_dir, image_path)) as img: width, height = img.size images = add_image(images, width, height, image_id, image_path) except: logger.info( "Unable to open {image_path}, can't extract width and height for COCO export".format( image_path=image_path, item=item ), exc_info=True, ) # skip tasks without annotations if not item['output']: # image wasn't load and there are no labels if not width: images = add_image(images, width, height, image_id, image_path) logger.warning('No annotations found for item #' + str(item_idx)) continue # concatenate results over all tag names labels = [] for key in item['output']: labels += item['output'][key] if len(labels) == 0: logger.debug(f'Empty bboxes for {item["output"]}') continue for label in labels: category_name = None for key in ['rectanglelabels', 'polygonlabels', 'labels']: if key in label and len(label[key]) > 0: category_name = label[key][0] break if category_name is None: logger.warning("Unknown label type or labels are empty") continue if not height or not width: if 'original_width' not in label or 'original_height' not in label: logger.debug( f'original_width or original_height not found in {image_path}' ) continue width, height = label['original_width'], label['original_height'] images = add_image(images, width, height, image_id, image_path) if category_name not in category_name_to_id: category_id = len(categories) category_name_to_id[category_name] = category_id categories.append({'id': category_id, 'name': category_name}) category_id = category_name_to_id[category_name] annotation_id = len(annotations) if 'rectanglelabels' in label or 'labels' in label: xywh = self.rotated_rectangle(label) if xywh is None: continue x, y, w, h = xywh x = x * label["original_width"] / 100 y = y * label["original_height"] / 100 w = w * label["original_width"] / 100 h = h * label["original_height"] / 100 annotations.append( { 'id': annotation_id, 'image_id': image_id, 'category_id': category_id, 'segmentation': [], 'bbox': [x, y, w, h], 'ignore': 0, 'iscrowd': 0, 'area': w * h, } ) elif "polygonlabels" in label: points_abs = [ (x / 100 * width, y / 100 * height) for x, y in label["points"] ] x, y = zip(*points_abs) annotations.append( { 'id': annotation_id, 'image_id': image_id, 'category_id': category_id, 'segmentation': [ [coord for point in points_abs for coord in point] ], 'bbox': get_polygon_bounding_box(x, y), 'ignore': 0, 'iscrowd': 0, 'area': get_polygon_area(x, y), } ) else: raise ValueError("Unknown label type") if os.getenv('LABEL_STUDIO_FORCE_ANNOTATOR_EXPORT'): annotations[-1].update({'annotator': get_annotator(item)}) with io.open(output_file, mode='w', encoding='utf8') as fout: json.dump( { 'images': images, 'categories': categories, 'annotations': annotations, 'info': { 'year': datetime.now().year, 'version': '1.0', 'description': '', 'contributor': 'Label Studio', 'url': '', 'date_created': str(datetime.now()), }, }, fout, indent=2, ) def convert_to_yolo( self, input_data, output_dir, output_image_dir=None, output_label_dir=None, is_dir=True, split_labelers=False, ): """Convert data in a specific format to the YOLO format. Parameters ---------- input_data : str The input data, either a directory or a JSON file. output_dir : str The directory to store the output files in. output_image_dir : str, optional The directory to store the image files in. If not provided, it will default to a subdirectory called 'images' in output_dir. output_label_dir : str, optional The directory to store the label files in. If not provided, it will default to a subdirectory called 'labels' in output_dir. is_dir : bool, optional A boolean indicating whether `input_data` is a directory (True) or a JSON file (False). split_labelers : bool, optional A boolean indicating whether to create a dedicated subfolder for each labeler in the output label directory. """ self._check_format(Format.YOLO) ensure_dir(output_dir) notes_file = os.path.join(output_dir, 'notes.json') class_file = os.path.join(output_dir, 'classes.txt') if output_image_dir is not None: ensure_dir(output_image_dir) else: output_image_dir = os.path.join(output_dir, 'images') os.makedirs(output_image_dir, exist_ok=True) if output_label_dir is not None: ensure_dir(output_label_dir) else: output_label_dir = os.path.join(output_dir, 'labels') os.makedirs(output_label_dir, exist_ok=True) categories, category_name_to_id = self._get_labels() data_key = self._data_keys[0] item_iterator = ( self.iter_from_dir(input_data) if is_dir else self.iter_from_json_file(input_data) ) for item_idx, item in enumerate(item_iterator): # get image path and label file path image_path = item['input'][data_key] # download image if not os.path.exists(image_path): try: image_path = download( image_path, output_image_dir, project_dir=self.project_dir, return_relative_path=True, upload_dir=self.upload_dir, download_resources=self.download_resources, ) except: logger.info( 'Unable to download {image_path}. The item {item} will be skipped'.format( image_path=image_path, item=item ), exc_info=True, ) # create dedicated subfolder for each labeler if split_labelers=True labeler_subfolder = str(item['completed_by']) if split_labelers else '' os.makedirs( os.path.join(output_label_dir, labeler_subfolder), exist_ok=True ) # identify label file path filename = os.path.splitext(os.path.basename(image_path))[0] filename = filename[ 0 : 255 - 4 ] # urls might be too long, use 255 bytes (-4 for .txt) limit for filenames label_path = os.path.join( output_label_dir, labeler_subfolder, filename + '.txt' ) # Skip tasks without annotations if not item['output']: logger.warning('No completions found for item #' + str(item_idx)) if not os.path.exists(label_path): with open(label_path, 'x'): pass continue # concatenate results over all tag names labels = [] for key in item['output']: labels += item['output'][key] if len(labels) == 0: logger.warning(f'Empty bboxes for {item["output"]}') if not os.path.exists(label_path): with open(label_path, 'x'): pass continue annotations = [] for label in labels: category_name = None category_names = [] # considering multi-label for key in ['rectanglelabels', 'polygonlabels', 'labels']: if key in label and len(label[key]) > 0: # change to save multi-label for category_name in label[key]: category_names.append(category_name) if len(category_names) == 0: logger.debug( "Unknown label type or labels are empty: " + str(label) ) continue for category_name in category_names: if category_name not in category_name_to_id: category_id = len(categories) category_name_to_id[category_name] = category_id categories.append({'id': category_id, 'name': category_name}) category_id = category_name_to_id[category_name] if ( "rectanglelabels" in label or 'rectangle' in label or 'labels' in label ): xywh = self.rotated_rectangle(label) if xywh is None: continue x, y, w, h = xywh annotations.append( [ category_id, (x + w / 2) / 100, (y + h / 2) / 100, w / 100, h / 100, ] ) elif "polygonlabels" in label or 'polygon' in label: points_abs = [(x / 100, y / 100) for x, y in label["points"]] annotations.append( [category_id] + [coord for point in points_abs for coord in point] ) else: raise ValueError(f"Unknown label type {label}") with open(label_path, 'w') as f: for annotation in annotations: for idx, l in enumerate(annotation): if idx == len(annotation) - 1: f.write(f"{l}\n") else: f.write(f"{l} ") with open(class_file, 'w', encoding='utf8') as f: for c in categories: f.write(c['name'] + '\n') with io.open(notes_file, mode='w', encoding='utf8') as fout: json.dump( { 'categories': categories, 'info': { 'year': datetime.now().year, 'version': '1.0', 'contributor': 'Label Studio', }, }, fout, indent=2, ) @staticmethod def rotated_rectangle(label): if not ( "x" in label and "y" in label and 'width' in label and 'height' in label ): return None label_x, label_y, label_w, label_h, label_r = ( label["x"], label["y"], label["width"], label["height"], label["rotation"] if "rotation" in label else 0.0, ) if abs(label_r) > 0: alpha = math.atan(label_h / label_w) beta = math.pi * ( label_r / 180 ) # Label studio defines the angle towards the vertical axis radius = math.sqrt((label_w / 2) ** 2 + (label_h / 2) ** 2) # Label studio saves the position of top left corner after rotation x_0 = ( label_x - radius * (math.cos(math.pi - alpha - beta) - math.cos(math.pi - alpha)) + label_w / 2 ) y_0 = ( label_y + radius * (math.sin(math.pi - alpha - beta) - math.sin(math.pi - alpha)) + label_h / 2 ) theta_1 = alpha + beta theta_2 = math.pi - alpha + beta theta_3 = math.pi + alpha + beta theta_4 = 2 * math.pi - alpha + beta x_coord = [ x_0 + radius * math.cos(theta_1), x_0 + radius * math.cos(theta_2), x_0 + radius * math.cos(theta_3), x_0 + radius * math.cos(theta_4), ] y_coord = [ y_0 + radius * math.sin(theta_1), y_0 + radius * math.sin(theta_2), y_0 + radius * math.sin(theta_3), y_0 + radius * math.sin(theta_4), ] label_x = min(x_coord) label_y = min(y_coord) label_w = max(x_coord) - label_x label_h = max(y_coord) - label_y return label_x, label_y, label_w, label_h def convert_to_voc( self, input_data, output_dir, output_image_dir=None, is_dir=True ): ensure_dir(output_dir) if output_image_dir is not None: ensure_dir(output_image_dir) output_image_dir_rel = output_image_dir else: output_image_dir = os.path.join(output_dir, 'images') os.makedirs(output_image_dir, exist_ok=True) output_image_dir_rel = 'images' def create_child_node(doc, tag, attr, parent_node): child_node = doc.createElement(tag) text_node = doc.createTextNode(attr) child_node.appendChild(text_node) parent_node.appendChild(child_node) data_key = self._data_keys[0] item_iterator = ( self.iter_from_dir(input_data) if is_dir else self.iter_from_json_file(input_data) ) for item_idx, item in enumerate(item_iterator): image_path = item['input'][data_key] annotations_dir = os.path.join(output_dir, 'Annotations') if not os.path.exists(annotations_dir): os.makedirs(annotations_dir) # Download image channels = 3 if not os.path.exists(image_path): try: image_path = download( image_path, output_image_dir, project_dir=self.project_dir, upload_dir=self.upload_dir, return_relative_path=True, download_resources=self.download_resources, ) except: logger.info( 'Unable to download {image_path}. The item {item} will be skipped'.format( image_path=image_path, item=item ), exc_info=True, ) else: full_image_path = os.path.join( output_image_dir, os.path.basename(image_path) ) # retrieve number of channels from downloaded image try: _, _, channels = get_image_size_and_channels(full_image_path) except: logger.warning(f"Can't read channels from image") # skip tasks without annotations if not item['output']: logger.warning('No annotations found for item #' + str(item_idx)) continue image_name = os.path.basename(image_path) xml_name = os.path.splitext(image_name)[0] + '.xml' # concatenate results over all tag names bboxes = [] for key in item['output']: bboxes += item['output'][key] if len(bboxes) == 0: logger.debug(f'Empty bboxes for {item["output"]}') continue if 'original_width' not in bboxes[0] or 'original_height' not in bboxes[0]: logger.debug( f'original_width or original_height not found in {image_name}' ) continue width, height = bboxes[0]['original_width'], bboxes[0]['original_height'] xml_filepath = os.path.join(annotations_dir, xml_name) my_dom = xml.dom.getDOMImplementation() doc = my_dom.createDocument(None, 'annotation', None) root_node = doc.documentElement create_child_node(doc, 'folder', output_image_dir_rel, root_node) create_child_node(doc, 'filename', image_name, root_node) source_node = doc.createElement('source') create_child_node(doc, 'database', 'MyDatabase', source_node) create_child_node(doc, 'annotation', 'COCO2017', source_node) create_child_node(doc, 'image', 'flickr', source_node) create_child_node(doc, 'flickrid', 'NULL', source_node) create_child_node(doc, 'annotator', get_annotator(item, ''), source_node) root_node.appendChild(source_node) owner_node = doc.createElement('owner') create_child_node(doc, 'flickrid', 'NULL', owner_node) create_child_node(doc, 'name', 'Label Studio', owner_node) root_node.appendChild(owner_node) size_node = doc.createElement('size') create_child_node(doc, 'width', str(width), size_node) create_child_node(doc, 'height', str(height), size_node) create_child_node(doc, 'depth', str(channels), size_node) root_node.appendChild(size_node) create_child_node(doc, 'segmented', '0', root_node) for bbox in bboxes: key = ( 'rectanglelabels' if 'rectanglelabels' in bbox else ('labels' if 'labels' in bbox else None) ) if key is None or len(bbox[key]) == 0: continue name = bbox[key][0] x = int(bbox['x'] / 100 * width) y = int(bbox['y'] / 100 * height) w = int(bbox['width'] / 100 * width) h = int(bbox['height'] / 100 * height) object_node = doc.createElement('object') create_child_node(doc, 'name', name, object_node) create_child_node(doc, 'pose', 'Unspecified', object_node) create_child_node(doc, 'truncated', '0', object_node) create_child_node(doc, 'difficult', '0', object_node) bndbox_node = doc.createElement('bndbox') create_child_node(doc, 'xmin', str(x), bndbox_node) create_child_node(doc, 'ymin', str(y), bndbox_node) create_child_node(doc, 'xmax', str(x + w), bndbox_node) create_child_node(doc, 'ymax', str(y + h), bndbox_node) object_node.appendChild(bndbox_node) root_node.appendChild(object_node) with io.open(xml_filepath, mode='w', encoding='utf8') as fout: doc.writexml(fout, addindent='' * 4, newl='\n', encoding='utf-8') def _get_labels(self): labels = set() categories = list() category_name_to_id = dict() for name, info in self._schema.items(): labels |= set(info['labels']) attrs = info['labels_attrs'] for label in attrs: if attrs[label].get('category'): categories.append( {'id': attrs[label].get('category'), 'name': label} ) category_name_to_id[label] = attrs[label].get('category') labels_to_add = set(labels) - set(list(category_name_to_id.keys())) labels_to_add = sorted(list(labels_to_add)) idx = 0 while idx in list(category_name_to_id.values()): idx += 1 for label in labels_to_add: categories.append({'id': idx, 'name': label}) category_name_to_id[label] = idx idx += 1 while idx in list(category_name_to_id.values()): idx += 1 return categories, category_name_to_id
4205e4bf4fc79365fec145fe8c3700630bcf4276
[ "Markdown", "Python", "Text" ]
22
Python
heartexlabs/label-studio-converter
e9a98c20d8cbf816d7af31261ed14be75d3cd18a
1ab9646cedf7620c18e9fc4d284733a34eacc85a
refs/heads/master
<file_sep>import javafx.application.Application; import javafx.application.Platform; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import javafx.util.Pair; import javafx.geometry.Insets; import javafx.scene.Node; /**Author: <NAME> * Username and Password Authenticator * */ public class Aute extends Application{ @Override public void start (Stage primaryStage){ //Loop( proram will continue until user name and password are entered correctly.) while(true){ String name = "Mario"; String pass = "<PASSWORD>"; Dialog<Pair<String, String>> dialog = new Dialog<>(); dialog.setTitle("Authenticator"); dialog.setHeaderText("Enter Username and Password"); ButtonType loginButtonType = new ButtonType("Login", ButtonBar.ButtonData.OK_DONE); dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); GridPane grid = new GridPane(); grid.setHgap(20); grid.setVgap(40); grid.setPadding(new Insets(20,150,10,10)); TextField username = new TextField(); username.setPromptText("Username"); PasswordField password = new PasswordField(); password.setPromptText("<PASSWORD>"); grid.add(new Label("Username: "), 0,0); grid.add(username, 1,0); grid.add(new Label("Password: "), 0,1); grid.add(password, 1,1); Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType); loginButton.setDisable(true); username.textProperty().addListener((observable, oldValue, newValue)->{ loginButton.setDisable(newValue.trim().isEmpty()); }); dialog.getDialogPane().setContent(grid); Platform.runLater(()-> username.requestFocus()); dialog.setResultConverter(dialogButton -> { if(dialogButton == loginButtonType){ return new Pair<>(username.getText(), password.getText()); }else{ System.exit(0); return null; } }); dialog.showAndWait(); //welcome message if correct , error message if incorrect. if(username.getText().equals(name)&&password.getText().equals(pass)){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("INFORMATION"); alert.setHeaderText(null); alert.setContentText("Welcome " + username.getText() + "!"); alert.showAndWait(); System.exit(0); }else{ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("INFORMATION"); alert.setHeaderText(null); alert.setContentText("Wrong Username or Password!"); alert.showAndWait(); } } } }
05a4a0db35e294b3c285020437d09cf1cca33bdc
[ "Java" ]
1
Java
MarioR9/Authenticator
bfb8783268f35f4dce3e0baa0a5d04775c350163
4d2cc7d3ff4e42a955e6aa472ce9f63f116cdfa3
refs/heads/master
<file_sep>package com.bobotropolis.lilyshout; import java.io.UnsupportedEncodingException; import lilypad.client.connect.api.Connect; import lilypad.client.connect.api.request.RequestException; import lilypad.client.connect.api.request.impl.MessageRequest; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import com.bobotropolis.lilyshout.cmds.ShoutCommand; import com.bobotropolis.lilyshout.listeners.ShoutListener; public class ShoutMain extends JavaPlugin{ private Connect connect; private ShoutListener listener; public void onEnable(){ this.saveDefaultConfig(); /* Get the connect */ connect = getConnect(); /* Prepare our stuff */ this.getCommand("admin").setExecutor(new ShoutCommand(this)); listener = new ShoutListener(this); } public void shout(String string){ if(string == null) return; /* Do it for our server of course */ this.getServer().broadcastMessage(string); /* Do this for every single server */ for(String serverName : this.getConfig().getStringList("servers")){ MessageRequest request = null; /* Prepare the request! */ try { request = new MessageRequest(serverName, "AdminChat", string); } catch (UnsupportedEncodingException e){ e.printStackTrace(); } /* Send it! */ try { connect.request(request); } catch (RequestException e){ e.printStackTrace(); } } } public Connect getConnect(){ Plugin pconnect = this.getServer().getPluginManager().getPlugin("LilyPad-Connect"); if(pconnect == null){ /* The plugin isn't loaded, shut down this plugin */ this.setEnabled(false); this.getLogger().info("AdminChat shut down, LilyPad-Connect not found."); return null; } return pconnect.getServer().getServicesManager().getRegistration(Connect.class).getProvider(); } }
0cac40dedc1b9482adf5434c055e7cbfd938693c
[ "Java" ]
1
Java
shawshark/AdminChat
d4ac79464281821ef5809d127345da75b13a2a10
cb3376c7b3d50b81778927f633c69aa199db7aa9
refs/heads/main
<file_sep># Libraries used import pandas as pd import matplotlib.pyplot as plt import os import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score os.chdir('M:/project/git-repo/imdb-rating/') df = pd.read_csv('./movies.csv') # ========================================== # EDA # ========================================== print(f"This data has {len(df)} rows, and {len(df.columns)} colums as following:") print(df.columns.values) print(" Data types ".center(30,'='),"\n", df.dtypes) # Explore missing values dfcols = list(df.columns.values) print(" Missing Values ".center(30,'=')) for c in dfcols: print(f"{c.ljust(15)} {df[c].isna().sum()}") # Convert data type from object to category df[df.select_dtypes(['object']).columns] = df.select_dtypes(['object']).apply(lambda x: x.astype('category')) df['year'] = df['year'].astype('category') # Should we impute missing values? sns.set_theme(style="whitegrid") sns.boxplot(x=df['budget']) # sns.displot(df, x="budget", binwidth = 10) # sns.displot(df, x="budget",binwidth=50, hue="company") df['rating'].value_counts() df['company'].value_counts() # 2385 companies df.select_dtypes(['float64']) # select specific types df.select_dtypes(['category']) # To do # drop NA of released, socre, vote, writer, star, country, company, runtime # decide whether shoud we delete budget columns or not # check outlier of numerical values # impute rating colums (maybe based on mode)
54c4d9574a01582d76e364e81d66d0737fcdcbff
[ "Python" ]
1
Python
GenCharisma/imdb-rating
a42b6678bb9adceff0b78832ca71420bcce52bbf
2d6173c1b411e55485db12e10745201a6b988b20
refs/heads/master
<repo_name>michpara/ITI1121-Introduction-to-Computing-II<file_sep>/Labs/Lab5/Geometric.java public class Geometric extends AbstractSeries { //instance variables public int i = 1; public double count = 0; public int count2 =0; //returns the next partial sum where it is the series like 1 + 1/2 + 1/4 + 1/8... public double next() { if(count2==0){ //the first time the method is called count = count/Math.pow(2,i-1) + 1; count2++; i++; return count; } else{ //anytime after the first time the method is called count += count2/Math.pow(2,i-1); i++; } return count; } } <file_sep>/Labs/Lab2/Combination.java public class Combination { //instance variables private int first; //intializes first private int second; //initializes second private int third; //initializes third //constructor public Combination( int first, int second, int third ) { this.first = first; this.second = second; this.third = third; } //checks if this Combination is equal to other public boolean equals( Combination other ) { if(first != other.first || second != other.second || third != other.third || other == null){ return false; } return true; } //returns a string representation of the Combination as first:second:third public String toString() { return first + ":" + second + ":" + third; } }<file_sep>/README.md # Introduction to Computing II <img src="https://media.giphy.com/media/l0HU7JI4zIb34QM5a/giphy.gif" width="100"> Labs for Introduction to Computing II **Course Outline**: Object-oriented programming. Abstraction principles: information hiding and encapsulation. Linked lists, stacks, queues, binary search trees. Iterative and recursive processing of data structures. Virtual machines. <file_sep>/Labs/Lab5/Arithmetic.java public class Arithmetic extends AbstractSeries { //instance variables public int i =1; public double count = 0; //the ith call to the method next returns S(i-1) + i where i is (1,2,3,4...) and S(i-1) is what was returned by the previous call to the method next() public double next() { count = count + i; i++; return count; } } <file_sep>/Labs/Lab3/TestFindAndReplace.java /* ITI 1121. Introduction to Computing II; Laboratory 3 * ITI 1521. Introduction a l'informatique II; Laboratoire 3 */ /** A series of tests for the method findAndReplace. * * @author <NAME> (<EMAIL>) */ //tests the findAndReplace method in Utils.java public class TestFindAndReplace { public static void main(String[] args){ boolean testPassed = (testInIsNull() && testQueryIsNull() && testReplacementIsNull() && testInAndQueryAreNull() && testInAndReplacementreNull() && testQueryAndReplacementreNull() && testAllNull() && testNotSameLength() && testNullInIn() && testNullInQuery() && testNullInReplacement() && testNoChange1() && testNoChange2() && testChangeFirst1() && testChangeFirst2() && testChangeLast() && testChangeLeft() && testMultipleChanges1() && testMultipleChanges2()); if (testPassed){ System.out.println("All Test passed: Success!"); } else{ System.out.println("Failure"); } } public static boolean testInIsNull() { String[] query = { "I" }; String[] replacement = { "You" }; if(Utils.findAndReplace( null, query, replacement ) == null){ return true; } else{ System.out.println("test 'testInIsNull' Failed"); return false; } } public static boolean testQueryIsNull() { String[] text = { "I", "understand" }; String[] replacement = { "You" }; if(Utils.findAndReplace( text, null, replacement ) == null){ return true; } else{ System.out.println("test 'testQueryIsNull' Failed"); return false; } } public static boolean testReplacementIsNull() { String[] text = { "I", "understand" }; String[] query = { "I" }; if(Utils.findAndReplace( text, query, null ) == null){ return true; } else{ System.out.println("test 'testReplacementIsNull' Failed"); return false; } } public static boolean testInAndQueryAreNull() { String[] replacement = { "You" }; if(Utils.findAndReplace( null, null, replacement ) == null){ return true; } else{ System.out.println("test 'testInAndQueryAreNull' Failed"); return false; } } public static boolean testInAndReplacementreNull() { String[] query = { "I" }; if(Utils.findAndReplace( null, query, null ) == null){ return true; } else{ System.out.println("test 'testInAndReplacementreNull' Failed"); return false; } } public static boolean testQueryAndReplacementreNull() { String[] text = { "I", "understand" }; if(Utils.findAndReplace( text, null, null ) == null){ return true; } else{ System.out.println("test 'testQueryAndReplacementreNull' Failed"); return false; } } public static boolean testAllNull() { if(Utils.findAndReplace( null, null, null ) == null){ return true; } else{ System.out.println("test 'testAllNull' Failed"); return false; } } public static boolean testNotSameLength() { String[] text = { "I", "understand" }; String[] query = { "I" }; String[] replacement = { "You", "They" }; if(Utils.findAndReplace( text, query, replacement ) == null){ return true; } else{ System.out.println("test 'testNotSameLength' Failed"); return false; } } public static boolean testNullInIn() { String[] text = { "I", null }; String[] query = { "I" }; String[] replacement = { "You" }; if(Utils.findAndReplace( text, query, replacement ) == null){ return true; } else{ System.out.println("test 'testNullInIn' Failed"); return false; } } public static boolean testNullInQuery() { String[] text = { "I", "understand" }; String[] query = { "I", null }; String[] replacement = { "You", "They" }; if(Utils.findAndReplace( text, query, replacement ) == null){ return true; } else{ System.out.println("test 'testNullInQuery' Failed"); return false; } } public static boolean testNullInReplacement() { String[] text = { "I", "understand" }; String[] query = { "I", "We" }; String[] replacement = { null, "They" }; if(Utils.findAndReplace( text, query, replacement ) == null){ return true; } else{ System.out.println("test 'testNullInReplacement' Failed"); return false; } } public static boolean testNoChange1() { String[] text = { "I", "understand" }; String[] query = { }; String[] replacement = { }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (text[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testNoChange1' Failed"); return false; } } public static boolean testNoChange2() { String[] text = { "I", "understand" }; String[] query = { "You" }; String[] replacement = { "I" }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (text[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testNoChange2' Failed"); return false; } } public static boolean testChangeFirst1() { String[] text = { "I", "understand" }; String[] query = { text[ 0 ] }; String[] replacement = { "You" }; String[] expected = { replacement[ 0 ], text[ 1 ] }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (expected[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testChangeFirst1' Failed"); return false; } } public static boolean testChangeFirst2() { String[] text = { "I", "understand" }; String[] query = { new String( "I" ) }; String[] replacement = { "You" }; String[] expected = { "You", "understand" }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (expected[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testChangeFirst2' Failed"); return false; } } public static boolean testChangeLast() { String[] text = { "I", "understand" }; String[] query = { new String( "understand" ) }; String[] replacement = { "see" }; String[] expected = { "I", "see" }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (expected[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testChangeLast' Failed"); return false; } } public static boolean testChangeLeft() { String[] text = { "I", "understand" }; String[] query = { new String( "understand" ), new String( "understand" ) }; String[] replacement = { "see", "grasp" }; String[] expected = { "I", "see" }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (expected[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testChangeLeft' Failed"); return false; } } public static boolean testMultipleChanges1() { String[] text = { "I", "like", "Java" }; String[] query = { new String( "I" ), new String( "like" ), new String( "Java" ) }; String[] replacement = { "You", "enjoy", "object-oriented programming" }; String[] expected = { "You", "enjoy", "object-oriented programming" }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (expected[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testMultipleChanges1' Failed"); return false; } } public static boolean testMultipleChanges2() { String[] text = { "I", "like", "Java" }; String[] query = { new String( "I" ), new String( "Java" ), new String( "like" ) }; String[] replacement = { "You", "object-oriented programming", "enjoy" }; String[] expected = { "You", "enjoy", "object-oriented programming" }; String[] result = Utils.findAndReplace( text, query, replacement ); boolean flag = true; if (result == null){ flag = false; } if (result == text){ flag = false; } if (text.length != result.length){ flag = false; } for ( int i=0; i<text.length; i++ ) { if (expected[i] != result[i]){ flag=false; } } if(flag){ return true; } else{ System.out.println("test 'testMultipleChanges2' Failed"); return false; } } } <file_sep>/Labs/Lab1/VotingRight.java import java.util.Scanner; public class VotingRight{ public static void main(String[] args){ Scanner myScan = new Scanner(System.in); //initializes myScan System.out.print("How old are you? "); int usersAge = myScan.nextInt(); int yearsLeft = 18-usersAge; String years; if(usersAge < 18){ if(yearsLeft == 1){ years = "year"; } else{ years = "years"; } System.out.println("You will be allowed to in " + yearsLeft + " " + years + "."); } else{ //if the user is older than or is 18 years old System.out.println("You have the right to vote!"); } } } <file_sep>/Labs/Lab5/TestBook.java public class TestBook { //test method public static void main(String[] args){ Book b1 = new Book("<NAME>","TAOCP",1970); Book b2 = new Book("<NAME>","TAOCP",1971); Book b3 = new Book("D. IAmNotKnuth","TAOCP",1970); Book b4 = new Book("<NAME>","TAOCP v2",1970); Book b5 = new Book("<NAME>","TAOCP",1970); System.out.println(b1 + " equals " + b2 + ": " + b1.equals(b2)); System.out.println(b1 + " equals " + b3 + ": " + b1.equals(b3)); System.out.println(b1 + " equals " + b4 + ": " + b1.equals(b4)); System.out.println(b1 + " equals " + b5 + ": " + b1.equals(b5)); Book b6 = new Book(null,"TAOCP",1971); Book b7 = new Book("D. IAmNotKnuth",null,1970); System.out.println(b1 + " equals " + b6 + ": " + b1.equals(b6)); System.out.println(b1 + " equals " + b7 + ": " + b1.equals(b7)); System.out.println(b1 + " equals " + null + ": " + b1.equals(null)); System.out.println(b6 + " equals " + b1 + ": " + b6.equals(b1)); System.out.println(b7 + " equals " + b1 + ": " + b7.equals(b1)); System.out.println(b6 + " equals " + b6 + ": " + b6.equals(b6)); System.out.println(b7 + " equals " + b7 + ": " + b7.equals(b7)); } } <file_sep>/Labs/Lab7/GraphicalView.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GraphicalView extends JFrame implements View { //instance variables private JLabel input; private Timer model; //creates the GUI for the timer public GraphicalView (Timer model, Controller controller) { setLayout (new GridLayout(2, 3)); //creates a 2 by 3 grid this.model = model; //initializes model //creates JButton (buttons) for all increments and decrements JButton incrementHours = new JButton("IncrementHours"); JButton decrementHours = new JButton("DecrementHours"); JButton incrementMinutes = new JButton("IncrementMinutes"); JButton decrementMinutes = new JButton("DecrementMinutes"); JButton incrementSeconds = new JButton("IncrementSeconds"); JButton decrementSeconds = new JButton("DecrementSeconds"); //initializes the input JLabel input = new JLabel(); //calls the button of same ID and invokes the action incrementSeconds.addActionListener(controller); incrementMinutes.addActionListener(controller); incrementHours.addActionListener(controller); decrementSeconds.addActionListener(controller); decrementMinutes.addActionListener(controller); decrementHours.addActionListener(controller); //adds the increments and inputs to the layout add(incrementHours); add(incrementMinutes); add(incrementSeconds); add(input); add(decrementHours); add(decrementMinutes); add(decrementSeconds); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set default close operation as exiting the application setSize(700, 100); //creates the window size setVisible(true); } //sets the text for the input as timer public void update () { input.setText(model.toString()); } } <file_sep>/Labs/Lab7/View.java public interface View { //updates the timer void update () ; }<file_sep>/Labs/Lab11/Iterative.java public class Iterative { public static BitList complement( BitList in ) { BitList result = new BitList(); Iterator i = in.iterator(); Iterator o = result.iterator(); while(i.hasNext()) { int bit = i.next(); if(bit == BitList.ONE) { o.add(BitList.ZERO); } else if(bit == BitList.ZERO) { o.add(BitList.ONE); } } return result; } public static BitList or( BitList a, BitList b ) { BitList result = new BitList(); Iterator first = a.iterator(); Iterator second = b.iterator(); Iterator third = result.iterator(); if(!first.hasNext()) { throw new IllegalArgumentException( "a is empty" ); } if(!second.hasNext()) { throw new IllegalArgumentException( "b is empty" ); } while(first.hasNext()) { if(!second.hasNext()) { throw new IllegalArgumentException( "a and b are not of the same size" ); } int firstBit = first.next(); int secondBit = second.next(); if(firstBit == BitList.ONE || secondBit == BitList.ONE) { third.add(BitList.ONE); } else { third.add(BitList.ZERO); } } if(second.hasNext()) { throw new IllegalArgumentException( "a and b are not of the same size" ); } return result; } public static BitList and( BitList a, BitList b ) { BitList result = new BitList(); Iterator first = a.iterator(); Iterator second = b.iterator(); Iterator third = result.iterator(); while(first.hasNext()) { int firstBit = first.next(); int secondBit = second.next(); if(firstBit == BitList.ZERO || secondBit == BitList.ZERO) { third.add(BitList.ZERO); } else { third.add(BitList.ONE); } } return result; } public static BitList xor( BitList a, BitList b ) { BitList result = new BitList(); Iterator first = a.iterator(); Iterator second = b.iterator(); Iterator third = result.iterator(); while(first.hasNext()) { int firstBit = first.next(); int secondBit = second.next(); if(firstBit == secondBit) { third.add(BitList.ZERO); } else { third.add(BitList.ONE); } } return result; } }<file_sep>/Labs/Lab6/DictionaryTest.java public class DictionaryTest { public static void assertEquals(int i, int j) { if(i!=j) { System.out.println("Failure, expected " + i + " and got " + j); } } public static void assertTrue(boolean b) { if(!b) { System.out.println("Failure, expected true, got false"); } } public static void assertFalse(boolean b) { if(b) { System.out.println("Failure, expected false, got true"); } } public static void testGetX() { System.out.println("test: testGetX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); assertEquals(Integer.valueOf(1), dict.get("X")); } public static void testGetY() { System.out.println("test: testGetY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); assertEquals(Integer.valueOf(2), dict.get("Y")); } public static void testGetZ() { System.out.println("test: testGetZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); assertEquals(Integer.valueOf(3), dict.get("Z")); } public static void testGetXX() { System.out.println("test: testGetXX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("X", Integer.valueOf(4)); assertEquals(Integer.valueOf(4), dict.get("X")); } public static void testGetYY() { System.out.println("test: testGetYY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Y", Integer.valueOf(4)); assertEquals(Integer.valueOf(4), dict.get("Y")); } public static void testGetZZ() { System.out.println("test: testGetZZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Z", Integer.valueOf(4)); assertEquals(Integer.valueOf(4), dict.get("Z")); } public static void testContainsEmpty() { System.out.println("test: testContainsEmpty"); Dictionary dict = new Dictionary(); assertFalse(dict.contains("X")); } public static void testContainsNotFound() { System.out.println("test: testContainsNoFound"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); assertFalse(dict.contains("W")); } public static void testContainsX() { System.out.println("test: testContainsX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); assertTrue(dict.contains("X")); } public static void testContainsY() { System.out.println("test: testContainsY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); assertTrue(dict.contains("Y")); } public static void testContainsZ() { System.out.println("test: testContainsZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); assertTrue(dict.contains("Z")); } public static void testContainsXX() { System.out.println("test: testContainsXX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("X", Integer.valueOf(4)); assertTrue(dict.contains("X")); } public static void testContainsYY() { System.out.println("test: testContainsYY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Y", Integer.valueOf(4)); assertTrue(dict.contains("Y")); } public static void testContainsZZ() { System.out.println("test: testContainsZZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Z", Integer.valueOf(4)); assertTrue(dict.contains("Z")); } public static void testPutDyncamicArray() { System.out.println("test: testPutDyncamicArray"); Dictionary dict = new Dictionary(); for (int i = 0; i < 1000; i++) { dict.put("X" + i, Integer.valueOf(i)); } for (int i = 0; i < 1000; i++) { assertEquals(Integer.valueOf(i), dict.get("X" + i)); } } public static void testReplaceX() { System.out.println("test: testReplaceX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.replace("X", Integer.valueOf(4)); assertEquals(Integer.valueOf(4), dict.get("X")); } public static void testReplaceY() { System.out.println("test: testReplaceY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.replace("Y", Integer.valueOf(4)); assertEquals(Integer.valueOf(4), dict.get("Y")); } public static void testReplaceZ() { System.out.println("test: testReplaceZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.replace("Z", Integer.valueOf(4)); assertEquals(Integer.valueOf(4), dict.get("Z")); } public static void testReplaceXX() { System.out.println("test: testReplaceXX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("X", Integer.valueOf(4)); dict.replace("X", Integer.valueOf(5)); assertEquals(Integer.valueOf(5), dict.get("X")); } public static void testReplaceYY() { System.out.println("test: testReplaceYY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Y", Integer.valueOf(4)); dict.replace("Y", Integer.valueOf(5)); assertEquals(Integer.valueOf(5), dict.get("Y")); } public static void testReplaceZZ() { System.out.println("test: testReplaceZZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Z", Integer.valueOf(4)); dict.replace("Z", Integer.valueOf(5)); assertEquals(Integer.valueOf(5), dict.get("Z")); } public static void testRemoveX() { System.out.println("test: testRemoveX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.remove("X"); assertFalse(dict.contains("X")); assertEquals(Integer.valueOf(2), dict.get("Y")); assertEquals(Integer.valueOf(3), dict.get("Z")); } public static void testRemoveY() { System.out.println("test: testRemoveY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.remove("Y"); assertFalse(dict.contains("Y")); assertEquals(Integer.valueOf(1), dict.get("X")); assertEquals(Integer.valueOf(3), dict.get("Z")); } public static void testRemoveZ() { System.out.println("test: testRemoveZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.remove("Z"); assertFalse(dict.contains("Z")); assertEquals(Integer.valueOf(1), dict.get("X")); assertEquals(Integer.valueOf(2), dict.get("Y")); } public static void testRemoveXX() { System.out.println("test: testRemoveXX"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("X", Integer.valueOf(4)); dict.remove("X"); assertEquals(Integer.valueOf(1), dict.get("X")); assertEquals(Integer.valueOf(2), dict.get("Y")); assertEquals(Integer.valueOf(3), dict.get("Z")); } public static void testRemoveYY() { System.out.println("test: testRemoveYY"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Y", Integer.valueOf(4)); dict.remove("Y"); assertEquals(Integer.valueOf(1), dict.get("X")); assertEquals(Integer.valueOf(2), dict.get("Y")); assertEquals(Integer.valueOf(3), dict.get("Z")); } public static void testRemoveZZ() { System.out.println("test: testRemoveZZ"); Dictionary dict = new Dictionary(); dict.put("X", Integer.valueOf(1)); dict.put("Y", Integer.valueOf(2)); dict.put("Z", Integer.valueOf(3)); dict.put("Z", Integer.valueOf(4)); dict.remove("Z"); assertEquals(Integer.valueOf(1), dict.get("X")); assertEquals(Integer.valueOf(2), dict.get("Y")); assertEquals(Integer.valueOf(3), dict.get("Z")); } public static void testGetStatic() { System.out.println("test: testStatic"); Dictionary d1 = new Dictionary(); Dictionary d2 = new Dictionary(); d1.put("X", Integer.valueOf(1)); assertFalse(d2.contains("X")); } public static void main(String[] args){ testGetX(); testGetY(); testGetZ(); testGetXX(); testGetYY(); testGetZZ(); testContainsEmpty(); testContainsNotFound(); testContainsX(); testContainsY(); testContainsZ(); testContainsXX(); testContainsYY(); testContainsZZ(); testPutDyncamicArray(); testReplaceX(); testReplaceY(); testReplaceZ(); testReplaceXX(); testReplaceYY(); testReplaceZZ(); testRemoveX(); testRemoveY(); testRemoveZ(); testRemoveXX(); testRemoveYY(); testRemoveZZ(); testGetStatic(); } }<file_sep>/Labs/Lab2/Test.java // Test.java --- Tests Combination, DoorLock and SecurityAgent // Author : <NAME> // Created On : Mon Jan 26 14:24:07 2004 // Last Modified By: turcotte // Last Modified On: Wed Feb 4 13:52:39 2015 import java.util.Random; //test method public class Test { public static void main( String[] args ) { Random generator = new Random(); // Creates a new security agent called bob! SecurityAgent bob = new SecurityAgent(); // Ask bob to give us access to the door lock DoorLock aLock = bob.getDoorLock(); // Let's find bob's secret combination Combination c = null; boolean open = false; int iter = 0; while ( ! open ) { // bob knows the combination and will // re-activate the DoorLock if ( ! aLock.isActivated() ) { bob.activateDoorLock(); } // let's create a new random combination int first = generator.nextInt(5) + 1; int second = generator.nextInt(5) + 1; int third = generator.nextInt(5) + 1; c = new Combination( first, second, third ); // if this combination opens the lock // we're done. if ( aLock.open( c ) ) { open = true; } iter++; } System.out.println( "Success!" ); System.out.println( "Number of attemtps: " + iter ); System.out.println( "The combination is: " + c ); } } <file_sep>/Labs/Lab3/Rational.java public class Rational { //instance variables private int numerator; private int denominator; // constructors public Rational(int numerator) { this(numerator, 1); } public Rational(int numerator, int denominator) { if(denominator < 0){ denominator = -1*denominator; numerator = -1*numerator; } this.numerator = numerator; this.denominator = denominator; reduce(); } //returns the numerator public int getNumerator() { return numerator; } //returns the denominator public int getDenominator() { return denominator; } //adds this Rational and other public Rational plus(Rational other) { //returns this Rational plus the other Rational int newDenominator = denominator * other.denominator; int newNumerator = numerator * other.denominator; int newOtherNumerator = other.numerator * denominator; int sum = newNumerator + newOtherNumerator; return new Rational(sum, newDenominator); } //adds Rational a and Rational b public static Rational plus(Rational a, Rational b) { return a.plus(b); //cals the plus method to add Rational a with Rational b } // Transforms this number into its reduced form private void reduce() { if(numerator ==0){ denominator =1; } else{ int reduced = gcd(Math.abs(numerator), denominator); //find the greatest commom divisor of the numerator and denominator numerator = numerator/reduced; //divide the numerator by this gcd denominator = denominator/reduced; //divide the denminator by this gcd } } // Euclid's algorithm for calculating the greatest common divisor private int gcd(int a, int b) { while (a != b) if (a > b) a = a - b; else b = b - a; return a; } //compares other to this Rational public int compareTo(Rational other) { int thisNewNum = other.denominator * numerator; int otherNewNum = other.numerator * denominator; return thisNewNum - otherNewNum; } //checks if this Rational equals other public boolean equals(Rational other) { if(numerator == other.numerator && denominator == other.denominator){ return true; } return false; } //returns a string representation of the fraction (ex. 1/2) public String toString() { return numerator + "/" + denominator; //returns the fraction in string form } } <file_sep>/Labs/Lab1/SquareArray.java public class SquareArray{ //creates an array and squares every element public static int[] createArray(int size){ int[] array = new int[size]; for(int i=0;i<array.length;i++){ array[i] = i*i; } return array; } //test method public static void main(String[] args){ int[] myArray = createArray(13); for(int i=0;i<myArray.length;i++){ System.out.println("The square of " + i +" is: " + myArray[i]); } } } <file_sep>/Labs/Lab5/TestSeries.java public class TestSeries { //test method public static void main(String[] args) { AbstractSeries sn; double[] tuple; sn = new Arithmetic(); System.out.println("The first five terms of the arithmetic series are:"); for (int n=0; n<5; n++) { System.out.println(sn.next()); } sn = new Geometric(); System.out.println(); System.out.println("The first five terms of the geometric series are:"); tuple = sn.take(5); for (int n=0; n<5; n++) { System.out.println(tuple[n]); } } } <file_sep>/Labs/Lab4/PhotoPost.java public class PhotoPost extends Post { //instance variables private String fileName; private String caption; //constructor public PhotoPost(String userName, String fileName, String caption) { super(userName); //overides userName this.fileName = fileName; this.caption = caption; } //gets the caption public String getCaption() { return caption; } //gets the FileName public String getFileName() { return fileName; } //returns a string representation of the photopost public String toString() { String str = new String(); str = super.toString() + ", " + fileName + ", " + caption; return str; } } <file_sep>/Labs/Lab5/Library.java import java.util.ArrayList; public class Library { //instance variables private ArrayList<Book> library = new ArrayList<Book>(); //creates an ArrayList of type Book //returns the book at index i public Book getBook(int i) { return library.get(i); } //returns the size of the library public int getSize() { return library.size(); } //adds Book b to the library public void addBook (Book b) { if(b == null){ return; } library.add(b); } //sorts the books using the BookComparator public void sort() { library.sort(new BookComparator()); } //prints the Library of books public void printLibrary() { for(int i = 0; i<library.size();i++){ System.out.println(library.get(i)); //prints each book individually } } } <file_sep>/Labs/Lab8/AccountTest.java public class AccountTest { public static void main(String args[]) { try { Account myAccount=new Account(); myAccount.deposit(600); myAccount.withdraw(300); myAccount.withdraw(400); } catch(NotEnoughMoneyException e){ System.out.println(e.getMessage()); System.out.println("You are missing " + e.getMissingAmount() + "$"); } } }<file_sep>/Labs/Lab5/Book.java public class Book { //instance variable private String author; private String title; private int year; //constructor public Book (String author, String title, int year) { this.author = author; this.title = title; this.year = year; } //returns the author public String getAuthor() { return author; } //returns the title public String getTitle() { return title; } //returns the year of publication public int getYear(){ return year; } //returns if other is equal to this Book public boolean equals(Object other) { if( other == null || getClass() != other.getClass()){ return false; //if other is null or if other is not the same class } Book o = (Book) other; //turn other in Book and assign it to o if(year != o.year) { return false; } if(title == null) { if(o.title != null) { return false; } }else if(!title.equals(o.title)) { return false; } if(author == null) { if(o.author != null) { return false; } } else if(!author.equals(o.author)) { return false; } return true; //if none of the previous if statements are true, return true } //returns a string representation of the Book as author: title (year) public String toString() { return(author+ ": " + title + " (" + year + ")"); //print as author: title (year) } } <file_sep>/Labs/Lab8/NotEnoughMoneyException.java public class NotEnoughMoneyException extends IllegalStateException{ private double amount; private double balance; public NotEnoughMoneyException(double amount, double balance){ super("You do not have enough money to withdraw " + amount); this.amount = amount; this.balance = balance; } public double getAmount(){ return amount; } public double getBalance(){ return balance; } public double getMissingAmount(){ return amount - balance; } }<file_sep>/Labs/Lab6/Dictionary.java public class Dictionary implements Map<String, Integer> { private final static int INITIAL_CAPACITY = 10; private final static int INCREMENT = 5; private int count; private Pair[] elems; public int getCount() { return count; } public int getCapacity() { return elems.length; } public Dictionary() { elems = new Pair[INITIAL_CAPACITY]; count = 0; } @Override public void put(String key, Integer value) { if(count == elems.length) { increaseCapacity(); } Pair pair = new Pair(key, value); elems[count++] = pair; } private void increaseCapacity() { Pair[] newElems = new Pair[count + INCREMENT]; for(int i = 0; i<elems.length; i++) { newElems[i] = elems[i]; } elems = newElems; } @Override public boolean contains(String key) { if(count == 0) { return false; } for(int i = 0; i< count; i++) { if(elems[i].getKey() == key) { return true; } } return false; } @Override public Integer get(String key) { int value = 0; for(int i = 0; i<count; i++) { if(elems[i].getKey().equals(key)) { value = elems[i].getValue(); } } return Integer.valueOf(value); } @Override public void replace(String key, Integer value) { for(int i = 0; i<count; i++) { if(elems[i].getKey() == key) { elems[i].setValue(value); } } } @Override public Integer remove(String key) { int temp = 0; int startIndex = 0; if(contains(key)) { temp = get(key); for(int i = 0; i<count; i++) { if(elems[i].getKey() == key) { startIndex = i; } } for(int j = startIndex; j<count-1; j++) { elems[j] = elems[j+1]; } elems[elems.length-1] = null; count--; } return Integer.valueOf(temp); } @Override public String toString() { String res; res = "Dictionary: {elems = ["; for (int i = count-1; i >= 0 ; i--) { res += elems[i]; if(i > 0) { res += ", "; } } return res +"]}"; } }<file_sep>/Labs/Lab1/FizzBuzz.java public class FizzBuzz{ public static void main(String[] args){ for(int i=1;i<31;i++){ //for i in range 1 to 30 if(i%15==0){ //if i is divisible by 15 System.out.println("FizzBuzz"); } else if(i%3==0){ //if i is divisible by 3 System.out.println("Fizz"); } else if(i%5==0){ //if i is divisible by 5 System.out.println("Buzz"); } } } } <file_sep>/Labs/Lab2/README.md # Lab 2 <file_sep>/Labs/Lab5/Series.java public interface Series{ //returns the next partial sum public double next(); } <file_sep>/Labs/Lab4/Likeable.java public interface Likeable{ //adds a like public void like(); //gets the number of likes public int getLikes(); } <file_sep>/Labs/Lab7/TextView.java public class TextView implements View { //instance variables private Timer model ; //constructor public TextView (Timer model) { this.model = model ; } //prints the string representation of the timer public void update() { System.out.println(model.toString()) ; } } <file_sep>/Labs/Lab9/Customer.java public class Customer{ private static final int MAX_NUM_ITEMS = 25; private int arrivalTime; private int numberOfItems; private int initialNumberOfItems; public Customer(int arrivalTime) { this.arrivalTime = arrivalTime; this.initialNumberOfItems = (int) ( ( MAX_NUM_ITEMS - 1 ) * Math.random() ) + 1; this.numberOfItems = initialNumberOfItems; } public int getArrivalTime() { return arrivalTime; } public int getNumberOfItems() { return numberOfItems; } public int getNumberOfServedItems() { return initialNumberOfItems - numberOfItems; } public void serve() { numberOfItems--; } }<file_sep>/Labs/Lab6/L6Q1.java /** * ITI 1521. Introduction à l'informatique II (Hiver 2008). * ITI 1121. Introduction to Computer Science II (Winter 2008). * * @author <NAME>, Université d'Ottawa/University of Ottawa */ public class L6Q1 { public static void main( String[] args ) { Stack<String> s; s = new ArrayStack<String>( 10 ); for ( int i=0; i<10; i++ ) { s.push( "Elem-" + i ); } s.clear(); while ( ! s.isEmpty() ) { System.out.println( s.pop() ); } for ( int i=0; i<10; i++ ) { s.push( "** Elem-" + i ); } while ( ! s.isEmpty() ) { System.out.println( s.pop() ); } } } // > java L6Q1 // ** Elem-9 // ** Elem-8 // ** Elem-7 // ** Elem-6 // ** Elem-5 // ** Elem-4 // ** Elem-3 // ** Elem-2 // ** Elem-1 // ** Elem-0<file_sep>/Labs/Lab8/Dictionary.java import java.util.Arrays; import java.util.NoSuchElementException; public class Dictionary implements Map<String, Integer> { private static class Pair { private final String key; private Integer value; private Pair(String key, Integer value) { this.key = key; this.value = value; } @Override public String toString() { return "{key=" + key + ",value=" + value + "}"; } } private final static int INITIAL_CAPACITY = 10; private final static int INCREMENT = 5; private int count; private Pair[] elems; public Dictionary() { elems = new Pair[INITIAL_CAPACITY]; count = 0; } @Override public void put(String key, Integer value) { if(key == null || value == null) { throw new NullPointerException(); } if (count == elems.length) { increaseCapacity(); } elems[count] = new Pair(key, value); count++; } private void increaseCapacity() { Pair[] copy; copy = new Pair[elems.length + INCREMENT]; System.arraycopy(elems, 0, copy, 0, count); elems = copy; } @Override public boolean contains(String key) { if(key == null) { throw new NullPointerException(); } boolean found = false; int pos = count - 1; while (pos >= 0 && !found) { if (elems[pos].key.equals(key)) { found = true; } else { pos--; } } return found; } @Override public Integer get(String key) throws NoSuchElementException { if(key == null) { throw new NullPointerException(); } boolean found = false; int pos = count - 1; while (pos >= 0 && !found) { if (elems[pos].key.equals(key)) { found = true; } else { pos--; } } if(!found || pos < 0) { throw new NoSuchElementException(); } return elems[pos].value; } @Override public void replace(String key, Integer value) throws NoSuchElementException { if(key == null || value == null) { throw new NullPointerException(); } boolean found = false; int pos = count - 1; while (pos >= 0 && !found) { if (elems[pos].key.equals(key)) { found = true; } else { pos--; } } if(!found || pos < 0) { throw new NoSuchElementException(); } elems[pos].value = value; } @Override public Integer remove(String key) throws NoSuchElementException { if(key == null) { throw new NullPointerException(); } boolean found = false; int pos = count - 1; while (pos >= 0 && !found) { if (elems[pos].key.equals(key)) { found = true; } else { pos--; } } if(!found || pos < 0) { throw new NoSuchElementException(); } Integer saved = elems[pos].value; while (pos < count - 1) { elems[pos] = elems[pos + 1]; pos++; } count--; elems[count] = null; // scrubbing return saved; } @Override public String toString() { Pair[] reverse; reverse = new Pair[count]; for (int i = 0; i < count; i++) { reverse[i] = elems[count - i - 1]; } return "Dictionary: {elems = " + Arrays.toString(reverse) + "}"; } }<file_sep>/Labs/Lab5/AbstractSeries.java public abstract class AbstractSeries implements Series{ //returns an array containing the next k partial sums of this series public double[] take(int k){ double[] nextPartialSums = new double[k]; for(int i=0;i<nextPartialSums.length;i++){ nextPartialSums[i] = next(); } return nextPartialSums; } }
5bc6c95513524cd57932207e13457de137d95d26
[ "Markdown", "Java" ]
30
Java
michpara/ITI1121-Introduction-to-Computing-II
8153e72901b9c0fb3beb2a813cc369f28d14542b
92642a7c61419b2804f4fb17c801554863a546fd
refs/heads/master
<repo_name>flitvious/GHReborn<file_sep>/zone.py import libtcodpy as libtcod import logger import entities class Tile: """a tile of the map and its properties""" def __init__(self, blocked, block_sight = None): self.blocked = blocked # all tiles start unexplored self.explored = False #by default, if a tile is blocked, it also blocks sight if block_sight is None: self.block_sight = blocked else: self.block_sight = block_sight class Rect: """A rectangle on the map. Used to characterize a room.""" def __init__(self, x, y, w, h): self.x1 = x self.y1 = y self.x2 = x + w self.y2 = y + h def center(self): """returns center of the rectangle""" center_x = (self.x1 + self.x2) / 2 center_y = (self.y1 + self.y2) / 2 return (center_x, center_y) def intersect(self, other): """returns true if this rectangle intersects with another one""" if (self.x1 <= other.x2 and self.x2 >= other.x1 and self.y1 <= other.y2 and self.y2 >= other.y1): return True else: return False class Zone: """A map, x by y of tiles""" def __init__(self, width=80, height=45): self.width = width self.height = height #map starts with all tiles "blocked" self.cells = [[Tile(blocked=True) for y in range(self.height)] for x in range(self.width)] self.entities = [] def __getitem__(self, index): """ Returns a tile specified by index. Proper way to call this is zone[x][y], with just zone[x] an array of tiles is returned """ # zone[x][y] means zone.__getitem__(x).__getitem__(y) which does the trick return self.cells[index] def add_entity(self, ent, x=None, y=None): """ Add an entity to the zone's list of objects at specified coords. If both coords are not set, random coords are picked""" # if both coords aren't set, use random if x is None or y is None: x, y = self.random_valid_coords() ent.set_zone(self, x, y) self.entities.append(ent) #objects[-1] - last added def random_valid_coords(self, max_tries=50): """Tries to return a random non-blocked tile inside the zone. If it fails, it returns the first non-blocked tile it finds""" for r in range(max_tries): x = libtcod.random_get_int(0, 0, self.width - 1) y = libtcod.random_get_int(0, 0, self.height - 1) if self.cells[x][y].blocked is False: return (x, y) # Okay, nothing reached in max tries. Time to check for valid tiles one by one for y in range(self.height): for x in range(self.width): if self.cells[x][y].blocked is False: logger.error("Could not find random coords, checking for a first valid tile.") return(x, y) # Okay, there are no non-blocked tiles.... put player in the corner logger.error("Hey, the zone has no valid coords! Returning zeroes.") return (0, 0) def is_blocked(self, x, y): """Checks whether a particular tile is blocked or not""" # first test the map tile if self.cells[x][y].blocked is True: logger.log(logger.types.movement, "Tile is blocked (wall)") return True # now check for any blocking objects for ent in self.entities: if ent.blocks and ent.x == x and ent.y == y: logger.log(logger.types.movement, "Tile is blocked (by " + ent.name + ")" ) return True logger.log(logger.types.movement, "Tile is not blocked!") return False def entity_at(self, x, y): """Returns the entity at coords or None""" for ent in self.entities: if ent.x == x and ent.y == y: return ent return None ######## Roomer part, make a different class of it eventually and call from zone class! ########## def roomer(self, room_max_size=10, room_min_size=6, max_rooms=30, max_monsters_per_room=3): """Fills zone with rooms, tunnels and monsters""" rooms = [] prev_num = 0 def populate_room(room): """Adds random objects to the room. Stub without actual monsters.""" for i in range(max_monsters_per_room): # choose random spot for this monster x = libtcod.random_get_int(0, room.x1 + 1, room.x2 - 1) y = libtcod.random_get_int(0, room.y1 + 1, room.y2 - 1) # check if the tile is not blocked by anything first if not self.is_blocked(x, y): #80% chance of getting an orc if libtcod.random_get_int(0, 0, 100) < 80: #create an orc obj = entities.Actor('o', 'orc', libtcod.desaturated_green, blocks=True, design=entities.Actor.designs.orc, ai=entities.AI.ais.basic_monster) self.add_entity(obj, x, y) else: #create a troll obj = entities.Actor('T', 'troll', libtcod.darker_green, blocks=True, design=entities.Actor.designs.troll, ai=entities.AI.ais.basic_monster) self.add_entity(obj, x, y) def has_intersections(candidate): """run through the existing rooms and see if they intersect with the candidate""" for other_room in rooms: if candidate.intersect(other_room) is True: # this room intersects another room return True return False def tunnelize(coords_new, coords_prev): """Draw a pair of tunnels vertically and horizontally between new and prev""" logger.log(logger.types.level_gen, "Tunnelizing between " + str(coords_new) + " and " + str(coords_prev)) new_x, new_y = coords_new prev_x, prev_y = coords_prev #draw a coin (random number that is either 0 or 1) if libtcod.random_get_int(0, 0, 1) == 1: #first move horizontally, then vertically self.carve_h_tunnel(prev_x, new_x, prev_y) # 0 3 3 self.carve_v_tunnel(prev_y, new_y, new_x) # 3 0 3 else: #first move vertically, then horizontally self.carve_v_tunnel(prev_y, new_y, prev_x) # 3 0 0 self.carve_h_tunnel(prev_x, new_x, new_y) # 0 3 0 # create rooms one by one for room_num in range(max_rooms): #random width and height w = libtcod.random_get_int(0, room_min_size, room_max_size) h = libtcod.random_get_int(0, room_min_size, room_max_size) #random position without going out of the boundaries of the map x = libtcod.random_get_int(0, 0, self.width - w - 1) y = libtcod.random_get_int(0, 0, self.height - h - 1) new_room = Rect(x, y, w, h) if has_intersections(new_room) is False: #this means there are no intersections, so this room is valid self.carve_room(new_room) rooms.append(new_room) # tunnelize current_room_idx = len(rooms) - 1 if current_room_idx > 0: logger.log(logger.types.level_gen, "Roomer: trying to tunnel #" + str(current_room_idx)) tunnelize(rooms[current_room_idx].center(), rooms[current_room_idx - 1].center()) #populate with monsters populate_room(new_room) def carve_room(self, rect): """go through the tiles inside the rectangle borders and make them passable""" # range gives one *less* than specified, so outer "walls" will be left in place for x in range(rect.x1, rect.x2): for y in range(rect.y1, rect.y2): self.cells[x][y].blocked = False self.cells[x][y].block_sight = False #logger.log(logger.types.level_gen, "Created a room") def carve_h_tunnel(self, x1, x2, y): """create a horizontal line of passable tiles between x1 and x2 and a specified y""" # minmax is for the thing to work in both directions for x in range(min(x1, x2), max(x1, x2) + 1): self.cells[x][y].blocked = False self.cells[x][y].block_sight = False def carve_v_tunnel(self, y1, y2, x): """create a vertical line of passable tiles between y1 and y2 and a specified x""" for y in range(min(y1, y2), max(y1, y2) + 1): self.cells[x][y].blocked = False self.cells[x][y].block_sight = False<file_sep>/logger.py import enums #Eventually make it into a proper class assigned to app # debug log switch VERBOSITY_DEBUG = True # debug log subtype suppression SHOW_INPUT = False SHOW_CHEATS = True SHOW_MOVEMENT = False SHOW_LEVEL_GEN = False SHOW_RENDERING = False SHOW_COMBAT = True SHOW_AI = False # error log switch VERBOSITY_ERROR = True # game log switch VERBOSITY_GAME = True # suppressor based on message class types = enums.enum('cheats', 'movement', 'level_gen', 'rendering', 'input', 'ai', 'combat') # rendering - rendering-related stuff (consoles, e.t.c.) # input - various keypresses (actions) # cheats - cheat codes # level_gen - level generation # ai - ai related stuff # movement - movement and collisions # combat - getting and receiving damage def log(subtype, message): """Output debug log message of given type""" if VERBOSITY_DEBUG: if subtype == types.cheats and not SHOW_CHEATS: return if subtype == types.movement and not SHOW_MOVEMENT: return if subtype == types.level_gen and not SHOW_LEVEL_GEN: return if subtype == types.input and not SHOW_INPUT: return if subtype == types.combat and not SHOW_COMBAT: return if subtype == types.ai and not SHOW_AI: return str(message) print "DEBUG (" + types.reverse_mapping[subtype] + "): " + message def error(message): """Output error log message of given type""" if VERBOSITY_ERROR: str(message) print "ERROR: " + message def game(message): """Output game information""" if VERBOSITY_GAME: print "GAME: " + message <file_sep>/entities.py import libtcodpy as libtcod import logger import math import enums from keyhandler import KeyHandler as k class Entity: """ This is a generic game entity that can be assigned to map. It can't act on its own. Actors inherit from it (and items, projectiles will) """ types = enums.enum('Entity', 'Actor') def __init__(self, char, name, color, blocks): self.char = char self.color = color self.name = name # map-specific stuff # these are none, added when zone sets them self.x = None self.y = None self.zone = None # whether it blocks passage or not self.blocks = blocks def get_type(self): """ Returns own type of entity in Entity.types.* Each child redefines this. """ #raise NotImplementedError("Subclass must implement abstract method") return Entity.types.Entity def set_zone(self, zone, x, y): """ Sets entity's zone and positions the object at given coords. """ self.zone = zone self.x = x self.y = y class Actor(Entity): """ An entity that can act, take turns and have stats dict. act() is called by engine each turn ai component must be passed as a constant: entities.AI.ais.basic_monster * ai - ai to use * design - design to use (hardcoded for now, later can be loaded) * stats['hp'] - stats are a dict """ designs = enums.enum('orc', 'troll', 'player') def __init__(self, char, name, color, blocks, ai, design): # call Entity's constructor class to setup the child Entity.__init__(self, char, name, color, blocks) # setup ai (it is a component, so will need an owner) if ai == AI.ais.player_control: # this ai just asks player for input self.ai = PlayerControl(owner=self) logger.log(logger.types.ai, "player_control ai assigned to " + self.name) elif ai == AI.ais.basic_monster: self.ai = BasicMonster(owner=self) logger.log(logger.types.ai, "basic_monster ai assigned to " + self.name) else: logger.error("Can't pick an ai for an actor") # setup stats based on design, hardcoded (later take from data files) if design == Actor.designs.player: self.stats = dict(max_hp=30, hp=30, defense=2, power=5) elif design == Actor.designs.orc: self.stats = dict(max_hp=10, hp=10, defense=2, power=5) elif design == Actor.designs.troll: self.stats = dict(max_hp=16, hp=16, defense=1, power=4) else: logger.error("Can't pick design for an actor") def get_type(self): """ Returns own type of entity in Entity.types.*. For now is used by main to call actor's act(). """ return Entity.types.Actor def act(self, act_data): """ This method is called each turn for all actors in the map. For now it only gets ai to work based on its type. act_data - dict containing all the stuff """ # for now we only need to call an ai properly ai_type = self.ai.get_type() if ai_type == AI.ais.player_control: # no inbound params for player result = self.ai.work(player_action=act_data['player_action']) elif ai_type == AI.ais.basic_monster: # we need to feed player and fov_map to it result = self.ai.work(player=act_data['player'], fov_map=act_data['fov_map']) else: logger.error('Unknown ai type') # skip its turn just in case result = True # true if turn was made, false if not return result def move(self, dx, dy): """move by the given amount""" # check if blocked by wall or entity if not self.zone.is_blocked(self.x + dx, self.y + dy): # not blocked, move there self.x += dx self.y += dy logger.log(logger.types.movement, self.name + " moved to " + str((self.x, self.y))) else: # tile is blocked, let's try to bump into object! entity = self.zone.entity_at(self.x + dx, self.y + dy) if not entity is None: #it is an entity self.bump(entity) else: #it is a wall logger.log(logger.types.movement, 'The ' + self.name + ' bumps into a wall. Ugh.') pass def step_towards(self, target_x, target_y): """ Moves one tile towards target coords """ #vector from this object to the target, and distance dx = target_x - self.x dy = target_y - self.y distance = math.sqrt(dx ** 2 + dy ** 2) #normalize it to length 1 (preserving direction), then round it and #convert to integer so the movement is restricted to the map grid dx = int(round(dx / distance)) dy = int(round(dy / distance)) self.move(dx, dy) def distance_to(self, other): """ Returns distance to another object """ dx = other.x - self.x dy = other.y - self.y return math.sqrt(dx ** 2 + dy ** 2) def bump(self, ent): """bumps into an entity (this gets called for entities only, not for walls)""" # this should check for factions ) # FIXME: attacking should be handled inside player! here only spontaneous collisions! # works only for actors. logger.log(logger.types.movement, "Bump called for " + self.name + " and " + ent.name) if (ent.get_type() == Entity.types.Actor): # if player, attack any monster if (self.ai.get_type() == AI.ais.player_control) and (ent.ai.get_type() == AI.ais.basic_monster): self.attack(ent) def take_damage(self, damage): """apply damage if possible""" if damage > 0: self.stats['hp'] -= damage logger.log(logger.types.combat, self.name + ' now has ' + str(self.stats['hp']) + ' hp of ' + str(self.stats['max_hp'])) def attack(self, target): """ attack another actor convert to send_damage eventually """ #a simple formula for attack damage damage = self.stats['power'] - target.stats['defense'] if damage > 0: #make the target take some damage logger.game(self.name.capitalize() + ' attacks ' + target.name + ' for ' + str(damage) + ' hit points.') target.take_damage(damage) else: logger.game(self.name.capitalize() + ' attacks ' + target.name + ' but it has no effect!') #### AIs ##### class AI: """ Base class for all AIs. AI is a component and so must have owner. """ ais = enums.enum('base', 'player_control', 'basic_monster') def __init__(self, owner): self.owner = owner def get_type(self): """ Returns the type of ai Used by Actor's act() to supply proper arguments children should redefine this """ return AI.ais.base def work(self): """ Returns True if this Actor's turn is made. children should redefine this """ raise NotImplementedError("Subclass must implement abstract method") class BasicMonster(AI): """ Component AI for a basic monster """ def get_type(self): """returns type of ai""" return AI.ais.basic_monster def work(self, player, fov_map): """ Chase and try to attack. Needs to know where the player is and if she can see the monster. """ #If you can see it, it can see you monster = self.owner if libtcod.map_is_in_fov(fov_map, monster.x, monster.y): #move towards player if far away if monster.distance_to(player) >= 2: monster.step_towards(player.x, player.y) elif player.stats['hp'] > 0: #close enough, attack! (if the player is still alive.) monster.attack(player) # did make a turn, okay! return True class PlayerControl(AI): """ Controlled by a human player """ def get_type(self): """returns type of ai""" return AI.ais.player_control def work(self, player_action): """ Make a turn based on player's action. Make no turn (return false) if passed action is not a game one. (or cancelled a skill) (or instant skill) """ if player_action == k.controls.none: # this can't happen, because we use wait_key. But just in case! logger.error('Got no action as player!') return True elif player_action == k.controls.other: # just pressed some stupid key return False elif player_action == k.game.move_N: self.owner.move(0, -1) return True elif player_action == k.game.move_NE: self.owner.move(1, -1) return True elif player_action == k.game.move_E: self.owner.move(1, 0) return True elif player_action == k.game.move_SE: self.owner.move(1, 1) return True elif player_action == k.game.move_S: self.owner.move(0, 1) return True elif player_action == k.game.move_SW: self.owner.move(-1, 1) return True elif player_action == k.game.move_W: self.owner.move(-1, 0) return True elif player_action == k.game.move_NW: self.owner.move(-1, -1) return True elif player_action == k.game.move_5: self.owner.move(0, 0) return True else: # this can't happen, but just in case! logger.error('Got no action as player!') return True<file_sep>/main.py ## for now this will be my libtcod tutorial import libtcodpy as libtcod import logger import enums import entities import zone import renderer from keyhandler import KeyHandler as k class Engine: """GHreborn Engine""" def __init__(self): # init the renderer self.renderer = renderer.Renderer(screen_width=80, screen_height=50, fps_limit=20) # init the input self.keyhandler = k() #keyhandler.KeyHandler() # init the map self.zone = zone.Zone() # populate zone with roomer algorithm self.zone.roomer(max_rooms=30) # init fov self.fov = renderer.Fov(algo=0, light_walls=True, light_radius=10) # load zone information to fov self.fov.read_zone(self.zone) # create a player object in the zone and make him a fighter self.player = entities.Actor('@', 'player', libtcod.white, blocks=True, design=entities.Actor.designs.player, ai=entities.AI.ais.player_control) # put player to random coords inside the zone self.zone.add_entity(self.player) def loop(self): """Endless loop""" while not self.renderer.is_closed(): # make renderer redraw the screen self.redraw() #build dict for act() method act_data = dict(player=self.player, fov_map=self.fov.map) # iterate over all entities in the zone for ent in self.zone.entities: if ent is self.player: # player is a special case! # player_made_turn is determined in ai (failed, cancelled skills and free retries, etc) player_made_turn = False while not player_made_turn: # wait for some input key = self.keyhandler.wait_for_key() # process controls # these will overlay any game action bound for the same key self.process_control_actions(action=self.keyhandler.process_control_keys(key)) # process cheats # these will overlay any game action bound for the same key self.process_cheat_actions(action=self.keyhandler.process_cheat_keys(key)) # get player's action act_data['player_action'] = self.keyhandler.process_game_key(key) # feed action to Actor. # if player didn't do any game action, repeat. player_made_turn = ent.act(act_data) else: # not player, regular mook result = ent.act(act_data) if result is False: logger.log(logger.types.ai, 'Actor ' + ent.name + 'could not act') def redraw(self): """Redraw for main loop""" # recompute fov for player position self.fov.recompute(self.player.x, self.player.y) # render and explore the zone self.renderer.explore_and_render_zone(self.zone, self.fov.map) # render all objects in the zone self.renderer.render_entities(self.zone.entities, self.fov.map) # blit out drawing buffer self.renderer.blit_con() # flush the console self.renderer.flush() # clear the objects self.renderer.clear_entities(self.zone.entities) def process_control_actions(self, action): """Run logic for control actions""" if action == k.controls.none or action == k.controls.other: pass elif action == k.controls.exit: quit(0) elif action == k.controls.fullscreen: self.renderer.toggle_fullscreen() def process_cheat_actions(self, action): """Run logic for cheat actions""" if action == k.cheats.teleport: logger.log(logger.types.cheats, "teleporting") self.player.x, self.player.y = self.zone.random_valid_coords() self.redraw() elif action == k.cheats.reveal_map: logger.log(logger.types.cheats, "exploring all the map") self.renderer.show_all(self.zone, self.zone.entities) self.redraw() def main(): """Engine init and main loop""" # init the new app! engine = Engine() # enter endless loop engine.loop() if __name__ == '__main__': main() <file_sep>/notes.md ## Misc stuff / Refactoring * libtcode zip should be integraed properly (subfolders at least), cheap stuff for now * Sort out fov_maps. Ae they per-object or single for player only? * properly implement color constants inside the renderer * todo - incapsulate all the damn properties and access through methods. Even `zone[x][y]` stuff. Incapsulate stats. * fix cheats.. aaaaw, to hell with this :) * step towards energy - per-entity rendering * remove map-related stuff from renderer and create mapper * move player-related bump functionality to player ai * error handling - use raise everywhere * distance calculation is shit, fix it with nice pathfinding algorithms. ## Design ### Extending Extension modules may be passed as **kwargs as many as needed ### Objects Sort out objects, inheritance and components. There clearly should be: * entity – any item, lever or creture in-game. * actor (entity) – entity that can act * can have *stats* dict (hp, defense, etc.) these are loaded from premades, i think * item (entity) – thing that can be *used* and *carried around*, but doesn't act on its own. * this has to wait until inventory system * stacks * item that flies around the level? no such thing. Maybe create a projectile class eventually. * ai component * must be called from actor's act ### Attacking/damage This works like messaging. Works between two actors. `self.emit_damage(damage_type, value, destination)`, e.g. send 3 hp damage to orc. This calls receiving actor's `actor.receieve_damage(Damage)`. Which handles the damage accordingly. Since we are creating mechas, they are living inventories. So `emit_damage` can be targeted or something and `receive_damage` distribute damage to components based on damage types. Damage class: types = enum self.type self.value self.source Emit creates damage entity, receive operates it. This way there can be multiple destinations for damage. Emit to: [orc, troll, everything-in-radius-5-of-tiles-around] ## Some sort of roadmap These are the features I want first: * scale 0 prototype — integral PC, monsters, basic items. Not too advanced. Will be used for city hub action later. * scale 1 prototype — fightable mecha (one simple arena level) * Mecha components, mounts and design * Mecha operation — game mechanics like weight, speed, e.t.c. * Getting and dealing damage (actor-to-actor and mirrored to components) * Repairing, customizing mecha (mounts) * Custom mecha design * Mecha salvage from other mecha (loot) * Mecha design files + constructor app(?) This stuff comes after the combat: * Random Maps * Wilderness * Plots<file_sep>/enums.py def enum(*sequential, **named): """ This simulates the enum functionality source: http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python usage: Numbers = enum('ZERO', 'ONE', 'TWO') >>> Numbers.ZERO 0 >>> Numbers.ONE 1 extra support for reverse mapping (to display in logs) >>> Numbers.reverse_mapping[0] 'ZERO' """ enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums)<file_sep>/keyhandler.py import libtcodpy as libtcod import enums import logger class KeyHandler: """Handles Key through libtcode""" controls = enums.enum('none', 'other', 'exit', 'fullscreen') cheats = enums.enum('none', 'other', 'teleport', 'reveal_map') game = enums.enum('none', 'other', 'move_N', 'move_NE', 'move_E', 'move_SE', 'move_S', 'move_SW', 'move_W', 'move_NW', 'move_5') def __init__(self): pass def process_control_keys(self, key): """ Checks if passed key corresponds to control action. if so, return control action const. """ if key.vk == libtcod.KEY_NONE: logger.log(logger.types.input, "key none") return KeyHandler.controls.none elif key.vk == libtcod.KEY_ESCAPE: logger.log(logger.types.input, "key escape") return KeyHandler.controls.exit elif key.vk == libtcod.KEY_ENTER and key.lalt: logger.log(logger.types.input, "key alt+enter") return KeyHandler.controls.fullscreen else: # some other key return KeyHandler.controls.other def process_cheat_keys(self, key): """ Checks if passed key corresponds to cheat action. if so, returns cheat action const. """ if key.vk == libtcod.KEY_NONE: return KeyHandler.cheats.none elif key.vk == libtcod.KEY_1 and key.lctrl: return KeyHandler.cheats.teleport elif key.vk == libtcod.KEY_2 and key.lctrl: return KeyHandler.cheats.reveal_map else: return KeyHandler.cheats.other def process_game_key(self, key): """ Checks if passed key corresponds to if passed key corresponds to any game action (that takes a turn). If so, returns cheat action const. """ if libtcod.console_is_key_pressed(libtcod.KEY_UP) or libtcod.console_is_key_pressed(libtcod.KEY_KP8): return KeyHandler.game.move_N elif libtcod.console_is_key_pressed(libtcod.KEY_DOWN) or libtcod.console_is_key_pressed(libtcod.KEY_KP2): return KeyHandler.game.move_S elif libtcod.console_is_key_pressed(libtcod.KEY_LEFT) or libtcod.console_is_key_pressed(libtcod.KEY_KP4): return KeyHandler.game.move_W elif libtcod.console_is_key_pressed(libtcod.KEY_RIGHT) or libtcod.console_is_key_pressed(libtcod.KEY_KP6): return KeyHandler.game.move_E elif libtcod.console_is_key_pressed(libtcod.KEY_KP7): return KeyHandler.game.move_NW elif libtcod.console_is_key_pressed(libtcod.KEY_KP9): return KeyHandler.game.move_NE elif libtcod.console_is_key_pressed(libtcod.KEY_KP1): return KeyHandler.game.move_SW elif libtcod.console_is_key_pressed(libtcod.KEY_KP3): return KeyHandler.game.move_SE elif libtcod.console_is_key_pressed(libtcod.KEY_KP5) or libtcod.console_is_key_pressed(libtcod.KEY_5): return KeyHandler.game.move_5 elif key.vk == libtcod.KEY_NONE: return KeyHandler.game.none else: return KeyHandler.game.other def wait_for_key(self): """wait for a key and return it""" return libtcod.console_wait_for_keypress(True) <file_sep>/renderer.py import libtcodpy as libtcod import logger #color constants ### these should be zone-specific! And also inside the class :) COLOR_WALL_DARK = libtcod.Color(0, 0, 100) COLOR_WALL_LIT = libtcod.Color(130, 110, 50) COLOR_GROUND_DARK = libtcod.Color(50, 50, 150) COLOR_GROUND_LIT = libtcod.Color(200, 180, 50) class Renderer: """Renders graphics""" def __init__(self, screen_width, screen_height, fps_limit): # store values self.screen_width = screen_width self.screen_height = screen_height self.fps_limit = fps_limit # turn on fps limit if > 0 if self.fps_limit > 0: logger.log(logger.types.rendering, "FPS limiter set to " + str(self.fps_limit)) libtcod.sys_set_fps(self.fps_limit) # import font libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) # root console / main window / 0 self.rootcon = libtcod.console_init_root(self.screen_width, self.screen_height, 'Ghreborn', False) # init primary console self.con = libtcod.console_new(self.screen_width, self.screen_height) def toggle_fullscreen(self): """Toggle fullscreen mode""" libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen()) def is_closed(self): """Wrapper around libtcod""" return libtcod.console_is_window_closed() def blit_con(self): """blit out the drawing buffer""" libtcod.console_blit(self.con, 0, 0, self.screen_width, self.screen_height, 0, 0, 0) def flush(self): """Flush everything to screen""" libtcod.console_flush() # Below things are strongly map-related. Should be separated into a Mapper class that calls renderer per-tile or something def explore_and_render_zone(self, zone, fov_map): """Renders lit and unlit zone tiles and explores them""" # renderer exploring = bad, fix this for y in range(zone.height): for x in range(zone.width): lit = libtcod.map_is_in_fov(fov_map, x, y) wall = zone[x][y].block_sight if not lit: #it's out of the player's FOV #if it's not visible right now, the player can only see it if it's explored if zone[x][y].explored: if wall: libtcod.console_set_char_background(self.con, x, y, COLOR_WALL_DARK, libtcod.BKGND_SET) else: libtcod.console_set_char_background(self.con, x, y, COLOR_GROUND_DARK, libtcod.BKGND_SET) else: #it is inside the player's fov if wall: libtcod.console_set_char_background(self.con, x, y, COLOR_WALL_LIT, libtcod.BKGND_SET) else: libtcod.console_set_char_background(self.con, x, y, COLOR_GROUND_LIT, libtcod.BKGND_SET) # explore the tile if not zone[x][y].explored: zone[x][y].explored = True def show_all(self, zone, entities): """Cheat function: show all the tiles and entities in a zone.""" # this repeats process_zone and render_objects, fix this somehow for y in range(zone.height): for x in range(zone.width): wall = zone[x][y].block_sight if wall: libtcod.console_set_char_background(self.con, x, y, COLOR_WALL_DARK, libtcod.BKGND_SET) else: libtcod.console_set_char_background(self.con, x, y, COLOR_GROUND_DARK, libtcod.BKGND_SET) for ent in entities: libtcod.console_set_default_foreground(self.con, ent.color) libtcod.console_put_char(self.con, ent.x, ent.y, ent.char, libtcod.BKGND_NONE) def render_entities(self, entities, fov_map): """Renders all passed entities""" for ent in entities: if libtcod.map_is_in_fov(fov_map, ent.x, ent.y): #render only visible objects libtcod.console_set_default_foreground(self.con, ent.color) libtcod.console_put_char(self.con, ent.x, ent.y, ent.char, libtcod.BKGND_NONE) def clear_entities(self, entities): """Clears all entities""" for ent in entities: libtcod.console_put_char(self.con, ent.x, ent.y, ' ', libtcod.BKGND_NONE) class Fov: """Fov map wrapper""" def __init__(self, algo, light_walls, light_radius): self.light_radius = light_radius self.light_walls = light_walls self.algo = algo # make an empty fov map for zone self.map = None def read_zone(self, zone): """Read the zone and adjust map values accordingly""" self.map = libtcod.map_new(zone.width, zone.height) for y in range(zone.height): for x in range(zone.width): #libtcode requires the opposite values, so invert them! libtcod.map_set_properties(self.map, x, y, not zone[x][y].block_sight, not zone[x][y].blocked) def recompute(self, x, y): """Compute fov for position""" libtcod.map_compute_fov(self.map, x, y, self.light_radius, self.light_walls, self.algo)
18179ba1a571f2f50530a9028d461db41cf5bf71
[ "Markdown", "Python" ]
8
Python
flitvious/GHReborn
f6d8f55fe9013fe2257c6827b90b67d2f47f2950
6788319326f4668efea7adb3249f03047e0a3c80
refs/heads/master
<repo_name>cthogg/commander-pages<file_sep>/bin/helpers.js const fs = require('fs'); exports.createFile = (dir, text) => { // eslint-disable-next-line fs.writeFile(dir, text, (err) => { if (err) { return console.log(err); } }); }; // eslint-disable-next-line exports.createDirectory = (dir, err) => { if (!fs.existsSync(dir, { recursive: true })) { fs.mkdirSync(dir, { recursive: true }); if (err) { return console.log(err); } } }; <file_sep>/README.md # Commander Pages - make websites from the command line. ## User Can - create a gatsby page from the command line - edit the gatsby theme `index.md` file from the prompt ## Install with yarn 1. Install the cli along with gatsby and a compatible gatsby theme `yarn add gatsby gatsby-theme-modern-portfolio commander-pages -D` 2. Run commander-pages to create example files for the gatsby theme. `yarn create-commander-page` 3. Set the options which are asked in the terminal 4. add `.cache` and `public` to the repo's `.gitignore` file 5. Check if correctly installed with `yarn gatsby develop` 6. Edit the page by editing `src/pages/markdown/index.md` ## Roadmap - deploy using the `netlify cli` - add more questions to createPagePrompt - add flags using commander-js to create default processes - https://github.com/SBoudrias/Inquirer.js ## Tutorials i used when creating this https://docs.npmjs.com/creating-and-publishing-scoped-public-packages<file_sep>/src/pages/markdown/index.md --- title: "I am <NAME>" subtitle: "I am a web developer" email: "<EMAIL>" linkedin: "https://www.linkedin.com/in/john_doe" textColor: 'black' backgroundColor: '#e5f1f6' fontUrl: '"https://fonts.googleapis.com/css?family=Overlock&display=swap"' fontFamily: 'Overlock, cursive;' --- ## Experience - Building websites <file_sep>/gatsby-config.js module.exports = { __experimentalThemes: [{ resolve: 'gatsby-theme-modern-portfolio', options: { siteTitle: 'Your site title', siteDescription: 'Here is a site title', }, }], }; <file_sep>/bin/createPagePrompt.js #! /usr/bin/env node // eslint-disable-next-line const inquirer = require('inquirer'); const chalk = require('chalk'); const createPage = require('./createPage'); console.log(chalk.bgWhite.black.bold('\nWelcome to Commander Pages\n')); const questions = [ { type: 'input', name: 'title', message: 'What is the title of your website?', default: 'I am <NAME>', }, { type: 'input', name: 'subtitle', message: 'and the subtitle?', default: 'I am a web developer', }, ]; inquirer.prompt(questions).then((answers) => { const { title, subtitle } = answers; const textFromAnswers = `--- title: "${title}" subtitle: "${subtitle}" email: "<EMAIL>" linkedin: "https://www.linkedin.com/in/john_doe" textColor: 'black' backgroundColor: '#e5f1f6' fontUrl: '"https://fonts.googleapis.com/css?family=Overlock&display=swap"' fontFamily: 'Overlock, cursive;' --- ## Experience - Building websites `; createPage.createPage(textFromAnswers); console.log(chalk.yellow.bold('\nPage Created Successfully')); console.log('\nplease run `yarn gatsby develop` to start\n'); }); <file_sep>/bin/createPage.js const fs = require('fs'); const path = require('path'); const helper = require('./helpers'); // const path = require('path'); // FIXME: what to do if in development? const packagePath = path.dirname(require.resolve('commander-pages/package.json')); // const packagePath = './'; // FIXME: should not have paths like this const templateDir = '/templates/'; const defaultIndexText = fs.readFileSync( `${packagePath}${templateDir}index.md`, 'utf8', ); const createPage = (indexText) => { const srcDir = './src/'; const pagesDir = './src/pages/'; const markdownDir = './src/pages/markdown/'; const markdownFileDir = `${markdownDir}index.md`; const text = fs.readFileSync( `${packagePath}${templateDir}gatsby-config.js`, 'utf8', ); helper.createDirectory(srcDir); helper.createDirectory(pagesDir); helper.createDirectory(markdownDir); // TODO: make console logs more developer friendly (possibly using color??) helper.createFile('gatsby-config.js', text); helper.createFile(markdownFileDir, indexText); }; createPage(defaultIndexText); module.exports.createPage = createPage;
4699597ab29b020371564485404ff5e17431469d
[ "JavaScript", "Markdown" ]
6
JavaScript
cthogg/commander-pages
152263d6d1869fd3ce3d501c242b4a26ca2d4f6a
7ddb02c936bdd3c440d85f7c1fcc48b50722bf9d
refs/heads/master
<repo_name>zIconKr/duitang<file_sep>/src/MainProduct.java import java.util.Scanner; public class MainProduct { public static void main(String[] args) { System.out.println("请输入一串数字:"); Scanner i=new Scanner(System.in); int o=i.nextInt(); //输入一串整型数字 String a=String.valueOf(o); //将整型转换成字符串 char[] number=a.toCharArray(); //将字符串转成字符数组 String[] n=new String[number.length]; //创建一个字符串数组,将上述字符数组转为字符串数组 int[] m=new int[number.length]; //创建一个整型数组,将上述字符串数组转为整型数组 for(int k=0;k<number.length;k++){ n[k]=number[k]+""; m[k]=Integer.parseInt(n[k]); } Product myproduct=new Product(); myproduct.z(m); } }<file_sep>/src/Product.java public class Product { void z(int m[]){ for(int l=0;l<m.length;l++){ int product=1; //乘积初始化为1 for(int p=0;p<m.length;p++){ if(l==p){ //当乘数为自己本身时,跳过本次乘积 continue; } product=product*m[p]; } System.out.println("第"+(l+1)+"个数的乘积为"+product); } } }
6207a9c5eec7927bb595d52473e0d8ad03235c92
[ "Java" ]
2
Java
zIconKr/duitang
d8a57ea19bde822b849c7dfe01bf2048c1a6f14d
390804e00bf0692269ce213ba60143a0fc160235
refs/heads/master
<file_sep> [ ![Download](https://api.bintray.com/packages/jfrog/reg2/jfrog%3Aauto-mat/images/download.svg) ](https://bintray.com/jfrog/reg2/jfrog%3Aauto-mat/_latestVersion) # What is auto-mat? Auto-mat is a docker container that allows you to analyse a Java heap dump from the commandline without any GUI involved. You can get html reports directly from the commandline. # How to run? All you need is Docker installed on your machine. cd to the location of your heap dump file, then: ```docker run --mount src=$(pwd),target=/data,type=bind -it docker.bintray.io/jfrog/auto-mat <dump filename> <heap size for mat> <reports>``` dump filename - hprof heap dump file name heap size for mat - how much memory to consume for this process e.g (5g) reports - a comma separated list of the following: suspects, overview, top_components. If empty no reports will be generated. You probably want the suspects. ### Example: ```docker run -it --mount src=$(pwd),target=/data,type=bind docker.bintray.io/jfrog/auto-mat heap1.hprof 11g suspects,overview``` # What problem does it solve? Analyzing large heap dumps is a long process which needs a lot of computing resources. Eclipse Memory Analyzer Tool (http://www.eclipse.org/mat/downloads.php) is GUI based tool to analyze heap dumps. It takes a lot of time to run an analysis for the first time with MAT and it consumes a lot of compute power, however when running for the second time it is fast, thats because MAT keeps indexes locally on the running machine. Auto-mat can help with that because it can let you run the analysis on any remote machine that has docker installed. Then you can copy the output to your local machine, run MAT and open the heap dump. Auto-mat will also generate HTML reports which might save you the effort of running MAT. # How to build: ```docker build . -t auto-mat:<tag name>``` # How it works? This is a simple docker wrapper for tools that came from eclipse MAT. Eclipse MAT exposes command line tool to generate indexes and reports. # Credits This tool uses: ubuntu:18.04 docker image https://hub.docker.com/_/ubuntu eclipse mat project https://www.eclipse.org/mat/ Open jdk https://openjdk.java.net/ <file_sep>FROM ubuntu:18.04 AS builder WORKDIR /opt RUN apt-get update && apt-get install -y wget unzip RUN wget -O mat.zip http://mirrors.uniri.hr/eclipse//mat/1.8/rcp/MemoryAnalyzer-1.8.0.20180604-linux.gtk.x86_64.zip RUN unzip mat.zip FROM ubuntu:18.04 RUN apt-get update && \ apt-get install -y openjdk-8-jdk && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* && \ rm -rf /var/cache/oracle-jdk8-installer; WORKDIR /opt COPY --from=builder /opt/mat /opt/mat COPY run.sh ./mat WORKDIR /data ENTRYPOINT ["/opt/mat/run.sh"] <file_sep>#!/usr/bin/env bash DUMPFILE=$1 MAXHEAP="16g" SUSPECTS="org.eclipse.mat.api:suspects" OVERVIEW="org.eclipse.mat.api:overview" TOP_COMPONENTS="org.eclipse.mat.api:top_components" if [ -z ${2+x} ]; then echo "Max heap not set, using default $MAXHEAP"; else echo "Max heap is set to: $2"; MAXHEAP=$2 fi if [ -z ${3+x} ]; then echo "No reports requested. Skipping generation"; else reports_for_command="" reports=$(echo $3 | tr "," " " | xargs) for report in $reports do if [ $report == 'suspects' ]; then reports_for_command="$reports_for_command $SUSPECTS" fi if [ $report == 'overview' ]; then reports_for_command="$reports_for_command $OVERVIEW" fi if [ $report == 'top_components' ]; then reports_for_command="$reports_for_command $TOP_COMPONENTS" fi done fi echo reports to generate: ${reports_for_command} /opt/mat/ParseHeapDump.sh ${DUMPFILE} $reports_for_command -vmargs -Xmx${MAXHEAP} -XX:-UseGCOverheadLimit
a3bb5d64568778c24cdada0fc0081bce31f4db21
[ "Markdown", "Dockerfile", "Shell" ]
3
Markdown
ric03uec/auto-mat
f10faab5e7532fa6bb80de2de5d095bd9cb5d998
83beff38736f8a3a367ca0baff3ad90eb98827e0
refs/heads/master
<file_sep>#include "BulleSort.h" void BulleSort(Sqlist * L) { for (int i = 0; i < L->length; i++) { for (int j = i+1; j < L->length; j++) { if (L->data[i] > L->data[j]) swap(L, i, j); } } }<file_sep>#include "KMPSubStr.h" void KMP_next(char *str, int length, int *next) { int i = 0, j = 1; next[0] = 0; while(j<length) { if (str[i] == str[j]) { next[j]=i+1; j++; i++; } else { if (i != 0) { i =next[ i - 1]; } else { next[j] = 0; j++; } } } } void KMP_SubStr(char * text, int text_length, char * pattern, int pattern_length,int *local) { int i = 0,j=0,l=0; int * next = (int*)malloc(sizeof(int)*pattern_length); KMP_next(pattern, pattern_length, next); while ((i<text_length)&&(j<pattern_length)) { if (text[i] == pattern[j]) { i++; j++; if (j == pattern_length) { local[l++]=i-pattern_length; j = 0; } } else { if (j == 0) { i++; } else { j = next[j - 1]; } } } } int KMP_SubStr_Num(char * text, int text_length, char * pattern, int pattern_length) { int num = 0; int i = 0; int j = 0; int * next = (int*)malloc(sizeof(int)*pattern_length); KMP_next(pattern, pattern_length, next); while ((i<text_length) && (j<pattern_length)) { if (text[i] == pattern[j]) { i++; j++; if (j == pattern_length) { num++; j = 0; } } else { if (j == 0) { i++; } else { j = next[j - 1]; } } } free(next); next = NULL; return num; } int main(void) { char text[20]; char pattern[10]; int text_len, pattern_len; int subnum=0; scanf("%s", text); scanf("%s", pattern); text_len=strlen(text); pattern_len = strlen(pattern); int* next = (int*)malloc(sizeof(int)*pattern_len); if (next != NULL) { KMP_next(pattern, pattern_len, next); for (int i = 0; i < pattern_len; i++) printf("%d", next[i]); free(next); next = NULL; } printf("\n"); //申请一个内存空间存放子字符串开始位置 int* local = (int*)malloc(sizeof(int)*text_len); if (local != NULL) { //malloc申请的内存默认不初试化 memset(local, 0, sizeof(int)*text_len); //统计子字符串开始的位置 KMP_SubStr(text, text_len, pattern, pattern_len, local); for (int i = 0; i < text_len; i++) printf("%d", local[i]); free(local); local = NULL; } //统计出现了几个子字符串 subnum = KMP_SubStr_Num(text, text_len, pattern, pattern_len); printf("\n%d", subnum); } <file_sep>#include "myheader.h" //交换线性表内的两个元素位置 void swap(Sqlist *L, int i, int j) { elemType temp; temp = L->data[i]; L->data[i] = L->data[j]; L->data[j] = temp; }<file_sep>#include "MaxAbsBetweenLeftAndRight.h" //#include <stdio.h> ArrayElem MaxAbsBetweenLeftAndRight(ArrayElem *array, int length) { ArrayElem max=-1000; for (int i = 0; i < length; i++) max=maxer(max, array[i]); max=maxer(max - array[length - 1], max-array[0]); return max; } /* int main(void) { int a[10] = { 2,7,3,1,1 }; int max; max = MaxAbsBetweenLeftAndRight(a, 5); printf("abs=%d", max); } */<file_sep>#pragma once #include "myheader.h" int Partition(Sqlist *L, int low, int high); void QuickSort(Sqlist *L,int s,int e);<file_sep>#include "MergeSort.h" //合并两个有序数组 void Merge(int * SR, int *TR, int st, int mid, int end) { int i=st, j=mid+1,k; for (k=st; i <= mid && j <=end; k++) { if (SR[i] < SR[j]) TR[k] = SR[i++]; else TR[k] = SR[j++]; } if (i <=st) { int m; for(m=i;m<mid;m++) TR[k++] = SR[i]; } if (j <=end) { int m; for(m=j;m<end;j++) TR[k++] = SR[j]; } } //将SR每两个相邻step长度的子数组归并到TR中,数组总长度为length void MergePass(int * SR, int *TR, int step, int length) { int i = 0; while (i <= length - step * 2) { Merge(SR, TR, i, i + step - 1, i + step * 2 -1); i += 2 * step; } if (i < length - step+1) { Merge(SR, TR, i, i + step - 1, length-1); } else { int j; for (j = i; j < length; j++) TR[j] = SR[j]; } } //非递归方式,空间复杂度降低 void MergeSort(Sqlist *L) { int * TR = (int*)malloc(L->length * sizeof(int)); int i = 1; while (i<L->length) { MergePass(L,TR,i,L->length); i = i * 2; MergePass(TR, L, i, L->length); i = i * 2; } }<file_sep>#include "2SubArraySumMax.h" //#include <stdio.h> ArrayElem TwoSubArraySumMax(ArrayElem *array, int length) { ArrayElem max=-1000; ArrayElem * arr1 = (ArrayElem *)malloc(sizeof(ArrayElem)*length); //ArrayElem * arr2 = (ArrayElem *)malloc(sizeof(ArrayElem)*length); ArrayElem maxL = -1000; ArrayElem cur_maxL = 0; ArrayElem maxR = -1000; ArrayElem cur_maxR = 0; //正序求0-i序列子数组的最大和(包含i) //反序求length-1到0的子数组的最大和 //第二次反序的时候可以省掉一个数组 for (int i = length-1; i >=0; i--) { cur_maxR += array[i]; maxR = maxer(cur_maxR, maxR); *(arr1 + i) = maxR; if (cur_maxR < 0) cur_maxR = 0; } for (int j =0; j < length-1; j++) { cur_maxL += array[j]; maxL = maxer(cur_maxL, maxL); //因为arr1[j]存放的是length-1到j包含i的字数组最大值 //maxL也包含j,所以不是不相交所以是arr1[j+1] max = maxer(max, maxL + arr1[j + 1]); if (cur_maxL < 0) cur_maxL = 0; } free(arr1); return max; } /* int main(void) { int a[10] = { 1,3,4,-9,1,2,2}; int max; max = TwoSubArraySumMax(a,7); printf("sum=%d", max); } */<file_sep>#pragma once #include "myheader.h" void InsertSort(Sqlist *L);<file_sep>#pragma once #include "myheader.h" void BulleSort(Sqlist * L);<file_sep>#pragma once #include <stdlib.h> #include <string.h> #include "SubArraySumMax.h" ArrayElem SubMatrixSumMax(ArrayElem *array, int row_len, int col_len);<file_sep>#pragma once #include "SubArraySumMax.h" int WaterProblem(ArrayElem *array, int length); int WaterProblem2(ArrayElem *array, int length);<file_sep>牛客算法精讲第四节(C语言+VS2017) ======================================= >markdown格式学习——[点击链接](http://guoyunsky.iteye.com/blog/1781885)<br> >[前讲?](#前讲) >[第一题?](#第一题) >[第二题?](#第二题) >[第三题?](#第三题) >[第四题?](#第四题) # 前讲 #### 题目: >找一个数组的连续子数组的最大和。 ``` typedef int ArrayElem; ArrayElem maxer(ArrayElem a, ArrayElem b) { return a > b ? a : b; } ArrayElem SubArraySumMax(ArrayElem *array, int length) { if (array == NULL || length == 0) return 0; //max存放array子数组最大和,初始值为系统最小值 //cur_max存放当前子数组的和 ArrayElem max = -100; ArrayElem cur_max = 0; for (int i = 0; i != length; i++) { cur_max += array[i]; //max保存目前所有子数组和中的最大值 max=maxer(max, cur_max); //如果当前最大值为0那么后续的数组不需要在前半段加一个负数使自己的和变小 //也就是重新寻找后面的子数组最大和 if (cur_max < 0) cur_max = 0; } return max; } ``` # 第一题 > 给定一个矩阵matrix,其中的值有正、有负、有0,返回子矩阵的最大累加和。 例如,矩阵matrix为: ``` -90 48 78 64 -40 64 -81 -7 66 ``` 其中,最大累加和的子矩阵为: ``` 48 78 -40 64 -7 66 ``` 所以返回累加和209。 ### 解题思路: 将4*4的矩阵看作是4行,那么子矩阵就必须是 1、12、123、1234; 2、23、234; 3、34; 4 共(1+4)*4/2种情况,每种情况的列相加得到一个数组(长度为矩阵列数),此时子矩阵和最大问题转换为字数组和最大问题。 ### 时间复杂度 >O(n^2\*m),其中n是行数,m是列数; 如果n>>m,那么以m作为列会大大降低时间复杂度,即O(m^2\*n); ``` ArrayElem SubMatrixSumMax(ArrayElem *array, int row_len, int col_len) { if (array == NULL || row_len == 0 || col_len == 0) return 0; ArrayElem *s = (ArrayElem *)malloc(sizeof(ArrayElem)*col_len); int max=-10000; int cur_lin_max; for (int i = 0; i < row_len; i++) { memset(s, 0, col_len * sizeof(ArrayElem)); for (int j = i; j < row_len; j++) { cur_lin_max = 0; for (int k = 0; k < col_len; k++) { //s里面存放的就是累加和,算出一个元素直接求子数组最大和 *(s + k) += array[j*col_len+k]; cur_lin_max += *(s + k); max=maxer(cur_lin_max, max); if (cur_lin_max < 0) cur_lin_max = 0; } } } free(s); return max; } ``` # 第二题 >给定一个数组,每个位置的值代表一个高度。那么整个数组可以看成是一个直方图。如果把这个直方图当作容器的话,求这个容器能装多少水。 例如: ``` [3,1,2,4] ``` >代表第一个位置高度为3,第二个位置高度为1,第三个位置高度为2,第四个位置高度为4。 >所以[3,1,2,4]这个数组代表的容器可以装3格的水。 #### 解题思路 >思路一: 每个元素能留多少水由它右边最大值maxR和左边最大值maxL中的较小值miner决定,元素i盛水值为miner-array[i]。 实现方法: 正反遍历两次得到两个数组分别记录元素i处左边最大值和右边最大值; 最后遍历遍历一遍得到蓄水量总和。 >思路二: 设数组长度为n,两个指针a,b分别指向元素1和n-1,那么1处的蓄水量由1左边和n-1右边的最大值决定,两者较小值减去array[1]就得到了1处的蓄水量,指针a往右移,那边最大值较小,那边指针往中间移。 ``` int WaterProblem(ArrayElem *array, int length) { if (array == NULL || length <=2) return 0; ArrayElem water = 0; ArrayElem maxL = array[0]; ArrayElem maxR = array[length - 1]; ArrayElem L = 1; ArrayElem R = length-2; while (L <= R) { if (maxL < maxR) { if(array[L]<=maxL) water += maxL - array[L]; else maxL = array[L]; L = L + 1; } else { if (array[R] <= maxR) water += maxR - array[R]; else maxR = array[R]; R = R -1; } } return water; } ``` # 第三题 >给定一个数组,长度大于2。找出不相交的两个数组,情况是很多的。请返回这么多情况中,两个不相交子数组最大的和。 例如: ``` [-1,3,4,-9,1,2] ``` #### 解题思路 >不相交子数组最大和,可以仿照蓄水思路一,设两个数组,正反序分别记录下i位置前后子数组最大和,然后数组对应位置相加。 >特别注意的是不相交,程序中有说明。 ``` max = maxer(max, maxL + arr1[j + 1]); ``` ``` ArrayElem TwoSubArraySumMax(ArrayElem *array, int length) { ArrayElem max=-1000; ArrayElem * arr1 = (ArrayElem *)malloc(sizeof(ArrayElem)*length); //ArrayElem * arr2 = (ArrayElem *)malloc(sizeof(ArrayElem)*length); ArrayElem maxL = -1000; ArrayElem cur_maxL = 0; ArrayElem maxR = -1000; ArrayElem cur_maxR = 0; //正序求0-i序列子数组的最大和(包含i) //反序求length-1到0的子数组的最大和 //第二次反序的时候可以省掉一个数组 for (int i = length-1; i >=0; i--) { cur_maxR += array[i]; maxR = maxer(cur_maxR, maxR); *(arr1 + i) = maxR; if (cur_maxR < 0) cur_maxR = 0; } for (int j =0; j < length-1; j++) { cur_maxL += array[j]; maxL = maxer(cur_maxL, maxL); //因为arr1[j]存放的是length-1到j包含i的字数组最大值 //maxL也包含j,所以不是不相交所以是arr1[j+1] max = maxer(max, maxL + arr1[j + 1]); if (cur_maxL < 0) cur_maxL = 0; } free(arr1); return max; } ``` # 第四题 给定一个长度为N(N>1)的整形数组arr,可以划分成左右两个部分,左部分为arr[0..K],右部分为arr[K+1..N-1],K可以取值的范围是[0,N-2]。求这么多划分方案中,左部分中的最大值减去右部分最大值的绝对值中,最大是多少? 例如: ``` [2,7,3,1,1] ``` 当左部为[2,7,3],右部为[1,1]时,左部分中的最大值减去右部分最大值的绝对值最大为6。最终返回6。 #### 解题思路 >1、将整个数组分为两部分——左边和右边,那么最大值一定是在其中一边; >2、| maxL-maxR |=max-maxL或maxR ,题目目的是使前面的式子最大; >3、假设数组最大值在左边,而右边部分一定包含array[length-1],如果右边长>1,那么maxR只会增大(因为如果减小,那就不是右边的最大值了); >结果就是两种情况: (1)max在左边,右边只包含最后一个元素; (2)max在右边,左边只包含第一个元素; ``` ArrayElem MaxAbsBetweenLeftAndRight(ArrayElem *array, int length) { ArrayElem max=-1000; for (int i = 0; i < length; i++) max=maxer(max, array[i]); max=maxer(max - array[length - 1], max-array[0]); return max; } ``` <file_sep>#pragma once #include "myheader.h" void SelectSort(Sqlist *L);<file_sep>#pragma once #include "SubArraySumMax.h" #include <math.h><file_sep>#pragma once #include "SubArraySumMax.h" #include <stdlib.h> ArrayElem TwoSubArraySumMax(ArrayElem *array, int length);<file_sep>#pragma once #define MAXSIZE 20 typedef int elemType; typedef struct S{ elemType data[MAXSIZE]; int length; }Sqlist; void swap(Sqlist *L, int i, int j); <file_sep>#include "QuickSort.h" void QuickSort(Sqlist *L,int s,int e) { int pivot; if (s < e) { pivot = Partition(L, s, e); QuickSort(L, s, pivot-1); QuickSort(L, pivot + 1,e); } } int Partition(Sqlist *L, int low, int high) { //优化初始分组值,放在low处 int m = (low + high) / 2; if (L->data[low] > L->data[m]) swap(L, low, m); if (L->data[m] > L->data[high]) swap(L, m, high); if (L->data[low] <L->data[m]) swap(L, low, m); int pivotkey = L->data[low]; while (low < high) { while (low < high&&L->data[high] >= pivotkey) high--; swap(L, low, high); while (low < high&&L->data[low] <= pivotkey) low++; swap(L, low, high); } return low; }<file_sep>#pragma once #include "stddef.h" #ifndef ArrayElem typedef int ArrayElem; #endif // !ArrayElem ArrayElem maxer(ArrayElem a, ArrayElem b); ArrayElem SubArraySumMax(ArrayElem *array, int length);<file_sep>#include "ShellSort.h" void ShellSort(Sqlist *L) { int increament = L->length; int i, j; do { increament = increament / 3 + 1; //下面的流程是对组轮流,先对所有组的同一位置的元素进行插入,然后再对所有组的下一个元素分别直接插入 for (i = increament; i<L->length; i++) { if (L->data[i] < L->data[i - increament]) { int temp = L->data[i]; for (j = i - increament; j > 0 && temp < L->data[j]; j -= increament) L->data[j + increament] = L->data[j]; L->data[j + increament] = temp; } } } while (increament>1); }<file_sep>#pragma once #include "myheader.h" void HeapSort(Sqlist * L);<file_sep>#include "SelectSort.h" //用简单选择排序进行从小到大排序 void SelectSort(Sqlist * L) { int i, j,temp; for (i = 0; i < L->length; i++) { temp = i; for(j=i+1;j<L->length;j++) { if (L->data[temp] > L->data[j]) temp = j; } swap(L, i, temp); } }<file_sep>#include "HeapSort.h" //如果建立的是大顶堆,那么序列最后的排序是从小到大,应为堆顶元素放在了序列最后 HeapAdjust(Sqlist *L, int s, int m) { int temp=L->data[s]; for (int i = s * 2+1; i <= m; i = i * 2+1) { if (i<m&&L->data[i] > L->data[i + 1]) { i++; } if (L->data[i] >= temp) break; L->data[s] = L->data[i]; s = i; } L->data[s] = temp; } void HeapSort(Sqlist *L) { int i; for (i = L->length / 2-1; i >=0; i--) { HeapAdjust(L,i,L->length); } for (int j = L->length-1; j>=0; j--) { swap(L, 0, j); HeapAdjust(L, 0, j - 1); } }<file_sep>#pragma once #include <stdio.h> #include <stdlib.h> #include <string.h> void KMP_next(char *str, int length,int *next); void KMP_SubStr(char* text,int text_length,char* pattern,int pattern_length,int *local); //返回匹配的模板字符串的位置 int KMP_SubStr_Num(char* text, int text_length, char* pattern, int pattern_length);//(拓展:返回匹配的个数)<file_sep>#include "SubMatrixSumMax.h" #include <stdio.h> ArrayElem SubMatrixSumMax(ArrayElem *array, int row_len, int col_len) { if (array == NULL || row_len == 0 || col_len == 0) return 0; ArrayElem *s = (ArrayElem *)malloc(sizeof(ArrayElem)*col_len); int max=-10000; int cur_lin_max; for (int i = 0; i < row_len; i++) { memset(s, 0, col_len * sizeof(ArrayElem)); for (int j = i; j < row_len; j++) { cur_lin_max = 0; for (int k = 0; k < col_len; k++) { *(s + k) += array[j*col_len+k]; cur_lin_max += *(s + k); max=maxer(cur_lin_max, max); if (cur_lin_max < 0) cur_lin_max = 0; } } } free(s); return max; } /* int main(void) { int a[10] = { -90,48,78,64,-40,64,-81,-7,66}; int max; max = SubMatrixSumMax(a,3,3); printf("max=%d", max); } */<file_sep>#pragma once #include "myheader.h" #include "stdlib.h" #include "string.h" void Merge(int * SR, int *TR, int st, int mid, int end); void MergePass(int * SR, int *TR, int step, int length); void MergeSort(Sqlist *L);<file_sep>#include "SubArraySumMax.h" //#include <stdio.h> //求两个值中的较小值 ArrayElem maxer(ArrayElem a, ArrayElem b) { return a > b ? a : b; } ArrayElem SubArraySumMax(ArrayElem *array, int length) { if (array == NULL || length == 0) return 0; //max存放array子数组最大和,初始值为系统最小值 //cur_max存放当前子数组的和 ArrayElem max = -100; ArrayElem cur_max = 0; for (int i = 0; i != length; i++) { cur_max += array[i]; //max保存目前所有子数组和中的最大值 max=maxer(max, cur_max); //如果当前最大值为0那么后续的数组不需要在前半段加一个负数使自己的和变小 //也就是重新寻找后面的子数组最大和 if (cur_max < 0) cur_max = 0; } return max; } /* int main(void) { int a[10] = { -2,-3,-4,-1,-5,-6 }; int max; max=SubArraySumMax(a, 6); printf("SubMatrixSumMax=%d", max); } */<file_sep>#pragma once #include "myheader.h" void ShellSort(Sqlist *L);<file_sep>#include "InsertSort.h" //²åÈ뷽ʽÅÅÐò void InsertSort(Sqlist *L) { int i,j,temp; for (i = 1; i < L->length; i++) { if (L->data[i] < L->data[i - 1]) { temp = L->data[i]; for (j = i - 1; L->data[j] > temp; j--) { L->data[j + 1] = L->data[j]; } L->data[j + 1] = temp; } } }<file_sep>#include <math.h> #include <stdio.h> #include "myheader.h" #include "BulleSort.h" //冒泡排序 #include "SelectSort.h" //选择排序 #include "InsertSort.h" //插入排序 #include "ShellSort.h" //希尔排序 #include "HeapSort.h" //堆排序 #include "QuickSort.h" //快速排序 #include "MergeSort.h" //归并排序 int main(void) { //初始化结构体 Sqlist L = { { 1,9,2,6,8,3,12,4,5,7 },10 }; //调用排序方法 MergeSort(&L); //打印排序后的序列 for(int i=0;i<L.length;i++) printf("%d ",L.data[i]); }<file_sep>#include "WaterProblem.h" #include <stdio.h> //方法一:使用两个指针来减少空间占用 int WaterProblem(ArrayElem *array, int length) { if (array == NULL || length <=2) return 0; ArrayElem water = 0; ArrayElem maxL = array[0]; ArrayElem maxR = array[length - 1]; ArrayElem L = 1; ArrayElem R = length-2; while (L <= R) { if (maxL < maxR) { if(array[L]<=maxL) water += maxL - array[L]; else maxL = array[L]; L = L + 1; } else { if (array[R] <= maxR) water += maxR - array[R]; else maxR = array[R]; R = R -1; } } return water; } //方法二:用两个数组保存第i个元素左边和右边的最大值 int WaterProblem2(ArrayElem *array, int length) { return 0; } /* int main(void) { int a[10] = {3,2,2,4,1,7,2,7}; int max; max = WaterProblem(a, 8); printf("water=%d", max); } */
42ad573753c53eb2097ae574231128f8ee3613bb
[ "Markdown", "C" ]
30
C
qzylinux/DataStructure
3d6d3205abcb6c0d84cadc7e140110fc7a5c42e4
a412a0b616352c06e975f914c44b7471a52d6ab3
refs/heads/master
<file_sep>namespace AAAG.Constants { public class Application { public const string Name = "AAAG Learning Site"; public const string ShortName = "AAAG"; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AAAG.Models { public class MarketsAndNews { public List<TickerQuote> Market { get; set; } public List<string> News { get; set; } } } <file_sep>namespace AAAG.Models { public class Position { public int Id { get; set; } public int SecurityId { get; set; } public decimal Shares { get; set; } public decimal Total { get; set; } public int BrokerageAccount { get; set; } //Navigation public virtual Security Security { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AAAG.Models { public class BrokerageAccount { public BrokerageAccount() { Positions = new HashSet<Position>(); Orders = new HashSet<Order>(); } public int Id { get; set; } [Required] [StringLength(10)] [RegularExpression("[A-Z][0-9]*")] public string AccountNumber { get; set; } [StringLength(100)] public string AccountTitle { get; set; } public decimal Total { get; set; } public decimal MarginBalance { get; set; } public bool IsRetirement { get; set; } public int CustomerId { get; set; } public decimal CashTotal { get; set; } public decimal PositionsTotal { get; set; } public int WatchListId { get; set; } //Navigation public ICollection<Position> Positions { get; set; } public ICollection<Order> Orders { get; set; } public WatchList WatchList { get; set; } } }
cd03458eadd2ba59034c321621523583cbdebd7a
[ "C#" ]
4
C#
hnjonesf/AAAG
58eaf337cde05c4d8f5f01935f7c61b407193bc9
2a8cda2a32c5410f90ae8a204411aa3905b39949
refs/heads/master
<file_sep># After Checkout Codestyle <file_sep><?php class ControllerModuleAfterCheckout extends Controller { public function index() { $this->load->language( "module/after_checkout" ); } // get filter association category private function afterCheckoutGetLastOrderId() { $this->load->model( 'module/after_checkout' ); return $this->model_module_after_checkout->afterCheckoutGetLastOrderId(); } // Add/Update Cart public function afterCheckoutUpdateOrder() { $json = array(); $json['error'] = false; //Get params $getOrderId = ( isset( $this->request->post['order_id'] ) ) ? htmlspecialchars( $this->request->post['order_id'] ) : ''; $getProducts = ( isset ( $this->request->post['products'] ) ) ? htmlspecialchars( $this->request->post['products'] ) : ''; $new_total = 0; $order_data = array(); $this->load->model( 'checkout/order' ); $this->load->model( 'module/after_checkout' ); try { if ( !empty( $getProducts ) && isset( $getOrderId ) ) { //получаем данные о сделанном заказе $order_info = $this->model_checkout_order->getOrder( $getOrderId ); if ( $order_info ) { $order_data['products'] = array(); // ------------------------------------------------------ Add Products $newProducts = array(); $products_array = explode( ',', $getProducts ); foreach ( $products_array as $product_id ) { $newProducts[] = $this->model_module_after_checkout->afterCheckoutGetProductStatusOff( $product_id ); } if ( $newProducts ) { foreach ( $newProducts as $x => $product ) { // compact array if ( strlen( $product['special'] ) > 0 ) { // if special price $order_data['products'][] = array( 'product_id' => $product['product_id'], 'name' => $product['name'], 'model' => $product['model'], 'option' => array(), 'quantity' => 1, 'subtract' => number_format( $product['subtract'], 4, '.', '' ), 'tax_class_id' => number_format( $product['tax_class_id'], 4, '.', '' ), 'price' => $this->tax->calculate( $product['special'], $product['tax_class_id'], $this->config->get( 'config_tax' ) ), 'total' => $this->tax->calculate( $product['special'], $product['tax_class_id'], $this->config->get( 'config_tax' ) ), ); $new_total += (float)$this->tax->calculate( $product['special'], $product['tax_class_id'], $this->config->get( 'config_tax' ) ); } else { $order_data['products'][] = array( 'product_id' => $product['product_id'], 'name' => $product['name'], 'model' => $product['model'], 'option' => array(), 'quantity' => 1, 'subtract' => number_format( $product['subtract'], 4, '.', '' ), 'tax_class_id' => number_format( $product['tax_class_id'], 4, '.', '' ), 'price' => $this->tax->calculate( $product['price'], $product['tax_class_id'], $this->config->get( 'config_tax' ) ), 'total' => $this->tax->calculate( $product['price'], $product['tax_class_id'], $this->config->get( 'config_tax' ) ), ); $new_total += (float)$this->tax->calculate( $product['price'], $product['tax_class_id'], $this->config->get( 'config_tax' ) ); } } } else { $json['error'] = true; } // ------------------------------------------------------ Get Last Order //получаем данные о последнем заказа по идентификатору $oldProducts = $this->model_module_after_checkout->afterCheckoutGetLastOrder( $getOrderId ); $old_products = array(); if ( $oldProducts ) { foreach ( $oldProducts as $x => $total ) { $old_products['order_id'] = $total['order_id']; // this sub_total if ( $total['code'] == 'sub_total' ) { $old_products['sub_total'] = $total['value']; } // this total if ( $total['code'] == 'total' ) { $old_products['total'] = $total['value']; } // this if not sub_total and total if ( $total['code'] != 'sub_total' && $total['code'] != 'total' ) { @$old_products['other'] += $total['value']; } } } else { $json['error'] = true; } // ------------------------------------------------------ Validate summary Order $a = $this->ach_format( $old_products['sub_total'] ); // сумма старого заказа $c = $this->ach_format( $old_products['total'] - $old_products['sub_total'] ); // сумма разницы между предварительной суммой и общей до нового заказа $order_data['sub_total'] = $this->ach_format( $a + $new_total ); // сумма нового заказа $order_data['total'] = $this->ach_format( $order_data['sub_total'] + $c ); // общая сумма //$after_checkout_update = true; $after_checkout_update = $this->model_module_after_checkout->afterCheckoutUpdateOrder( $getOrderId, $order_data ); // ------------------------------------------------------ Send Email // ------------------------------------------------------ Send SMS if ( !$after_checkout_update ) { $this->log->write('Ошибка обновления данных ордера заказа 1 !'); $json['error'] = true; } } else { $this->log->write("Тестовый режим модуля \"Заказ плюс\". Попытка записи новой суммы в ордер заказа."); $json['error'] = true; }//end if order info unset( $oldProducts ); unset( $old_products ); unset( $newProducts ); unset( $products_array ); } else { $this->log->write('Нет данных в значениях $getProducts и $getOrderId'); $json['error'] = true; } $this->cart->clear(); unset( $getOrderId ); unset( $order_info ); unset( $getProducts ); } catch ( Exception $e ) { $this->log->write('Ошибка обновления данных ордера заказа 2 !'); $this->log->write($e->getMessage()); $json['error'] = true; } if ( isset( $this->request->server['HTTP_ORIGIN'] ) ) { $this->response->addHeader( 'Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN'] ); $this->response->addHeader( 'Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS' ); $this->response->addHeader( 'Access-Control-Max-Age: 1000' ); $this->response->addHeader( 'Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With' ); } $this->response->addHeader( 'Content-Type: application/json' ); $this->response->setOutput( json_encode( $json ) ); } // Pages public function afterCheckoutGetPage() { $this->load->model( 'module/after_checkout' ); $data = array(); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes if ( $this->config->get( 'after_checkout_information' ) ) { $data['after_checkout_pages'] = array(); $data['after_checkout_pages_count'] = 0; $page = ( isset( $this->request->post['page'] ) ) ? htmlspecialchars( $this->request->post['page'] ) : false; //int pages if ( !$page ) { $after_checkout_pages = $this->model_module_after_checkout->afterCheckoutGetPages( $this->config->get( 'after_checkout_information' ) ); // Get Pages if( $after_checkout_pages ){ $after_checkout_pages = $after_checkout_pages[0]; $data['after_checkout_pages']['title'] = $after_checkout_pages['title']; $data['after_checkout_pages']['description'] = $this->afterCheckoutFormatDescription( $after_checkout_pages['description'] ); } } else { $target = ( isset( $this->request->post['target'] ) ) ? htmlspecialchars( $this->request->post['target'] ) : 0; $data['after_checkout_pages_count'] = htmlspecialchars( $this->request->post['page'] ); $after_checkout_products = ( isset( $this->request->post['products'] ) ) ? htmlspecialchars( $this->request->post['products'] ) : 0; if ( !empty( $after_checkout_products ) ) { if ( strlen( $after_checkout_products ) > 1 ) { $after_checkout_products_array = explode( ',', $after_checkout_products ); } else { $after_checkout_products_array = $after_checkout_products; } } if ( $target ) { $after_checkout_pages = $this->model_module_after_checkout->afterCheckoutGetPagesId( $target ); // Get Pages $data['after_checkout_pages']['title'] = $after_checkout_pages['title']; $data['after_checkout_pages']['description'] = $this->afterCheckoutFormatDescription( $after_checkout_pages['description'] ); $data['after_checkout_pages']['keywords'] = @$after_checkout_products_array; } } $this->response->setOutput( $this->afterCheckoutTemplate( DIR_SYSTEM . 'library/local_script/after_checkout/template/template.tpl', $data ) ); } else { die(); } } // Format private function afterCheckoutFormatDescription( $description ) { $new_description = $description; // if enabled format tags if ( $this->config->get( "after_checkout_enable_tags" ) ) { preg_match_all( '/\{(.+?)\}/', $description, $template ); if ( !empty( $template ) ) { //если есть вообще теги на странице if ( count( $template[0] ) > 0 ) { $arData = array(); $arCt = array(); $arCategory = array(); $arPt = array(); $arProduct = array(); $a = 0; $b = 0; /// Обработка массивов // Work Category foreach ( $template[0] as $key ) { if ( strpos( $key, 'category=' ) ) { $arCt[] = str_replace( "category=", "", $template[1][$a] ); } $a++; } unset( $a ); // Work Products foreach ( $template[0] as $key ) { if ( strpos( $key, 'product=' ) ) { $arPt[] = str_replace( "product=", "", $template[1][$b] ); } $b++; } unset( $b ); // Get source if ( count( $arCt ) > 0 ) { foreach ( $arCt as $key ) { $arCategory[] = htmlentities( $this->afterCheckoutGetCategory( $key ) ); } } if ( count( $arPt ) > 0 ) { foreach ( $arPt as $key ) { $arProduct[] = htmlentities( $this->afterCheckoutGetProduct( $key ) ); } } $point1 = 0; foreach ( $template[0] as $k ) { if ( strpos( $k, "category=" ) ) { $new_description = str_replace( $k, html_entity_decode( $arCategory[$point1], ENT_QUOTES, 'UTF-8' ), $new_description ); $point1++; } } $point2 = 0; foreach ( $template[0] as $k ) { if ( strpos( $k, "product=" ) ) { $new_description = str_replace( $k, html_entity_decode( $arProduct[$point2], ENT_QUOTES, 'UTF-8' ), $new_description ); $point2++; } } $c = 0; foreach ( $template[0] as $key ) { if ( strpos( $new_description, "{latest}" ) ) { $arData['latest'] = $this->afterCheckoutGetLatest(); if ( $arData['latest'] ) { $new_description = str_replace( "{latest}", $arData['latest'], $new_description ); } else { $new_description = str_replace( "{latest}", "Not found !", $new_description ); } } sleep( 0.3 ); if ( strpos( $new_description, "{bestseller}" ) ) { $arData['bestseller'] = $this->afterCheckoutGetBestseller(); if ( $arData['bestseller'] ) { $new_description = str_replace( "{bestseller}", $arData['bestseller'], $new_description ); } else { $new_description = str_replace( "{bestseller}", "Not found !", $new_description ); } } sleep( 0.3 ); if ( strpos( $new_description, "{special}" ) ) { $arData['special'] = $this->afterCheckoutGetSpecial(); if ( $arData['special'] ) { $new_description = str_replace( "{special}", $arData['special'], $new_description ); } else { $new_description = str_replace( "{special}", "Not found !", $new_description ); } } sleep( 0.3 ); if ( strpos( $new_description, "{association}" ) ) { $arData['association'] = $this->afterCheckoutGetAssociations(); if ( $arData['association'] ) { $new_description = str_replace( "{association}", $arData['association'], $new_description ); } else { $new_description = str_replace( "{association}", "Not found !", $new_description ); } } $c++; } unset( $arData ); unset( $template ); unset( $c ); unset( $arCt ); unset( $arCategory ); unset( $arPt ); unset( $arProduct ); } } } return html_entity_decode( $new_description, ENT_QUOTES, 'UTF-8' ); } // Template: Category private function afterCheckoutGetCategory( $category_id ) { $this->load->model( 'catalog/category' ); $this->load->model( 'catalog/product' ); $this->load->model( 'tool/image' ); $this->load->language( 'product/category' ); $this->load->language( "module/after_checkout" ); // users $limit = ( strlen( $this->config->get( "after_checkout_count_output_product" ) ) > 0 ) ? $this->config->get( "after_checkout_count_output_product" ) : 10; $button = $this->config->get( "after_checkout_button" ); if ( isset( $button['add'] ) ) { $data['button_addons'] = $button['add']; } else { $data['button_addons'] = $this->language->get( 'button_addons' ); } if ( isset( $button['continue'] ) ) { $data['after_checkout_button_finish'] = $button['continue']; } else { $data['after_checkout_button_finish'] = $this->language->get( 'after_checkout_button_finish' ); } unset( $button ); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes $data['button_addons_success'] = $this->language->get( 'button_addons_success' ); $data['button_addons_success_checked'] = $this->language->get( 'button_addons_success_checked' ); $category_info = $this->model_module_after_checkout->afterCheckoutGetCategory( $category_id ); if ( $category_info ) { $data['title'] = $category_info['name']; $data['text_refine'] = $this->language->get( 'text_refine' ); $data['text_empty'] = $this->language->get( 'text_empty' ); $data['text_quantity'] = $this->language->get( 'text_quantity' ); $data['text_manufacturer'] = $this->language->get( 'text_manufacturer' ); $data['text_model'] = $this->language->get( 'text_model' ); $data['text_price'] = $this->language->get( 'text_price' ); $data['text_tax'] = $this->language->get( 'text_tax' ); $data['text_points'] = $this->language->get( 'text_points' ); $data['text_compare'] = sprintf( $this->language->get( 'text_compare' ), ( isset( $this->session->data['compare'] ) ? count( $this->session->data['compare'] ) : 0 ) ); $data['text_sort'] = $this->language->get( 'text_sort' ); $data['text_limit'] = $this->language->get( 'text_limit' ); $data['button_cart'] = $this->language->get( 'button_cart' ); $data['button_wishlist'] = $this->language->get( 'button_wishlist' ); $data['button_compare'] = $this->language->get( 'button_compare' ); $data['button_continue'] = $this->language->get( 'button_continue' ); $data['button_list'] = $this->language->get( 'button_list' ); $data['button_grid'] = $this->language->get( 'button_grid' ); $data['products'] = array(); $filter_data = array( 'filter_category_id' => $category_id, 'sort' => 'p.sort_order', 'order' => 'ASC', 'start' => 0, 'limit' => $limit ); $results = $this->model_catalog_product->getProducts( $filter_data ); foreach ( $results as $result ) { if ( $result['image'] ) { $image = $this->model_tool_image->resize( $result['image'], $this->config->get( 'config_image_product_width' ), $this->config->get( 'config_image_product_height' ) ); } else { $image = $this->model_tool_image->resize( 'placeholder.png', $this->config->get( 'config_image_product_width' ), $this->config->get( 'config_image_product_height' ) ); } if ( ( $this->config->get( 'config_customer_price' ) && $this->customer->isLogged() ) || !$this->config->get( 'config_customer_price' ) ) { $price = $this->currency->format( $this->tax->calculate( $result['price'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $price = false; } if ( (float)$result['special'] ) { $special = $this->currency->format( $this->tax->calculate( $result['special'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $special = false; } if ( $this->config->get( 'config_tax' ) ) { $tax = $this->currency->format( (float)$result['special'] ? $result['special'] : $result['price'] ); } else { $tax = false; } if ( $this->config->get( 'config_review_status' ) ) { $rating = (int)$result['rating']; } else { $rating = false; } $data['products'][] = array( 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'description' => utf8_substr( strip_tags( html_entity_decode( $result['description'], ENT_QUOTES, 'UTF-8' ) ), 0, $this->config->get( 'config_product_description_length' ) ) . '..', 'price' => $price, 'special' => $special, 'tax' => $tax, 'minimum' => $result['minimum'] > 0 ? $result['minimum'] : 1, 'rating' => $result['rating'], 'href' => $this->url->link( 'product/product', '&product_id=' . $result['product_id'] ), 'view' => $result['viewed'] ); } //random array if ( $this->config->get( 'after_checkout_random_output_product' ) == 'on' ) { shuffle( $data['products'] ); } $file = DIR_SYSTEM . 'library/local_script/after_checkout/template/category.tpl'; if ( file_exists( $file ) ) { return $this->afterCheckoutTemplate( $file, $data ); } } return 'Not found !'; } // Template: Product private function afterCheckoutGetProduct( $product_id ) { $this->load->language( "module/after_checkout" ); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes $button = $this->config->get( "after_checkout_button" ); if ( isset( $button['add'] ) ) { $data['button_addons'] = $button['add']; } else { $data['button_addons'] = $this->language->get( 'button_addons' ); } if ( isset( $button['continue'] ) ) { $data['after_checkout_button_finish'] = $button['continue']; } else { $data['after_checkout_button_finish'] = $this->language->get( 'after_checkout_button_finish' ); } unset( $button ); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes $data['button_addons_success'] = $this->language->get( 'button_addons_success' ); $data['button_addons_success_checked'] = $this->language->get( 'button_addons_success_checked' ); $this->load->language( "product/product" ); $data['text_select'] = $this->language->get( 'text_select' ); $data['text_manufacturer'] = $this->language->get( 'text_manufacturer' ); $data['text_model'] = $this->language->get( 'text_model' ); $data['text_not_price'] = $this->language->get( 'text_not_price' ); $data['text_reward'] = $this->language->get( 'text_reward' ); $data['text_points'] = $this->language->get( 'text_points' ); $data['text_stock'] = $this->language->get( 'text_stock' ); $data['text_discount'] = $this->language->get( 'text_discount' ); $data['text_tax'] = $this->language->get( 'text_tax' ); $data['text_option'] = $this->language->get( 'text_option' ); $data['text_empty'] = $this->language->get( 'text_empty' ); $data['text_write'] = $this->language->get( 'text_write' ); $data['text_note'] = $this->language->get( 'text_note' ); $data['text_payment_recurring'] = $this->language->get( 'text_payment_recurring' ); $data['text_loading'] = $this->language->get( 'text_loading' ); $data['entry_qty'] = $this->language->get( 'entry_qty' ); $data['entry_name'] = $this->language->get( 'entry_name' ); $data['entry_review'] = $this->language->get( 'entry_review' ); $data['entry_rating'] = $this->language->get( 'entry_rating' ); $data['entry_good'] = $this->language->get( 'entry_good' ); $data['entry_bad'] = $this->language->get( 'entry_bad' ); $data['button_continue'] = $this->language->get( 'button_continue' ); $data['continue'] = HTTP_SERVER; $data['products'] = array(); $this->load->model( 'tool/image' ); $this->load->model( 'catalog/product' ); //$results = $this->model_catalog_product->getProduct($product_id); $results = $this->model_module_after_checkout->afterCheckoutGetProductStatusOff( $product_id ); if ( $results ) { if ( $results['image'] ) { $image = $this->model_tool_image->resize( $results['image'], $this->config->get( 'config_image_product_width' ), $this->config->get( 'config_image_product_height' ) ); } else { $image = $this->model_tool_image->resize( 'placeholder.png', $this->config->get( 'config_image_product_width' ), $this->config->get( 'config_image_product_height' ) ); } if ( ( $this->config->get( 'config_customer_price' ) && $this->customer->isLogged() ) || !$this->config->get( 'config_customer_price' ) ) { $price = $this->currency->format( $this->tax->calculate( $results['price'], $results['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $price = false; } if ( (float)$results['special'] ) { $special = $this->currency->format( $this->tax->calculate( $results['special'], $results['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $special = false; } if ( $this->config->get( 'config_tax' ) ) { $tax = $this->currency->format( (float)$results['special'] ? $results['special'] : $results['price'] ); } else { $tax = false; } if ( $this->config->get( 'config_review_status' ) ) { $rating = (int)$results['rating']; } else { $rating = false; } $data['product'] = array( 'product_id' => $results['product_id'], 'thumb' => $image, 'name' => $results['name'], 'description' => utf8_substr( strip_tags( html_entity_decode( $results['description'], ENT_QUOTES, 'UTF-8' ) ), 0, $this->config->get( 'config_product_description_length' ) ) . '..', 'price' => $price, 'special' => $special, 'tax' => $tax, 'minimum' => $results['minimum'] > 0 ? $results['minimum'] : 1, 'rating' => $rating, 'href' => $this->url->link( 'product/product', '&product_id=' . $results['product_id'] ), 'view' => $results['viewed'] ); $file = DIR_SYSTEM . 'library/local_script/after_checkout/template/product.tpl'; if ( file_exists( $file ) ) { return $this->afterCheckoutTemplate( $file, $data ); } }// end if results; return 'Not found !'; } // Template: Bestseller private function afterCheckoutGetBestseller() { $limit = $this->config->get( "after_checkout_count_output_product" ); $width = $this->config->get( "config_image_category_width" ); $height = $this->config->get( "config_image_category_height" ); $this->load->language( 'module/bestseller' ); $data['heading_title'] = $this->language->get( 'heading_title' ); $data['text_tax'] = $this->language->get( 'text_tax' ); $data['button_cart'] = $this->language->get( 'button_cart' ); $data['button_wishlist'] = $this->language->get( 'button_wishlist' ); $data['button_compare'] = $this->language->get( 'button_compare' ); $this->load->model( 'catalog/product' ); $this->load->model( 'tool/image' ); $data['products'] = array(); $this->load->language( "module/after_checkout" ); $button = $this->config->get( "after_checkout_button" ); if ( isset( $button['add'] ) ) { $data['button_addons'] = $button['add']; } else { $data['button_addons'] = $this->language->get( 'button_addons' ); } if ( isset( $button['continue'] ) ) { $data['after_checkout_button_finish'] = $button['continue']; } else { $data['after_checkout_button_finish'] = $this->language->get( 'after_checkout_button_finish' ); } unset( $button ); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes $data['button_addons_success'] = $this->language->get( 'button_addons_success' ); $data['button_addons_success_checked'] = $this->language->get( 'button_addons_success_checked' ); $results = $this->model_catalog_product->getBestSellerProducts( $limit ); if ( $results ) { foreach ( $results as $result ) { if ( $result['image'] ) { $image = $this->model_tool_image->resize( $result['image'], $width, $height ); } else { $image = $this->model_tool_image->resize( 'placeholder.png', $width, $height ); } if ( ( $this->config->get( 'config_customer_price' ) && $this->customer->isLogged() ) || !$this->config->get( 'config_customer_price' ) ) { $price = $this->currency->format( $this->tax->calculate( $result['price'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $price = false; } if ( (float)$result['special'] ) { $special = $this->currency->format( $this->tax->calculate( $result['special'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $special = false; } if ( $this->config->get( 'config_tax' ) ) { $tax = $this->currency->format( (float)$result['special'] ? $result['special'] : $result['price'] ); } else { $tax = false; } if ( $this->config->get( 'config_review_status' ) ) { $rating = $result['rating']; } else { $rating = false; } $data['products'][] = array( 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'description' => utf8_substr( strip_tags( html_entity_decode( $result['description'], ENT_QUOTES, 'UTF-8' ) ), 0, $this->config->get( 'config_product_description_length' ) ) . '..', 'price' => $price, 'special' => $special, 'tax' => $tax, 'rating' => $rating, 'href' => $this->url->link( 'product/product', 'product_id=' . $result['product_id'] ), 'view' => $result['viewed'] ); } //random array if ( $this->config->get( 'after_checkout_random_output_product' ) == 'on' ) { shuffle( $data['products'] ); } $file = DIR_SYSTEM . 'library/local_script/after_checkout/template/bestseller.tpl'; if ( file_exists( $file ) ) { return $this->afterCheckoutTemplate( $file, $data ); } } else { return false; } } // Template: Special private function afterCheckoutGetSpecial() { $limit = $this->config->get( "after_checkout_count_output_product" ); $width = $this->config->get( "config_image_category_width" ); $height = $this->config->get( "config_image_category_height" ); $this->load->language( 'module/special' ); $data['heading_title'] = $this->language->get( 'heading_title' ); $data['text_tax'] = $this->language->get( 'text_tax' ); $data['button_cart'] = $this->language->get( 'button_cart' ); $data['button_wishlist'] = $this->language->get( 'button_wishlist' ); $data['button_compare'] = $this->language->get( 'button_compare' ); $this->load->language( "module/after_checkout" ); $button = $this->config->get( "after_checkout_button" ); if ( isset( $button['add'] ) ) { $data['button_addons'] = $button['add']; } else { $data['button_addons'] = $this->language->get( 'button_addons' ); } if ( isset( $button['continue'] ) ) { $data['after_checkout_button_finish'] = $button['continue']; } else { $data['after_checkout_button_finish'] = $this->language->get( 'after_checkout_button_finish' ); } unset( $button ); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes $data['button_addons_success'] = $this->language->get( 'button_addons_success' ); $data['button_addons_success_checked'] = $this->language->get( 'button_addons_success_checked' ); $this->load->model( 'catalog/product' ); $this->load->model( 'tool/image' ); $data['products'] = array(); $filter_data = array( 'sort' => 'pd.name', 'order' => 'ASC', 'start' => 0, 'limit' => $limit ); $results = $this->model_catalog_product->getProductSpecials( $filter_data ); if ( $results ) { foreach ( $results as $result ) { if ( $result['image'] ) { $image = $this->model_tool_image->resize( $result['image'], $width, $height ); } else { $image = $this->model_tool_image->resize( 'placeholder.png', $width, $height ); } if ( ( $this->config->get( 'config_customer_price' ) && $this->customer->isLogged() ) || !$this->config->get( 'config_customer_price' ) ) { $price = $this->currency->format( $this->tax->calculate( $result['price'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $price = false; } if ( (float)$result['special'] ) { $special = $this->currency->format( $this->tax->calculate( $result['special'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $special = false; } if ( $this->config->get( 'config_tax' ) ) { $tax = $this->currency->format( (float)$result['special'] ? $result['special'] : $result['price'] ); } else { $tax = false; } if ( $this->config->get( 'config_review_status' ) ) { $rating = $result['rating']; } else { $rating = false; } $data['products'][] = array( 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'description' => utf8_substr( strip_tags( html_entity_decode( $result['description'], ENT_QUOTES, 'UTF-8' ) ), 0, $this->config->get( 'config_product_description_length' ) ) . '..', 'price' => $price, 'special' => $special, 'tax' => $tax, 'rating' => $rating, 'href' => $this->url->link( 'product/product', 'product_id=' . $result['product_id'] ), 'view' => $result['viewed'] ); } //random array if ( $this->config->get( 'after_checkout_random_output_product' ) == 'on' ) { shuffle( $data['products'] ); } $file = DIR_SYSTEM . 'library/local_script/after_checkout/template/special.tpl'; if ( file_exists( $file ) ) { return $this->afterCheckoutTemplate( $file, $data ); } } else { return false; } } // Template: Latest private function afterCheckoutGetLatest() { $limit = $this->config->get( "after_checkout_count_output_product" ); $width = $this->config->get( "config_image_category_width" ); $height = $this->config->get( "config_image_category_height" ); $this->load->language( 'module/latest' ); $data['heading_title'] = $this->language->get( 'heading_title' ); $data['text_tax'] = $this->language->get( 'text_tax' ); $data['button_cart'] = $this->language->get( 'button_cart' ); $data['button_wishlist'] = $this->language->get( 'button_wishlist' ); $data['button_compare'] = $this->language->get( 'button_compare' ); $this->load->language( "module/after_checkout" ); $button = $this->config->get( "after_checkout_button" ); if ( isset( $button['add'] ) ) { $data['button_addons'] = $button['add']; } else { $data['button_addons'] = $this->language->get( 'button_addons' ); } if ( isset( $button['continue'] ) ) { $data['after_checkout_button_finish'] = $button['continue']; } else { $data['after_checkout_button_finish'] = $this->language->get( 'after_checkout_button_finish' ); } unset( $button ); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes $data['button_addons_success'] = $this->language->get( 'button_addons_success' ); $data['button_addons_success_checked'] = $this->language->get( 'button_addons_success_checked' ); $this->load->model( 'catalog/product' ); $this->load->model( 'tool/image' ); $data['products'] = array(); $filter_data = array( 'sort' => 'p.date_added', 'order' => 'DESC', 'start' => 0, 'limit' => $limit ); $results = $this->model_catalog_product->getProducts( $filter_data ); if ( $results ) { foreach ( $results as $result ) { if ( $result['image'] ) { $image = $this->model_tool_image->resize( $result['image'], $width, $height ); } else { $image = $this->model_tool_image->resize( 'placeholder.png', $width, $height ); } if ( ( $this->config->get( 'config_customer_price' ) && $this->customer->isLogged() ) || !$this->config->get( 'config_customer_price' ) ) { $price = $this->currency->format( $this->tax->calculate( $result['price'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $price = false; } if ( (float)$result['special'] ) { $special = $this->currency->format( $this->tax->calculate( $result['special'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $special = false; } if ( $this->config->get( 'config_tax' ) ) { $tax = $this->currency->format( (float)$result['special'] ? $result['special'] : $result['price'] ); } else { $tax = false; } if ( $this->config->get( 'config_review_status' ) ) { $rating = $result['rating']; } else { $rating = false; } $data['products'][] = array( 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'description' => utf8_substr( strip_tags( html_entity_decode( $result['description'], ENT_QUOTES, 'UTF-8' ) ), 0, $this->config->get( 'config_product_description_length' ) ) . '..', 'price' => $price, 'special' => $special, 'tax' => $tax, 'rating' => $rating, 'href' => $this->url->link( 'product/product', 'product_id=' . $result['product_id'] ), 'view' => $result['viewed'] ); } //random array if ( $this->config->get( 'after_checkout_random_output_product' ) == 'on' ) { shuffle( $data['products'] ); } $file = DIR_SYSTEM . 'library/local_script/after_checkout/template/latest.tpl'; if ( file_exists( $file ) ) { return $this->afterCheckoutTemplate( $file, $data ); } $file_template = DIR_TEMPLATE . $this->config->get( 'config_template' ) . '/template/module/latest.tpl'; if ( file_exists( $file_template ) ) { return $this->load->view( $this->config->get( 'config_template' ) . '/template/module/latest.tpl', $data ); } else { return $this->load->view( 'default/template/module/latest.tpl', $data ); } } else { return false; } } // Template: Association private function afterCheckoutGetAssociations() { $last_order_id = $this->afterCheckoutGetLastOrderId(); $data = array(); $data['heading_title'] = $this->language->get( 'heading_title' ); $data['text_tax'] = $this->language->get( 'text_tax' ); $data['button_cart'] = $this->language->get( 'button_cart' ); $data['button_wishlist'] = $this->language->get( 'button_wishlist' ); $data['button_compare'] = $this->language->get( 'button_compare' ); $data['after_checkout_themes'] = ( strlen( $this->config->get( "after_checkout_page_themes" ) ) > 0 ) ? $this->config->get( "after_checkout_page_themes" ) : 0; //themes $this->load->language( "module/after_checkout" ); $button = $this->config->get( "after_checkout_button" ); if ( isset( $button['add'] ) ) { $data['button_addons'] = $button['add']; } else { $data['button_addons'] = $this->language->get( 'button_addons' ); } if ( isset( $button['continue'] ) ) { $data['after_checkout_button_finish'] = $button['continue']; } else { $data['after_checkout_button_finish'] = $this->language->get( 'after_checkout_button_finish' ); } unset( $button ); $data['button_addons_success'] = $this->language->get( 'button_addons_success' ); $data['button_addons_success_checked'] = $this->language->get( 'button_addons_success_checked' ); if ( $this->config->get( "after_checkout_count_output_product" ) ) { $limit = $this->config->get( "after_checkout_count_output_product" ); } else { $limit = 10; } $data['products'] = $this->afterCheckoutGetAssociationsCategory( $last_order_id['order_categories'], $limit ); if ( !$data['products'] ) { return false; } return $this->afterCheckoutTemplate( DIR_SYSTEM . 'library/local_script/after_checkout/template/associations.tpl', $data ); } private function afterCheckoutGetAssociationsCategory( $category_id, $limit ) { $data = array(); $width = $this->config->get( "config_image_category_width" ); $height = $this->config->get( "config_image_category_height" ); $this->load->model( 'catalog/product' ); $this->load->model( 'tool/image' ); $products = array(); $unique_products = array(); if ( isset( $category_id ) ) { $l = 0; // идентификатор лимита для цикла foreach ( $category_id as $category ) { $results = null; $results = $this->model_catalog_product->getProducts( array( 'filter_category_id' => $category, 'sort' => 'p.date_added', 'start' => 0, 'limit' => $limit ) ); if ( $results ) { //random array if ( $this->config->get( 'after_checkout_random_output_product' ) == 'on' ) { shuffle( $results ); } foreach ( $results as $result ) { if ( $result['image'] ) { $image = $this->model_tool_image->resize( $result['image'], $width, $height ); } else { $image = $this->model_tool_image->resize( 'placeholder.png', $width, $height ); } if ( ( $this->config->get( 'config_customer_price' ) && $this->customer->isLogged() ) || !$this->config->get( 'config_customer_price' ) ) { $price = $this->currency->format( $this->tax->calculate( $result['price'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $price = false; } if ( (float)$result['special'] ) { $special = $this->currency->format( $this->tax->calculate( $result['special'], $result['tax_class_id'], $this->config->get( 'config_tax' ) ) ); } else { $special = false; } if ( $this->config->get( 'config_tax' ) ) { $tax = $this->currency->format( (float)$result['special'] ? $result['special'] : $result['price'] ); } else { $tax = false; } if ( $this->config->get( 'config_review_status' ) ) { $rating = $result['rating']; } else { $rating = false; } $products[] = array( 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'description' => utf8_substr( strip_tags( html_entity_decode( $result['description'], ENT_QUOTES, 'UTF-8' ) ), 0, $this->config->get( 'config_product_description_length' ) ) . '..', 'price' => $price, 'special' => $special, 'tax' => $tax, 'rating' => $rating, 'href' => $this->url->link( 'product/product', 'product_id=' . $result['product_id'] ), 'view' => $result['viewed'] ); } $unique_products = @array_unique( $products ); } else { return false; } if ( $l >= $limit ) { break; } $l++; } } return $unique_products; } // View template private function afterCheckoutTemplate( $template, $data = array() ) { $file = $template; if ( file_exists( $file ) ) { extract( $data ); ob_start(); require( $file ); $output = ob_get_contents(); ob_end_clean(); } else { trigger_error( 'Error: Could not load template ' . $file . '!' ); exit(); } return $output; } // Format number private function ach_format( $num, $dec = 4, $dp = ".", $ts = "" ) { return number_format( (float)$num, $dec, $dp, $ts ); } }
aa07893d85709ffd12b81d49f102572a19419471
[ "Markdown", "PHP" ]
2
Markdown
webdev74/after_checkout
8e072071b68bf80c10bfc12f4cffb717ecd22a38
a807f32b48573bebdd0b70e8ad6cb514eb6928de
refs/heads/master
<file_sep>#!/bin/sh # export OMP_NUM_THREADS=16 # export KMP_AFFINITY=granularity=fine,proclist=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30],explicit # export OMP_NUM_THREADS=34 # export KMP_AFFINITY=granularity=fine,proclist=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66],explicit export OMP_NUM_THREADS=68 export KMP_AFFINITY=granularity=fine,proclist=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67],explicit # export OMP_NUM_THREADS=272 # export KMP_AFFINITY=compact # flat mode # for touch in 0 1 # do # for use_mcdram in 0 1 # do # ./triad_knl.out 67108864 $use_mcdram $touch # ./triad_knl.out 33554432 $use_mcdram $touch # ./triad_knl.out 16777216 $use_mcdram $touch # ./triad_knl.out 8388608 $use_mcdram $touch # ./triad_knl.out 4194304 $use_mcdram $touch # ./triad_knl.out 2097152 $use_mcdram $touch # ./triad_knl.out 1048600 $use_mcdram $touch # ./triad_knl.out 524288 $use_mcdram $touch # ./triad_knl.out 262144 $use_mcdram $touch # ./triad_knl.out 139888 $use_mcdram $touch # ./triad_knl.out 65536 $use_mcdram $touch # ./triad_knl.out 32768 $use_mcdram $touch # done # done # cache mode for touch in 0 1 do ./triad_knl.out 67108864 0 $touch ./triad_knl.out 33554432 0 $touch ./triad_knl.out 16777216 0 $touch ./triad_knl.out 8388608 0 $touch ./triad_knl.out 4194304 0 $touch ./triad_knl.out 2097152 0 $touch ./triad_knl.out 1048600 0 $touch ./triad_knl.out 524288 0 $touch ./triad_knl.out 262144 0 $touch ./triad_knl.out 139888 0 $touch ./triad_knl.out 65536 0 $touch ./triad_knl.out 32768 0 $touch done <file_sep>#!/bin/sh for i in 2000 3000 5000 8000 10000 16000 do ./dgemm_cublas_pascal.out $i done <file_sep>#include <iostream> #include <cstdlib> #include <algorithm> #include <random> #include <chrono> #include <x86intrin.h> __attribute__((noinline)) void triad(const double* __restrict x, const double* __restrict y, double* __restrict z, const double s, const int val_size) { #pragma omp parallel { const auto size = val_size; const auto s_vec = _mm256_set1_pd(s); #pragma omp for nowait for (int i = 0; i < size; i += 4) { const auto x_vec = _mm256_load_pd(x + i); const auto y_vec = _mm256_load_pd(y + i); const auto dst = _mm256_fmadd_pd(s_vec, x_vec, y_vec); _mm256_store_pd(z + i, dst); } } } __attribute__((noinline)) void reference(const std::vector<double>& x, const std::vector<double>& y, std::vector<double>& z, const double s) { const int size = x.size(); for (int i = 0; i < size; i++) { z[i] = s * x[i] + y[i]; } } void first_touch(double* x, double* y, double* z, const int val_size) { #pragma omp parallel for for (int i = 0; i < val_size; i++) { x[i] = y[i] = z[i] = 0.0; } } void check(const std::vector<double>& z_ref, const double* z) { const auto size = z_ref.size(); for (size_t i = 0; i < size; i++) { if (z_ref[i] != z[i]) { std::cout << "mismatch\n"; std::cout << z_ref[i] << " " << z[i] << std::endl; std::exit(1); } } } #define BENCH(repr, size) \ do { \ using namespace std::chrono; \ const int LOOP = 10000; \ const auto beg = system_clock::now(); \ for (int i = 0; i < LOOP; i++) repr; \ const auto end = system_clock::now(); \ const double dur = duration_cast<milliseconds>(end - beg).count(); \ const double band_width = \ 3.0 * size * sizeof(double) / ((dur * 1.0e-3 / double(LOOP)) * 1.0e9); \ std::cerr << "array " << size << " " << band_width << " [GB/s] "; \ std::cerr << dur << " [ms]\n"; \ } while (0) int main(const int argc, const char* argv[]) { int val_size = 1 << 25; bool touch = true; if (argc >= 2) val_size = std::atoi(argv[1]); if (argc >= 3) touch = std::atoi(argv[2]); const double s = 2.0; double *x_vec = nullptr; double *y_vec = nullptr; double *z_vec = nullptr; posix_memalign((void**)&x_vec, 32, val_size * sizeof(double)); posix_memalign((void**)&y_vec, 32, val_size * sizeof(double)); posix_memalign((void**)&z_vec, 32, val_size * sizeof(double)); if (touch) first_touch(x_vec, y_vec, z_vec, val_size); std::mt19937 mt; std::uniform_real_distribution<double> urd(0, 1.0); std::generate_n(x_vec, val_size, [&mt, &urd](){return urd(mt);}); std::generate_n(y_vec, val_size, [&mt, &urd](){return urd(mt);}); std::fill_n(z_vec, val_size, 0.0); std::vector<double> x_vec_ref(val_size), y_vec_ref(val_size), z_vec_ref(val_size); std::copy_n(x_vec, val_size, x_vec_ref.begin()); std::copy_n(y_vec, val_size, y_vec_ref.begin()); std::copy_n(z_vec, val_size, z_vec_ref.begin()); reference(x_vec_ref, y_vec_ref, z_vec_ref, s); // BENCH(reference(x_vec_ref, y_vec_ref, z_vec_ref, s, val_size), val_size); BENCH(triad(x_vec, y_vec, z_vec, s, val_size), val_size); check(z_vec_ref, z_vec); free(x_vec); free(y_vec); free(z_vec); } <file_sep>#include <iostream> #include <cstdlib> #include <algorithm> #include <random> #include <chrono> #include <x86intrin.h> int mat_size = 4096; // ver1 __attribute__((noinline)) void dgemm1(const double* __restrict x, const double* __restrict y, double* __restrict z) { #pragma omp parallel { const auto N = mat_size; const auto vindex = _mm256_set_epi32(7 * N, 6 * N, 5 * N, 4 * N, 3 * N, 2 * N, N, 0); #pragma omp for for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { auto sum_vec = _mm512_setzero_pd(); for (int k = 0; k < N; k += 8) { const auto xvec = _mm512_load_pd(&x[N * i + k]); const auto yvec = _mm512_i32gather_pd(vindex, &y[N * k + j], 8); sum_vec = _mm512_fmadd_pd(xvec, yvec, sum_vec); } z[N * i + j] = _mm512_reduce_add_pd(sum_vec); } } } } // ver2 __attribute__((noinline)) void dgemm2(const double* __restrict x, const double* __restrict y, double* __restrict z) { #pragma omp parallel { const auto N = mat_size; constexpr int nib = 4; constexpr int njb = 8; // fix constexpr int nkb = 8; #pragma omp for for (int ib = 0; ib < N; ib += nib) { for (int kb = 0; kb < N; kb += nkb) { for (int jb = 0; jb < N; jb += njb) { auto sum0_vec = _mm512_load_pd(&z[N * ib + jb]); auto sum1_vec = _mm512_load_pd(&z[N * (ib + 1) + jb]); auto sum2_vec = _mm512_load_pd(&z[N * (ib + 2) + jb]); auto sum3_vec = _mm512_load_pd(&z[N * (ib + 3) + jb]); for (int k = kb; k < kb + nkb; k++) { const auto y_vec = _mm512_load_pd(&y[N * k + jb]); const auto x0_vec = _mm512_set1_pd(x[N * ib + k]); const auto x1_vec = _mm512_set1_pd(x[N * (ib + 1) + k]); const auto x2_vec = _mm512_set1_pd(x[N * (ib + 2) + k]); const auto x3_vec = _mm512_set1_pd(x[N * (ib + 3) + k]); sum0_vec = _mm512_fmadd_pd(x0_vec, y_vec, sum0_vec); sum1_vec = _mm512_fmadd_pd(x1_vec, y_vec, sum1_vec); sum2_vec = _mm512_fmadd_pd(x2_vec, y_vec, sum2_vec); sum3_vec = _mm512_fmadd_pd(x3_vec, y_vec, sum3_vec); } _mm512_store_pd(&z[N * ib + jb], sum0_vec); _mm512_store_pd(&z[N * (ib + 1) + jb], sum1_vec); _mm512_store_pd(&z[N * (ib + 2) + jb], sum2_vec); _mm512_store_pd(&z[N * (ib + 3) + jb], sum3_vec); } } } } } // ver3 __attribute__((noinline)) void dgemm3(const double* __restrict x, const double* __restrict y, double* __restrict z) { #pragma omp parallel { const auto N = mat_size; constexpr int nib = 4; constexpr int njb = 16; constexpr int nkb = 4; #pragma omp for for (int ib = 0; ib < N; ib += nib) { for (int kb = 0; kb < N; kb += nkb) { for (int jb = 0; jb < N; jb += njb) { auto sum00_vec = _mm512_load_pd(&z[N * ib + jb ]); auto sum01_vec = _mm512_load_pd(&z[N * ib + jb + 8]); auto sum10_vec = _mm512_load_pd(&z[N * (ib + 1) + jb ]); auto sum11_vec = _mm512_load_pd(&z[N * (ib + 1) + jb + 8]); auto sum20_vec = _mm512_load_pd(&z[N * (ib + 2) + jb ]); auto sum21_vec = _mm512_load_pd(&z[N * (ib + 2) + jb + 8]); auto sum30_vec = _mm512_load_pd(&z[N * (ib + 3) + jb ]); auto sum31_vec = _mm512_load_pd(&z[N * (ib + 3) + jb + 8]); for (int k = kb; k < kb + nkb; k++) { const auto y0_vec = _mm512_load_pd(&y[N * k + jb ]); const auto y1_vec = _mm512_load_pd(&y[N * k + jb + 8]); const auto x0_vec = _mm512_set1_pd(x[N * ib + k]); const auto x1_vec = _mm512_set1_pd(x[N * (ib + 1) + k]); const auto x2_vec = _mm512_set1_pd(x[N * (ib + 2) + k]); const auto x3_vec = _mm512_set1_pd(x[N * (ib + 3) + k]); sum00_vec = _mm512_fmadd_pd(x0_vec, y0_vec, sum00_vec); sum01_vec = _mm512_fmadd_pd(x0_vec, y1_vec, sum01_vec); sum10_vec = _mm512_fmadd_pd(x1_vec, y0_vec, sum10_vec); sum11_vec = _mm512_fmadd_pd(x1_vec, y1_vec, sum11_vec); sum20_vec = _mm512_fmadd_pd(x2_vec, y0_vec, sum20_vec); sum21_vec = _mm512_fmadd_pd(x2_vec, y1_vec, sum21_vec); sum30_vec = _mm512_fmadd_pd(x3_vec, y0_vec, sum30_vec); sum31_vec = _mm512_fmadd_pd(x3_vec, y1_vec, sum31_vec); } _mm512_store_pd(&z[N * ib + jb ], sum00_vec); _mm512_store_pd(&z[N * ib + jb + 8], sum01_vec); _mm512_store_pd(&z[N * (ib + 1) + jb ], sum10_vec); _mm512_store_pd(&z[N * (ib + 1) + jb + 8], sum11_vec); _mm512_store_pd(&z[N * (ib + 2) + jb ], sum20_vec); _mm512_store_pd(&z[N * (ib + 2) + jb + 8], sum21_vec); _mm512_store_pd(&z[N * (ib + 3) + jb ], sum30_vec); _mm512_store_pd(&z[N * (ib + 3) + jb + 8], sum31_vec); } } } } } __attribute__((noinline)) void reference(const double* __restrict x, const double* __restrict y, double* __restrict z, const int N = mat_size) { #pragma omp parallel for for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) z[N * i + j] += x[N * i + k] * y[N * k + j]; } void check(const double* z_ref, const double* z, const double eps = 1.0e-8) { for (int i = 0; i < mat_size * mat_size; i++) { if (std::abs(z_ref[i] - z[i]) / z[i] >= eps) { std::cout << "mismatch\n"; std::cout << z_ref[i] << " " << z[i] << std::endl; std::exit(1); } } } #define BENCH(repr) \ do { \ using namespace std::chrono; \ const int LOOP = 20; \ const auto beg = system_clock::now(); \ for (int i = 0; i < LOOP; i++) repr; \ const auto end = system_clock::now(); \ const double elapsed = \ duration_cast<milliseconds>(end - beg).count(); \ const double flops = \ mat_size * mat_size * (2.0 * mat_size - 1.0) / ((elapsed * 1.0e-3 / double(LOOP)) * 1.0e9); \ std::cerr << "array " << mat_size << " " << flops << " [GFLOPS] "; \ std::cerr << elapsed << " [ms]\n"; \ } while (0) int main(const int argc, const char* argv[]) { double *x_mat = nullptr; double *y_mat = nullptr; double *z_mat = nullptr; if (argc >= 2) mat_size = std::atoi(argv[1]); const int tot_size = mat_size * mat_size * sizeof(double); posix_memalign((void**)&x_mat, 64, tot_size); posix_memalign((void**)&y_mat, 64, tot_size); posix_memalign((void**)&z_mat, 64, tot_size); double *x_mat_ref = new double [mat_size * mat_size]; double *y_mat_ref = new double [mat_size * mat_size]; double *z_mat_ref = new double [mat_size * mat_size]; #pragma omp parallel for for (int i = 0; i < mat_size * mat_size; i++) { x_mat[i] = double(i + 1); y_mat[i] = double(-i - 1); z_mat[i] = 0.0; } std::copy_n(x_mat, mat_size * mat_size, x_mat_ref); std::copy_n(y_mat, mat_size * mat_size, y_mat_ref); std::copy_n(z_mat, mat_size * mat_size, z_mat_ref); BENCH(reference(x_mat_ref, y_mat_ref, z_mat_ref)); BENCH(dgemm3(x_mat, y_mat, z_mat)); check(z_mat_ref, z_mat); free(x_mat); free(y_mat); free(z_mat); delete [] x_mat_ref; delete [] y_mat_ref; delete [] z_mat_ref; } <file_sep>#!/bin/sh ./triad_hsw.out 67108864 1 ./triad_hsw.out 33554432 1 ./triad_hsw.out 16777216 1 ./triad_hsw.out 8388608 1 ./triad_hsw.out 4194304 1 ./triad_hsw.out 2097152 1 ./triad_hsw.out 1048600 1 ./triad_hsw.out 524288 1 ./triad_hsw.out 262144 1 ./triad_hsw.out 139888 1 ./triad_hsw.out 65536 1 ./triad_hsw.out 32768 1 <file_sep>#!/bin/sh #PJM -L rscgrp=debug-cache #PJM -L node=1 #PJM -L elapse=00:30 #PJM -g gh41 #PJM --omp thread=272 #PJM --mpi proc=1 #PJM -j # export KMP_AFFINITY=verbose,granularity=fine,proclist=[0,1,2,3,4,5,6,7],explicit # ./triad_knl.out 67108864 0 # export KMP_AFFINITY=verbose,granularity=fine,proclist=[0,1,17,18,34,35,51,52],explicit # ./triad_knl.out 67108864 0 export OMP_NUM_THREADS=16 export KMP_AFFINITY=granularity=fine,proclist=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30],explicit ./triad_knl.out 131072 0 export OMP_NUM_THREADS=34 export KMP_AFFINITY=granularity=fine,proclist=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66],explicit ./triad_knl.out 131072 0 export OMP_NUM_THREADS=68 export KMP_AFFINITY=granularity=fine,proclist=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67],explicit ./triad_knl.out 131072 0 export OMP_NUM_THREADS=272 export KMP_AFFINITY=compact ./triad_knl.out 131072 0 <file_sep>KNL = hist_knl.out ASM = hist_knl.s CXX = icpc WARNINGS = -Wall -Wextra CXX_FLAGS = -O3 -std=c++11 $(WARNINGS) -qopenmp -xMIC-AVX512 LIBRARY = -lmemkind PASCAL = hist_pascal.out PTX = hist_pascal.ptx SASS = hist_pascal.sass CUBIN = hist_pascal.cubin NVCC = nvcc CUDA_HOME = /usr/local/cuda # CUDA_HOME=/home/app/cuda/cuda-7.0 NVCCFLAGS = -O3 -std=c++11 -arch=sm_60 -Xcompiler "$(WARNINGS) -O3" -ccbin=g++ -lineinfo -Xptxas -v # NVCCFLAGS = -O3 -std=c++11 -arch=sm_35 -Xcompiler "$(WARNINGS) -O3" -ccbin=g++ -lineinfo -Xptxas -v INCLUDE = -I$(CUDA_HOME)/include -I$(CUDA_HOME)/samples/common/inc knl: $(KNL) $(ASM) pascal: $(PASCAL) $(SASS) $(PTX) $(CUBIN) $(PTX): hist_pascal.cu $(SASS): $(CUBIN) $(CUBIN): hist_pascal.cu .SUFFIXES: .SUFFIXES: .cu .out .cu.out: $(NVCC) $(NVCCFLAGS) $(INCLUDE) $< -o $@ .SUFFIXES: .cu .cubin .cu.cubin: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -cubin $< -o $@ .SUFFIXES: .cubin .sass .cubin.sass: $(CUDA_HOME)/bin/cuobjdump -sass $< | c++filt > $@ .SUFFIXES: .cu .ptx .cu.ptx: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -ptx $< -o $@ .SUFFIXES: .cpp .s .cpp.s: $(CXX) $(CXX_FLAGS) -S $< $(LIBRARY) -o $@ .SUFFIXES: .cpp .out .cpp.out: $(CXX) $(CXX_FLAGS) $< $(LIBRARY) -o $@ clean: rm -f $(KNL) $(ASM) $(PASCAL) $(SASS) $(PTX) $(CUBIN) <file_sep>#!/bin/sh for tb_size in 64 128 256 512 do # ./daxpy_random_pascal.out 67108864 $tb_size # ./daxpy_random_pascal.out 33554432 $tb_size # ./daxpy_random_pascal.out 16777216 $tb_size # ./daxpy_random_pascal.out 8388608 $tb_size # ./daxpy_random_pascal.out 4194304 $tb_size # ./daxpy_random_pascal.out 2097152 $tb_size ./daxpy_random_pascal.out 1048600 $tb_size ./daxpy_random_pascal.out 524288 $tb_size ./daxpy_random_pascal.out 262144 $tb_size ./daxpy_random_pascal.out 139888 $tb_size ./daxpy_random_pascal.out 65536 $tb_size ./daxpy_random_pascal.out 32768 $tb_size ./daxpy_random_pascal.out 16384 $tb_size ./daxpy_random_pascal.out 8192 $tb_size done <file_sep>KNL = triad_knl.out triad_knl_mpi.out triad_knl.s HSW = triad_hsw.out triad_hsw.s SKL = triad_skl.out triad_skl.s CXX = icpc MPI_CXX = mpiicpc WARNINGS = -Wall -Wextra CXX_FLAGS = -O3 -std=c++11 $(WARNINGS) -qopenmp KNL_OPT = -xMIC-AVX512 -qopt-prefetch=4 SKL_OPT = -xCORE-AVX512 HSW_OPT = -xCORE-AVX2 KNL_LIB = -lmemkind PASCAL = triad_pascal.out PTX = triad_pascal.ptx SASS = triad_pascal.sass CUBIN = triad_pascal.cubin CUDA_HOME = /usr/local/cuda ARCH = -arch=sm_60 # CUDA_HOME = /home/app/cuda/cuda-7.0 # ARCH = -arch=sm_35 NVCC = nvcc NVCCFLAGS = -O3 -std=c++11 $(ARCH) -Xcompiler "$(WARNINGS) -O3" -ccbin=g++ -lineinfo -Xptxas -v INCLUDE = -I$(CUDA_HOME)/include -I$(CUDA_HOME)/samples/common/inc hsw: $(HSW) skl: $(SKL) knl: $(KNL) pascal: $(PASCAL) $(SASS) $(PTX) $(CUBIN) $(PTX): triad_pascal.cu $(SASS): $(CUBIN) $(CUBIN): triad_pascal.cu .SUFFIXES: .SUFFIXES: .cu .out .cu.out: $(NVCC) $(NVCCFLAGS) $(INCLUDE) $< -o $@ .SUFFIXES: .cu .cubin .cu.cubin: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -cubin $< -o $@ .SUFFIXES: .cubin .sass .cubin.sass: $(CUDA_HOME)/bin/cuobjdump -sass $< | c++filt > $@ .SUFFIXES: .cu .ptx .cu.ptx: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -ptx $< -o $@ triad_knl.out: triad_knl.cpp $(CXX) $(CXX_FLAGS) $(KNL_OPT) $< $(KNL_LIB) -o $@ triad_knl_mpi.out: triad_knl_mpi.cpp $(MPI_CXX) $(CXX_FLAGS) $(KNL_OPT) $< $(KNL_LIB) -o $@ triad_hsw.out: triad_hsw.cpp $(CXX) $(CXX_FLAGS) $(HSW_OPT) $< -o $@ triad_skl.out: triad_skl.cpp $(CXX) $(CXX_FLAGS) $(SKL_OPT) $< -o $@ triad_knl.s: triad_knl.cpp $(CXX) -S -masm=intel $(CXX_FLAGS) $(KNL_OPT) $< $(KNL_LIB) -o $@ triad_hsw.s: triad_hsw.cpp $(CXX) -S -masm=intel $(CXX_FLAGS) $(HSW_OPT) $< -o $@ triad_skl.s: triad_skl.cpp $(CXX) -S -masm=intel $(CXX_FLAGS) $(SKL_OPT) $< -o $@ clean: rm -f $(KNL) $(HSW) $(SKL) $(PASCAL) $(SASS) $(PTX) $(CUBIN) <file_sep>#!/bin/sh val_size=67108864 export OMP_NUM_THREADS=68 export KMP_AFFINITY=granularity=fine,proclist=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67],explicit for sd in 0 1000 500 100 do ./hist_knl.out $val_size 1000 $sd done export OMP_NUM_THREADS=272 export KMP_AFFINITY=compact for sd in 0 1000 500 100 do ./hist_knl.out $val_size 1000 $sd done <file_sep>KNL = overhead_knl.out ASM = overhead_knl.s CXX = icpc WARNINGS = -Wall -Wextra CXX_FLAGS = -O3 -std=c++11 $(WARNINGS) -qopenmp -xMIC-AVX512 -qopt-prefetch=4 LIBRARY = -lmemkind PASCAL = overhead_pascal.out PTX = overhead_pascal.ptx SASS = overhead_pascal.sass CUBIN = overhead_pascal.cubin CUDA_HOME = /usr/local/cuda NVCC = nvcc NVCCFLAGS = -O3 -std=c++11 -arch=sm_60 -Xcompiler "$(WARNINGS) -O3" -ccbin=g++ -lineinfo -Xptxas -v INCLUDE = -I$(CUDA_HOME)/include -I$(CUDA_HOME)/samples/common/inc knl: $(KNL) $(ASM) pascal: $(PASCAL) $(SASS) $(PTX) $(CUBIN) $(PTX): overhead_pascal.cu $(SASS): $(CUBIN) $(CUBIN): overhead_pascal.cu .SUFFIXES: .SUFFIXES: .cu .out .cu.out: $(NVCC) $(NVCCFLAGS) $(INCLUDE) $< -o $@ .SUFFIXES: .cu .cubin .cu.cubin: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -cubin $< -o $@ .SUFFIXES: .cubin .sass .cubin.sass: $(CUDA_HOME)/bin/cuobjdump -sass $< | c++filt > $@ .SUFFIXES: .cu .ptx .cu.ptx: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -ptx $< -o $@ .SUFFIXES: .cpp .s .cpp.s: $(CXX) $(CXX_FLAGS) -S -masm=intel $< $(LIBRARY) -o $@ .SUFFIXES: .cpp .out .cpp.out: $(CXX) $(CXX_FLAGS) $< $(LIBRARY) -o $@ clean: rm -f $(KNL) $(ASM) $(PASCAL) $(SASS) $(PTX) $(CUBIN) <file_sep>KNL = daxpy_random_knl.out daxpy_random_knl.s CXX = icpc WARNINGS = -Wall -Wextra CXX_FLAGS = -O3 -std=c++11 $(WARNINGS) -qopenmp KNL_OPT = -xMIC-AVX512 -qopt-prefetch=4 KNL_LIB = -lmemkind PASCAL = daxpy_random_pascal.out PTX = daxpy_random_pascal.ptx SASS = daxpy_random_pascal.sass CUBIN = daxpy_random_pascal.cubin CUDA_HOME = /usr/local/cuda ARCH = -arch=sm_60 # CUDA_HOME = /home/app/cuda/cuda-7.0 # ARCH = -arch=sm_35 NVCC = nvcc NVCCFLAGS = -O3 -std=c++11 $(ARCH) -Xcompiler "$(WARNINGS) -O3" -ccbin=g++ -lineinfo -Xptxas -v INCLUDE = -I$(CUDA_HOME)/include -I$(CUDA_HOME)/samples/common/inc knl: $(KNL) pascal: $(PASCAL) $(SASS) $(PTX) $(CUBIN) $(PTX): daxpy_random_pascal.cu $(SASS): $(CUBIN) $(CUBIN): daxpy_random_pascal.cu .SUFFIXES: .SUFFIXES: .cu .out .cu.out: $(NVCC) $(NVCCFLAGS) $(INCLUDE) $< -o $@ .SUFFIXES: .cu .cubin .cu.cubin: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -cubin $< -o $@ .SUFFIXES: .cubin .sass .cubin.sass: $(CUDA_HOME)/bin/cuobjdump -sass $< | c++filt > $@ .SUFFIXES: .cu .ptx .cu.ptx: $(NVCC) $(NVCCFLAGS) $(INCLUDE) -ptx $< -o $@ daxpy_random_knl.out: daxpy_random_knl.cpp $(CXX) $(CXX_FLAGS) $(KNL_OPT) $< $(KNL_LIB) -o $@ daxpy_random_knl.s: daxpy_random_knl.cpp $(CXX) -S -masm=intel $(CXX_FLAGS) $(KNL_OPT) $< $(KNL_LIB) -o $@ clean: rm -f $(KNL) $(PASCAL) $(SASS) $(PTX) $(CUBIN) <file_sep>#include <iostream> #include <chrono> #include <omp.h> void func(const int loop = 10000) { using namespace std::chrono; const auto beg = system_clock::now(); for (int i = 0; i < loop; i++) { #pragma omp parallel {} } const auto end = system_clock::now(); std::cout << static_cast<double>(duration_cast<microseconds>(end - beg).count()) / static_cast<double>(loop) << " [microseconds]\n"; } int main() { func(); } <file_sep>#!/bin/sh export OMP_NUM_THREADS=68 export KMP_AFFINITY=noverbose,granularity=fine,scatter for i in 2000 3000 5000 8000 10000 16000 32000 do ./dgemm_mkl_knl.out $i done <file_sep>#!/bin/sh # export OMP_NUM_THREADS=16 # export KMP_AFFINITY=granularity=fine,proclist=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30],explicit # export OMP_NUM_THREADS=34 # export KMP_AFFINITY=granularity=fine,proclist=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66],explicit export OMP_NUM_THREADS=68 export KMP_AFFINITY=granularity=fine,proclist=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67],explicit # export OMP_NUM_THREADS=272 # export KMP_AFFINITY=compact # flat mode # for touch in 0 1 # do # for use_mcdram in 0 1 # do # ./daxpy_random_knl.out 67108864 $use_mcdram $touch # ./daxpy_random_knl.out 33554432 $use_mcdram $touch # ./daxpy_random_knl.out 16777216 $use_mcdram $touch # ./daxpy_random_knl.out 8388608 $use_mcdram $touch # ./daxpy_random_knl.out 4194304 $use_mcdram $touch # ./daxpy_random_knl.out 2097152 $use_mcdram $touch # ./daxpy_random_knl.out 1048600 $use_mcdram $touch # ./daxpy_random_knl.out 524288 $use_mcdram $touch # ./daxpy_random_knl.out 262144 $use_mcdram $touch # ./daxpy_random_knl.out 139888 $use_mcdram $touch # ./daxpy_random_knl.out 65536 $use_mcdram $touch # ./daxpy_random_knl.out 32768 $use_mcdram $touch # done # done # cache mode # for touch in 0 1 # do touch=1 # ./daxpy_random_knl.out 67108864 0 $touch # ./daxpy_random_knl.out 33554432 0 $touch # ./daxpy_random_knl.out 16777216 0 $touch # ./daxpy_random_knl.out 8388608 0 $touch # ./daxpy_random_knl.out 4194304 0 $touch # ./daxpy_random_knl.out 2097152 0 $touch ./daxpy_random_knl.out 1048600 0 $touch ./daxpy_random_knl.out 524288 0 $touch ./daxpy_random_knl.out 262144 0 $touch ./daxpy_random_knl.out 139888 0 $touch ./daxpy_random_knl.out 65536 0 $touch ./daxpy_random_knl.out 32768 0 $touch ./daxpy_random_knl.out 16384 0 $touch ./daxpy_random_knl.out 8192 0 $touch # done <file_sep>#include <iostream> #include <algorithm> #include <random> #include <chrono> typedef int Dtype; // typedef double Dtype; __attribute__((noinline)) void make_hist(const int* val, Dtype* bin, const int val_size) { #pragma omp parallel for for (int i = 0; i < val_size; i++) { #pragma omp atomic bin[val[i]]++; } } __attribute__((noinline)) void make_hist_critical(const int* val, Dtype* bin, const int val_size) { #pragma omp parallel for for (int i = 0; i < val_size; i++) { #pragma omp critical { bin[val[i]]++; } } } __attribute__((noinline)) void reference(const int* val, Dtype* bin, const int val_size) { for (int i = 0; i < val_size; i++) { bin[val[i]] += 1.0; } } __attribute__((noinline)) void reference_novector(const int* val, Dtype* bin, const int val_size) { #pragma novector for (int i = 0; i < val_size; i++) { bin[val[i]] += 1.0; } } void first_touch(int* val, const int val_size, Dtype* bin, const int bin_size) { #pragma omp parallel for for (int i = 0; i < val_size; i++) { val[i] = 0; } #pragma omp parallel for for (int i = 0; i < bin_size; i++) { bin[i] = 0.0; } } void check(const Dtype* bin_ref, const Dtype* bin, const int size) { for (int i = 0; i < size; i++) { if (bin_ref[i] != bin[i]) { std::cout << "mismatch\n"; std::cout << bin_ref[i] << " " << bin[i] << std::endl; std::exit(1); } } } #define BENCH(repr, max, size, sd) \ do { \ using namespace std::chrono; \ const int LOOP = 100; \ const auto beg = system_clock::now(); \ for (int i = 0; i < LOOP; i++) repr; \ const auto end = system_clock::now(); \ const double dur = duration_cast<milliseconds>(end - beg).count(); \ std::cerr << "range [0 : " << max << "] "; \ if (sd == 0) { \ std::cerr << "uniform "; \ } else { \ std::cerr << "sd " << sd << " "; \ } \ std::cerr << "array size " << size << " "; \ std::cerr << dur << " [ms]\n"; \ } while (0) int main(const int argc, const char* argv[]) { int val_size = 10000000; int bin_size = 1000; double sd = 0; if (argc >= 2) val_size = std::atoi(argv[1]); if (argc >= 3) bin_size = std::atoi(argv[2]); if (argc >= 4) sd = std::atof(argv[3]); // allocate resources int *val = nullptr, *val_ref = nullptr, *val_ref2 = nullptr, *val_ref3 = nullptr; Dtype *bin = nullptr, *bin_ref = nullptr, *bin_ref2 = nullptr, *bin_ref3 = nullptr; posix_memalign((void**)&val, 64, val_size * sizeof(int)); posix_memalign((void**)&bin, 64, bin_size * sizeof(Dtype)); posix_memalign((void**)&val_ref, 64, val_size * sizeof(int)); posix_memalign((void**)&bin_ref, 64, bin_size * sizeof(Dtype)); posix_memalign((void**)&val_ref2, 64, val_size * sizeof(int)); posix_memalign((void**)&bin_ref2, 64, bin_size * sizeof(Dtype)); posix_memalign((void**)&val_ref3, 64, val_size * sizeof(int)); posix_memalign((void**)&bin_ref3, 64, bin_size * sizeof(Dtype)); // dist L2 cache data first_touch(val, val_size, bin, bin_size); // initialize std::mt19937 mt; if (sd == 0) { std::uniform_int_distribution<> uid(0, bin_size - 1); std::generate_n(val, val_size, [&mt, &uid](){return uid(mt);}); } else if (sd > 0.0) { std::normal_distribution<> nd(bin_size / 2, sd); int cnt = 0; while (true) { const auto ret = int(std::floor(nd(mt))); if (ret >= 0 && ret < bin_size) val[cnt++] = ret; if (cnt == val_size) break; } } else { std::cerr << "sd should be >= 0.\n"; std::exit(1); } std::copy_n(val, val_size, val_ref); std::copy_n(val, val_size, val_ref2); std::copy_n(val, val_size, val_ref3); std::fill_n(bin, bin_size, 0.0); std::copy_n(bin, bin_size, bin_ref); std::copy_n(bin, bin_size, bin_ref2); std::copy_n(bin, bin_size, bin_ref3); BENCH(reference(val_ref, bin_ref, val_size), bin_size, val_size, sd); BENCH(reference_novector(val_ref2, bin_ref2, val_size), bin_size, val_size, sd); BENCH(make_hist(val, bin, val_size), bin_size, val_size, sd); BENCH(make_hist_critical(val_ref3, bin_ref3, val_size), bin_size, val_size, sd); check(bin_ref, bin, bin_size); check(bin_ref2, bin_ref, bin_size); check(bin_ref3, bin_ref, bin_size); free(val); free(bin); free(val_ref); free(bin_ref); free(val_ref2); free(bin_ref2); free(val_ref3); free(bin_ref3); } <file_sep>#!/bin/sh for tb_size in 64 128 256 512 do ./triad_pascal.out 67108864 $tb_size ./triad_pascal.out 33554432 $tb_size ./triad_pascal.out 16777216 $tb_size ./triad_pascal.out 8388608 $tb_size ./triad_pascal.out 4194304 $tb_size ./triad_pascal.out 2097152 $tb_size ./triad_pascal.out 1048600 $tb_size ./triad_pascal.out 524288 $tb_size ./triad_pascal.out 262144 $tb_size ./triad_pascal.out 139888 $tb_size ./triad_pascal.out 65536 $tb_size ./triad_pascal.out 32768 $tb_size done <file_sep>#!/bin/sh for i in 4000 5000 8000 10000 16000 32000 do ./sgemm_cublas_pascal.out $i done <file_sep>#!/bin/sh val_size=67108864 for sd in 0 1000 500 100 10 do ./hist_pascal.out $val_size 1000 $sd done <file_sep>KNL = dgemm_knl.out dgemm_mkl_knl.out ASM = dgemm_knl.s CXX = icpc WARNINGS = -Wall -Wextra CXX_INCLUDE = CXX_LIBS = CXX_FLAGS = -qopenmp -O3 -std=c++11 $(WARNINGS) -mkl=parallel -xMIC-AVX512 PASCAL = dgemm_pascal.out dgemm_cublas_pascal.out PTX = dgemm_pascal.ptx SASS = dgemm_pascal.sass CUBIN = dgemm_pascal.cubin NVCC = nvcc CUDA_HOME = /usr/local/cuda ARCH = -arch=sm_60 # CUDA_HOME = /home/app/cuda/cuda-7.0 # ARCH = -arch=sm_35 NVCCFLAGS = -O3 -std=c++11 $(ARCH) -Xcompiler "$(WARNINGS) -O3 -fopenmp" -ccbin=g++ -lineinfo -Xptxas -v NVCCINCLUDE = -I$(CUDA_HOME)/include -I$(CUDA_HOME)/samples/common/inc NVCCLIBS = -lcublas knl: $(KNL) $(ASM) pascal: $(PASCAL) $(SASS) $(PTX) $(CUBIN) $(PTX): dgemm_pascal.cu $(SASS): $(CUBIN) $(CUBIN): dgemm_pascal.cu .SUFFIXES: .SUFFIXES: .cu .out .cu.out: $(NVCC) $(NVCCFLAGS) $(NVCCINCLUDE) $< $(NVCCLIBS) -o $@ .SUFFIXES: .cu .cubin .cu.cubin: $(NVCC) $(NVCCFLAGS) $(NVCCINCLUDE) -cubin $< $(NVCCLIBS) -o $@ .SUFFIXES: .cubin .sass .cubin.sass: $(CUDA_HOME)/bin/cuobjdump -sass $< | c++filt > $@ .SUFFIXES: .cu .ptx .cu.ptx: $(NVCC) $(NVCCFLAGS) $(NVCCINCLUDE) -ptx $< $(NVCCLIBS) -o $@ .SUFFIXES: .cpp .s .cpp.s: $(CXX) $(CXX_FLAGS) $(CXX_INCLUDE) -S -masm=intel $< $(CXX_LIBS) -o $@ .SUFFIXES: .cpp .out .cpp.out: $(CXX) $(CXX_FLAGS) $(CXX_INCLUDE) $< $(CXX_LIBS) -o $@ clean: rm -f $(KNL) $(ASM) $(PASCAL) $(SASS) $(PTX) $(CUBIN) <file_sep>#!/bin/sh # without mcdram mpiexec.hydra -n 4 ./triad_knl_mpi.out 67108864 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 33554432 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 16777216 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 8388608 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 4194304 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 2097152 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 1048576 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 524288 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 262144 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 131072 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 65536 0 mpiexec.hydra -n 4 ./triad_knl_mpi.out 32768 0 # with mcdram mpiexec.hydra -n 4 ./triad_knl_mpi.out 67108864 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 33554432 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 16777216 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 8388608 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 4194304 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 2097152 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 1048576 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 524288 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 262144 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 131072 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 65536 1 mpiexec.hydra -n 4 ./triad_knl_mpi.out 32768 1 <file_sep>#!/bin/sh export OMP_NUM_THREADS=68 export KMP_AFFINITY=noverbose,granularity=fine,scatter for i in 4000 5000 8000 10000 16000 32000 40000 do ./sgemm_mkl_knl.out $i done
8d72e263d76cf5cadc49824d527ccbf09312af86
[ "Makefile", "C++", "Shell" ]
22
Shell
kohnakagawa/knl_vs_p100
e277918d2eb949a4188531c23e7ad5d75fee7a40
0c246c00123689aad3644dce441191f38bc7dd8b
refs/heads/master
<repo_name>Peachysalmon/nameofapp<file_sep>/spec/models/product_spec.rb require 'rails_helper' describe Product do let (:product) { Product.create!(name: "race bike") } let (:user) { User.create!(email: "<EMAIL>", password: "<PASSWORD>") } before do product.comments.create!(rating: 1, user: user, body: "Awful bike!") product.comments.create!(rating: 3, user: user, body: "Ok bike!") product.comments.create!(rating: 5, user: user, body: "Great bike!") end it "returns the average rating of all comments" do expect(product.comments.average_rating).to eq 3 end end
a453eaf549b3d7ebd6d7cd22144c1a4a1c7de0b7
[ "Ruby" ]
1
Ruby
Peachysalmon/nameofapp
6d4087fd9867ec067f67d05a693de29ef1e95d4d
f2b056fcfce3ab93b27ea62023e92a44e0b5d2df
refs/heads/main
<repo_name>ravi0818/Signup-Login<file_sep>/README.md http://ravi.infinityfreeapp.com/ <file_sep>/index.php <?php session_start(); $_SESSION['loggedin'] = false; ?> <?php include 'snippet/config.php'; if ($_SERVER["REQUEST_METHOD"] == "POST") { $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $dob = $_POST['dob']; $password = $_POST['password']; $cpassword = $_POST['cpassword']; if ($password != $cpassword) { echo '<script>alert("Password mismatch")</script>'; } else if (strlen($password) < 8) { echo '<script>alert("Password is too short")</script>'; } else { $sql = "SELECT * FROM user_details WHERE email='$email'"; $result = mysqli_query($conn, $sql); $num = mysqli_num_rows($result); if ($num == 0) { $sql = "INSERT INTO user_details (fname,lname,dob, email, password) VALUES ('$fname','$lname','$dob', '$email', '$password')"; $result = mysqli_query($conn, $sql); if ($result) { header("location: login.php"); } else { echo '<script>alert("Error")</script>'; } } else { echo '<script>alert("Email is already registered")</script>'; } } } ?> <!DOCTYPE html> <html> <head> <title></title> <?php include 'snippet/links.php' ?> </head> <body> <div class="container-fluid"> <div class="row"> <?php include 'snippet/leftside.php' ?> <div class="col-lg-6 mx-auto form-div"> <h2 class="text-center">Sign up</h2><br> <form action="" method="POST"> <div class="row form-group"> <div class="col"> <label for="fname">First Name</label> <input type="text" class="form-control" placeholder="First name" name="fname" required> </div> <div class="col"> <label for="lname">Last Name</label> <input type="text" class="form-control" placeholder="Last name" name="lname" required> </div> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" class="form-control" placeholder="Email" name="email" required> </div> <div class="form-group" style="width:48%"> <label for="dob">Date of Birth</label> <input type="date" class="form-control" placeholder="" name="dob" required> </div> <div class="row form-group"> <div class="col"> <label for="password">Password</label> <input type="<PASSWORD>" class="form-control" placeholder="Minimum 8 characters" name="password" required> </div> <div class="col"> <label for="cpassword">Confirm Password</label> <input type="<PASSWORD>" class="form-control" placeholder="Confirm Password" name="cpassword" required> </div> </div> <div class="form-group form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox"> Remember me </label> </div><br> <button type="submit" class="btn btn-primary">Sign Up</button> </form> <div class="pt-5"> <sapn>Existing user? <a href="login.php">Log in</a></span> </div> </div> </div> </div> <?php $conn->close(); ?> </body> </html><file_sep>/dashboard.php <?php session_start(); if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != true) { header("location: index.php"); exit; } ?> <!DOCTYPE html> <html> <head> <title></title> <?php include 'snippet/links.php' ?> </head> <body> <div class="container-fuild dashboard"> <div class="row"> <div class='col-lg-3 mx-auto p-2' style="margin-top:20%"> <div>Logged in successfully.....</div><br> <a href="snippet/logout.php" class="btn btn-primary p-3 w-100">Log Out</a> </div> </div> </div> </body> </html><file_sep>/login.php <?php session_start(); $_SESSION['loggedin'] = false; ?> <?php include 'snippet/config.php'; if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = $_POST['email']; $password = $_POST['password']; $sql = "SELECT * FROM user_details WHERE email='$email' AND password='$<PASSWORD>'"; $result = mysqli_query($conn, $sql); $num = mysqli_num_rows($result); if ($num == 1) { session_start(); $_SESSION['loggedin'] = true; header("location: dashboard.php"); } else { echo '<script>alert("Invalid Credentials")</script>'; } } ?> <!DOCTYPE html> <html> <head> <title></title> <?php include 'snippet/links.php' ?> </head> <body> <div class="container-fluid"> <div class="row"> <?php include 'snippet/leftside.php' ?> <div class="col-lg-6 mx-auto form-div"> <h2 class="text-center">Log in</h2><br> <form action="" method="POST"> <div class="form-group"> <label for="email">Email</label> <input type="text" class="form-control" placeholder="Email" name="email" required> </div> <div class="form-group"> <label for="password">Password</label> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" required> </div> <div class="form-group form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox"> Remember me </label> </div><br> <button type="submit" class="btn btn-primary">Log in</button> </form> <div class="pt-5"> <sapn>Not registered? <a href="index.php">Sign up</a></span> </div> </div> </div> </div> <?php $conn->close(); ?> </body> </html>
92109b269bfb92382cb9a5e6dd03423811ba604d
[ "Markdown", "PHP" ]
4
Markdown
ravi0818/Signup-Login
5f5ec90ab36c3e1c3ce3276efabd6d7a43355623
eaef3a353ac3571423baceaae92de7db3bc5f154
refs/heads/master
<repo_name>Abderrahim01/elleptic_curve_encryption<file_sep>/ellipticcurve.py class EllipticCurve(object): def __init__(self, a, b, p): self.a = a self.b = b self.p = p def __eq__(self, C): return (self.a,self.b) == (C.a,C.b) def has_point(self, x, y): return (y**2) % self.p == (x ** 3 + self.a * x + self.b ) % self.p def __str__(self): return 'y^2 = x^3 + {}x+ {}'.format(self.a, self.b) <file_sep>/Test1.py from random import randint from point import Point, Inf from ellipticcurve import EllipticCurve from gen import Gen from string import ascii_lowercase ## # # Fontions utilise pour le TP # ## # Fonction pour le teste de primalite # def isPrime(num): for x in range(int(num) - 1, 1, -1): if int(num) % x == 0: return False ## Fonction pour chiffrer un message # def chiffrer(m, pubR, g): k = randint(1, g.get_modulo() - 1) inf = Inf(g.point.curve) y1 = k * g.point y2 = m + (pubR * k) while y1 == inf or y2 == inf: k = randint(1, g.get_modulo() - 1) y1 = k * g.point y2 = m + (pubR * k) return y1, y2 ## Fonction pour dechiffrer un message # def dechiffrer(y1, y2, privR): return (y2 + (-y1 * privR)) ## Debut du TP a = 1 b = 6 p = 137 c = EllipticCurve(a, b, p) inf = Inf(c) # list_char = ['!','"','#','$','%','&','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','^','_','`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~','[',']'] list_gen = [] ## Generer la liste des generateurs avec leur ordre pour une courbe elliptique for i in range(p): for y in range(p): if c.has_point(i, y): point = Point(c, i, y) p2 = point #n = 1 list_point = [] list_point.append(point) while True: tmp = point point = point + p2 if point == inf: break list_point.append(point) #n = n + 1 list_gen.append(Gen(tmp, (len(list_point) + 1))) for gen in list_gen: print(gen) ## Choix du generateur gen = list_gen[8] ## Generation des cles pour Alice et Bob privB, pubB = gen.gen_keys() privA, pubA = gen.gen_keys() ##Question 1 & Question 2 : ## On cree un message en forme de point eliptirque de la courbe m = gen.point * 90 print 'Generateur : {}, cle genere pour Bob : {}, {}'.format(str(gen), privB, pubB) print 'Generateur : {}, cle genere pour Alice : {}, {}'.format(str(gen), privA, pubA) ## Chiffrement du point y1, y2 = chiffrer(m, pubB, gen) print 'Message clair {}, Message chiffre : {},{}'.format(m, y1, y2) message_dechiffre = dechiffrer(y1, y2, privB) print 'Message chiffre {},{}, Message clair : {}'.format(y1, y2, message_dechiffre) print print ##Question 5 : with open('test', 'r') as f: text = f.read() n = 1 lettre_p = [] for lettre in text: n = n + 1 lettre_p.append((lettre, gen.point * n)) for i, p in lettre_p: print(i + ' ' + str(p)) list_ltr_p_c = [] for lettre, ltr_p in lettre_p: y1, y2 = chiffrer(ltr_p, pubB, gen) print 'Message clair {}, Message chiffre : {},{}'.format(ltr_p, y1, y2) list_ltr_p_c.append((y1, y2)) print print for y1,y2 in list_ltr_p_c: print("{} {}".format(y1,y2)) phrase = "" for y1, y2 in list_ltr_p_c: message_dechiffre = dechiffrer(y1, y2, privB) print 'Message chiffre {},{}, Message clair : {}'.format(y1, y2, message_dechiffre) for lettre, ltr_p in lettre_p: if ltr_p == message_dechiffre: print lettre phrase = phrase + lettre print(phrase) ##Question 7 : print("Donnez cle prive pour dechiffree : ") privtest = int(input("Entrer cle priv :")) print("Message a dechiffrer : ") x1 = int(input("y1_x : ")) y1 = int(input("y1_y : ")) y1_c = Point(c,x1,y1) x1 = int(input("y2_x : ")) y1 = int(input("y2_y : ")) y2_c = Point(c,x1,y1) message_dechiffre = dechiffrer(y1_c,y2_c,privtest) print("Message chiffre {},{}, message en clair : {}".format(y1_c,y2_c,message_dechiffre)) ##Question 8 : ''' list_char2 = list(ascii_lowercase) list_char2 = list_char2 + ['1', '2', '4', '5', '6', '7', '8', '9', '0', '#', '@', '!', '&', '$', '%'] list_char2.insert(0, '*') p = 37 c8 = EllipticCurve(2, 9, p) inf = Inf(c8) list_point = [] list_gen = [] for i in range(p): for y in range(p): if c.has_point(i, y): point = Point(c, i, y) point2 = Point(c, i, y) n = 1 list_point = [] list_point.append(point2) while True: point2 = point2 + point if point2 == inf: break list_point.append(point2) n = n + 1 list_gen.append(Gen(point, (len(list_point) + 1))) ''' <file_sep>/gen.py from random import randint from point import Point, Inf class Gen(Point): def __init__(self, point, ordre): self.point = point self.ordre = ordre def __eq__(self, G): return (self.curve, self.x, self.y, self.ordre) == (G.curve, G.x, G.y, G.ordre) def __str__(self): return '({}, {}), {}'.format(self.point.x, self.point.y, self.ordre) def get_modulo(self): return self.point.curve.p def gen_keys(self): inf = Inf(self.point.curve) priv = randint(1, self.ordre - 1) pub = self.point * priv while pub == inf: priv = randint(1, self.ordre - 1) pub = self.point * priv return priv, pub <file_sep>/point.py class Point(object): def __init__(self, curve, x, y): self.curve = curve self.x = x % curve.p self.y = y % curve.p if not self.curve.has_point(x, y): raise ValueError('{} is not on curve {}'.format(self, self.curve)) def __str__(self): return '({}, {})'.format(self.x, self.y) def __getitem__(self, index): return [self.x, self.y][index] def __eq__(self, Q): return (self.curve, self.x, self.y) == (Q.curve, Q.x, Q.y) def __neg__(self): return Point(self.curve, self.x, -self.y) def __mul__(self,n): assert isinstance(n, (int, long)) assert n > 0 n = n % self.curve.p if n == 0: return Inf(self.curve) else: Q = self R = Inf(self.curve) i = 1 while i <= n: if n & i == i: R = R + Q Q = Q + Q i = i << 1 return R def __rmul__(self, n): return self * n def __add__(self, Q): """Add two points together. We need to take care of special cases: * Q is the infinity point (0) * P == Q * The line crossing P and Q is vertical. """ assert self.curve == Q.curve # 0 + P = P if isinstance(Q, Inf): return self xp, yp, xq, yq = self.x, self.y, Q.x, Q.y m = None # P == Q if self == Q: if self.y == 0: R = Inf(self.curve) else: m = ((3 * xp * xp + self.curve.a) * mod_inverse(2 * yp, self.curve.p)) % self.curve.p # Vertical line elif xp == xq : R = Inf(self.curve) # Common case else: m = ((yq - yp) * mod_inverse(xq - xp, self.curve.p)) % self.curve.p if m is not None: xr = (m ** 2 - xp - xq) % self.curve.p yr = (m * (xp - xr) - yp) % self.curve.p R = Point(self.curve, xr, yr) return R class Inf(Point): def __init__(self,curve): self.curve=curve def __eq__(self,Q): return isinstance(Q,Inf) def __neg__(self): return self def __add__(self,Q): return Q def __str__(self): return 'INF' def mod_inverse(a, n): ##Return the inverse of a mod n. b = n if abs(b) == 0: return (1, 0, a) x1, x2, y1, y2 = 0, 1, 1, 0 while abs(b) > 0: q, r = divmod(a, b) x = x2 - q * x1 y = y2 - q * y1 a, b, x2, x1, y2, y1 = b, r, x1, x, y1, y return x2 % n <file_sep>/Test2.py from ellipticcurve import EllipticCurve from point import Point,Inf from gen import Gen from math import * modulo=11 c = EllipticCurve(1,6,modulo) inf = Inf(c) list_gen = [] for i in range(modulo): for y in range(modulo): if c.has_point(i, y): point = Point(c, i, y) p2 = point list_point = [] list_point.append(point) while True: tmp = point point = point + p2 if point == inf: break list_point.append(point) list_gen.append(Gen(tmp, (len(list_point) + 1))) print print "Liste des point de la courbe :" for i in list_gen: print i print print "P =" ,list_gen[0] P = list_gen[0] print print "Calculer l'ensemble G : " i=1 p2 = inf list_L = [] while True: print str(P.point)," * ",i," = ",str((P.point+p2)) if (P.point+p2) == inf: r = i break else: i = i + 1 p2 = P.point + p2 print "Ordre = ",r m = int(round(sqrt(r))) print "m = ",m p2 = P.point for i in range(m-1): list_L.append(p2) p2 = p2 + P.point s = -p2 print print "Liste L :" for l in list_L: print(l) print "s =",str(s) print print "Choix de la cle prive" q = 5 * P.point print "Q = ", str(q) list_j = [] for j in range(1,m-1): p3 = (j * s) + q if p3 in list_L: list_j.append((j,p3)) print print print("List j :") for i, p2 in list_j: print i," ",str(p2) print print for i in range(1,m-1): for j, p2 in list_j: if p2 in list_L and p2 == i*P.point: print 'point :', i*P.point print "Cle prive : ",((i+m*j)%modulo)
29e05cefd97086a730457fd1a3468b9a58ae0b7f
[ "Python" ]
5
Python
Abderrahim01/elleptic_curve_encryption
7ce4342db9fcf863f13bf2c9c37daad981e7346d
645139ce4464f31ba8b2c2a6b0e32c471f4d1da7
refs/heads/master
<file_sep>/* * 创建标注 */ export default function creatLabelLayer (map,options) { if(!options.hasOwnProperty("id")||!map){ throw new Error("标注图层必须要要传入地图和id"); return; } map.addLayer({ "id": `${options.id}`, "type": "symbol", "source": { type: `${options.sourceType}`,//'geojson', data: options.data }, "interactive":options.interactive, "layout": { "text-size": { base: options.textSize||14, stops:options.stops||[[3, 12], [7, 14], [15, 16]], }, "text-font": options.font|| ["Microsoft YaHei Regular"], "text-max-width": 20, "text-offset": [0, 0.2], "text-anchor": options.anchor||"top", "text-field": ['get','space'], }, "paint": { "text-color": `${options.color||'#333'}`, "text-halo-color": `${options.haloColor||"#fff"}`, "text-halo-width": options.haloWidth||1.25, }, }); } <file_sep>export default function changeOpacity(map,options) { let opacityNum =options.opacityVal; switch (options.layerType) { case "蜂巢图": case "格网图": for(let val of options.layerArr){ let layer = map.getLayer(val); if(layer){ let data = layer.getData()._data; let mapVOptions = layer.mapVOptions; mapVOptions.globalAlpha = parseInt(opacityNum, 10) / 100; layer.update(data, mapVOptions); } } break; case "热力图": for(let val of options.layerArr){ let layer = map.getLayer(val); if(layer){ layer.setOpacity(parseInt(opacityNum, 10) / 100); } } break; default: for(let val of options.layerArr){ let layer = map.getLayer(val); if(layer){ if (layer.type === "fill-extrusion") { map.setPaintProperty(layer.id, "fill-extrusion-opacity", parseInt(opacityNum, 10) / 100); }else if (layer.type === "raster") { map.setPaintProperty(layer.id, "raster-opacity", parseInt(opacityNum, 10) / 100); }else if (layer.type === "fill") { let num = layer.id.indexOf("drill")!=-1&&.2||1; map.setPaintProperty(layer.id, "fill-opacity", parseInt(opacityNum, 10) / 100*num); } else if (layer.type === "line") { map.setPaintProperty(layer.id, "line-opacity", parseInt(opacityNum, 10) / 100); } else if (layer.type === "symbol"&&layer.id.indexOf("font")!=-1) { map.setPaintProperty(layer.id, "text-opacity", parseInt(opacityNum, 10) / 100); }else if (layer.type === "symbol"&&layer.id.indexOf("icon")!=-1){ map.setPaintProperty(layer.id, "icon-opacity", parseInt(opacityNum, 10) / 100); }else if(layer.type === 'circle'){ map.setPaintProperty(layer.id, "circle-opacity", parseInt(opacityNum,10) / 100); } else if(layer.props&&layer.props.colorRange){ let colorRange = layer.props.colorRange; for (let i = 0, l = colorRange.length; i < l; i++) { colorRange[i][3] = (parseInt(opacityNum, 10) / 100) * 255; } layer.setStyle({ colorRange }); layer.update(); } } } } } <file_sep>import GetColorVal from './getColorValClass'; import getJenksBreaks from './getJenksBreaks'; export default function resetLegendArrFn(valueArr,legendType,colorArr){ let legendArr = [], MINNUM = Math.min.call(null, ...valueArr),colorLegendArr=[]; let jenksArrTemp = getJenksBreaks(valueArr, colorArr.length-1); let jenksArr = jenksArrTemp.map((item, index) => parseInt(item) || 0); if (jenksArr && jenksArr.length > 1) { for (let i = 0, l = jenksArr.length; i < l; i++) { if (i === 0) { if (parseInt(MINNUM) <= jenksArr[0]) { legendArr.push({ type: legendType, value: colorArr[i], caption: `${parseFloat(MINNUM).toFixed(0)}~${Math.floor(jenksArr[i + 1])}` }) }else { legendArr.push({ type: legendType, value: colorArr[i], caption: `${parseFloat(jenksArr[0]).toFixed(0)}~${Math.floor(jenksArr[i + 1])}` }) } colorLegendArr.push([Math.floor(jenksArr[i + 1]),new GetColorVal(colorArr[i]).colorRGB2Hex()]); }else if(i!==l-1){ legendArr.push({ type: legendType, value: colorArr[i], caption: `${Math.ceil(jenksArr[i])}~${Math.ceil(jenksArr[i + 1])}` }) colorLegendArr.push([Math.floor(jenksArr[i + 1]),new GetColorVal(colorArr[i]).colorRGB2Hex()]); } } } else if (jenksArr.length === 1) { let name = Math.ceil(jenksArr[0])>0&&`0 ~ ${Math.ceil(jenksArr[0])}`||Math.ceil(jenksArr[0])===0&&`-1 ~ 0`||Math.ceil(jenksArr[0])<0&&`${Math.ceil(jenksArr[0])} ~ 0`; legendArr.push({ type: legendType, value: colorArr[0], caption:name }) colorLegendArr.push([Math.ceil(jenksArr[0]),new GetColorVal((colorArr[0])).colorRGB2Hex()]); } else { throw new Error("重置图例数据传参有误!"); } return [legendArr,colorLegendArr]; } <file_sep>//import addImgLoad from "../addImgLoad"; export default function createMVTLayer(map, options){ return new Promise(async resolve => { if(!options.hasOwnProperty("url")||!options.hasOwnProperty("id")){ throw new Error("mvt服务传参必须要有服务url和服务Id"); return; } //await addImgLoad(map,options); let url =options.url; if(url&&url.indexOf('.json')!==-1){ map.addStyle( `${url}`); }else { map.addStyle( `${url}/tileFeature/vectorstyles.json?type=MapBox_GL&styleonly=true`); } setTimeout(() => { const layersArr = map.getStyle().layers,layerId=[],l = map.getStyle().layers.length; let sourceName = ''; if (l > 0) { for (let i = 0; i < l; i++) { if (url.indexOf(layersArr[i].source) !== -1) { sourceName = layersArr[i].source; layerId.push(layersArr[i].id); } } }; resolve ({ layerId:layerId, sourceId:[`${sourceName}`] }); },3000); }) }; <file_sep>export default function createScatterLayer(options,map) { return new Promise(async resolve => { const _Options = options; if(!map.getSource(`source_${_Options.id}`)){ map.addSource(`source_${_Options.id}`, { type: "vector", tiles:[`${_Options.url}/tiles/{z}/{x}/{y}.mvt`], }); } if(!map.getLayer(`icon_${_Options.id}`)){ map.addLayer({ "type":"symbol", "layout":{ "visibility":"visible", "icon-size":.5, "icon-image":_Options.imgPath }, "minzoom":0, "maxzoom":21, "paint":{}, "source-layer":_Options.sourceLayer, "id":`icon_${_Options.id}`, "source":`source_${_Options.id}`, }) } resolve({ sourceId:[`source_${_Options.id}`], layerId:[`icon_${_Options.id}`], }); }); } <file_sep>import { Loading } from 'element-ui' import mapboxgl from 'mapbox-gl'; import '@supermap/iclient-mapboxgl'; export default function getRestData (obj,fn) { const loading = Loading.service({ fullscreen:true, lock:true, spinner: 'el-icon-loading', text:"正在获取数据... ...", background: 'rgba(0, 0, 0, 0.7)' }); return new Promise((resolve, reject) => { const params = new SuperMap.GetFeaturesBySQLParameters({ queryParameter:{ name:`${obj.datasets}@${obj.datasource}`, }, fromIndex:obj.fromIndex||0, toIndex:obj.toIndex||1000, maxFeatures:obj.maxFeatures||1000, datasetNames:[`${obj.datasource}:${obj.datasets}`] }); new mapboxgl.supermap.FeatureService(obj.dataUrl).getFeaturesBySQL(params,(res) => { try { if(res.result.features){ let features =res.result.features; if(fn&&typeof fn === "function"){ features=fn(features,obj); } loading.close(); resolve([features]); }else { loading.close(); resolve([]); } } catch (e) { loading.close(); resolve([]); } }) }); } <file_sep>// 对外提供对组件的引用,注意组件必须声明 name import layerControl from './src/index.vue' // 为组件提供 install 安装方法,供按需引入 layerControl.install = Vue => { Vue.component(layerControl.name, layerControl) } export default layerControl <file_sep># 基础地图组件 ### registry ``` npm config set registry 'http://192.168.100.14:8081/repository/npm-group/' ``` ### Install ``` npm install supermbgl-ui -S ``` ### Usage ``` import Vue from "vue" import supermbglUi from 'supermbgl-ui' import 'supermbgl-ui/lib/supermbgl-ui.css' Vue.use(supermbglUi) ``` ###在项目中使用 1.组件 ``` #调用方法 <base-map :mapList="mapList" :map="this.map" :paintControll="true" @getBaseMap="getBaseMap"></base-map> ``` 2.参数说明 ``` #map * map type:Object 已加载完成的map 实例化对象 * paintControll(是否使用平移插件) //argumentss type:boolean 默认true 不使用选false * mapLsit: type Array 默认为空 //arguments name: "矢量图", 底图图层的名字 显示在右下角的文字字段 key: "map_vec", 统一命名 底图 id 和sourceID 不可重复 path: '', 图层的在线地址 bounds: "", 图层的边界 默认图层ID和sourceId 为当前key加map_vec_bounds label: "", 图层的标准 默认图层ID和sourceId 为当前key加map_vec_label center: [], 设置切换之后 地图的中心点 默认为空 空为不移动中心点 checked:true, 选中当前的图层 默认为false 数组里只可选一个 ``` <file_sep>// 对外提供对组件的引用,注意组件必须声明 name import mapLegend from './src/index.vue' // 为组件提供 install 安装方法,供按需引入 mapLegend.install = Vue => { Vue.component(mapLegend.name, mapLegend) } export default mapLegend <file_sep>//import addImgLoad from './addImgLoad' export function resetBorderColor(map,id,value){ if(!map.getLayer(id)){ throw new Error("layerId不存在") return; }else { map.setPaintProperty(id,'line-color',value) } }; export function resetBorderWidth(map,id,value){ if(!map.getLayer(id)){ throw new Error("layerId不存在") return; }else { map.setPaintProperty(id,'line-width',value) } }; export default (async function resetIconConfig (map,id,imgPath){ if(!map.getLayer(id)){ throw new Error("layerId不存在") return; }else { /* let imgPath = `/mongo/file/download/${value}`; await addImgLoad(map,{ iconPath:imgPath, iconName:imgPath });*/ map.setLayoutProperty(id,'icon-image',imgPath); } }) <file_sep>export default function createBlockLayer(options, map) { return new Promise(async resolve => { const _Options = options; map.addSource(`block_fill_source_${_Options.id}`, { type: 'geojson', data: _Options.fillFeatures }); map.addSource(`block_icon_source_${_Options.id}`, { type: 'geojson', data: _Options.pointFeatures }); map.addLayer({ id: `block_fill_${_Options.id}`, 'type': 'fill-extrusion', 'minzoom': 0, 'source':`block_fill_source_${_Options.id}`, 'paint': { 'fill-extrusion-color': ['get','color'], 'fill-extrusion-base': 1, 'fill-extrusion-height': ['get', 'height'], 'fill-extrusion-opacity': .75 } }); map.addLayer({ "type": "line", "source": `block_fill_source_${_Options.id}`, "minzoom": 0, "layout": { "line-join": "miter", "line-miter-limit": 2, "line-round-limit": 1.05, }, "paint": { "line-color": _Options.mapConfig.boderConfig.color || "#219bc0", "line-opacity": 1, "line-width": _Options.mapConfig.boderConfig.width || 0.75 }, "id": `block_line_${_Options.id}` }); map.addLayer({ "id": `block_font_${_Options.id}`, "type": "symbol", "source":`block_icon_source_${_Options.id}`, "interactive": true, "layout": { "text-size": { base: 10, stops: [ [3, 12], [7, 14], [15, 16] ], }, "text-font": [ "Arial Regular" ], "text-max-width": 20, "text-offset": [0, 0.2], "text-anchor": "top", "text-field": "{name}", }, "paint": { "text-color": "#333", "text-halo-color": "#ffffff", "text-halo-width": 1.25, }, }); map.addLayer({ "id": `block_label_${_Options.id}`, "type": "symbol", "source":`block_icon_source_${_Options.id}`, "interactive": true, "layout": { "text-size": { base: 10, stops: [ [3, 12], [7, 14], [15, 16] ], }, "text-font": [ "Arial Regular" ], "text-max-width": 20, "text-letter-spacing": -.5, "text-offset": [0.25, 1.75], "text-anchor": "top", "text-field": "{value}", }, "paint": { "text-color": "#333", "text-halo-color": "#ffffff", "text-halo-width": 1.25, }, }); resolve({ layerId:[`block_fill_${_Options.id}`,`block_line_${_Options.id}`,`block_font_${_Options.id}`,`block_label_${_Options.id}`], sourceId:[`block_fill_source_${_Options.id}`,`block_icon_source_${_Options.id}`] }); }); } <file_sep>// 对外提供对组件的引用,注意组件必须声明 name import drillMap from './src/index.vue' // 为组件提供 install 安装方法,供按需引入 drillMap.install = Vue => { Vue.component(drillMap.name, drillMap) } export default drillMap <file_sep> export default function creatRestLayer(map,options){ if(!options.hasOwnProperty("url")||!options.hasOwnProperty("id")){ throw new Error("rest服务传参不对必须要有服务url和图层id"); return; } let layerObj = { id: options.id, type: options.type, source: { "type": options.type, "tiles": [options.url], "tileSize": options.tileSize||256, rasterSource: 'iserver' }, "minzoom": options.minzoom, "maxzoom": options.maxzoom }; if(options.beforeLayer){ map.addLayer(layerObj,options.beforeLayer); }else { map.addLayer(layerObj); } } <file_sep> import addImgLoad from "../addImgLoad"; export default (async function creatICONLayer (map,options) { if(!options.hasOwnProperty("id")||!map){ throw new Error("mvt服务传参不对必须要有服务url和服务Id"); return; } await addImgLoad(map,options); map.addLayer({ "id": `${options.id}`, "type": "symbol", "source": { type: `${options.sourceType}`,//'geojson', data: options.data }, "interactive":options.interactive, "layout": { // 使用图片资源 'icon-image': options.iconName, // 缩放 'icon-size': options.iconSize||{ base: .2, stops: [ [4, .2], [7, .5], [15, .6] ], }, // 旋转角度 'icon-rotate': options.iconRotate, // 偏移量 'icon-offset': options.offset, // 跟随地图转动,推拉(3d效果那种)Mapbox 中叫 bearing 和 pitch 'icon-allow-overlap': options.overlap, } }); }) <file_sep>/* * 上钻下钻功能 * * */ <file_sep>export default function getFeatures(map,options){ let timeCount = 0,features =[]; let setInterVal = setInterval(()=>{ timeCount++; features = map.querySourceFeatures(`${options.sourceName}`, { sourceLayer: `${options.sourceLayer}` }); if(timeCount>=60&&features.length===0){ window.clearInterval(setInterVal) }else if(features>0){ window.clearInterval(setInterVal) } },1000) return features; }<file_sep>import GetColorVal from '../getColorValClass' export default function addHexagonLayer(options,map){ return new Promise(async resolve => { const _Options = options; map.addSource(`hexagon_fill_source_${_Options.id}`, { type: 'geojson', data: _Options.fillFeatures }); map.addLayer({ id: `hexagon_fill_${_Options.id}`, 'type': 'fill', 'minzoom': 0, 'source':`hexagon_fill_source_${_Options.id}`, 'paint': { 'fill-color': ['get','color'], 'fill-opacity': .75 } }); map.addLayer({ "type": "line", "source": `hexagon_fill_source_${_Options.id}`, "minzoom": 0, "layout": { "line-join": "miter", "line-miter-limit": 2, "line-round-limit": 1.05, }, "paint": { "line-color": _Options.mapConfig.boderConfig.color || "#219bc0", "line-opacity": 1, "line-width": _Options.mapConfig.boderConfig.width || 0.75 }, "id": `hexagon_line_${_Options.id}` }); let props = { extruded: true, radius: 400, autoHighlight: true, upperPercentile: 99, coverage: 80, elevationScale: 400, opacity: 0.8, // lightSettings 光照配置参数,配置三维光照效果, lightSettings: { lightsPosition: [-122.5, 37.7, 3000, -122.2, 37.9, 3000], // 指定为`[x,y,z]`的光在平面阵列中的位置 ambientRatio: 0.2, //光照的环境比例 diffuseRatio: 0.5, //光的漫反射率 specularRatio: 0.3, //光的镜面反射率 lightsStrength: [1.0, 0.0, 2.0, 0.0], //平面阵列中指定为“[x,y]`的灯的强度。 长度应该是`2 x numberOfLights` numberOfLights: 4 //光照值 } }; if(_Options.legendArr.length>0){ props.colorRange=[]; for(let val of _Options.legendArr){ props.colorRange.push(new GetColorVal(val.value).rgbColorToRGB()); } }else { props.colorRange=[ [217, 222, 242], [188, 199, 248], [158, 175, 246], [136, 157, 246], [98, 127, 247], [62, 100, 255] ]; } let deckglLayer = new _Options.mapboxgl.supermap.DeckglLayer("hexagon-layer", { data:_Options.pointFeatures.features, props, callback: { getPosition: function (d) { return d.geometry.coordinates; }, getElevationValue: d => { return parseInt(d[0]["properties"]['value']) || 0; }, getColorValue: d => parseInt(d[0]["properties"]['value']), }, }); map.addLayer(deckglLayer); resolve({ layerId:[`${deckglLayer.id}`,`hexagon_fill_${_Options.id}`,`hexagon_line_${_Options.id}`], sourceId:[`${deckglLayer.id}`,`hexagon_fill_source_${_Options.id}`] }); }); } <file_sep># supermbg-ui 基于 vue-cli3 的 map 成果库 ### registry ``` npm config set registry "http://192.168.100.14:8081/repository/npm-group/" ``` ### Install ``` npm install supermbgl-ui -S ``` ### Usage ``` import Vue from "vue" import supermbglUi from 'supermbgl-ui' import 'supermbgl-ui/lib/supermbgl-ui.css' Vue.use(supermbglUi) ``` ###在项目中使用 1.组件 ``` #举例 <base-map :mapList="mapList" @getBaseMap="getBaseMap"></base-map> ``` 2.工具 ``` #举例 this.mapCore.PaintControlClass() ``` <file_sep>/** * arguments: * num(获取颜色个数) type:int; * isRelative(是否获取同一色系的) type:bool; * colorVal:(获取同一色系的时候必填) '#121212' * amt(同色系的明暗程度变化) + 变亮 -变暗 * */ export default class GetColorVal { constructor(colorVal,num,isRelative,amt){ this.num = num; this.isRelative = isRelative; this.colorVal = colorVal; this.amt = amt; } //获取随机颜色 getRandomColor(){ let HSLArr =[]; for(let i =0;i<this.num;i++){ let randomHSLValue = this.randomHSL(); if (i > 0&&Math.abs(randomHSLValue[0] - HSLArr[i - 1][0]) < 0.25) { i--; continue; // 重新获取随机色 } randomHSLValue[1] = 0.7 + (randomHSLValue[1] * 0.2); // [0.7 - 0.9] 排除过灰颜色 randomHSLValue[2] = 0.4 + (randomHSLValue[2] * 0.4); // [0.4 - 0.8] 排除过亮过暗色 randomHSLValue = randomHSLValue.map( (item) => { return parseFloat(item.toFixed(2)); }); HSLArr.push(randomHSLValue); return HSLArr.map( (item) => { return 'rgb(' + this.hslToRgb.apply(this,item).toString()+ ')'; }); } } //生成随机色值 randomHSL(){ let H = Math.random(); let S = Math.random(); let L = Math.random(); return [H, S, L]; } //获取同一色系的颜色 getAllRelationColor(amt){ let col = this.colorVal.toLowerCase(); let usePound = false; if(col.indexOf("rgb")!==-1){ col=col.replace(/rgb/,''); col=this.colorRGB2Hex(); } if (col[0] == "#") { col = col.slice(1); usePound = true; } let num = parseInt(col,16); let r = (num >> 16) + amt; if (r > 255) r = 255; else if (r < 0) r = 0; let b = ((num >> 8) & 0x00FF) + amt; if (b > 255) b = 255; else if (b < 0) b = 0; let g = (num & 0x0000FF) + amt; if (g > 255) g = 255; else if (g < 0) g = 0; return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16); } /** * HSL颜色值转换为RGB * H,S,L 设定在 [0, 1] 之间 * R,G,B 返回在 [0, 255] 之间 * * @param H 色相 * @param S 饱和度 * @param L 亮度 * @returns Array RGB色值 */ hslToRgb(){ let H =this.colorVal[0],S = this.colorVal[1],L = this.colorVal[2]; let R, G, B; if (+S === 0) { R = G = B = L; // 饱和度为0 为灰色 } else { let hsl2Rgb = function (p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1/6) return p + (q - p) * 6 * t; if (t < 1/2) return q; if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; }; let Q = L < 0.5 ? L * (1 + S) : L + S - L * S; let P = 2 * L - Q; R = hsl2Rgb(P, Q, H + 1 / 3); G = hsl2Rgb(P, Q, H); B = hsl2Rgb(P, Q, H - 1 / 3); } return [Math.round(R * 255), Math.round(G * 255), Math.round(B * 255)]; } //颜色转换 /** * RGB颜色值转换为HEX * R,G,B 设定在 [0, 255] 之间 * HEX 返回 #****** * @returns HEX色值 */ colorRGB2Hex(){ let rgb = this.colorVal.split(','); let r = parseInt(rgb[0].split('(')[1]); let g = parseInt(rgb[1]); let b = parseInt(rgb[2].split(')')[0]); let hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); return hex; } //RGBColorTorgb /** * RGB颜色值转换为RGB [255,255,255] * R,G,B 设定在 [0, 255] 之间 * rgb 返回在 [0, 255] 之间 * @returns rgb色值 */ RGBColorTorgb(){ let rgb = (this.colorVal + "").split(','); let r = parseInt(rgb[0]); let g = parseInt(rgb[1]); let b = parseInt(rgb[2]); return `rgba(${r},${g},${b},)`; } /** * RGB颜色值转换为rgb * R,G,B 设定在 [0, 255] 之间 * rgb 返回在 [0, 255] 之间 * @returns [] rgb色值 */ rgbColorToRGB(){ let rgb = this.colorVal.split(','); let r = parseInt(rgb[0].split('(')[1]); let g = parseInt(rgb[1]); let b = parseInt(rgb[2].split(')')[0]); return [r, g, b] } //hexToRgb /** * hex 例如 #000000 * * rgb 返回在 [0, 255] 之间 * @returns [] rgb色值 */ hexToRgb(){ let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(this.colorVal); return result ? `rgb(${parseInt(result[1], 16)},${parseInt(result[2], 16)}, ${parseInt(result[3], 16)})`:"rgb(255,255,255)" } hexToRgba(colorVal,opacity){ let opacityVal = opacity&&(Math.abs(opacity)>=1&&1||Math.abs(opacity))||1; let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(this.colorVal); return result ? `rgba(${parseInt(result[1], 16)},${parseInt(result[2], 16)}, ${parseInt(result[3], 16)},${opacityVal})`:"rgb(255,255,255)" } init(){ if(this.isRelative){ this.getAllRelationColor(this.amt); }else { this.getRandomColor(); } } } <file_sep> /** * mapCore 地图的核心代码 * mapConfig 可视化配置 * baseMap 底图切换 * figAttr 图属联动 * drillMap 上钻下钻 */ //require("./_static/index"); import mapCore from './_mapcore/index.js' if(!window.supermbglUi){ window.supermbglUi ={}; window.supermbglUi['_mapCore'] = mapCore; }else { window.supermbglUi['_mapCore'] = mapCore; } import layerControl from './src/layerControl/index.js' import mapConfig from './src/mapConfig' import figAttr from './src/figAttr/index.js' import drillMap from './src/drillMap/index.js' import mapLegend from './src/mapLegend/index.js' // 存储组件列表 const components = [ layerControl, mapLegend, mapConfig, figAttr, drillMap ] import MapMixin from './_mapcore/_sourceModel/index'; //定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,则所有的组件都将被注册 const install = function (Vue) { // 判断是否安装 if (install.installed) return install.installed = true Vue.mixin(MapMixin); // 遍历注册全局组件 components.map(component => Vue.component(component.name, component)) //下面这个写法也可以 //components.map(component => Vue.use(component)) } // 判断是否是直接引入文件 if (typeof window !== 'undefined' && window.Vue) { install(window.Vue) } export default { // 导出的对象必须具有 install,才能被 Vue.use() 方法安装 install, // 以下是具体的组件列表 ...components } <file_sep>/** 自然断点法 * args data type:Array int 必传; num 分段个数 int 选传 * 默认分段个数 6 * 如果传入的数组去重个数小于默认值或者传入的分段个数值 * 将会按照当前的数组的个数去分段 * */ export default function getJenksBreaks(data,num=6){ if(!data||!Array.isArray(data)||data.length===0){ console.warn("自然分段的数据必须为数组并且数组的个数大于0!"); //防止意外错误,返回一个空数组 return []; } //设置默认的分段个数 data.sort((a,b)=>a-b); //对数组进行向下取整并且去重 let tD=data.map((item,index) => Math.floor(item)||0),tL=0; tD = [...(new Set(tD))]; //对传入num参数进行二次处理 tL =tD.length; num = tL<num&&tL||num; let k = data.length, kArr=[],mathArr1=[],mathArr2=[],res=[],v=0; for (let j = 0; j <= k; j++){ mathArr1[j]=[]; mathArr2[j]=[]; res[j]=0; for(let i=0;i<=num;i++){ mathArr1[j][i]=0; mathArr2[j][i]=0; } } for (let i = 1; i <= num; i++) { mathArr1[1][i] = 1; mathArr2[1][i] = 0; for (let j = 2; j <= k; j++){ mathArr2[j][i]=Number.MAX_VALUE; } } for (let l = 2; l <= k; l++) { let s1=0,s2=0,w=0,i3=0; for (let m = 1; m <= l; m++) { i3 = l - m + 1; let val=parseFloat(data[i3-1]); s2 += val * val; s1 += val; w++; v = s2 - (s1 * s1) / w; let i4 = i3 - 1; if (i4 != 0) { for (let j = 2; j <= num; j++) { if (mathArr2[l][j] >= (v + mathArr2[i4][j - 1])) { mathArr1[l][j] = i3; mathArr2[l][j] = v + mathArr2[i4][j - 1]; } } } } mathArr1[l][1] = 1; mathArr2[l][1] = v; } kArr[num - 1] = parseFloat(data[k-1]); for (let j = num; j >= 2; j--) { let id = parseFloat(mathArr1[k][j]) - 2; kArr[j - 2] = parseFloat(data[id]); k = parseFloat( mathArr1[k][j] - 1); } let resetKArr=[]; for(let i =0,l=kArr.length;i<l;i++){ if(!isNaN(kArr[i])&&kArr[i]!==undefined){ resetKArr.push(kArr[i]); } } resetKArr=[...new Set(resetKArr)]; return resetKArr; }; <file_sep>export default function createWMSLayer(map,options) { return new Promise(resolve => { const _Options = options; map.addLayer({ 'id': `${_Options.id}`, 'type': 'raster', 'source': { 'type': 'raster', "tiles": [`${_Options.url}`], 'tileSize': 256, }, }); resolve({ sourceId:[`${_Options.id}`], layerId:[`${_Options.id}`], }); }); } <file_sep> export default function addImgLoad (map,iconObj) { return new Promise((resolve, reject) => { map.loadImage(`${iconObj.iconPath}`, (error, img) => { if (img) { if (!map.hasImage(`${iconObj.iconPath}`)) { map.addImage(`${iconObj.iconPath}`, img); } resolve(); } if (error) { resolve(); console.log(error); } }); }); } <file_sep> import Source from './Source'; import Layer from './Layer'; const MapMixin = { data: function () { return { map: null, layers:null, overlayLayers:null, detailLayers:null, sourceList:{}, sourceNames:[], excludeSourceNames:['tdt-search-', 'tdt-route-', 'smmeasure', 'mapbox-gl-draw'] } }, created(){ }, mounted(){ if(this.map){ this.map.on("load",()=> { this.style = this.map.getStyle(); this.layers = this.map.getStyle().layers; this.overlayLayers = this.map.overlayLayersManager; this._initLayers(); this._initSource(); }); } }, methods: { getSourceList() { let sourceList = {}; for (let key in this.sourceList) { if (key && this.excludeSource(key)) { sourceList[key] = this.sourceList[key]; } } return sourceList; }, getSourceNames() { const names = []; this.sourceNames.forEach(element => { if (element && this.excludeSource(element)) { names.push(element); } }); return names; }, excludeSource(key) { for (let i = 0; i < this.excludeSourceNames.length; i++) { if (key.indexOf(this.excludeSourceNames[i]) >= 0) { return false; } } return true; }, getLegendStyle(sourceName) { if (sourceName) { return this.sourceList[sourceName] ? this.sourceList[sourceName].style : ''; } const sourceList = Object.values(this.sourceList) || []; const styles = sourceList.filter(item => !!item.style); return styles; }, getLayers() { return this.detailLayers; }, getLayersBySourceLayer(sourceName, sourceLayer) { return this.sourceList[sourceName]['sourceLayerList'][sourceLayer]; }, getSourceLayersBySource(sourceName) { return this.sourceList[sourceName]['sourceLayerList']; }, addSourceStyle(sourceName, sourceStyle) { if (this.sourceList[sourceName]) { this.sourceList[sourceName]['style'] = sourceStyle; } }, _initLayers() { this.layers && (this.detailLayers = this.layers.map(layer => { return this.map.getLayer(layer.id); })); const overLayerList = Object.values(this.overlayLayers); overLayerList.forEach(overlayer => { if (overlayer.id) { this.detailLayers.push({ id: overlayer.id, visibility: overlayer.visibility ? 'visible' : 'none', source: overlayer.id }); } }); }, _initSource() { this.detailLayers && this.detailLayers.forEach(layer => { if (!this.sourceList[layer['source']]) { this.sourceList[layer['source']] = new Source({ source: layer['source'] }); this.sourceNames.push(layer['source']); } this.sourceList[layer['source']].addLayer(new Layer(layer), layer['sourceLayer']); }); }, } }; export default MapMixin ; <file_sep>/** * arguments * type:bd09togcj02 gcj02tobd09 wgs84togcj02 type string * lng type float * lat type float */ class GeoCodeTransformClass { constructor(type,lng,lat){ this.x_PI = 3.14159265358979324 * 3000.0 / 180.0; this.PI = 3.1415926535897932384626; this.a = 6378245.0; this.ee = 0.00669342162296594323; this.type = type; this.lng = lng; this.lat = lat; } out_of_china(){ return (this.lng < 72.004 || this.lng > 137.8347) || ((this.lat < 0.8293 || this.lat > 55.8271) || false); } transformlat(){ let ret = -100.0 + 2.0 * this.lng + 3.0 * this.lat + 0.2 * this.lat * this.lat + 0.1 * this.lng * this.lat + 0.2 * Math.sqrt(Math.abs(this.lng)); ret += (20.0 * Math.sin(6.0 * this.lng * this.PI) + 20.0 * Math.sin(2.0 * this.lng * this.PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(this.lat * this.PI) + 40.0 * Math.sin(this.lat / 3.0 * this.PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(this.lat / 12.0 * this.PI) + 320 * Math.sin(this.lat * this.PI / 30.0)) * 2.0 / 3.0; return ret } transformlng(){ var ret = 300.0 + this.lng + 2.0 * this.lat + 0.1 * this.lng * this.lng + 0.1 * this.lng * this.lat + 0.1 * Math.sqrt(Math.abs(this.lng)); ret += (20.0 * Math.sin(6.0 * this.lng * this.PI) + 20.0 * Math.sin(2.0 * this.lng * this.PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(this.lng * this.PI) + 40.0 * Math.sin(this.lng / 3.0 * this.PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(this.lng / 12.0 * this.PI) + 300.0 * Math.sin(this.lng / 30.0 * this.PI)) * 2.0 / 3.0; return ret } /** * 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换 * 即 百度 转 谷歌、高德 * @param bd_lon * @param bd_lat * @returns {*[]} */ bd09togcj02(){ let x = this.lng - 0.0065; let y = this.lat - 0.006; let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * this.x_PI); let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * this.x_PI); let gg_lng = z * Math.cos(theta); let gg_lat = z * Math.sin(theta); return [gg_lng, gg_lat] } /** * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换 * 即谷歌、高德 转 百度 * @param lng * @param lat * @returns {*[]} */ gcj02tobd09() { let z = Math.sqrt(this.lng * this.lng + this.lat * this.lat) + 0.00002 * Math.sin(this.lat *this.x_PI); let theta = Math.atan2(this.lat, this.lng) + 0.000003 * Math.cos(this.lng * this.x_PI); let bd_lng = z * Math.cos(theta) + 0.0065; let bd_lat = z * Math.sin(theta) + 0.006; return [bd_lng, bd_lat] } /** * WGS84转GCj02 * @param lng * @param lat * @returns {*[]} */ wgs84togcj02() { if (this.out_of_china(this.lng, this.lat)) { return [this.lng, this.lat] } else { let dlat = this.transformlat(this.lng - 105.0, this.lat - 35.0); let dlng = this.transformlng(this.lng - 105.0, this.lat - 35.0); let radlat = this.lat / 180.0 * this.PI; let magic = Math.sin(radlat); magic = 1 - this.ee * magic * magic; let sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * this.PI); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * this.PI); let mglat = this.lat + dlat; let mglng = this.lng + dlng; return [mglng, mglat] } } init(){ switch (this.type) { case "bd09togcj02": return this.bd09togcj02(); break; case "gcj02tobd09": return this.gcj02tobd09(); break; case "wgs84togcj02": return this.wgs84togcj02(); break; } } }<file_sep>/** * Created by gaowe on 2020/2/12. */ function regHandler(str){ const userAgent = navigator.userAgent, rMsie = /(msie\s|trident.*rv:)([\w.]+)/, rFirefox = /(firefox)\/([\w.]+)/, rOpera = /(opera).+version\/([\w.]+)/, rChrome = /(chrome)\/([\w.]+)/, rSafari = /version\/([\w.]+).*(safari)/; let browser; let version; let match = null; const ua = userAgent.toLowerCase(); function uaMatch(ua){ match = rMsie.exec(ua); if(match != null){ return { browser : "IE", version : match[2] || "0" }; } match = rFirefox.exec(ua); if (match != null) { return { browser : match[1] || "", version : match[2] || "0" }; } match = rOpera.exec(ua); if (match != null) { return { browser : match[1] || "", version : match[2] || "0" }; } match = rChrome.exec(ua); if (match != null) { return { browser : match[1] || "", version : match[2] || "0" }; } match = rSafari.exec(ua); if (match != null) { return { browser : match[2] || "", version : match[1] || "0" }; } if (match != null) { return { browser : "", version : "0" }; } } let browserMatch = uaMatch(ua); if (browserMatch.browser){ browser = browserMatch.browser; version = browserMatch.version; } let osInfoNum =regOSInfoFn(); if(browser==="IE"&&parseInt(version)<=11){ let regWarp= document.getElementById("reg-warp"); let regBg =document.getElementById("reg-bg"); let closeRegBtn = document.getElementById("close-reg-btn"); let remarkBox = document.getElementById("remark-box"); let btnCancel = document.getElementById("btn-cancel"); let btnHref32 = document.getElementById("btn-href-32"); let btnHref64 = document.getElementById("btn-href-64"); let contentBox = document.getElementById("content-box"); contentBox.innerHTML=str; regWarp.style.display="block"; regBg.style.display="block"; btnCancel.onclick = function(){ regWarp.style.display="none"; regBg.style.display="none"; }; closeRegBtn.onclick = function(){ regWarp.style.display="none"; regBg.style.display="none"; }; if(osInfoNum===64){ remarkBox.innerHTML="(您的系统位64位,我们推荐您下载64位的谷歌浏览器!)"; btnHref32.style.display="none"; }else if(osInfoNum===32){ remarkBox.innerHTML="(您的系统位32位,我们推荐您下载32位的谷歌浏览器!)"; btnHref64.style.display="none"; } /* this.$confirm('浏览器版本过低(目前IE只支持IE11/IE(edge)版本!为了您更好的体验,我们建议您使用谷歌浏览器,去下载?', '提示', { confirmButtonText: '去下载', cancelButtonText: '取消', type: 'warning' }).then(() => { const elt = document.createElement('a'); elt.setAttribute('href', 'google.zip'); elt.setAttribute('download', ''); elt.style.display = 'none'; document.body.appendChild(elt); elt.click(); document.body.removeChild(elt); }).catch(() => { });*/ } function regOSInfoFn(){ let _pf = navigator.platform,appVer = navigator.userAgent,_bit=null; if(_pf == "Win32" || _pf == "Windows") { if(appVer.indexOf("WOW64")>-1){ _bit = 64; }else{ _bit = 32; } return _bit; } } } regHandler("浏览器版本过低(目前IE只支持IE11/IE(edge)版本!"); <file_sep>export default function creatRestLayer(map,options){ /* [ //图像显示4个点的位置信息 [73.146939, 53.857304], //左上 [135.409885, 53.857304], //右上 [135.409885, 17.894901], //右下 [73.146939, 17.894901] //左下 ] */ if(!options.hasOwnProperty("url")||!options.hasOwnProperty("id")){ throw new Error("mvt服务传参不对必须要有服务url和服务Id"); return; } map.addLayer({ id: `${options.id}`, //图层名称 type: "raster", //显示类型为栅格 source: { type: "image", //数据源为类型为image url: `${options.url}`, //图像地址 coordinates:`${options.coordinates}` } }); } <file_sep>//创建散点图 export default function createScatterLayer(options,map) { return new Promise(async resolve => { const _Options = options; map.addSource(`fill_${_Options.id}`, { type: 'geojson', data: _Options.fillFeatures }); map.addSource(`icon_${_Options.id}`, { type: 'geojson', data: _Options.pointFeatures }); map.addLayer({ "id": `fill_${_Options.id}`, "maxzoom": 21, "type": "fill", "layout": {}, "paint": { "fill-color": ['get', 'color'], "fill-opacity": 1, }, "source": `fill_${_Options.id}`, "minzoom": 0 }); map.addLayer({ "id": `line_${_Options.id}`, "maxzoom": 21, "type": "line", "layout": { "line-join": "miter", "line-miter-limit": 2, "line-round-limit": 1.05, }, "paint": { "line-color": _Options.mapConfig.boderConfig.color || "#219bc0", "line-opacity": 1, "line-width": _Options.mapConfig.boderConfig.width || 0.75 }, "source": `fill_${_Options.id}`, "minzoom": 0 }); map.addLayer({ "id": `icon_${_Options.id}`, type: 'symbol', "source": `icon_${_Options.id}`, "interactive": true, layout: { // 使用图片资源 'icon-image': _Options.imgPath, // 缩放 'icon-size': { base: .4, stops: [ [3, .4], [7, .5], [15, .6] ], }, // 旋转角度 'icon-rotate': 0, // 偏移量 'icon-offset': [0, -15], // 跟随地图转动,推拉(3d效果那种)Mapbox 中叫 bearing 和 pitch 'icon-allow-overlap': true, } }); map.addLayer({ "id": `font_${_Options.id}`, "type": "symbol", "source": `icon_${_Options.id}`, "interactive": true, "layout": { "text-size": { base: 10, stops: [ [3, 12], [7, 14], [15, 16] ], }, "text-font": [ "Arial Regular" ], "text-max-width": 20, "text-offset": [0, 0.2], "text-anchor": "top", "text-field": "{name}", }, "paint": { "text-color": "#333", "text-halo-color": "#ffffff", "text-halo-width": 1.25, 'text-opacity':1 }, }); map.addLayer({ "id": `label_${_Options.id}`, "type": "symbol", "source": `icon_${_Options.id}`, "interactive": true, "layout": { "text-size": { base: 10, stops: [ [3, 12], [7, 14], [15, 16] ], }, "text-font": [ "Arial Regular" ], "text-max-width": 20, "text-letter-spacing": -.5, "text-offset": [0.25, 1.75], "text-anchor": "top", "text-field": "{value}", }, "paint": { "text-color": "#333", "text-halo-color": "#ffffff", "text-halo-width": 1.25, 'text-opacity':1 }, }); resolve({ layerId: [`fill_${_Options.id}`, `line_${_Options.id}`, `icon_${_Options.id}`, `font_${_Options.id}`, `label_${_Options.id}`], sourceId:[`fill_${_Options.id}`, `icon_${_Options.id}`] }); }) }; <file_sep>import Vue from "vue"; /*import mapboxgl from '../_static/_libs/mapboxgl/mapbox-gl-enhance' import "../_static/_libs/iclient-mapboxgl/iclient-mapboxgl.min" import mapMixin from '../_mapcore/_sourceModel/index'*/ /*function callHook(vm, hook, ...params) { const { options } = vm.constructor; options.mixins && options.mixins.forEach(mixin => { mixin[hook] && mixin[hook].call(vm, ...params); }); options[hook] && options[hook].call(vm, ...params); // 调用子组件的生命周期 }*/ /* export default class MapGetter extends Vue { data(){ return { map:null, } } methods(){ _SourceConfig(map){ return new SourceConfig({map:null}) } } }*/
2535f37a64683ca587917645fc0dcdbe666ba005
[ "JavaScript", "Markdown" ]
29
JavaScript
CH-JD/supermbg-ui
94618d95570cd3f656e7a19c3df6b49bf04ca1a6
26c50915d2aa263f0068f8204ca2033345f4b488
refs/heads/master
<repo_name>aniruddhsinghal5/spotifyaccgen<file_sep>/spotify.sh #!/bin/bash red='\033[0;31m' cyan='\033[0;36m' yell='\033[1;33m' white="\e[37m" green='\033[92m' trap ctrl_c INT ctrl_c() { clear printf "$white[$red CTRL + C$white ] Okay, I will get Exit..." sleep 3 clear exit } echo "" printf "$cyan ======================================= \n" printf "$yell -+SPOTIFY ACCOUNT CREATOR+-\n" printf "$cyan ======================================= \n" printf "$red CREATED BY$white <NAME> \n" printf "$cyan ======================================= \n" printf "$white" cat <<EOF EOF daftar(){ random=$(echo $RANDOM) curl=$(curl -s "https://spclient.wg.spotify.com:443/signup/public/v1/account/" --data "iagree=true&birth_day=17&platform=Android-ARM&creation_point=client_mobile&password=$<PASSWORD>&key=142b583129b2df829de3656f9eb484e6&birth_year=2000&email=<EMAIL>&gender=male&app_version=849800892&birth_month=12&password_repeat=$pswd") status=$(echo $curl | grep -Po '(?<=status":)[^},]*' | tr -d '[]"' | sed 's/\(<[^>]*>\|<\/>\|{1|}\)//g') if [[ $status =~ "1" ]]; then date +%H:%M:%S printf "$white[$green Success$white ] => $user.<EMAIL>|$pswd\n" echo "[ Sukses ]$<EMAIL>|$pswd" >> accounts.txt else date +%H:%M:%S printf "$white[$red Failed$white ] => $<EMAIL>.<EMAIL>|$pswd\n" fi } read -p "Amount( To Be Generated) : " jumlah read -p "Username (To Be Kept) : " user read -p "Password (To Be Kept) : " <PASSWORD> for (( i = 0; i < $jumlah; i++ )); do daftar $user $pswd done <file_sep>/README.md # spotifyaccgen Automatically create a free spotify account # How To Install - apt update && pkg upgrade - apt install curl git - git clone https://github.com/aniruddhsinghal5/spotifyaccgen - cd spotifyaccgen - bash spotify.sh # Run This Everytime To Use : - cd spotifyaccgen - bash spotify.sh
1b0b553add5c18e827074cf359ecfd125959c7fb
[ "Markdown", "Shell" ]
2
Shell
aniruddhsinghal5/spotifyaccgen
5f73d797aef205dd28f3197ab2b80ec135f8fd29
7d922baad78e4a99628b08347ed99654c2888f4c
refs/heads/master
<repo_name>NahomKibreab/Sundance-Mazda-Project<file_sep>/frontend/src/hooks/useStripe.js import { useState } from "react"; import axios from "axios"; export default function useStripe() { const [product, setProduct] = useState({ name: "React from FB", price: 10, productBy: "facebook", }); const [status, setStatus] = useState(null); const [email, setEmail] = useState(null); const makePayment = (token) => { const body = { token, product, }; setEmail(token.email); return axios .post("http://localhost:8000/payment", { ...body }) .then((response) => { console.log("Response", response); const { status } = response; console.log("Status", status); confirmed(status); }) .catch((error) => console.log(error)); }; const confirmed = (status) => { if (status === 200) { setStatus(status); } }; return { product, makePayment, setProduct, status, email }; } <file_sep>/frontend/src/components/HomePage.js import { Card, CardActionArea, CardHeader, CardMedia, Grid, Typography, } from "@mui/material"; import axios from "axios"; import { useEffect, useState } from "react"; import { useHistory } from "react-router"; import HomeCarousel from "./HomeCarousel"; import Map from "./HomeMap"; export default function HomePage() { const [carModels, setCarModels] = useState(); const path = useHistory(); useEffect(() => { axios.get("/api/cars/models").then(({ data }) => { setCarModels(data); }); }, []); const models = carModels && carModels.map((carModel, index) => { return ( <Grid item xs={11} sm={7} lg={3} key={index}> <Card raised> <CardActionArea onClick={() => path.push(`/cars/${carModel.id}`)}> <CardHeader title={`${carModel.year} ${carModel.model} ${carModel.trim}`} subheader={`$${new Intl.NumberFormat().format( carModel.price / 100 )}`} /> <CardMedia component="img" width="30%" image={carModel.image_links[0]} alt={carModel.model} /> </CardActionArea> </Card> </Grid> ); }); const location = { address: "Sundance Mazda, 17990 102 Ave NW, Edmonton, AB", lat: 53.544013658365934, lng: -113.63180428465739, }; return ( <> <Grid container justifyContent="center" sx={{ backgroundColor: "#bec2cb" }} > <Grid item paddingBottom={2} paddingTop={2}> <Typography variant="h3" fontWeight="light" color="white"> Sundance Mazda </Typography> <Typography variant="h7"> Edmonton's Premier Dealer, serving Edmonton since 1985. </Typography> </Grid> </Grid> <Grid container> <Grid item> <HomeCarousel /> </Grid> </Grid> <Grid container justifyContent="center" spacing={2} mt={2}> <Grid item xs={12}> <Typography variant="h5">Manager's Specials</Typography> </Grid> {models} </Grid> <Map location={location} zoomLevel={17} /> </> ); } <file_sep>/frontend/src/components/NavBar.js import * as React from "react"; import AppBar from "@mui/material/AppBar"; import Box from "@mui/material/Box"; import Toolbar from "@mui/material/Toolbar"; import IconButton from "@mui/material/IconButton"; import AccountCircle from "@mui/icons-material/AccountCircle"; import MenuItem from "@mui/material/MenuItem"; import Menu from "@mui/material/Menu"; import { Avatar, Button, Grid, useMediaQuery } from "@mui/material"; import { PhoneEnabled } from "@mui/icons-material"; import { Link } from "react-router-dom"; import MenuDrawer from "./MenuDrawer"; export default function NavBar() { const [auth, setAuth] = React.useState(true); const [anchorEl, setAnchorEl] = React.useState(null); const [phoneNumber, setPhoneNumber] = React.useState(null); const [menu, setMenu] = React.useState(null); const hideInMobileMode = useMediaQuery((theme) => theme.breakpoints.up("md")); // const anchorElOnChange = (event) => { // setAuth(event.target.checked); // }; // const menuOnChange = (event) => { // setAuth(event.target.checked); // }; const handleAnchorEl = (event) => { setAnchorEl(event.currentTarget); }; const handlePhoneNumber = (event) => { setPhoneNumber(event.currentTarget); }; // const handleMenu = (event) => { // setMenu(event.currentTarget); // }; const anchorElOnClose = () => { setAnchorEl(null); }; const phoneNumberOnClose = () => { setPhoneNumber(null); }; const menuOnClose = () => { setMenu(null); }; const mazdaLogo = () => { return ( <IconButton size="large" edge="start" color="inherit" aria-label="menu"> <Link to="/" style={{ textDecoration: "none", color: "inherit" }}> <Avatar alt="Mazda Logo" variant="square" src="/images/Sundance-Logo-3.png" /> </Link> </IconButton> ); }; return ( <Box sx={{ flexGrow: 1, marginBottom: "64px" }}> {/* <FormGroup> <FormControlLabel control={ <Switch checked={auth} onChange={handleChange} aria-label="login switch" /> } label={auth ? 'Logout' : 'Login'} /> </FormGroup> */} <AppBar position="fixed"> <Toolbar> {hideInMobileMode ? mazdaLogo() : <MenuDrawer />} <Menu id="menu-appbar" anchorEl={menu} anchorOrigin={{ vertical: "top", horizontal: "left", }} keepMounted transformOrigin={{ vertical: "top", horizontal: "left", }} open={Boolean(menu)} onClose={menuOnClose} > <MenuItem onClick={menuOnClose}>Profile</MenuItem> <MenuItem onClick={menuOnClose}>My account</MenuItem> </Menu> <Box sx={{ flexGrow: 1 }}> {!hideInMobileMode ? ( <Grid container justifyContent="center" alignItems="center" spacing={1} > <Grid item>{mazdaLogo()}</Grid> </Grid> ) : ( <> <Link to="/" style={{ textDecoration: "none", color: "inherit" }} > <Button color="inherit">Home</Button> </Link> &#124; <Link to="/cars" style={{ textDecoration: "none", color: "inherit" }} > <Button color="inherit">Inventory</Button> </Link> &#124; <Link to="/about" style={{ textDecoration: "none", color: "inherit" }} > <Button color="inherit">About Us</Button> </Link> &#124; <Link to="/videos" style={{ textDecoration: "none", color: "inherit" }} > <Button color="inherit">Videos</Button> </Link> &#124; <a href="https://www.sundancemazda.com/en/news/list/reviews" style={{ textDecoration: "none", color: "inherit" }} target="_blank" rel="noreferrer" > <Button color="inherit">Reviews</Button> </a> &#124; <a href="https://www.sundancemazda.com/en/news?limit=12" style={{ textDecoration: "none", color: "inherit" }} target="_blank" rel="noreferrer" > <Button color="inherit">News</Button> </a> </> )} </Box> {auth && ( <div> <IconButton size="small" aria-label="account of current user" aria-controls="menu-appbar" aria-haspopup="true" onClick={handlePhoneNumber} color="inherit" > <PhoneEnabled /> </IconButton> {hideInMobileMode && ( <IconButton size="small" aria-label="account of current user" aria-controls="menu-appbar" aria-haspopup="true" onClick={handleAnchorEl} color="inherit" sx={{ ml: 2 }} > <AccountCircle /> </IconButton> )} <Menu id="menu-appbar" anchorEl={anchorEl} anchorOrigin={{ vertical: "top", horizontal: "right", }} keepMounted transformOrigin={{ vertical: "top", horizontal: "right", }} open={Boolean(phoneNumber)} onClose={phoneNumberOnClose} > <MenuItem onClick={phoneNumberOnClose}> Sales: 1-844-394-3633 </MenuItem> <MenuItem onClick={phoneNumberOnClose}> Service: 1-844-472-8053 </MenuItem> <MenuItem onClick={phoneNumberOnClose}> Parts: 1-780-454-7278 </MenuItem> </Menu> <Menu id="menu-appbar" anchorEl={anchorEl} anchorOrigin={{ vertical: "top", horizontal: "right", }} keepMounted transformOrigin={{ vertical: "top", horizontal: "right", }} open={Boolean(anchorEl)} onClose={anchorElOnClose} > <MenuItem onClick={anchorElOnClose}>My Profile</MenuItem> <MenuItem onClick={anchorElOnClose}>My Garage</MenuItem> <MenuItem onClick={anchorElOnClose}>Log Out</MenuItem> </Menu> </div> )} </Toolbar> </AppBar> </Box> ); } <file_sep>/frontend/src/components/CarLists.js import { Grid, TextField } from "@mui/material"; import { Box } from "@mui/system"; import SearchIcon from "@mui/icons-material/Search"; import VehicleCard from "./VehicleCard"; import useVehiclesData from "../hooks/useVehiclesData"; import { useState } from "react"; import Status from "./Status"; export default function CarLists() { const { cars } = useVehiclesData(); const carLists = Object.values(cars); const [searchCars, setSearchCars] = useState(); const vehicles = carLists.map((car, index) => ( <Grid item key={index}> <VehicleCard {...car} index={index} /> </Grid> )); const searchResults = (results) => { return results.map((car, index) => ( <Grid item key={index}> <VehicleCard {...car} index={index} /> </Grid> )); }; const search = (event) => { const word = event.target.value.toLowerCase(); const results = carLists.filter((car) => { const values = Object.values(car).map((value) => { if (typeof value === "string") { return value.toLowerCase(); } return value.toString(); }); return values.includes(word); }); setSearchCars(results); return results; }; if (cars || carLists) { return ( <Grid container item justifyContent="center" spacing={2} md={10} sx={{ marginTop: "16px" }} > <Grid container item xs={12} justifyContent="center"> <Grid item xs={6} sm={4}> <Box sx={{ display: "flex", alignItems: "flex-end", justifyContent: "center", }} > <SearchIcon sx={{ color: "action.active", mr: 1, my: 0.5 }} /> <TextField id="input-search" label="Search" variant="standard" onChange={(event) => search(event)} /> </Box> </Grid> </Grid> {searchCars && searchCars.length > 0 ? searchResults(searchCars) : vehicles} </Grid> ); } else { return <Status />; } } <file_sep>/frontend/src/components/CarDetails.js import { Button, Card, CardContent, CardHeader, Divider, FormControl, Grid, InputLabel, MenuItem, Paper, Select, Typography, useMediaQuery, } from "@mui/material"; import CarCarousel from "./CarCarousel"; import CarDetailsTab from "./CarDetailsTab"; import ConfirmationModalFinanace from "./ConfirmationModalFinance"; import { useParams, useHistory } from "react-router-dom"; import useVehiclesData from "../hooks/useVehiclesData"; import { Box } from "@mui/system"; import BasicTable from "./BasicTable"; import StripeCheckout from "react-stripe-checkout"; import useStripe from "../hooks/useStripe"; import { useState, useEffect } from "react"; import SnackbarNotification from "./SnackbarNotification"; import axios from "axios"; import calculateMonthly from "../Utils/CalculateMonthly"; import CarSpinCarousel from "./CarSpinCarousel"; import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord"; import ConfirmationModal from "./ConfirmationModal"; export default function CarDetails() { const { getCarById } = useVehiclesData(); let params = useParams(); const path = useHistory(); const car = getCarById(params.carId); // Setting Term for monthly payments const [years, setYears] = useState(7); // Track the payment method const [paymentMethod, setPaymentMethod] = useState(); const handleChange = (event) => { setYears(event.target.value); }; // Setting Down payment const [downPayment, setDownPayment] = useState(2000); const handleChangeDown = (event) => { setDownPayment(event.target.value); }; // Once payment completed confirmation modal pops up const [confirmation, setConfirmation] = useState(false); // Success Notification const [open, setOpen] = useState(false); const handleClick = () => { setOpen(true); }; const handleClose = (event, reason) => { if (reason === "clickaway") { return; } setOpen(false); }; // Stripe Payment Custome hooks const { product, setProduct, makePayment, status, email } = useStripe(); const totalPrice = car && Number.parseInt(car.price + car.price * 0.05 + 29900); useEffect(() => { if (car) { setProduct({ name: `${car.year} ${car.model} ${car.trim}`, price: totalPrice, productBy: car.make, }); } }, [car]); // Display success notification if Stripe payment completed useEffect(() => { if (status) { handleClick(); setConfirmation(true); axios.put(`/api/cars/${car.id}`).then((res) => { console.log("response from sold car route", res); }); } }, [status, email]); const matches = useMediaQuery((theme) => theme.breakpoints.down("sm")); const styles = () => { if (matches) { return {}; } return { display: "flex", flexDirection: "column", alignItems: "center", }; }; const paymentBoxStyles = () => { return { height: "395px", padding: "1em", display: "flex", flexDirection: "column", }; }; const imageList = car && car.image_links.filter((image, index) => (index > 0 ? image : null)); if (car) { return ( <> <Card sx={{ border: "none", boxShadow: "none" }}> <CardHeader title={`${car.year} ${car.model} ${car.trim}`} subheader={`$${new Intl.NumberFormat().format(car.price / 100)}`} /> <CarSpinCarousel image1={car.carousel_links[0]} image2={car.carousel_links[1]} image3={car.carousel_links[2]} /> <Grid container justifyContent="center" alignItems="center"> <Grid item xs={12} sm={4}> <Typography sx={{ display: "flex", justifyContent: "center", alignItems: "center", }} > <FiberManualRecordIcon fontSize="small" /> Stock Number: {car.stock_number} </Typography> </Grid> <Grid item xs={12} sm={4}> <Typography sx={{ display: "flex", justifyContent: "center", alignItems: "center", }} > <FiberManualRecordIcon fontSize="small" /> Exterior Color: {car.ext_color} </Typography> </Grid> <Grid item xs={12} sm={4}> <Typography sx={{ display: "flex", justifyContent: "center", alignItems: "center", }} > <FiberManualRecordIcon fontSize="small" /> Interior Color: {car.int_color} </Typography> </Grid> </Grid> <CardContent sx={styles()}> <CarCarousel imageList={imageList} /> </CardContent> <CarDetailsTab specs={car.specs} features={car.features} /> <CardContent> <Typography variant="h4" mb={2}> Price Details </Typography> <Grid container spacing={2}> <Grid item xs={12} sm={6}> <Paper varinat="contained" sx={paymentBoxStyles()} elevation={10} > <Box sx={{ mb: 2 }}> <Typography variant="h5" sx={{ fontWeight: "light" }}> Pay Monthly </Typography> </Box> <Divider variant="middle" /> <Box sx={{ mt: 2, mb: 0, display: "flex", justifyContent: "center", alignItems: "center", }} > <Typography variant="h5" sx={{ fontWeight: "bold" }}> {`$${new Intl.NumberFormat().format( calculateMonthly( totalPrice / 100 - downPayment, 2.99, years ) )}`} </Typography> <ConfirmationModalFinanace term={years} downPayment={downPayment} amount={totalPrice / 100 - downPayment} monthly={calculateMonthly( totalPrice / 100 - downPayment, 2.99, years )} /> </Box> <Box sx={{ display: "flex", justifyContent: "center", }} > <Box sx={{ minWidth: 120, padding: 2 }}> <FormControl fullWidth={false}> <InputLabel id="term-select">Years</InputLabel> <Select labelId="term-select" id="term-select" value={years} label="Years" onChange={handleChange} > <MenuItem value={2}>Two</MenuItem> <MenuItem value={3}>Three</MenuItem> <MenuItem value={4}>Four</MenuItem> <MenuItem value={5}>Five</MenuItem> <MenuItem value={6}>Six</MenuItem> <MenuItem value={7}>Seven</MenuItem> </Select> </FormControl> </Box> <Box sx={{ minWidth: 120, padding: 2 }}> <FormControl fullWidth={false}> <InputLabel id="down-payment-select"> Cash Down </InputLabel> <Select labelId="down-payment-select" id="down-payment-select" value={downPayment} label="Down Payment" onChange={handleChangeDown} > <MenuItem value={2000}>$2,000</MenuItem> <MenuItem value={3000}>$3,000</MenuItem> <MenuItem value={4000}>$4,000</MenuItem> <MenuItem value={5000}>$5,000</MenuItem> </Select> </FormControl> </Box> </Box> <Box sx={{ mt: 0, mb: 2, ml: 2, mr: 2 }}> <BasicTable price={car.price} tax={car.price * 0.05} /> </Box> <Divider variant="middle" /> <StripeCheckout stripeKey={process.env.REACT_APP_STRIPE_SKEY} token={makePayment} name={`${car.year} ${car.model} ${car.trim}`} amount={downPayment * 100} > <Button variant="contained" color="secondary" sx={{ mt: 2 }} onClick={() => setPaymentMethod("finance")} > Pay Deposit </Button> </StripeCheckout> {paymentMethod === "finance" && ( <ConfirmationModal open={confirmation} setOpen={setConfirmation} car={car && car} term={years} downPayment={downPayment} amount={totalPrice / 100 - downPayment} monthly={calculateMonthly( totalPrice / 100 - downPayment, 2.99, years )} paymentMethod={paymentMethod} /> )} <SnackbarNotification open={open} handleClose={handleClose} message={ email && `Payment confirmed! Bill of sale has been sent to ${email}` } /> </Paper> </Grid> <Grid item xs={12} sm={6}> <Paper varinat="contained" sx={paymentBoxStyles()} elevation={10} > <Box sx={{ mb: 2 }}> <Typography variant="h5" sx={{ fontWeight: "light" }}> Pay Once </Typography> </Box> <Divider variant="middle" /> <Box sx={{ m: 2 }}> <Typography variant="h5" sx={{ fontWeight: "bold" }} >{`$${new Intl.NumberFormat().format( (totalPrice / 100).toFixed(2) )}`}</Typography> </Box> <Divider variant="middle" /> <Box sx={{ m: 2 }}> <BasicTable price={car.price} tax={car.price * 0.05} /> </Box> <Divider variant="middle" /> <Box sx={{ m: 2 }}> <Typography variant="h6" sx={{ fontWeight: "bold" }}> Total:{" $"} {new Intl.NumberFormat().format( (totalPrice / 100).toFixed(2) )} </Typography> </Box> <Divider variant="middle" /> <StripeCheckout stripeKey={process.env.REACT_APP_STRIPE_SKEY} token={makePayment} name={`${car.year} ${car.model} ${car.trim}`} amount={product.price} > <Button variant="contained" color="secondary" sx={{ mt: 2 }} onClick={() => setPaymentMethod("cash")} > Pay Total </Button> </StripeCheckout> {paymentMethod === "cash" && ( <ConfirmationModal open={confirmation} setOpen={setConfirmation} car={car && car} paymentMethod={paymentMethod} /> )} <SnackbarNotification open={open} handleClose={handleClose} message={ email && `Payment confirmed! Bill of sale has been sent to ${email}` } /> </Paper> </Grid> </Grid> </CardContent> </Card> </> ); } return null; } <file_sep>/planning/User_Stories.md 1. A user can browse inventory of vehicles. 2. A user can select a vehicle and see more information. 3. A user can see and select options for paying cash or finance options. 4. A user can click the buy button and purchase or finance the vehicle. 5. A user can sign a bill of sale for a cash deal. 6. A user can sign a bill of sale and finance contract for finance deal. 7. A user can save cars to there garage and browse or purchase them later. 8. A user can visit the landing page Admin(Stretch?) 1. A admin can add and remove cars from the inventory 2. Can run an announcemnt banner that will show on the website. 2. (Strech) Can chat real time with the user<file_sep>/backend/db/schema/create.sql DROP TABLE IF EXISTS garage CASCADE; DROP TABLE IF EXISTS orders CASCADE; DROP TABLE IF EXISTS users CASCADE; DROP TABLE IF EXISTS vehicles CASCADE; CREATE TABLE vehicles ( id SERIAL PRIMARY KEY NOT NULL, year INTEGER NOT NULL, mileage INTEGER , make VARCHAR(255) NOT NULL, model VARCHAR(255) NOT NULL, stock_number VARCHAR(255) NOT NULL, trim VARCHAR(255) NOT NULL, price INTEGER NOT NULL, avaliable BOOLEAN NOT NULL DEFAULT TRUE, ext_color VARCHAR(255) , int_color VARCHAR(255) , specs TEXT [], features TEXT [], image_links TEXT [], carousel_links TEXT [] ); CREATE TABLE users ( id SERIAL PRIMARY KEY NOT NULL, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, address VARCHAR(255) NOT NULL, phone_number VARCHAR(255) NOT NULL ); CREATE TABLE orders ( id SERIAL PRIMARY KEY NOT NULL, user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, vehicle_id INTEGER REFERENCES vehicles(id) ON DELETE CASCADE, total_price INTEGER NOT NULL, order_date TIMESTAMP DEFAULT now() ); CREATE TABLE garage ( id SERIAL PRIMARY KEY NOT NULL, user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, vehicles INTEGER[] ); <file_sep>/planning/Stack_Choices.md ## Front End React, Sass, TailwindCSS, ## Back End Node, Express, Postgres<file_sep>/frontend/src/components/CarCarousel.js import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader import { Carousel } from "react-responsive-carousel"; import "../styles/slide.css"; export default function CarCarousel(props) { const images = props.imageList.map((image) => { return ( <div key={image}> <img src={image} alt="Mazda Pictures" /> </div> ); }); return ( <Carousel className="car-carousel" infiniteLoop={true}> {images} </Carousel> ); } <file_sep>/frontend/src/components/BusinessHours.js import * as React from "react"; import PropTypes from "prop-types"; import Tabs from "@mui/material/Tabs"; import Tab from "@mui/material/Tab"; import Typography from "@mui/material/Typography"; import Box from "@mui/material/Box"; function TabPanel(props) { const { children, value, index, ...other } = props; return ( <div role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {value === index && ( <Box sx={{ p: 3 }}> <Typography>{children}</Typography> </Box> )} </div> ); } TabPanel.propTypes = { children: PropTypes.node, index: PropTypes.number.isRequired, value: PropTypes.number.isRequired, }; function a11yProps(index) { return { id: `simple-tab-${index}`, "aria-controls": `simple-tabpanel-${index}`, }; } export default function BusinessHours() { const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <Box sx={{}}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label="Business Hours" centered textColor="inherit" indicatorColor="secondary" > <Tab label="Sales" {...a11yProps(0)} /> <Tab label="Service" {...a11yProps(1)} /> <Tab label="Parts" {...a11yProps(2)} /> </Tabs> </Box> <TabPanel value={value} index={0} className="business-hours"> <table> <tbody> <tr> <td>Monday</td> <td>9:00AM - 8:30PM</td> </tr> <tr> <td>Tuesday</td> <td>9:00AM - 8:30PM</td> </tr> <tr> <td>Wednesday</td> <td>9:00AM - 8:30PM</td> </tr> <tr> <td>Thursday</td> <td>9:00AM - 8:30PM</td> </tr> <tr> <td>Friday</td> <td>9:00AM - 6:00PM</td> </tr> <tr> <td>Saturday</td> <td>9:00AM - 6:00PM</td> </tr> <tr> <td>Sunday</td> <td>12:00PM - 5:00PM</td> </tr> </tbody> </table> </TabPanel> <TabPanel value={value} index={1} className="business-hours"> <table> <tbody> <tr> <td>Monday</td> <td>7:00AM - 5:00PM</td> </tr> <tr> <td>Tuesday</td> <td>7:00AM - 5:00PM</td> </tr> <tr> <td>Wednesday</td> <td>7:00AM - 5:00PM</td> </tr> <tr> <td>Thursday</td> <td>7:00AM - 5:00PM</td> </tr> <tr> <td>Friday</td> <td>7:00AM - 5:00PM</td> </tr> <tr> <td>Saturday</td> <td>8:00AM - 4:00PM</td> </tr> <tr> <td>Sunday</td> <td>Closed</td> </tr> </tbody> </table> </TabPanel> <TabPanel value={value} index={2} className="business-hours"> <table> <tbody> <tr> <td>Monday</td> <td>7:30AM - 5:00PM</td> </tr> <tr> <td>Tuesday</td> <td>7:30AM - 5:00PM</td> </tr> <tr> <td>Wednesday</td> <td>7:30AM - 5:00PM</td> </tr> <tr> <td>Thursday</td> <td>7:30AM - 5:00PM</td> </tr> <tr> <td>Friday</td> <td>7:30AM - 5:00PM</td> </tr> <tr> <td>Saturday</td> <td>8:00AM - 4:00PM</td> </tr> <tr> <td>Sunday</td> <td>Closed</td> </tr> </tbody> </table> </TabPanel> </Box> ); } <file_sep>/backend/db/index.js // load .env data into process.env require("dotenv").config(); const { Pool } = require("pg"); const pool = new Pool({ user: process.env.PGUSER, host: process.env.PGHOST, database: process.env.PGDATABASE, password: <PASSWORD>, port: process.env.PGPORT, }); pool .connect() .catch((e) => console.log(`Error connecting to Postgres server:\n${e}`)); module.exports = pool; <file_sep>/frontend/src/components/Videos.js import { Grid, Typography } from "@mui/material"; import ReactPlayer from "react-player"; export default function Videos() { return ( <> <Grid container justifyContent="center" sx={{ backgroundColor: "#bec2cb" }} > <Grid item py={1}> <Typography variant="h3" fontWeight="light" color="white"> Helpful Videos </Typography> <Typography variant="h5">Featuring Our Staff</Typography> </Grid> </Grid> <Grid container justifyContent="center" spacing={2} mt={2}> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=juEqvlETN30" width="370px" height="180px" /> </Grid> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=xs5LwT9p_-Y" width="370px" height="180px" /> </Grid> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=f5EwnrDWZbk" width="370px" height="180px" /> </Grid> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=Gl3ft2TuQWc" width="370px" height="180px" /> </Grid> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=48OV6jOU2oM" width="370px" height="180px" /> </Grid> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=iX6I8IP1dmY" width="370px" height="180px" /> </Grid> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=xQMY43AFW2w" width="370px" height="180px" /> </Grid> <Grid item xs={12} md={6} lg={4} sx={{ display: "flex", justifyContent: "center" }} > <ReactPlayer url="https://www.youtube.com/watch?v=_JlJ7ug0W-E" width="370px" height="180px" /> </Grid> </Grid> </> ); } <file_sep>/frontend/src/components/Status.js import { Paper } from "@mui/material"; export default function Status() { return ( <div style={{ position: "absolute", width: "100vw", height: "100vh", backgroundColor: "rgba(0,0,0,.5)", }} > <Paper sx={{ position: "relative", top: "50%", left: "50%", width: 0, }} > <img src="/images/status.png" alt="loading status" className="App-logo" style={{ height: "unset" }} /> </Paper> </div> ); } <file_sep>/planning/Routes.md ### Routes #### Users - GET /users - Browse users - GET /users/:user_id - Read specific user - POST /users - Create new user - PUT /users/:user_id - Edit a specific user - DELETE /users/:user_id/ - Delete a user #### Inventory - GET /cars - Browse cars - GET /cars/:car_id - Read specific car #### Garage - GET /garage/:user_id - Browse specific users garage - POST /garage/:user_id/ - Add a car to a users garage - DELETE /garage/:user_id/ - Delete a specific order #### Login - GET /login - Browse login page - POST /login - Login a user ### Checkout - GET /checkout/:car_id - Purchase a specific car #### Home - GET / - Home page<file_sep>/backend/routes/vehicles.js const router = require("express").Router(); module.exports = (db) => { // list all avaliable cars router.get("/cars", (req, res) => { db.query(`SELECT * from vehicles WHERE avaliable=true;`).then((data) => { res.send(data.rows); }); }); // change the car to unavaliable / sold router.put("/cars/:car_id", (req, res) => { db.query(`UPDATE vehicles set avaliable=false WHERE id=$1;`, [ req.params.car_id, ]).then((data) => { res.send(data.rows); }); }); // list only the unique car models router.get("/cars/models", (req, res) => { db.query( `SELECT DISTINCT ON (model) id, year, model, make, trim, price, image_links FROM vehicles WHERE avaliable=true LIMIT 3;` ).then((data) => { res.send(data.rows); }); }); return router; }; <file_sep>/frontend/src/Utils/CalculateMonthly.js // Function for calculating monthly payments function calculateMonthly(amount, rate, term) { const intrate = rate / 100 / 12; const months = term * 12; if (intrate === 0) { return amount / months; } const x = Math.pow(1 + intrate, months); const monthly = (amount * x * intrate) / (x - 1); return Math.round(monthly * 100) / 100; } export default calculateMonthly; <file_sep>/frontend/src/components/VehicleCard.js import * as React from "react"; import Card from "@mui/material/Card"; import CardMedia from "@mui/material/CardMedia"; import CardContent from "@mui/material/CardContent"; import CardActions from "@mui/material/CardActions"; import IconButton from "@mui/material/IconButton"; import Typography from "@mui/material/Typography"; import FavoriteIcon from "@mui/icons-material/Favorite"; import ShareIcon from "@mui/icons-material/Share"; import { CardActionArea, Grid, Button } from "@mui/material"; import { useHistory } from "react-router-dom"; export default function VehicleCard(props) { const { id, model, year, price, trim, mileage, image_links } = props; const path = useHistory(); const carDetails = () => { path.push(`/cars/${id}`); }; return ( <Card sx={{ maxWidth: 400 }} raised> <CardActionArea onClick={carDetails}> <CardMedia component="img" height="194" image={image_links[0]} alt={model} /> <CardContent> <Grid container> <Grid item sx={{ textAlign: "left", flexGrow: 1 }}> <Typography variant="h6" color="text.secondary"> {year} {model} </Typography> </Grid> <Grid item> <Typography variant="h6" color="text.secondary" sx={{ fontWeight: "bold" }} > {`$${new Intl.NumberFormat().format(price / 100)}`} </Typography> </Grid> </Grid> <Grid container> <Grid item sx={{ textAlign: "left", flexGrow: 1 }}> <Typography variant="body1" color="text.secondary"> {trim} </Typography> </Grid> <Grid item> <Typography variant="body1" color="text.secondary"> Est. Payment for 5 years </Typography> </Grid> </Grid> <Grid container> <Grid item sx={{ textAlign: "left", flexGrow: 1 }}> <Typography variant="body1" color="text.secondary"> {`Mileage: ${mileage}km`} </Typography> </Grid> <Grid item> <Typography variant="body1" color="text.secondary"> {`$${new Intl.NumberFormat().format( price / (12 * 5) / 100 )}/mo`} </Typography> </Grid> </Grid> </CardContent> </CardActionArea> <CardActions disableSpacing> <Grid container> <Grid item sx={{ flexGrow: 1, textAlign: "left" }}> <IconButton aria-label="add to favorites"> <FavoriteIcon /> </IconButton> <IconButton aria-label="share"> <ShareIcon /> </IconButton> </Grid> <Grid item> <Button variant={"contained"} color={"secondary"} onClick={carDetails} > Buy Now </Button> </Grid> </Grid> </CardActions> </Card> ); } <file_sep>/frontend/src/components/About.js import { Grid, Typography, useMediaQuery } from "@mui/material"; import Map from "./HomeMap"; import ReactPlayer from "react-player"; export default function About() { const mobileMode = useMediaQuery((theme) => theme.breakpoints.down("md")); const location = { address: "Sundance Mazda, 17990 102 Ave NW, Edmonton, AB", lat: 53.544013658365934, lng: -113.63180428465739, }; return ( <Grid container justifyContent="center"> <Grid container justifyContent="center" sx={{ backgroundColor: "#bec2cb" }} > <Grid item py={1}> <Typography variant="h3" fontWeight="light" color="#fff"> Welcome to Sundance Mazda </Typography> <Typography variant="h5"> Your Mazda Dealer of Choice in Greater Edmonton </Typography> </Grid> </Grid> <Grid item xs={12} pt={2} px={4}> <Typography variant="h7"> Welcome to Sundance Mazda, your go-to destination for Mazda vehicles, parts, and accessories in Greater Edmonton. Located at 17990 - 102 Ave NW in Edmonton, Alberta, we have proudly served the Greater Edmonton area since 1975. Run by the Reid family, we care about our customers as if they were one of our own. At Sundance Mazda, not only do we sell new and pre-owned Mazda vehicles, but we also offer our clients personalized service based on their needs and budget. What's more, our staff speaks several languages, including Swahili, Hindi, Tagalog, Spanish, Urdu, Gujarati, German, Patwa, and Punjabi. This is what makes the Sundance Mazda experience one of a kind! </Typography> <Typography variant="h5" m={2}> Sundance Mazda: Your Destination for Expert Service </Typography> <Typography variant="h7"> Sundance Mazda offers a complete collection of brand new Mazda vehicles as well as reliable pre-owned vehicles that have been inspected by our dedicated, knowledgeable team of technicians - including two Mazda Master Technicians! If you need servicing, Sundance Mazda offers a wide range of after-sales services such as repairs and maintenance, and we also offer genuine Mazda parts and accessories. At Sundance Mazda, customer service is our top priority and that’s why we have competitive prices on Mazda products and services. We also have many promotions, rebates, and incentives that are updated regularly. We'll do whatever it takes to provide our clients with the service and respect they deserve! To learn more about Sundance Mazda and the services and vehicles we offer, contact us today at 1-844-394-3671 or online using our contact form. </Typography> </Grid> <Grid item xs={12}> <Map location={location} zoomLevel={17} /> </Grid> </Grid> ); } <file_sep>/frontend/src/hooks/useVehiclesData.js import { useEffect, useState } from "react"; import axios from "axios"; export default function useVehiclesData() { const [cars, setCars] = useState({}); useEffect(() => { axios.get("/api/cars").then((res) => { console.log("res", res); res.data.forEach((car) => { const newCar = {}; newCar[`${car.id}`] = car; setCars((prev) => ({ ...prev, ...newCar })); }); }); }, []); const getCarById = (id) => { return cars[`${id}`]; }; return { cars, getCarById, setCars }; } <file_sep>/planning/Project_Description.md ## Project Title Sundance Mazda ## Project Description Our app will be for a single dealership. It will allow users to browse inventory, select a vehicle and purchase it online. ## Target Audience After discussion with the manager of Sundance Mazda the biggest issue they had with their website was that a user could not acctually purchase the vehicle completly onlne. We want to target that user that want to make there purchase online with minimal interaction with dealership staff. He also mentioned some styling concerns. ## Team Members <NAME> <NAME> <file_sep>/README.md # Final Project for Lighthouse Labs # Sundance Mazda Sundance Mazda is a project to create a e-commerce site for a single car dealership. The goal of the project was to create a site that allowed a user to buy a vehicle completly online, looked great, and was designed to be responsive for all media types. The manager and owner of Sundance Mazda (Located in Edmonton, AB) were kind enough to allow us to use their dealership for our project. This repository was created by building our own skelton using Node, Express and Postgres back end. The front end was created using React and Material UI for styling. Stripe and Google Maps API's are used for payment and map functionality. ## Authors Created by: <NAME> - <EMAIL> - [Github](https://github.com/Abaid77) - [LinkedIn](https://www.linkedin.com/in/amit-baid-300898220/) <NAME> - You can find me on [LinkedIn](https://www.linkedin.com/in/nahom-mehanzel/) or [Github](https://github.com/NahomKibreab). ## App Functions The site includes the following functionality: - Single page app created using React. - Uses Google Maps API to show a map with the dealers location. - Uses Stripe API to collect payment from the customer. - Responsive design for mobile/tablet/desktop. - Communicates with the server via Axios(JSON) and HTTP request. - Communicates with the database using Postgres(PG Native API). - Nav Bar: - is fixed to the top. - has padding on both side. - contains the Sundance Mazda logo in the top left. - contains links for Home, Inventory, About Us, Videos, Reviews and News. - contains a phone Icon with links to the phone numbers for all departments. - contains a user icon with link to My Profile, My Garage, and Logout. - changes to drawer menu with menu button on left for tablet and mobile. - links and user icon disappear and links are moved to drawer menu. - is styled using MAterial UI. - Footer Bar: - contains the address, email and phone number for the dealership. - contains icons for links to Facebook, Twitter and Instagram. - contains clickable abs to show the hours for all departments. - contains helpful links. - is on every page. - is mobile responsive. - is styled using Material UI. - Home Page: - contains a banner with the dealers name and tag line. - contains a responsive carousel to display offers. The carousel: - rotates automatically between pictures. - has 3 different sets of pictures for mobile/tablet/desktop and switches based on media size. - will stop rotating if you hover your mouse over the picture. - contains 3 boxes to showcase Manager Specials. These boxes: - pull data and pictures from the data base. - are links to the details page for those vehicles. - are changed to column and resized for tablet and mobile. - contains a full width intergrated Google Maps with the dealers location centered and pinned. - responsive design for mobile/tablet/desktop - is styled using Material UI. - Inventory Page: - displays the entire inventory of the dealer from the database, with each vehicle on its own card. These vehicle cards: - pull info from the database in order to display info about each vehicle. - are changed to column and resized for tablet and mobile. - have icons for adding to my garage and sharing the link. - have a buy now button that links to the details page for that vehicle. - clicking anywhere will also link to the details page for that vehicle. - has a searbar at the top. The search bar: - allows user to search by year, make, model, trim or any other term. - checks all fields in the vehicles table for matches and then only shows matching vehciles. - updates as the user is typing. - is styled using Material UI. - Car Detials Page: - displays the year, model, trim and price at the top of the page. - has a responsive carousel at the top that: - displays pictures of the correct make, model,trim and color by accessing them from the database. - rotates through 3 pictures to show all angles of the vehicle. - does not stop rotating on mouse over. - is resized to fit for mobile and tablet. - displays details about the stock number, exterior and interior colors. - has a 2nd responsive carousel that: - shows pictures of the actual vehicle at the dealer by accessing them from the database. - does not rotate automatically. - has arrows on either side to scroll through the pictures. - has clickable thumbnails below. - the current picture will be high lighted in the thumbnails. - is resized to fit for mobile and tablet. - has tabs to display specifications and features. These tabs: - allow the user to click between specs and features and displays the correct info from the database. - automatically create 2 columns from the data in order to display. - each item is highlighted on mouse over and has a star icon. - has a price details section with 2 boxes for a pay monthly option or pay once option. These boxes: - display the price, taxes, shipping and either total for pay once or monthly payment for pay monthly. - allows the user to choose the number of years and down payment for pay monthly, and updates automatically as changed. - has a ? icon which opens a modal with detailed information on the financing. This modal is updated based on the users choices for term and down payment. - has a pay deposit/total button at the bottom which will call the Stripe API to collect either the full payment or cash down. This button open a confirmation popper that confirms payment and email of bill of sale, changes the status of the vehicle in the database to sold and opens a confirmation modal that: - displays all information about that transaction taken from the database and user inputs. - is designed to look like a bill of sale would and contains seller's info, buyer's info, vehicle info, purchase info and in the case of monthly payment info. - has a button at the bottom to print all documents. - cannot be closed until the DONE button is clicked. - redirects user to home page after closing. - resizes for extra small media size. - About Us Page: - displays a welcome banner at the top. - displays a welcome message from the dealer. - displays page wide interactive Google Map with dealership centered and pinned. - responsive design for mobile/tablet/desktop - is styled using Material UI. - Videos Page: - displays a banner on the top with a title. - displays embeded youtube videos created by the staff of the dealership. - responsive design for mobile/tablet/desktop - is styled using Material UI. ## Getting Started 1. Create the `.env` by using `.env.example` as a reference: `cp .env.example .env` 2. Update the .env file with your correct local information on both the frontend and backend. - Front End: REACT_APP_STRIPE_SKEY= (YOUR STRIPE PUBLIC KEY) REACT_APP_GOOGLE_MAPS_KEY= (YOUR GOOGLE MAPS API KEY) - Back End: PGHOST=localhost PGUSER=mazda PGDATABASE=mazda PGPASSWORD=<PASSWORD> PGPORT=5432 EXPRESSPORT=8000 STRIPE_SKEY= (YOUR STRIPE SECRET KEY) 3. Install dependencies: `npm i` in both the frontend and backend folder. 4. Reset the data base using `npm run reset` in the backend folder. (You can use this command anytime to reset the database to intial state) 5. From the backend folder run `npm start` to launch the database. 6. From the frontend folder run `npm start` to launch the react app. 7. Visis `http://localhost:3000` Please note: - The data base is seeded with 6 different vehicles copied for a total of 12 vehicles. - The user login/logout profile and garage are for demo purposes only. - The Reviews and News links are links to the actualy Sundance Mazda website. - If you have any issues or questions please feel free to contact us with info above. ## Screenshots !["Screenshot of home page desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Home-DT-1.png?raw=true) ###### Home page desktop version !["Screenshot of home page desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Home-DT-2.png?raw=true) ###### Home page desktop version !["Screenshot of home page tablet size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Home-Tab-1.png?raw=true) ###### Home page tablet version !["Screenshot of home page mobile size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Home-Mob-1.png?raw=true) ###### Home page mobile version !["Screenshot of menu drawer"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/MenuDrawer.png) ###### Menu Drawer for tablet and mobile !["Screenshot of inventory page desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Inv-DT-1.png?raw=true) ###### Inventory page desktop version !["Screenshot of inventory page mobile size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Inv-Mob-1.png?raw=true) ###### Inventory page mobile version !["Screenshot of car details page desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Details-DT-1.png?raw=true) ###### Car details page desktop version !["Screenshot of car details page desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Details-DT-2.png?raw=true) ###### Car details page desktop version !["Screenshot of car details page desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Details-DT-3.png?raw=true) ###### Car details page desktop version !["Screenshot of car details page desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Details-DT-3.png?raw=true) ###### Car details page desktop version !["Screenshot of car details page mobile size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Details-Mob-1.png?raw=true) ###### Car details page mobile version !["Screenshot of footer desktop size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Footer-DT-1.png?raw=true) ###### Footer desktop version !["Screenshot of footer mobile size"](https://github.com/NahomKibreab/Sundance-Mazda-Project/blob/master/frontend/public/images/screenshots/Footer-Mob-1.png?raw=true) ###### Footer mobile version ## Dependencies ### Front End - @emotion/react: 11.4.1 - @emotion/styled: 11.3.0 - @mui/icons-material: 5.0.1 - @mui/material: 5.0.1 - @testing-library/jest-dom: 5.14.1 - @testing-library/react: 11.2.7 - @testing-library/user-event: 12.8.3 - axios: 0.21.4 - google-map-react: 2.1.10 - react: 17.0.2 - react-dom: 17.0.2 - react-player: 2.9.0 - react-responsive-carousel: 3.2.21 - react-router-dom: 5.3.0 - react-scripts: 4.0.3 - react-stripe-checkout: 2.6.3 - web-vitals: 1.1.2 ### Back End - cors: 2.8.5 - dotenv: 10.0.0 - express: 4.17.1 - pg: 8.7.1 - stripe: 8.176.0 - uuid: 8.3.2 ## Dev Dependencies ### Front End - @iconify/icons-mdi: 1.1.31 - @iconify/react: 3.0.1 ### Back End - morgan: 1.10.0 - nodemon: 2.0.13 <file_sep>/backend/server.js require("dotenv").config(); const express = require("express"); const app = express(); const PORT = process.env.EXPRESSPORT || 8000; const morgan = require("morgan"); const db = require("./db"); const cors = require("cors"); const { v4: uuidv4 } = require("uuid"); const stripe = require("stripe")(process.env.STRIPE_SKEY); app.use(morgan("dev")); app.use(express.json()); app.use(cors()); // api const vehicles = require("./routes/vehicles"); app.use("/api", vehicles(db)); app.get("/", (req, res) => { res.send(`Server is listening on port ${PORT}`); }); app.get("/db", (req, res) => { db.query( ` select * from test; ` ).then((data) => { res.json(data.rows); }); }); // Stripe payment endpoint app.post("/payment", (req, res) => { const { product, token } = req.body; console.log("Product", product); console.log("Price", product.price); const idempotencyKey = uuidv4(); return stripe.customers .create({ email: token.email, source: token.id, }) .then((customer) => { stripe.charges.create( { amount: product.price, currency: "usd", customer: customer.id, }, { idempotencyKey } ); }) .then((result) => res.status(200).json(result)) .catch((err) => console.log(err)); }); app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
45933480ac287b0aa14d2dddb0683aff0f43c7ca
[ "JavaScript", "SQL", "Markdown" ]
22
JavaScript
NahomKibreab/Sundance-Mazda-Project
ef1e609a4b9280367a44a2d4bac1eb035f251b8b
5a65e4f9e4cc60df3817dfd8db6d98b225253e06
refs/heads/master
<repo_name>psyvisions/slot-machine-1<file_sep>/index.php <?php try{ require_once 'Appconfig.php'; $u1 = User::get_instance(); } catch (Exception $e){ dump_it($e->getTraceAsString()); } require_once 'Header.php'; ?> <body> <div id="slots"> <div id="slots-reel1" class="slots-reel"> <div class="slots-line"></div> </div> <div id="slots-reel2" class="slots-reel"> <div class="slots-line"></div> </div> <div id="slots-reel3" class="slots-reel"> <div class="slots-line"></div> </div> <div id="slots-status"> <div id="slots-status-display"></div> </div> <!--just for activating tooltips--> <script type="text/javascript"> $(function () { $("[rel='popover']").popover(); }); </script> <!-- Verify --> <div id="verify"> <div class="verify_field"> <label class="field_name">Client seed</label> <span class="field_question badge badge-info" rel="popover" data-title="Client seed" data-placement="top" data-content=" This is the first of the two values which have direct effect on generating of random symbols. You can put here any string or number. If you don't enter anything, string will be randomly filled with your browser. So you have direct impact on generating of random symbols and before the spin slot-machine doesn't know what value will be used and it can't adjust its seed for your loosing. ">?</span> <br /> <!--(Your lucky number)--> <input id="client_seed" name="client_seed" type="text" value="" /> </div> <div class="verify_field"> <label class="field_name">New Hash(server seed)</label> <span class="field_question badge badge-info" rel="popover" data-title="New hashed server seed" data-placement="top" data-content=" This is the second of the two values. It is provided by slot-machine. Because it was hashed, you can't to know what the values actually will be used for generating of symbols before a spin. After the spin slot-machine put here new hashed seed and this field copies to the field below. ">?</span> <br /> <input readonly id="new_hashed_server_seed" name="hashed_server_seed" type="text" value="" /> </div> <div class="verify_field"> <label class="field_name">Last Hash(server seed)</label> <span class="field_question badge badge-info" rel="popover" data-title="Last hashed server seed" data-placement="top" data-content=" After the spin was done the copy of the field above will be placed here. ">?</span> <br /> <input readonly id="last_hashed_server_seed" name="hashed_server_seed" type="text" value="" /> </div> <div class="verify_field"> <label class="field_name">Server seed</label> <span class="field_question badge badge-info" rel="popover" data-title="Server seed" data-placement="top" data-content=" Here you can see what really values was used for the seeding of random symbols generator. You can sure that exactly these values was provided by slot-machine before the spin (for generating of random symbols) if you hash this string using SHA1 function. Or just click &quot;Verify&quot; button and it will be done automatically. If everything ok, fields will be highlighted blue color. So you can be sure that slot-machine doesn&apos;t adjust the values for to its advantage. ">?</span> <br /> <input readonly id="server_seed" name="server_seed" type="text" value="" /> </div> <div class="verify_field"> <label class="field_name">Symbols</label> <span class="field_question badge badge-info" rel="popover" data-title="Symbols" data-placement="top" data-content=" The last field contains the symbols which are generated using exactly these client and server seeds. When you press &quot;Verify&quot; the field is highlighted with green if client and server seeds correspond to symbols are outputed and red otherwise. So if you change client seed and press &quot;Verify&quot; the color of field &quot;Symbols&quot; may be changed to red in case of mismatching the symbols for given seeds and ones was generated ">?</span> <br /> <input readonly id="symbols" name="symbols" type="text" value="" /> </div> <button id="verify_button" class="btn" aria-hidden="true">Verify</button> </div> <!-- /Verify --> <!-- Chat --> <div id="yshout"></div> <!-- Slots body --> <div id="slots-body"> <img id="slots-logo" src="images/bsm-logo.png" alt="SatoshiSlots.com"> <img id="slots-paytable" src="images/bsm-paytable.png" alt="Paytable"> <div id="slots-address" class="slots-display"> <?php echo $u1->bitcoin_receive_address; ?> </div> <div id="slots-balance" class="slots-display">0</div> <div id="slots-bet" class="slots-display">0</div> <button id="slots-minus001" class="slots-button slots-minus"></button> <button id="slots-minus01" class="slots-button slots-minus"></button> <button id="slots-minus1" class="slots-button slots-minus"></button> <button id="slots-plus001" class="slots-button slots-plus"></button> <button id="slots-plus01" class="slots-button slots-plus"></button> <button id="slots-plus1" class="slots-button slots-plus"></button> <button id="slots-spin" class="slots-button"></button> <button id="slots-lastbet" class="slots-button slots-bottombutton"></button> <button id="slots-maxbet" class="slots-button slots-bottombutton"></button> <button id="slots-autoplay" class="slots-button slots-bottombutton"></button> <button id="slots-cashout" class="slots-button slots-bottombutton" data-toggle="modal" data-target="#cashout_modal"></button> </div> <!-- Statistic tables --> <div id="statistic"> <?php echo '<span class="table_header">Last 20 transactions</span> <br />'; Transaction::show_transactions($option = 'last'); echo '<a href="fullList.php?option=last">Full list</a><br /><br />'; echo '<span class="table_header">20 biggest winners</span> <br />'; Transaction::show_transactions($option = 'biggestwinners'); echo '<a href="fullList.php?option=biggestwinners">Full list</a><br /><br />'; echo '<span class="table_header">Interesting facts</span> <br />'; show_interesting_facts(); ?> </div> <!-- /Statistic tables --> <!-- /Slots body --> </div> <!-- Modal cashout dialog --> <div id="cashout_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Cashout</h3> </div> <div class="modal-body"> <!-- (Default) --> <div id="default_confirmed_cashout_message" > <h5>Please, wait...</h5> <div class="progress progress-striped active"> <div class="bar" style="width: 100%;"></div> </div> </div> <!--No bitcoin connection--> <div id="no_bitcoin_connection_message" style="display: none" class="alert alert-error"> <span class="label label-error">No bitcoin connection</span> <p> No bitcoin connection. Please try later. </p> </div> <!-- display when money which user sent was confirmed --> <div id="confirmed_cashout_message" style="display: none" class="alert alert-success"> <span class="label label-success">Success</span> <p> Your coins were sent successfully, here is the transaction ID: <br /> <span id="txid">THE_TRANSACTION_ID_FROM_BLOCKCHAIN.INFO HERE</span> </p> </div> <!-- display when money which user sent was NOT confirmed --> <div id="not_confirmed_cashout_message" style="display: none" class="alert alert-info"> <span class="label label-info">Info</span> <p> There aren't enough confirmations of your deposit just yet. <br /> Please wait 10 mins and try again. Thank you! </p> </div> <!-- Zero balance --> <div id="zero_cashout_message" style="display: none" class="alert alert-info"> <p> <span class="label label-info">Info</span> Your balance is 0 </p> </div> <div id="paying_out_off_message" style="display: none" class="alert alert-info"> <p> <span class="label label-info">Info</span> Paying out is off now. </p> </div> <!-- Big win --> <div id="big_money_message" style="display: none" class="alert"> <p> <span class="label label-warning">Big win!</span> There are not enough funds in the hot wallet to pay that. Please contact support to get payment from the secure cold wallet </p> </div> <!-- Trying to cashout when game is running --> <div id="spin_is_running_cashout_message" style="display: none" class="alert alert-info"> <p> <span class="label label-info">Info</span> You can cashout only when the game is not running </p> </div> </div> <div class="modal-footer"> <button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Ok</button> </div> </div> <!-- /Modal cashout dialog --> <!-- Sounds --> <div id="audio"> <audio id="spin5sec" preload="auto"> <source src="sounds/mp3/Spin_5sec.mp3" /> <source src="sounds/wav/Spin_5sec.wav" /> </audio> <audio id="win" preload="auto"> <source src="sounds/mp3/Win.mp3" /> <source src="sounds/wav/Win.wav" /> </audio> <audio id="loose" preload="auto"> <source src="sounds/mp3/Loose.mp3" /> <source src="sounds/wav/Loose.wav" /> </audio> <audio id="spinbutton" preload="auto"> <source src="sounds/mp3/Button_SPIN_only.mp3" /> <source src="sounds/wav/Button_SPIN_only.wav" /> </audio> <audio id="buttons" preload="auto"> <source src="sounds/mp3/Button_all_the_rest.mp3" /> <source src="sounds/wav/Button_All_the_rest.wav" /> </audio> <audio id="cashregister" preload="auto"> <source src="sounds/mp3/Cash_Register.mp3" /> <source src="sounds/wav/Cash_Register.wav" /> </audio> </div> <!-- /Sounds --> <script type="text/javascript"> function get_cookie ( cookie_name ){ var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' ); if ( results ) return ( unescape ( results[2] ) ); else return null; } $(document).ready(function(){ slot = new Slot(); slot.linesFilling(); slot.bitcoinConnection.checkForBitcoinConnection(); slot.checkSlotOptions(); slot.syncWithServer().done(function() { slot.updateBalanceAndBet(); }); //slot.updateBalanceAndBet(); slot.initAudio(); $('button#slots-spin').on('click', function(){ try{ slot.audio.spinbutton.play(); } catch(e){ if (window.console){ console.log(e+" Audio doesn't supported")} } slot.spin() }); $('button#slots-maxbet').on('click', function(){ slot.audio.buttons.play(); slot.makeMaxBet(); }); //BIND EVENTS--------------------------------------------------------------------------- $('div#slots-body').bind('spinFinished', function(e, status, param2) { if (slot.autoplay == true){ autoplay(); } }); $('button#slots-autoplay').bind('autoplayTrigger', function(e, status, param2) { }); $('div#slots-body').bind('newIncommingPayment', function(e, status, param2) { if (window.console) console.log('newIncommingPayment = '+status); }); //when response for spin is getting $('div#slots-body').bind('responseSpinGetting', function(e, successStatus, param2) { if (successStatus){ slot.afterSpinResponseGetting(); } }); //AUTOPLAY--------------------------------------------------------------------------- function autoplay(){ if ( !slot.spin() ){ slot.autoplay = false; $('button#slots-autoplay').removeClass('active'); return false; } } $('button#slots-autoplay').on('click', function(){ slot.audio.buttons.play(); if ( slot.autoplay == true ){//toggle to false //$('button#slots-autoplay').trigger('autoplayTrigger', ['false', 'Param 2']); $('button#slots-autoplay').removeClass('active'); slot.autoplay = false; return; } else{//toggle to true //$('button#slots-autoplay').trigger('autoplayTrigger', ['true', 'Param 2']); $('button#slots-autoplay').addClass('active'); slot.autoplay = true; } autoplay(); }); $('button#slots-lastbet').on('click', function(){ slot.audio.buttons.play(); slot.setBetTo(slot.getLastBet()); }); //plus $('button.slots-plus').on('click', function(){ slot.audio.buttons.play(); var buttonPlusId = this.id; switch(buttonPlusId){ case 'slots-plus001': slot.incBetTo(0.01); break; case 'slots-plus01': slot.incBetTo(0.1); break; case 'slots-plus1': slot.incBetTo(1); break; } }); //minus $('button.slots-minus').on('click', function(){ slot.audio.buttons.play(); var buttonPlusId = this.id; switch(buttonPlusId){ case 'slots-minus001': slot.decBetTo(0.01); break; case 'slots-minus01': slot.decBetTo(0.1); break; case 'slots-minus1': slot.decBetTo(1); break; } }); $('button#slots-cashout').on('click', function(){ slot.audio.buttons.play(); slot.checkSlotOptions(); if (window.console) console.log('-==Start cashing out==-'); //show default waiting bar $("div#default_confirmed_cashout_message").css("display", "block"); //... and hide others $("div#confirmed_cashout_message").css("display", "none"); $("div#not_confirmed_cashout_message").css("display", "none"); $("div#zero_cashout_message").css("display", "none"); $("div#paying_out_off_message").css("display", "none"); $("div#big_money_message").css("display", "none"); $("div#spin_is_running_cashout_message").css("display", "none"); $("div#no_bitcoin_connection_message").css("display", "none"); slot.bitcoinConnection.checkForBitcoinConnection().always(function() { //do the connection checking in .done(function...) because we need to get //response from bitcoind first if (window.console) console.log('---checkForBitcoinConnection---'); if ( !slot.bitcoinConnection.newCheck ){ $("div#default_confirmed_cashout_message").css("display", "none"); $("div#no_bitcoin_connection_message").css("display", "block"); return false; } $.post("AjaxRequestsProcessing.php", { slot: "cashOut", amount: slot.currentUserBalance}) .done(function(cashOut) { cashOut = $.parseJSON(cashOut); //hide waiting bar $("div#default_confirmed_cashout_message").css("display", "none"); //if not enough confirmations (2 at least) if (cashOut.amount == '-101'){ $("div#not_confirmed_cashout_message").css("display", "block"); $("div#confirmed_cashout_message").css("display", "none"); } //enough confirmations else if (cashOut.amount > '0'){ var txid = '<a href="http://blockchain.info/search?search='+cashOut.txid+'">'+ cashOut.txid +'</a>'; $("div#confirmed_cashout_message span#txid").html(txid); $("div#not_confirmed_cashout_message").css("display", "none"); $("div#confirmed_cashout_message").css("display", "block"); //sound of money balance changed slot.audio.cashregister.play(); slot.syncWithServer() .success(function() { slot.updateBalanceAndBet(); }); } //sping is running => no cashout else if (slot.state == "started"){ $("div#spin_is_running_cashout_message").css("display", "block"); } //zero on balance else if (cashOut.amount == '0'){ $("div#zero_cashout_message").css("display", "block"); } //slot machine is off else if (cashOut.amount == '-200'){ $("div#paying_out_off_message").css("display", "block"); } //money were won > slot wallet amount else if (cashOut.amount == '-500'){ $("div#big_money_message").css("display", "block"); } if (window.console) console.log('cashOut: '); if (window.console) console.log(cashOut); //sync money after withdrawn slot.syncWithServer(); }) .fail(function(){ if (window.console) console.error('Bad request in isBitcoinConnected function'); }) }); }); //verify seeds and symbols $('button#verify_button').on('click', function(){ //1) check that rand symbols match to symbols for given client and server seeds var seeds = new Array(); seeds['clientSeed'] = $('div#verify input#client_seed').val();//slot.getClientSeed(); seeds['serverSeeds'] = $('div#verify input#server_seed').val(); var symbolsForChecking = $('div#verify input#symbols').val(); //check all seeds are not empty and animate them if they are if (seeds['clientSeed'].length == 0){//no string $('div#verify input#client_seed').css('opacity',0.5).stop().animate({opacity: 1}, 300); return false; } if (seeds['serverSeeds'].length == 0){ $('div#verify input#server_seed').css('opacity',0.5).stop().animate({opacity: 1}, 300); return false; } if (symbolsForChecking.length == 0){ $('div#verify input#symbols').css('opacity',0.5).stop().animate({opacity: 1}, 300); return false; } var arrServerSeeds = null; //serverSeeds should be an array try{ //var arrServerSeeds = eval( "("+seeds['serverSeeds']+")"); arrServerSeeds = $.parseJSON(seeds['serverSeeds']); } catch(e){ if (window.console) console.fail('Error '+e+'. arrServerSeeds = '+arrServerSeeds); } // realSymbols in JSON format var realSymbols = slot.calcSymbolsFromClientSeedAndServerSeeds(seeds['clientSeed'], arrServerSeeds); var animateSpeed = 2000; var warningColor = '#AD3A3A'; var successColor = '#3AAD50'; var seedsSuccessColor = '#3A87AD'; //mismatch // $('div#verify input#symbols').parent().removeClass('fail done'); if (symbolsForChecking != realSymbols){ if (window.console) console.log('symbolsForChecking != realSymbols'); $('div#verify input#symbols').css('background', warningColor).stop().animate({backgroundColor : '#FFF'}, animateSpeed); // $('div#verify input#symbols').parent().addClass('control-group fail'); } else if (symbolsForChecking == realSymbols){ if (window.console) console.log('symbolsForChecking == realSymbols'); $('div#verify input#symbols').css('background', successColor).stop().animate({backgroundColor : '#FFF'}, animateSpeed); // $('div#verify input#symbols').parent().addClass('control-group done'); } //2) check that Hash(server seed) == Hash (raw Server seed) var jsonServerSeed = $('div#verify input#server_seed').val(); var hashedServerSeed = $('div#verify input#last_hashed_server_seed').val(); //check hashed and unhashed for matching // $('div#verify input#server_seed').parent().removeClass('fail info'); // $('div#verify input#last_hashed_server_seed').parent().removeClass('fail info'); if (slot.isUnhashedAndHashedSeedsMatch(jsonServerSeed, hashedServerSeed)){ if (window.console) console.log('isUnhashedAndHashedSeedsMatch == true'); $('div#verify input#server_seed').css('background', seedsSuccessColor).stop().animate({backgroundColor : '#FFF'}, animateSpeed); $('div#verify input#last_hashed_server_seed').css('background', seedsSuccessColor).stop().animate({backgroundColor : '#FFF'}, animateSpeed); } //mismatch else{ if (window.console) console.log('isUnhashedAndHashedSeedsMatch == false'); $('div#verify input#server_seed').css('background', warningColor).stop().animate({backgroundColor : '#FFF'}, animateSpeed); $('div#verify input#last_hashed_server_seed').css('background', warningColor).stop().animate({backgroundColor : '#FFF'}, animateSpeed); } }); //run once slot.getHashedServerSeeds(); slot.getClientSeed(); //requests per interval //too many requests to server db setInterval(slot.checkSlotOptions, slot.timeouts.checkSlotOptionsInterval); setInterval(slot.checkForNewIncommingPayment, slot.timeouts.checkForNewIncommingPaymentInterval); setInterval(slot.bitcoinConnection.checkForBitcoinConnection, slot.timeouts.bitcoinCheckConnectionInterval); //setInterval(slot.updateInterestingFacts, slot.timeouts.updateInterestingFactsInterval); }); </script> </body> </html><file_sep>/showstats.php <?php require_once 'Appconfig.php'; require_once 'Dumpit.php'; try { //show stats tables //show_generated_total_weight_table(); possible_combinations(); } catch (Exception $e) { dump_it($e->getTraceAsString()); } ?> <file_sep>/Header.php <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding">--> <title>Bitcoin Slot Machine</title> <!--<link href="css/style.min.css" rel="stylesheet">--> <link href="css/style.css" rel="stylesheet"> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script src="js/jquery.min.js"></script> <script src="js/jquery.animate-colors-min.js"></script> <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>--> <script src="bootstrap/js/bootstrap.min.js"></script> <?php if ($_SESSION['host'] == 'localhost'){ ?> <script src="js/symbols-table.js"></script> <?php } else{?> <!-- the script below used to connect to 3rd party server, TODO: obfuscate it properly --> <!--<script src="js/symbols-table.obfuscated.js"></script>--> <script src="js/symbols-table.js"></script> <?php }?> <script src="js/mersenne-twister.min.js"></script> <script src="js/crc32.min.js"></script> <script src="js/sha256.min.js"></script> <script src="js/sha1.min.js"></script> <!--<script src="js/slot.min.js"></script>--> <script src="js/slot.js"></script> <!--chat script addded--> <!--<script src="https://bitbandit.eu/chat/js/jquery.js" type="text/javascript"></script>--> <script src="https://bitbandit.eu/chat/js/yshout.js" type="text/javascript"></script> <link rel="stylesheet" href="https://bitbandit.eu/chat/example/css/dark.yshout.css" /> <script type="text/javascript"> new YShout({ yPath: 'https://bitbandit.eu/chat/' }); </script> </head><file_sep>/__test.php <?php require_once 'Appconfig.php'; //function strToHex($string) //{ // $hex=''; // for ($i=0; $i < strlen($string); $i++) // { // $hex .= dechex(ord($string[$i])); // } // return $hex; //} $db = DBconfig::get_instance(); try { // $str[0] = 520 + 818675; // $str[1] = 520 + 398568; // $str[2] = 520 + 654792; // $str[0] = sha1($str[0]); // $str[1] = sha1($str[1]); // $str[2] = sha1($str[2]); // dump_it($str); // $user = User::get_instance(); // //$t = new Transaction('1111111', 500100, true, $user->uid); // // $bitcoin_client_instance = MyBitcoinClient::get_instance(); // if ($bitcoin_client_instance->can_connect()) { // echo 'Connect: can_connect <br />'; // echo 'Full balance: '.$bitcoin_client_instance->getbalance(); // echo '<br/>'; // //echo $bitcoin_client_instance->getinfo(); // } // $randomizer = Randomizer::get_instance(); // $seed = sha1('lCCMX5Fw3AjK89fYJ7PFFnpb3TDbdaEa1'); // dump_it($seed); // //sscanf(crc32($seed), "%u", $unsigned_seed); // $seed = crc32($seed); // dump_it($seed); // //$seed = hexdec($seed); //dump_it($seed); // $seed = base_convert($seed, 16, 36); // dump_it($seed); // // $seed = base_convert($seed, 36, 16); // dump_it($seed); //$seed = intval($seed, 16); //dump_it($seed-1 % PHP_INT_MAX); // $seed = dechex($seed); // dump_it($seed); // $seed = strToHex($seed); // dump_it($seed); // $randomizer->mt_srand($seed);//reinit // echo $rand_num = $randomizer->mt_rand(); $slot = Slot::get_instance(); $slot->get_new_payline_and_servers_seeds(1); dump_it($slot); dump_it($_SESSION); // echo $rand_num = $randomizer->mt_rand(); // echo $rand_num = $randomizer->mt_rand(); // dump_it(mt_getrandmax()); dump_it(PHP_INT_MAX); // $amount = $bitcoin_client_instance->getbalance('ultraNewWallet'); // dump_it($bitcoin_client_instance->getbalance('ultraNewWallet')); // dump_it($bitcoin_client_instance->getbalance('SlotBank')); // $bitcoin_client_instance->move('ultraNewWallet', 'SlotBank', $amount, 0,'Move from the user account to the common slot bitcoin account'); // // dump_it($bitcoin_client_instance->getbalance('ultraNewWallet')); // // //dump_it($bitcoin_client_instance->query_arg_to_parameter('getrawtransaction bf4ffc37b48f99403f44c1d2d65da82c6480f88c3fbaf95b2519e023b27d309f')); // //dump_it($bitcoin_client_instance->query('decoderawtransaction 01000000015a3a6801276cc5c06eed99fac43f32b017dfe17a48545e75264372885af2a509010000008a473044022046e7bb771b2a8665e9c081968afb685b2af7d09e22c2e185185a0ab7f4c34de9022023e1b6984b274b5df3c18e198e5ea9483f2416889904c96ae2d5c795413a5bd101410489f6dc4e14ac9f2d59ae926c4a5f2546daee14d578ada6b3cb0d1b9c3cb59758b40e7265e5b58595073f1fcecf2a3046636a6a62202cf057af5a7315dd524619ffffffff02a0bb0d00000000001976a91494e0e7a97a51e19fd57a05e3901cfaccf595d7dd88ac30c11d00000000001976a914a2c324ca1403c123779a9d4bcce45fb6ec5c43d688ac00000000')); // //dump_it($bitcoin_client_instance->query('getrawtransaction bf4ffc37b48f99403f44c1d2d65da82c6480f88c3fbaf95b2519e023b27d309f')); // // $raw_transaction_arr = ($bitcoin_client_instance->query('getrawtransaction', '<KEY>', '1')); // dump_it($raw_transaction_arr['vout'][1]['scriptPubKey']['addresses'][0]); //dump_it($bitcoin_client_instance->gettransaction('<KEY>')); //dump_it($bitcoin_client_instance->gettransaction); /* $user = User::get_instance(); //$u->auth(); dump_it($user); $slot = Slot::get_instance($user); dump_it($slot); //Transaction::show_transactions($option = 'last20'); //$t = new Transaction(); //$t->get_from_db('asfdasfd'); //$t = new Transaction($transaction_id = 'asfdasfd', $money_amount = 123, $deposit = false); //dump_it($t); //echo 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //dump_it($_SERVER); $m = MyBitcoinClient::get_instance(); dump_it($m->can_connect()); dump_it($m); /* echo $m->getbalance('900b15b28c5dbdb15fb626dbde50861b14274384'); echo '<br>'; echo $m->getbalance('SlotBank'); echo '<br>'; echo $acc = $m->getaccount('<KEY>'); echo $m->getbalance($acc); echo '<br>'; $slot = Slot::get_instance(); echo Slot::$bitcoin_address; echo '<br>'; echo Slot::$bitcoin_account_name; //echo $slot->bitcoin dump_it($m->getaddressesbyaccount('SlotBank')); * */ //dump_it($m->listreceivedbyaccount()); //dump_it($m->getaddressesbyaccount('myWallet')); //dump_it($m->getinfo()); //echo $m->getreceivedbyaccount('<KEY>'); //echo $m->move('<KEY>', 'myWallet', 0.01, 5, 'move BTC between accounts' ); //dump_it(getdate()); //echo date('h:i:s d.m.Y'); } catch (Exception $exc) { dump_it($exc->getTraceAsString()); } ?><file_sep>/AjaxRequestsProcessing.php <?php /** * Description of AjaxRequestsProcessing * * @author vadim24816 */ //for special requests define("SPECIAL_REQUEST_LIMIT_TIME_INTERVAL", 0.1); //for all requests to AjaxRequestsProcessing.php define("GLOBAL_REQUEST_LIMIT_TIME_INTERVAL", 0.00); //set limit for request amount from the same user //true - no more requests! //false - save last_request_time and let make requests function is_limit_time_interval_expired($request_limit_time_interval) { //$request_limit_time_interval = 0.2;//1 request per $request_limit_time_interval sec //if not set, set to current time if ( !isset($_SESSION['last_request_time']) ){ $_SESSION['last_request_time'] = microtime(true); } //if request_limit_time_interval is expired if ( (microtime(true) - $_SESSION['last_request_time']) > $request_limit_time_interval){ //save current time $_SESSION['last_request_time'] = microtime(true); return false; } else{ //output error in response echo '{"request_processing" : "false", "time_since_last_request" : "'. (microtime(true) - $_SESSION['last_request_time']) .'", "time_limit" : "'. $request_limit_time_interval .'" }'; return true; } } if ( is_limit_time_interval_expired(GLOBAL_REQUEST_LIMIT_TIME_INTERVAL) ) return false; $time_start = microtime(true); require_once 'Appconfig.php'; if (!empty($_POST['slot'])){ $post_request = $_POST['slot']; } else { //redirect to main page header('Location: https://'.$_SERVER['HTTP_HOST']); exit('No slot option in POST array'); } //$user = User::get_instance(); //$slot = Slot::get_instance($user); //$_SESSION['MyBitcoinClient'] = (empty($_SESSION['MyBitcoinClient']))? MyBitcoinClient::get_instance() : $_SESSION['MyBitcoinClient']; //$_SESSION['User'] = (empty($_SESSION['User']))? User::get_instance() : $_SESSION['User']; //$_SESSION['Slot'] = (empty($_SESSION['Slot']))? Slot::get_instance($_SESSION['User']) : $_SESSION['Slot']; // $mbc = $_SESSION['MyBitcoinClient']; $user = $_SESSION['User']; $slot = $_SESSION['Slot']; switch ($post_request) { case 'cashOut': try{ $amount = 0; if (!empty($_POST['amount'])){ $amount = $_POST['amount']; } $out = $user->cash_out($amount); $out = json_encode($out); if ($out){ echo $out; } else{ //echo '{"cashOut":"0"}'; echo '0'; } } catch (Exception $e){ dump_it($e->getTraceAsString()); } break; case 'getHashedServerSeeds': $server_seeds = $slot->getHashedServerSeeds(); $json = json_encode($server_seeds); echo $json; break; case 'sync': $user->update_from_db(); if ($return_string = json_encode($user)){ echo $return_string; } break; case 'spinPressed': if ( is_limit_time_interval_expired(SPECIAL_REQUEST_LIMIT_TIME_INTERVAL) ){ return false; } //no bet if (!isset($_POST['currentBet']) || !isset($_POST['clientSeed'])){ echo 'bet wasn\'t transferred or client seed is wrong'; return false; } //normal mode $client_seed = $_POST['clientSeed']; $betFromClient = $_POST['currentBet']; //Array [Objs] // dump_it($slot); $arr_of_spin_res = $slot->spin($betFromClient, $client_seed); $time_end = microtime(true); $script_time = $time_end-$time_start; $script_time = sprintf('%.4F s', $script_time); $arr_of_spin_res_with_script_time = array_merge($arr_of_spin_res, array('spin_script_time' => $script_time)); $json = json_encode($arr_of_spin_res_with_script_time); echo $json; break; case 'checkForIncommingPayment': if ( is_limit_time_interval_expired(SPECIAL_REQUEST_LIMIT_TIME_INTERVAL) ){ return false; } //$start_time = microtime(true); $cashed_in_value = $user->cash_in(); $cashed_in_value = json_encode($cashed_in_value); $time_end = microtime(true) - $time_start; echo $cashed_in_value;//.' '.$time_end; break; case 'getInterestingFacts': $cashed_out_money = Transaction::get_total_cached_out_money(); $total_spin_number = $slot->get_total_spin_number(); $json = '{"cashed_out_money":"'.$cashed_out_money.'","games_played":"'.$total_spin_number.'"}'; echo $json; break; case 'options': //neccecary params if ( empty($_POST['power']) // empty($_POST['paying_out']) || // empty($_POST['maxbet']) ){ return false; } if ($_POST['power'] == 'check_options'){ $options['playing'] = $slot->get_option('playing'); $options['paying_out'] = $slot->get_option('paying_out'); $options['maxbet'] = $slot->get_option('maxbet'); echo json_encode($options); return true; } //for admin only! if ($_SESSION['admin']){ //echo 'You are not logged as admin'; //return false; $options['playing'] = $slot->set_option('playing', $_POST['power']); $options['paying_out'] = $slot->set_option('paying_out', $_POST['paying_out']); $options['maxbet'] = $slot->set_option('maxbet', $_POST['maxbet']); if (!$options['playing'] || !$options['paying_out'] || !$options['maxbet']){ echo 'Nothing'; } else{ echo json_encode($options); } } break; case 'transactions': $table = 'Wrong params'; //between from and to dates if (!empty($_POST['fromDate']) && !empty($_POST['toDate'])){// && !empty($_POST['option'])){ $fromDate = ($_POST['fromDate']); $toDate = ($_POST['toDate']); //if request from admin page if (!empty($_POST['page']) && $_POST['page'] == 'admin'){ $table = Transaction::show_transactions('transactions',0, 0, $fromDate, $toDate, 'admin'); $table .= Transaction::show_grouped_by_user($fromDate, $toDate); $table .= Transaction::show_cach_in_out_profit_payback_table($fromDate, $toDate); } //if request from other page else{ $table = Transaction::show_transactions('transactions',0, 0, $fromDate, $toDate); } } if (!empty($_POST['to']) && !empty($_POST['option'])){ $option = $_POST['option']; $from = $_POST['from']; $to = $_POST['to']; $table = Transaction::show_transactions($option, $from, $to); } echo $table; break; case 'bitcoin_connect': if ( is_limit_time_interval_expired(SPECIAL_REQUEST_LIMIT_TIME_INTERVAL) ){ return false; } //$start_time = microtime(true); echo $mbc->check_last_connect(); // if ($mbc->check_last_connect() === true){ // $time_end = microtime(true) - $time_start; // //echo 'true '.$time_end; // echo 'true'; // } // else{ // echo 'false'; // } break; default: break; } class AjaxRequestsProcessing { } ?> <file_sep>/Randomizer.php <?php /** * Description of Randomizer * * @author vadim24816 */ require_once 'Appconfig.php'; //js and php (mt_rand) MTs are return different values //... this php MT implementation returns the same values like js one require_once 'mersenne_twister.php'; use mersenne_twister\twister; class Randomizer { //make it singletone protected static $randomizer; private function __construct(){} private function __clone(){} private function __wakeup(){} public static function get_instance(){ if (is_null(self::$randomizer)){ self::$randomizer = new Randomizer(); //self::$slot->slot_filling(); return self::$randomizer; } return self::$randomizer; } //reinit generator of mt_rand() using mt_srand() public function mt_srand($seed = null){ if ($seed === null){ mt_srand(); } else{ mt_srand($seed); } } //return new random number using mt_rand() public function mt_rand(){ $rand_num = mt_rand(0, 63); return $rand_num; } //return rand number from 0 to 63 public function mersenne_twister_int32($seed = null){ if ($seed === null){ $twister_32 = new twister(); } else{ $twister_32 = new twister($seed); } //return $twister_32->rangeint(0, 63); return $twister_32->int32(); } } ?> <file_sep>/nbproject/private/private.properties copy.src.files=false copy.src.target=E:\\xampp\\htdocs\\PhpProject1 index.file=index.php remote.connection=dev_bitbandit.eu-e661a1 remote.upload=MANUALLY run.as=REMOTE url=jolnir.orangewebsite.com <file_sep>/Transaction.php <?php /** * Description of Transaction * * @author vadim24816 */ require_once 'Appconfig.php'; class Transaction { private $transaction_date, $transaction_time, $money_amount, $transaction_id, $deposit, $uid; public function __construct($transaction_id = '', $money_amount = 0, $deposit = false, $uid = 0) { $this->transaction_id = $transaction_id; $this->money_amount = $money_amount; $this->deposit = $deposit; //deposit == 1|true -> deposit money / deposit == 0|false -> withdraw //save at the creating moment $this->transaction_time = ''; // = $transaction_time; $this->transaction_date = ''; $this->uid = $uid; $this->save_in_db(); } public function save_in_db() { $db = DBconfig::get_instance(); $res = $db->query("INSERT INTO transactions(transaction_id, money_amount, deposit, transaction_date, transaction_time, uid) VALUES('$this->transaction_id', '$this->money_amount', '$this->deposit', NOW(), NOW(), '$this->uid') "); if (!$res) { return FALSE; } return true; } public function get_from_db($transaction_id) { $db = DBconfig::get_instance(); $transaction = $db->mysqli_fetch_array('SELECT * FROM transactions WHERE transaction_id = \'' . $transaction_id . '\''); //if there is no user with given uid if ($transaction == FALSE) { return FALSE; } //the user is found else { $this->transaction_id = $transaction_id; $this->money_amount = $transaction['money_amount']; $this->deposit = $transaction['deposit']; $this->transaction_date = $transaction['transaction_date']; $this->transaction_time = $transaction['transaction_time']; $this->uid = $transaction['uid']; return TRUE; } } //endNum == 0 --> no limit public static function show_transactions($option = 'last', $startNum = 0, $endNum = 20, $from_date = '2012-11-01', $to_date = '2052-11-01', $from_page = 'index') { $db = DBconfig::get_instance(); $limit = "LIMIT $startNum , $endNum"; if ($endNum == 0) $limit = ' '; $query = 'SELECT * FROM transactions tr1 '; //show last 20 by time if ($option == 'last') { //$query = 'SELECT * FROM transactions ORDER BY `transaction_date` DESC , `transaction_time` DESC '.$limit; //make query without limits $query .= 'ORDER BY `transaction_date` DESC , `transaction_time` DESC '; //for counting total number of rows $total_records_query = $query; //limit the query $query .= $limit; } elseif ($option == 'biggestwinners') { //$query = 'SELECT * FROM transactions WHERE `deposit` = 0 ORDER BY `money_amount` DESC '.$limit; $query .= 'WHERE `deposit` = 0 ORDER BY `money_amount` DESC ';//.$limit; $total_records_query = $query; $query .= $limit; } elseif ($option == 'transactions'){ //$query = "SELECT * FROM transactions WHERE transaction_date BETWEEN '$from_date' AND '$to_date' ORDER BY `transaction_date` DESC , `transaction_time` DESC ".$limit; $query .= "WHERE transaction_date BETWEEN '$from_date' AND '$to_date' ORDER BY `transaction_date` DESC , `transaction_time` DESC ";//.$limit; $total_records_query = $query; $query .= $limit; } else{ return false; } $table_width = 400; if ($from_page == 'admin'){ $table_width = 700; } //get total number of rows $total_records_res = $db->query($total_records_query); //$total_records_value = mysqli_num_rows($res); $total_records_value = $total_records_res->num_rows; //query for transactions (with limits) $res = $db->query($query); $output = '<div class="transactions"><input id="total_records" type="hidden" value="'.$total_records_value.'"/><table class="table" border="2px" style="width: '.$table_width.'px;">';//start stats table $output .= '<tr> <td>Transaction time</td> <td>Money</td> <td>Transaction ID</td>'; if (!empty($_SESSION['admin']) && $from_page == 'admin' && $_SESSION['admin'] == 'true'){ $output .= '<td>UID</td>'; } $output .= '</tr> '; while ($transactions = $db->mysqli_fetch_array_by_result($res)) { if ($transactions['deposit']) { $money_column = '<td class="deposit">Deposit: '.$transactions['money_amount'].' </td>'; //$color = '#E2001A'; } else { //$color = '#25803C'; $money_column = '<td class="withdrawn">Withdrawn: '.$transactions['money_amount'].' </td>'; } $output .= '<tr> <td>' . $transactions['transaction_date'] . ' ' . $transactions['transaction_time'] . '</td>' . $money_column . '<td><a href="http://blockchain.info/search?search='.$transactions['transaction_id'].'">' . substr($transactions['transaction_id'], 0, 9) . '</a></td>'; if (!empty($_SESSION['admin']) && $from_page == 'admin' && $_SESSION['admin'] == 'true'){ $output .= '<td>' . $transactions['uid'] . '</td>'; } $output .= '</tr> '; } $output .= '</table></div>';//end echo $output; } public static function show_grouped_by_user($from_date, $to_date){ $db = DBconfig::get_instance(); $query = " SELECT t.uid, deposited_table.deposited, withdrawn_table.withdrawn FROM transactions t LEFT JOIN ( SELECT d1.uid, sum(d1.money_amount) deposited, d1.deposit FROM transactions as d1 WHERE d1.deposit = 1 AND d1.transaction_date BETWEEN '$from_date' AND '$to_date' GROUP BY d1.uid ) as deposited_table ON deposited_table.uid = t.uid LEFT JOIN ( SELECT d0.uid, sum(d0.money_amount) withdrawn, d0.deposit FROM transactions as d0 WHERE d0.deposit = 0 AND d0.transaction_date BETWEEN '$from_date' AND '$to_date' GROUP BY d0.uid ) as withdrawn_table ON withdrawn_table.uid = t.uid WHERE t.transaction_date BETWEEN '$from_date' AND '$to_date' GROUP BY t.uid ORDER BY t.id "; $output = " <br /> <table class=\"table\" border=\"1px\"> <tr> <td>Grouped by UID</td> <td>Total deposited</td> <td>Total withdrawn</td> <td>Total deposited - withdrawn</td> </tr> "; $res = $db->query($query); while ($transactions_grouped_by_user = $db->mysqli_fetch_array_by_result($res)){ foreach ($transactions_grouped_by_user as $key => $value) { if ($value == NULL){ $transactions_grouped_by_user[$key] = '0'; } } $dif = $transactions_grouped_by_user['deposited'] - $transactions_grouped_by_user['withdrawn']; $output .= '<tr> <td>'.$transactions_grouped_by_user['uid'].'</td> <td>'.$transactions_grouped_by_user['deposited'].'</td> <td>'.$transactions_grouped_by_user['withdrawn'].'</td> <td>'.$dif.'</td> </tr>'; } $output .= '</table>'; return $output; } public static function show_cach_in_out_profit_payback_table($from_date, $to_date){ $total_cached_out = Transaction::get_total_cached_out_money($from_date, $to_date); $total_cached_in = Transaction::get_total_cached_in_money($from_date, $to_date); if ($total_cached_in != 0){ $payback = ($total_cached_out/$total_cached_in)*100; $payback = round($payback, 2); } else{ $total_cached_in = 0; $payback = 100; } $profit = $total_cached_in - $total_cached_out; $output_start = " <br /> <table class=\"table\" border=\"1px\" > <tr> <td>Cash in</td> <td>Cash out</td> <td>Profit</td> <td>Payback %</td> "; $output_end = " </tr> <tr> <td>$total_cached_in</td> <td>$total_cached_out</td> <td>$profit</td> <td>$payback</td> </tr> </table> "; echo $output_start.$output_end; } //just gives a total of all the money cashed out, sums up all the withdraw transactions public static function get_total_cached_out_money($from_date = '2012-11-01', $to_date = '2052-11-01'){ $db = DBconfig::get_instance(); $query = "SELECT SUM(money_amount) FROM transactions WHERE `deposit` = 0 AND `transaction_date` BETWEEN '$from_date' AND '$to_date'"; $total_cached_out = $db->mysqli_fetch_array($query); if (!$total_cached_out[0]){ return 0; } return round($total_cached_out[0], 2); } public static function get_total_cached_in_money($from_date = '2012-11-01', $to_date = '2052-11-01'){ $db = DBconfig::get_instance(); $query = "SELECT SUM(money_amount) FROM transactions WHERE `deposit` = 1 AND `transaction_date` BETWEEN '$from_date' AND '$to_date'"; $total_cached_in = $db->mysqli_fetch_array($query); if (!$total_cached_in[0]){ return 0; } return $total_cached_in[0]; } } ?><file_sep>/Payline.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of Payline * * @author vadim24816 */ require_once 'Appconfig.php'; //array of 3 symbols like: ['pyramid', 'bitcoin', 'anonymous'] class Payline { public $sym1, $sym2, $sym3; public $multiplier, $bet_from_client; //make the object with given symbols public function __construct($sym1, $sym2, $sym3, $multiplier = 0, $bet_from_client = 0) { if (!Symbol::is_symbol($sym1) || !Symbol::is_symbol($sym2) || !Symbol::is_symbol($sym3)){ echo 'Not a symbols was given'; return; } $this->sym1 = $sym1; $this->sym2 = $sym2; $this->sym3 = $sym3; $this->bet_from_client = $bet_from_client; $this->$multiplier = $multiplier; } //return symbols as array public function get_symbols_array(){ $syms = array(3); $syms[0] = $this->sym1; $syms[1] = $this->sym2; $syms[2] = $this->sym3; return $syms; } } //$payline1 = new Payline(Symbol::$anarchy, Symbol::$bitcoin, Symbol::$pyramid); //$payline1 = $payline1->get_symbols_array(); ?> <file_sep>/Symbol.php <?php /** * Description of Symbol * * @author vadim24816 */ require_once 'Appconfig.php'; class Symbol { public $name; public $pic; public static $pyramid = 'pyramid';//bars=anti new world order public static $bitcoin = 'bitcoin';//cherries=bitcoin public static $anonymous = 'anonymous';//plums=anonymous public static $onion = 'onion';//watermelons=onion public static $anarchy = 'anarchy';//oranges=anarchy public static $peace = 'peace';//lemons=peace logo public static $blank = 'blank';// public static $any = 'any';//any symbol [from blank to pyramid] //if symbol was given return true, false else. public static function is_symbol($sym){ $all_symbols = self::get_array_of_all_symbols(); for ($i=0;$i<8;$i++){ if ($sym == $all_symbols[$i]){ return TRUE; } } //if not a symbol return FALSE; } protected static function get_array_of_all_symbols(){ $symbols = array(8); $symbols[0] = self::$pyramid; $symbols[1] = self::$bitcoin; $symbols[2] = self::$anonymous; $symbols[3] = self::$onion; $symbols[4] = self::$anarchy; $symbols[5] = self::$peace; $symbols[6] = self::$blank; $symbols[7] = self::$any; return $symbols; } } ?> <file_sep>/js/slot.js function Slot(){ var slot = this; slot.currentBet = 0; slot.lastPayline = ''; slot.currentPayline = ''; slot.emptyPayline = {bet_from_client: "0", multiplier: 0, sym1: "blank", sym2: "blank", sym3: "blank"}; slot.autoplay = false; slot.currentUserBalance = 0; slot.currentClientSeed = '123456'; slot.lastBet = 0; slot.symbolsPerReel = 64; slot.arrayOfSymbolsId = new Array(); slot.onceFilledLine = false; slot.onceStarted = false; slot.internetConnection = true; slot.rotationTime = { //rotation time for every reel in ms reel1: 2000, reel2: 3000, reel3: 5000 }; //max spin time is the max time of every reel rotates slot.maxSpinTime = Math.max(slot.rotationTime.reel1,slot.rotationTime.reel2,slot.rotationTime.reel3); slot.totalSymbolsNumber = 7; slot.state = 'stop'; //make slot state 'stop' slot.getStateStop = function(){ slot.state = 'stop'; } //make slot state 'started' slot.getStateStarted = function(){ slot.state = 'started'; } slot.timeouts = { bitcoinConnection: 5000, //5s and out by timeout checkSlotOptionsInterval: 5*60*1000, //5min = 5*60*1000 //checkForNewIncommingPaymentInterval: 5000, //5s || 60s checkForNewIncommingPaymentInterval: 5000, //30s //bitcoinCheckConnectionInterval: 10000, //10s bitcoinCheckConnectionInterval: 11000, //60s updateInterestingFactsInterval: 10000 } //check matching server seed and its hash slot.isUnhashedAndHashedSeedsMatch = function(jsonServerSeed, hashedServerSeed){ var cryptObj = new CryptoJS.SHA1(jsonServerSeed); var hashedJsonServerSeed = cryptObj.toString(); if (window.console){ console.log('jsonServerSeed = '+jsonServerSeed); console.log('hashedJsonServerSeed = '+hashedJsonServerSeed); console.log('hashedServerSeed = '+hashedServerSeed); } if (hashedJsonServerSeed == hashedServerSeed){ return true; } else{ return false; } }; //verify (int)client seed, (array) serverSeeds and symbols are got from last spin slot.calcSymbolsFromClientSeedAndServerSeeds = function(clientSeed, serverSeeds){ //get CryptoJS obj from client seed var CryptoJSobj = CryptoJS.SHA1(clientSeed.toString()); //get hash Of Client Seed in HEX format var hashOfClientSeed = CryptoJSobj.toString(CryptoJS.enc.Hex); //numbers of symbols on every reel var symNums = new Array(3); var twisters = new Array(3) for (var i=0; i<3; i++){ //get twisted sequence from given seeds twisters[i] = new MersenneTwister(crc32_x64(hashOfClientSeed)+crc32_x64(serverSeeds[i])); //get number from 0 to 63 symNums[i] = twisters[i].genrand_int32() % 64; } var wt = new weightTable(); var symbols = new Array(); for (var i=0; i<3; i++){ symbols[i] = wt.getSymNameOnReelByNumber(i, symNums[i]); } var symbolsJson = JSON.stringify(symbols); return symbolsJson; }; slot.bitcoinConnection = { //slot.bitcoinConnection.newCheck used for checking connection with bitcoin //use for cashout newCheck: false, //use for checking new payments lastCheck: true, checkForBitcoinConnection : function(){ //no connection newCheck slot.bitcoinConnection.newCheck = false; return $.ajax({ type: "POST", url: "AjaxRequestsProcessing.php", dataType: "text", data: { slot: "bitcoin_connect" }, //set timeout for request timeout: slot.timeouts.bitcoinConnection }) .done(function(is_bitcoin_connected){ slot.bitcoinConnection.newCheck = ( is_bitcoin_connected ) ? true : false; //if response was got then there is internet connection slot.internetConnection = true; if (window.console) { console.log('bitcoin connection = '+slot.bitcoinConnection.newCheck)}; }) .fail(function(){ slot.bitcoinConnection.newCheck = false; //no response == no connection slot.internetConnection = false; if (window.console) { console.log('Exit by timeout '+slot.timeouts.bitcoinConnection+'ms. Bitcoin connection = '+slot.bitcoinConnection.newCheck)}; }) .always (function(){ if (window.console) { console.log('checkForBitcoinConnection exit. bitcoin connection = '+slot.bitcoinConnection.newCheck)}; //keep last checking slot.bitcoinConnection.lastCheck = slot.bitcoinConnection.newCheck; }) } }; slot.musicOn = true; slot.audio = { spin5sec: null, win: null, loose: null, spinbutton: null, cashregister: null, //in case if buttons pressed oftenly buttons: { element: null, play: function(){ try{ //stop emulation slot.audio.buttons.element.pause(); slot.audio.buttons.element.currentTime = 0; slot.audio.buttons.element.play(); } catch(e){ if (window.console){ console.warn(e+" Audio doesn't supported")} } } } } //by default set the last bet before every new spin slot.setLastBetByDefault = function(){ if (slot.currentBet == 0){ slot.setBetTo(slot.getLastBet()); } } //just warm-up if have no deposit slot.warmup = { isLastWarned : false, isWarmup : true, //10 times of spin without deposite count : 10, dec : function(){ if (this.count > 1){ this.count -= 1; } else{ //if (this.count < 0) this.count -= 1; this.isWarmup = false; //slot.statusDisplay.show(this.lastWarn(), 15); } }, couldWin : function(){ return "YOU could have WON "+slot.currentPayline.multiplier+" times your bet.\n Please feed me some bitcoins! :)"; }, couldntWin : function(){ return "You lost nothing. Let's try for real now? :)"; }, lastWarn : function(){ if ( !slot.warmup.isLastWarned && !slot.warmup.isWarmup ){ //show last warning only 1 time after 10 free spins slot.warmup.isLastWarned = true; return "No more free spins buddy, time to play for real :)"; } } } //sounds slot.initAudio = function(){ slot.audio.spin5sec = document.getElementById('spin5sec'); slot.audio.win = document.getElementById('win'); slot.audio.loose = document.getElementById('loose'); slot.audio.spinbutton = document.getElementById('spinbutton'); slot.audio.buttons.element = document.getElementById('buttons'); slot.audio.cashregister = document.getElementById('cashregister'); } //generate new or get entered by user slot.getClientSeed = function(){ var seed_entered_by_client = $('div#verify input#client_seed').val(); var client_seed; if (typeof(seed_entered_by_client) != 'string' || seed_entered_by_client.length == 0 || slot.currentClientSeed == seed_entered_by_client){// client_seed = Math.round(Math.random()*2000000);//0--2 000 000 } else{ client_seed = seed_entered_by_client; } $('div#verify input#client_seed').val(client_seed) return client_seed; } //checking using multiplier in payline that was returned by server function isWin(){ if (slot.currentPayline.multiplier > 0){ return true; } else{ return false; } } slot.winChecker = function(){ //in case of warmup - just first 10 times if (slot.warmup.isWarmup){ //if win if (isWin()){ slot.statusDisplay.show(slot.warmup.couldWin(), 12); try{ slot.audio.win.play(); } catch(e){ if (window.console){ console.warn(e+" Audio doesn't supported")} } } //if lose else if (!isWin()){ slot.statusDisplay.show(slot.warmup.couldntWin()); try{ slot.audio.loose.play(); } catch(e){ if (window.console){ console.warn(e+" Audio doesn't supported")} } } //else if(slot.warmup.) } //normal mode else { if (isWin()){ //won_money = round(multiplier * bet) var won_money = Math.round((slot.currentPayline.multiplier*slot.currentPayline.bet_from_client)*100)/100; slot.statusDisplay.show('You WON '+ won_money +' (Bet '+slot.currentPayline.bet_from_client+'x'+slot.currentPayline.multiplier+')', 17); try{ slot.audio.win.play(); } catch(e){ if (window.console){ console.warn(e+" Audio doesn't supported")} } } if(!isWin() && slot.currentPayline.bet_from_client){//slot.currentPayline.bet_from_client != 'undefined' slot.statusDisplay.show('You lost '+ slot.currentPayline.bet_from_client +'. Better luck on the next spin!', 17); try{ slot.audio.loose.play(); } catch(e){ if (window.console){ console.warn(e+" Audio doesn't supported")} } } } } //display beneath the slot slot.statusDisplay = { messages : { connectionError : "There seems to be connectivity problem, please check your internet connection", connectionRecover : "The connection is back on, you can play!", noBitcoinConnection : "Can't check incoming payment, no bitcoin connection.", bitcoinConnectionRecover : "Bitcoin connection is recovered.", playingOff : "Playing is off", payingOutOff: "Paying out is off", playingAndPayingOutOff: "Playing and paying out are off" }, //get message get : function(){ //$('div#slots-status-display').css('opacity',1); return $('div#slots-status-display').text(); }, //show message show : function(str){ $('div#slots-status-display').css('opacity',1); //default font size var fontSize = 17; //if other font size given if (arguments.length == 2){ //if given as string if (typeof arguments[1] == 'string'){ fontSize = parseInt(arguments[1]); } if (typeof arguments[1] == 'number'){ fontSize = arguments[1]; } } else{ fontSize = 17; } $('div#slots-status-display').css('font-size', fontSize); $('div#slots-status-display').text(str); }, clear : function(delay){//set delay in ms delay = (arguments.length == 1) ? parseInt(delay) : 500; //default delay = 500 $('div#slots-status-display').stop().animate({opacity: 0}, delay); setTimeout("$('div#slots-status-display').text('');", delay); } }; //default options. updated from server slot.options = { 'playing': 'on', 'paying_out': 'on', 'maxbet': 0 }; slot.checkSlotOptions = function(){ $.post("AjaxRequestsProcessing.php", { slot: "options", power: 'check_options'}) .done(function(options) { slot.internetConnection = true; if (window.console) console.log(options); options = $.parseJSON(options); slot.options.playing = options.playing; slot.options.paying_out = options.paying_out; slot.options.maxbet = options.maxbet; if ((slot.options.playing == 'off') && (slot.options.paying_out == 'off')){ //slot.statusDisplay.show('Playing and paying out are off'); slot.statusDisplay.show(slot.statusDisplay.messages.playingAndPayingOutOff); } else if (slot.options.playing == 'off'){ //slot.statusDisplay.show('Playing is off'); slot.statusDisplay.show(slot.statusDisplay.messages.playingOff); } else if (slot.options.paying_out == 'off'){ //slot.statusDisplay.show('Paying out is off'); slot.statusDisplay.show(slot.statusDisplay.messages.payingOutOff); } else if ( slot.statusDisplay.get() == 'Paying out is off' || slot.statusDisplay.get() == 'Playing is off' || slot.statusDisplay.get() == 'Playing and paying out are off' ){ slot.statusDisplay.clear(); } //if last message was an fail if (slot.statusDisplay.get() == slot.statusDisplay.messages.connectionError){ slot.statusDisplay.show(slot.statusDisplay.messages.connectionRecover); } }) .fail(function(){ if (window.console) console.error('Client error. Error in ajax admin-->options power request, bad response'); slot.statusDisplay.show(slot.statusDisplay.messages.connectionError, 15); slot.internetConnection = false; //slot.statusDisplay.show('Connection fail.'); }); }; slot.updateInterestingFacts = function(){ $.post("AjaxRequestsProcessing.php", { slot: "getInterestingFacts"}) .done(function(interestingFacts) { interestingFacts = $.parseJSON(interestingFacts); $('td#total_cached_out').text('Cashed out money: '+ interestingFacts.cashed_out_money +' BTC'); $('td#total_spin_number').text('Games played: '+ interestingFacts.games_played); if (window.console) console.log('updateInterestingFacts'); }) .fail(function(){ if (window.console) console.error('Client error. Error in ajax updateInterestingFacts request, bad response'); //slot.statusDisplay.show('Connection fail.'); }); } slot.checkForNewIncommingPayment = function(){ //no connection, no money if ( !slot.bitcoinConnection.lastCheck && slot.statusDisplay.get() != slot.statusDisplay.messages.connectionError ){ slot.statusDisplay.show(slot.statusDisplay.messages.noBitcoinConnection, 15); if (window.console) console.warn('No bitcoin connection'); return false; } //if connection was recovered if ( slot.statusDisplay.get() == slot.statusDisplay.messages.noBitcoinConnection && slot.statusDisplay.get() != slot.statusDisplay.messages.connectionError){ slot.statusDisplay.show(slot.statusDisplay.messages.bitcoinConnectionRecover); slot.statusDisplay.clear(2000); } $.post("AjaxRequestsProcessing.php", { slot: "checkForIncommingPayment"}) .done(function(payment) { slot.internetConnection = true; payment = $.parseJSON(payment); //sync only if balances different if (payment.amount > 0){ slot.timeouts.checkForNewIncommingPaymentInterval = 61000;//61sec after payment was received $('div#slots-body').trigger('newIncommingPayment', ['false', 'Param 2']); //update balance slot.setCurrentUserBalance(slot.currentUserBalance + payment.amount); slot.audio.cashregister.play(); slot.updateBalanceAndBet(); if (window.console){ console.log('balance.amount = '+payment.amount); console.log('slot.currentUserBalance = '+slot.currentUserBalance); console.log('Balance updated'); console.log(payment); } } //if last message was a fail if (slot.statusDisplay.get() == slot.statusDisplay.messages.connectionError){ slot.statusDisplay.show(slot.statusDisplay.messages.connectionRecover); } }) .fail(function(){ if (window.console) console.error('Client error. Error in ajax checkForIncommingPayment request, bad response'); slot.statusDisplay.show(slot.statusDisplay.messages.connectionError, 15); slot.internetConnection = false; }) .always(function(){ }); } slot.getHashedServerSeeds = function(){ var getHashedServerSeeds; $.post("AjaxRequestsProcessing.php", { slot: "getHashedServerSeeds"}) .done(function(getHashedServerSeeds){ getHashedServerSeeds = $.parseJSON(getHashedServerSeeds); $('div#verify input#new_hashed_server_seed').val(getHashedServerSeeds); //if (window.console) console.log('getHashedServerSeeds = '+getHashedServerSeeds); }) .fail(function(){ if (window.console) console.error('Client error. Error in ajax result server seed request, bad response'); }); } slot.sendToServerThatSpinPressed = function(){ //fill payline by blank symbols slot.fillPayLine(slot.emptyPayline); //get random client seed or entered by user var clientSeed = slot.getClientSeed(); //keep it slot.currentClientSeed = clientSeed; $.post("AjaxRequestsProcessing.php", { slot: "spinPressed", currentBet: slot.currentBet, clientSeed: clientSeed }) .done(function(arrayReturnedByServerSpin) { slot.internetConnection = true; arrayReturnedByServerSpin = $.parseJSON(arrayReturnedByServerSpin); if (arrayReturnedByServerSpin == -1){ slot.options.playing = 'off'; slot.statusDisplay.show('Slot machine is off'); return false; } //if (paylineReturnedByServerSpin == '[Bet <= 0 or Bet not number.]'){ if (arrayReturnedByServerSpin == -2){ slot.statusDisplay.show('Bad bet'); return false; } slot.currentPayline = arrayReturnedByServerSpin['new_payline']; slot.fillPayLine(slot.currentPayline); slot.rememberLastShowedSymbols(); //here will be other hashed server seeds already! slot.getHashedServerSeeds(); //when result (new payline, user win/lose) was received, client sync with server slot.syncWithServer(); //if client has made bet then he stars to play with real money if (slot.currentPayline.bet_from_client > 0){ slot.warmup.isWarmup = false; } var symbolsJson = slot.calcSymbolsFromClientSeedAndServerSeeds(clientSeed, arrayReturnedByServerSpin['server_seeds']); var lastHashedServerSeed = $('div#verify input#new_hashed_server_seed').val(); //fill last hashed server seed field $('div#verify input#last_hashed_server_seed').val(lastHashedServerSeed); //show symbols after spin is finished(!) setTimeout(function(){ $('div#verify input#symbols').val(symbolsJson); $('div#verify input#server_seed').val(JSON.stringify(arrayReturnedByServerSpin['server_seeds'])); }, slot.maxSpinTime-500); //if last message was an fail if (slot.statusDisplay.get() == slot.statusDisplay.messages.connectionError){ slot.statusDisplay.show(slot.statusDisplay.messages.connectionRecover); } //do event "responseSpinGetting" when response was really got $('div#slots-body').trigger('responseSpinGetting', ['true', 'Param2']); return true; }) .fail(function(){ if (window.console) console.error('Client error. Error in ajax spin request, bad response'); slot.statusDisplay.show(slot.statusDisplay.messages.connectionError, 15); slot.internetConnection = false; $('div#slots-body').trigger('responseSpinGetting', ['false', 'Param2']); }); } slot.symbols = { 'pyramid': 0, 'bitcoin': 1, 'anonymous': 2, 'onion': 3, 'anarchy': 4, 'peace': 5, 'blank': 6 } //set user balance slot.setCurrentUserBalance = function(money_balance){ //check user money with user current bet if (money_balance > slot.currentBet){ slot.currentUserBalance = money_balance - slot.currentBet;//new Number(money_balance - slot.currentBet); } //if current bet > user money on server else{ slot.currentBet = 0; slot.currentUserBalance = money_balance; } } //full sync with server slot.syncWithServer = function(){ user = null; return $.post("AjaxRequestsProcessing.php", { slot: "sync" }) .done(function(slotValues) { user = $.parseJSON(slotValues); slot.setCurrentUserBalance(user.money_balance); //slot.updateBalanceAndBet(); }) .fail(function(){ if (window.console) console.error('Error in syncWithServer'); }); } //show last symbols slot.lastShowedSymbols = { //fill it by blank symbols reel1: {top: 6, center: 6, bottom: 6}, reel2: {top: 6, center: 6, bottom: 6}, reel3: {top: 6, center: 6, bottom: 6} } slot.getValidSymbolByName = function(symbol){ if (typeof(symbol) == 'number' && symbol >= 0 && symbol <= 6){ return symbol; } if ( typeof(slot.symbols[symbol]) == 'undefined'){ return false; } else{ return slot.symbols[symbol]; } } //fill payline slot.fillPayLine = function(payline){ // $('div#slots-reel1 > div.slots-line > div.payline').attr('class', 'slots-symbol'+slot.getValidSymbolByName(slot.currentPayline.sym1)+' payline'); // $('div#slots-reel2 > div.slots-line > div.payline').attr('class', 'slots-symbol'+slot.getValidSymbolByName(slot.currentPayline.sym2)+' payline'); // $('div#slots-reel3 > div.slots-line > div.payline').attr('class', 'slots-symbol'+slot.getValidSymbolByName(slot.currentPayline.sym3)+' payline'); $('div#slots-reel1 > div.slots-line > div.payline').attr('class', 'slots-symbol'+slot.getValidSymbolByName(payline.sym1)+' payline'); $('div#slots-reel2 > div.slots-line > div.payline').attr('class', 'slots-symbol'+slot.getValidSymbolByName(payline.sym2)+' payline'); $('div#slots-reel3 > div.slots-line > div.payline').attr('class', 'slots-symbol'+slot.getValidSymbolByName(payline.sym3)+' payline'); } //fill line (top/center/bottom) in slot slot.fillLine = function(symbol){ $('div.slots-line').append('<div class="slots-symbol'+ symbol +'"></div>'); } //There is no spoon slot.restoreLastShowedSymbols = function(){ $('div#slots-reel1 > div.slots-line > div.oldpayline').prev().attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel1.top); $('div#slots-reel1 > div.slots-line > div.oldpayline').attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel1.center+' oldpayline'); $('div#slots-reel1 > div.slots-line > div.oldpayline').next().attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel1.bottom); $('div#slots-reel2 > div.slots-line > div.oldpayline').prev().attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel2.top); $('div#slots-reel2 > div.slots-line > div.oldpayline').attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel2.center+' oldpayline'); $('div#slots-reel2 > div.slots-line > div.oldpayline').next().attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel2.bottom); $('div#slots-reel3 > div.slots-line > div.oldpayline').prev().attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel3.top); $('div#slots-reel3 > div.slots-line > div.oldpayline').attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel3.center+' oldpayline'); $('div#slots-reel3 > div.slots-line > div.oldpayline').next().attr('class', 'slots-symbol'+slot.lastShowedSymbols.reel3.bottom); } //remember who you are slot.rememberLastShowedSymbols = function(){ slot.lastShowedSymbols.reel1.top = slot.arrayOfSymbolsId[0][0]; slot.lastShowedSymbols.reel1.center = slot.getValidSymbolByName(slot.currentPayline.sym1); slot.lastShowedSymbols.reel1.bottom = slot.arrayOfSymbolsId[0][2]; slot.lastShowedSymbols.reel2.top = slot.arrayOfSymbolsId[1][0]; slot.lastShowedSymbols.reel2.center = slot.getValidSymbolByName(slot.currentPayline.sym2); slot.lastShowedSymbols.reel2.bottom = slot.arrayOfSymbolsId[1][2]; slot.lastShowedSymbols.reel3.top = slot.arrayOfSymbolsId[2][0]; slot.lastShowedSymbols.reel3.center = slot.getValidSymbolByName(slot.currentPayline.sym3); slot.lastShowedSymbols.reel3.bottom = slot.arrayOfSymbolsId[2][2]; } //fills lines of symbols for all reels slot.linesFilling = function(){ var reelNumber = 0; $('div.slots-line').each(function(){ slot.arrayOfSymbolsId[reelNumber] = new Array(); for (var i = 0; i < slot.symbolsPerReel; i++) { var id = Math.round(Math.random()*(slot.totalSymbolsNumber-1)); //reelLineSymbols keep wrong id for payline! //because payline gets new id after request to server slot.arrayOfSymbolsId[reelNumber][i] = id; if (!slot.onceFilledLine){ $(this).append('<div class="slots-symbol'+ id +'"></div>'); } else{ $(this).children('div :nth-child('+(i+1)+')').attr('class','slots-symbol'+ id); } } $(this).css({marginTop: -(slot.symbolsPerReel-3)*125 + 'px'}); reelNumber++; }); //add classes oldpayline and payline $('div.slots-line :nth-child(2)').addClass('payline'); $('div.slots-line :nth-child(63)').addClass('oldpayline'); if (!slot.onceFilledLine){ slot.onceFilledLine = true; slot.rememberLastShowedSymbols(); } } //Main function. Make 1 spin slot.spin = function(){ if (slot.internetConnection == false){ return false; } if (slot.options.playing == 'off'){ //slot.statusDisplay.show('Playing is off'); slot.statusDisplay.show(slot.statusDisplay.messages.playingOff); if (window.console) console.log('Playing off'); return false; } //already started if (slot.state == 'started'){ if (window.console) console.log('[Slot started already. Wait while it have stoped! ]'); return false; } //if real money was deposited, but no bet had made if (slot.currentUserBalance > 0 && slot.currentBet <= 0){ slot.statusDisplay.show("Please place a bet"); //then warmup is over slot.warmup.isWarmup = false; return false; } //no money deposited and no warmup times rest if (slot.currentBet <= 0 && slot.currentUserBalance <= 0 && slot.warmup.isWarmup == false){ slot.statusDisplay.show(slot.warmup.lastWarn(), 15); if (window.console) console.log('[Current bet = 0. Not worth the trouble]'); return false; } //if user already played for real, so it isn't need to warn him if (slot.currentUserBalance > 0){ slot.warmup.isLastWarned = true; } //------------------------------------------------------------------------------------------------------ //spin really started from here------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------ if ( slot.autoplay ){ //status display shows message before spin longer if autoplay, then clear it setTimeout('slot.statusDisplay.clear()', Math.round(slot.maxSpinTime/1.5)); } else{ setTimeout('slot.statusDisplay.clear()', Math.round(slot.maxSpinTime/4)); } //restore last showed symbols if there is last show exists slot.linesFilling(); if (slot.onceStarted){ slot.restoreLastShowedSymbols(); } //play only if spin was ran try{ slot.audio.spin5sec.play(); } catch(e){ if (window.console){ console.log(e+" Audio doesn't supported")} } //save last payline slot.lastPayline = slot.currentPayline; slot.sendToServerThatSpinPressed(); //slot started slot.getStateStarted(); // setTimeout('slot.getStateStop()', slot.maxSpinTime); //bet was slot.lastBet = slot.currentBet; slot.currentBet = 0; slot.updateBalanceAndBet(); slot.animateSlot(); //sync the result with the server //setTimeout('slot.syncWithServer()', 0/*slot.maxSpinTime-1000*/); //set last bet as current bet after spin //uncomment! //setTimeout('slot.setLastBetByDefault()', slot.maxSpinTime+500); //setTimeout('slot.statusDisplay.show()', slot.maxSpinTime+100); //check for win //setTimeout('slot.winChecker()', slot.maxSpinTime+100); slot.onceStarted = true; setTimeout('slot.spinFinished()', slot.maxSpinTime+100); return true; } slot.spinFinished = function(){ slot.getStateStop(); //make after spin slot.setLastBetByDefault(); slot.winChecker(); // -1 warmup spin if (slot.warmup.isWarmup){ slot.warmup.dec(); } //update balance slot.updateBalanceAndBet(); //event spinFinished $('div#slots-body').trigger('spinFinished', ['false', 'Param2']); } // slot.afterSpinResponseGetting = function(){ } slot.animateSlot = function(){ $('div.slots-line').each(function(){ $(this).css({marginTop: -(slot.symbolsPerReel-3)*125 + 'px'}); }); $('div#slots-reel1 > div.slots-line').animate({marginTop: 0}, slot.rotationTime.reel1); $('div#slots-reel2 > div.slots-line').animate({marginTop: 0}, slot.rotationTime.reel2); $('div#slots-reel3 > div.slots-line').animate({marginTop: 0}, slot.rotationTime.reel3); } slot.incBetTo = function(val){ val = Number(val); val = Math.round(val*100) / 100; //can't inc bet -- bet can't to be greater than balance if (slot.currentUserBalance - val < 0){ if (window.console) console.log("[can't inc bet]"); return false; } //check for maxBet if ( (slot.currentBet + val) > slot.options.maxbet ){ slot.statusDisplay.show("Max bet is "+slot.options.maxbet); slot.statusDisplay.clear(1000); return false; } slot.currentUserBalance -= val; slot.currentBet += val; slot.currentUserBalance = Math.round(slot.currentUserBalance * 100) / 100; slot.currentBet = Math.round(slot.currentBet * 100) / 100; slot.updateBalanceAndBet(); } slot.decBetTo = function(val){ val = Number(val); val = Math.round(val*100) / 100; if (slot.currentBet - val < 0){ if (window.console) console.log("[can't dec bet]"); return false; } slot.currentUserBalance += val; slot.currentBet -= val; slot.currentUserBalance = Math.round(slot.currentUserBalance * 100) / 100; slot.currentBet = Math.round(slot.currentBet * 100) / 100; slot.updateBalanceAndBet(); } slot.setBetTo = function(val){ val = parseFloat(val); val = Number(val); val = Math.round(val*100) / 100; //val should be >= 0 if (val < 0){ return 0; } //val should be < currentUserBalance if ( (slot.currentUserBalance + slot.currentBet - val < 0) || (val > slot.options.maxbet)){ if (window.console) console.log("[Not enough money or bet too big. Max bet had been made.]"); val = slot.getMaxBet(); //return 0; } //bet back to balance slot.currentUserBalance = slot.currentBet + slot.currentUserBalance; //make bet slot.currentBet = val; //balance minus bet slot.currentUserBalance -= slot.currentBet; //round all slot.currentUserBalance = Math.round(slot.currentUserBalance * 100) / 100; slot.currentBet = Math.round(slot.currentBet * 100) / 100; slot.updateBalanceAndBet(); } //retfresh values on page slot.updateBalanceAndBet = function(){ slot.currentUserBalance = Math.round(slot.currentUserBalance * 100) / 100; slot.currentBet = Math.round(slot.currentBet * 100) / 100; $('div#slots-balance').text(slot.currentUserBalance); $('div#slots-bet').text(slot.currentBet); } //return max bet and fill current bet field slot.getMaxBet = function(){ if ( slot.currentUserBalance <= 0 ){ return 0; } var maxMoney = slot.currentUserBalance + slot.currentBet; //return all user money or maxbet possible return (maxMoney <= slot.options.maxbet) ? maxMoney : slot.options.maxbet; } slot.makeMaxBet = function(){ var maxBet = slot.getMaxBet(); slot.setBetTo(maxBet); } slot.getLastBet = function(){ if (slot.lastBet == 0){ if (window.console) console.log('[There is no last bet]'); return 0; } return slot.lastBet; } } // console.log('some msg'); // console.info('information'); // console.warn('some warning'); // console.error('some error'); // console.assert(false, 'YOU FAIL'); <file_sep>/Slot.php <?php /** * Description of Slot * * @author vadim24816 */ require_once 'Appconfig.php'; class Slot { protected static $slot; protected $log_every_spin; public $user; public static $bitcoin_account_name = 'SlotBank'; public static $bitcoin_address; private function __construct(){} private function __clone(){} //private function __wakeup(){} private function init($user){ $this->user = $user; } public static function get_instance($user = null){ if ( is_null(self::$slot) ){ self::$slot = new Slot(); //keep Slot in SESSION //$_SESSION['Slot'] = self::$slot; //if user not exist it will create him! //init object self::$slot->init($user); // if ($user == null){ // self::$slot->user = User::get_instance(); //// self::$user = User::get_instance(); // } // else{ // self::$slot->user = user; //// self::$user = $user; // } // dump_it(self::$slot->user); //keep User in SESSION // $_SESSION['User'] = self::$user; //common account for all money in slot self::$bitcoin_account_name = 'SlotBank'; /* if (!empty($_SESSION['server_seeds'])){ self::$slot->server_seeds = $_SESSION['server_seeds']; } * */ // if ( empty(self::$slot->server_seeds) ){ // self::$slot->server_seeds = self::$slot->getServerSeeds(); // } $bitcoin_client_instance = MyBitcoinClient::get_instance(); if ($bitcoin_client_instance->check_last_connect() === true){ try{ self::$bitcoin_address = $bitcoin_client_instance->getaccountaddress(self::$bitcoin_account_name); } catch (Exception $e){ dump_it($e->getTraceAsString()); } } self::$slot->log_every_spin = true; $weight_table = WeightTable::get_instance(); self::$slot->reel1 = new Reel('reel1'); self::$slot->reel1->reel_line = $weight_table->get_symbols_reel_line($weight_table->symbol_weight_reel1); self::$slot->reel2 = new Reel('reel2'); self::$slot->reel2->reel_line = $weight_table->get_symbols_reel_line($weight_table->symbol_weight_reel2); self::$slot->reel3 = new Reel('reel3'); self::$slot->reel3->reel_line = $weight_table->get_symbols_reel_line($weight_table->symbol_weight_reel3); self::$slot->reels[0] = self::$slot->reel1; self::$slot->reels[1] = self::$slot->reel2; self::$slot->reels[2] = self::$slot->reel3; self::$slot->playing = 'on'; self::$slot->paying_out = 'on'; self::$slot->maxbet = 0; return self::$slot; } return self::$slot; } protected $last_payline, $is_admin;//, $reels = array(3); public $reel1,$reel2,$reel3, $reels; public $currentBet, $currentUserBalance, $lastBet, $state; public $playing, $paying_out, $maxbet;// = true; public $result_seeds, $server_seeds; public function is_valid_client_seed($client_seed){ if (!is_string($client_seed)){ return false; } else{ return true; } } //validate client's bet public function is_valid_bet($bet_from_client){ //not a number if (!is_numeric($bet_from_client)){ return false; } //$this->user->update_from_db();//too slow //350ms if ( $bet_from_client >= 0 && $bet_from_client <= $this->user->money_balance && $bet_from_client <= $this->maxbet ){ return true; } else { return false; } } public function get_total_spin_number(){ $db = DBconfig::get_instance(); $query = 'SELECT COUNT(id) FROM spins'; $total_spin_number = $db->mysqli_fetch_array($query); return $total_spin_number[0]; } public function save_spin_in_db($uid, $user_bet, $payline, $won_money){ $db = DBconfig::get_instance(); $res = $db->query("INSERT INTO spins(uid, user_bet, payline, won_money, spin_time) VALUES('$uid', '$user_bet', '$payline', '$won_money', NOW()) "); if (!$res) { return FALSE; } return true; } public function save_options_in_db(){ $db = DBconfig::get_instance(); $res = $db->query("UPDATE slot_options SET `option_value` = '$this->playing' WHERE `option_name` = 'playing' "); if (!$res) { return FALSE; } $res = $db->query("UPDATE slot_options SET `option_value` = '$this->paying_out' WHERE `option_name` = 'paying_out' "); if (!$res) { return FALSE; } $res = $db->query("UPDATE slot_options SET `option_value` = '$this->maxbet' WHERE `option_name` = 'maxbet' "); if (!$res) { return FALSE; } return true; } public function get_option_from_db(){ $db = DBconfig::get_instance(); $options['playing'] = $db->mysqli_fetch_array("SELECT option_value FROM slot_options WHERE option_name = 'playing' "); $options['paying_out'] = $db->mysqli_fetch_array("SELECT option_value FROM slot_options WHERE option_name = 'paying_out' "); $options['maxbet'] = $db->mysqli_fetch_array("SELECT option_value FROM slot_options WHERE option_name = 'maxbet' "); $this->playing = $options['playing']['option_value']; $this->paying_out = $options['paying_out']['option_value']; $this->maxbet = $options['maxbet']['option_value']; return $options; } public function get_option($option_name){ if ($option_name != 'playing' && $option_name != 'paying_out' && $option_name != 'maxbet'){ return false; } $this->get_option_from_db(); switch ($option_name) { case 'paying_out': return $this->paying_out; break; case 'playing': return $this->playing; break; case 'maxbet': return $this->maxbet; break; default: return false; break; } } public function set_option($option_name, $option_value){ /* if (!$_SESSION['admin']){ return false; } */ if ( !$this->is_admin ){ return false; } if ($option_name == 'paying_out'){ $this->paying_out = ($option_value == 'on') ? 'on' : 'off'; } elseif ($option_name == 'playing') { $this->playing = ($option_value == 'on') ? 'on' : 'off'; } elseif ($option_name == 'maxbet') { $this->maxbet = ( is_numeric($option_value) ) ? $option_value : 0; } if ($this->save_options_in_db()){ return $option_value; } else{ return false; } } //make spin public function spin($bet_from_client, $client_seed){ $this->get_option_from_db(); if ($this->playing === 'off'){ //echo 'Slot-machine powered off'; return -1; } //todo: limit the number of spins for the same uid (e.g.: 1 spin per 6 second if (!$this->is_valid_bet($bet_from_client)){ //echo '[Bet <= 0 or Bet not number.]'; return -2; } if (!$this->is_valid_client_seed($client_seed)){ return -3; } $this->currentBet = $bet_from_client; //bet was $this->lastBet = $this->currentBet; $this->user->money_balance -= $this->currentBet; $this->currentBet = 0; $arr_of_new_payline_and_servers_seeds = $this->get_new_payline_and_servers_seeds($client_seed); // dump_it($arr_of_new_payline_and_servers_seeds); $new_payline = $arr_of_new_payline_and_servers_seeds['new_payline']; $paytable = Paytable::get_instance(); $win_combination_name = $paytable->paylines_matching_with_wins($new_payline); //user gets money he won $won_money = $paytable->payoff_value($new_payline) * $bet_from_client; $this->user->money_balance += $won_money; //... $new_payline->bet_from_client = $bet_from_client; $new_payline->multiplier = $paytable->payoff_value($new_payline); //keep last payline//not used(?) $this->last_payline = $new_payline; $s = $this->user->save_in_db(); $this->user->update_from_db(); //logging every spin (by default) if ( $this->log_every_spin ) $this->save_spin_in_db($this->user->uid, $bet_from_client, $win_combination_name, $won_money ); $arr_of_new_payline_and_servers_seeds['new_payline']->bet_from_client = $new_payline->bet_from_client; $arr_of_new_payline_and_servers_seeds['new_payline']->multiplier = $new_payline->multiplier; return $arr_of_new_payline_and_servers_seeds; } //return array [ new randomly generated payline; and array of 3 server seeds ] //get new random number for all 3 reel.. public function get_new_payline_and_servers_seeds($client_seed){ //hash client_seed, because it can be string of any symbols $hashed_client_seed = sha1($client_seed); //generate new server seeds $server_seeds = $this->getServerSeeds(); for ($i = 0; $i < 3; $i++){ //hash all 3 server seeds //..using client and server seed $syms[$i] = $this->reels[$i]->get_new_randomly_choosed_symbol($hashed_client_seed, $server_seeds[$i]); } $new_payline = new Payline($syms[0], $syms[1], $syms[2]); //generate new seeds HERE, because last seeds was used for getting payline above in this func $this->generateServerSeeds(); $res_arr = array('new_payline' => $new_payline, 'server_seeds' => $server_seeds); //dump_it($res_arr); return $res_arr; } //get random generated 3 server seeds public function generateServerSeeds(){ for ($i = 0; $i < 3; $i++){ $server_seeds[$i] = sha1(mt_rand()); } $this->server_seeds = $server_seeds; // $_SESSION['server_seeds'] = $server_seeds; return $server_seeds; } //just get 3 current server seeds public function getServerSeeds(){ if (!empty($this->server_seeds)){ return $this->server_seeds; } // elseif (!empty($_SESSION['server_seeds'])){ // $this->server_seeds = $_SESSION['server_seeds']; // } else{ $this->server_seeds = $this->generateServerSeeds(); } return $this->server_seeds; } public function getHashedServerSeeds(){ $server_seeds = $this->getServerSeeds(); $json_server_seeds = json_encode($server_seeds); //wanna string? get it! return sha1($json_server_seeds); } } class WeightTable{ //make it singletone protected static $weight_table; private function __construct(){} private function __clone(){} private function __wakeup(){} public static function get_instance(){ if (is_null(self::$weight_table)){ self::$weight_table = new WeightTable(); self::$weight_table->total_weight_table_filling(); return self::$weight_table; } return self::$weight_table; } //protected public $reel1,$reel2,$reel3; public $symbol_weight_reel1,$symbol_weight_reel2,$symbol_weight_reel3; public function total_weight_table_filling(){ //the symbol weight/amount on reelN $this->symbol_weight_reel1[Symbol::$pyramid] = 4; $this->symbol_weight_reel1[Symbol::$bitcoin] = 5; $this->symbol_weight_reel1[Symbol::$anonymous] = 6; $this->symbol_weight_reel1[Symbol::$onion] = 6; $this->symbol_weight_reel1[Symbol::$anarchy] = 7; $this->symbol_weight_reel1[Symbol::$peace] = 8; $this->symbol_weight_reel1[Symbol::$blank] = 28; $this->symbol_weight_reel2[Symbol::$pyramid] = 3; $this->symbol_weight_reel2[Symbol::$bitcoin] = 4; $this->symbol_weight_reel2[Symbol::$anonymous] = 4; $this->symbol_weight_reel2[Symbol::$onion] = 5; $this->symbol_weight_reel2[Symbol::$anarchy] = 5; $this->symbol_weight_reel2[Symbol::$peace] = 6; $this->symbol_weight_reel2[Symbol::$blank] = 37; $this->symbol_weight_reel3[Symbol::$pyramid] = 1; $this->symbol_weight_reel3[Symbol::$bitcoin] = 2; $this->symbol_weight_reel3[Symbol::$anonymous] = 3; $this->symbol_weight_reel3[Symbol::$onion] = 4; $this->symbol_weight_reel3[Symbol::$anarchy] = 6; $this->symbol_weight_reel3[Symbol::$peace] = 6; $this->symbol_weight_reel3[Symbol::$blank] = 42; //total: 64 for every reel } //return the filled line (array) that consists of 64 symbols with considering the weight table function get_symbols_reel_line($reel){ //weight_arr == reel line $weight_arr = array(64); $current_num_in_weight_arr = 0;//counter in weight_arr //for every symbol foreach ($reel as $key => $value) { for ($i = 0; $i < $reel[$key]; $i++){ $weight_arr[$current_num_in_weight_arr] = $key; //total number of processed cells $current_num_in_weight_arr++; } } return $weight_arr; } } ?><file_sep>/Appconfig.php <?php /** * Description of appconfig * * @author vadim24816 */ if ($_SERVER['HTTP_HOST'] == 'bitbandit.eu'){ AppConfig::$domainname = '.bitbandit.eu'; } elseif ($_SERVER['HTTP_HOST'] == '192.168.3.11'){ AppConfig::$domainname = '192.168.3.11'; } elseif ($_SERVER['HTTP_HOST'] == 'localhost'){ AppConfig::$domainname = 'localhost'; } elseif ($_SERVER['HTTP_HOST'] == '127.0.0.1') { AppConfig::$domainname = '127.0.0.1'; } //must be first! ini_set('session.gc_maxlifetime', AppConfig::now_plus_x_years()); ini_set('session.cookie_lifetime', AppConfig::now_plus_x_years()); //set session via https session_set_cookie_params( AppConfig::now_plus_x_years(), '/', //path AppConfig::$domainname,//current domain //'',//any //'.bitbandit.eu', //cant work on local true, //secure false //http only ); require_once 'User.php'; require_once 'Slot.php'; require_once 'Reel.php'; require_once 'bitcoin/bitcoin.inc'; require_once 'MyBitcoinClient.php'; require_once 'Payline.php'; require_once 'Paytable.php'; require_once 'Symbol.php'; session_start(); //relocate browser to https require_once 'relocateToSecureScheme.php'; require_once 'Dumpit.php'; require_once 'DBconfig.php'; //require_once 'MyBitcoinClient.php'; require_once 'Randomizer.php'; require_once 'Payline.php'; require_once 'Paytable.php'; require_once 'Cookie.php'; //require_once 'bitcoin/bitcoin.inc'; //require_once 'User.php'; //require_once 'Slot.php'; require_once 'Transaction.php'; require_once 'functions.php'; //$user = User::get_instance(); //$slot = Slot::get_instance($user); $_SESSION['MyBitcoinClient'] = (empty($_SESSION['MyBitcoinClient']))? MyBitcoinClient::get_instance() : $_SESSION['MyBitcoinClient']; $_SESSION['User'] = (empty($_SESSION['User']))? User::get_instance() : $_SESSION['User']; $_SESSION['Slot'] = (empty($_SESSION['Slot']))? Slot::get_instance($_SESSION['User']) : $_SESSION['Slot']; //Cookies should be enabled class AppConfig{ public static $domainname = 'bitbandit.eu'; public static $min_confirmations_for_cash_out = '2'; //public static $message_bitcoin_show_when_user_withdrawn_money = 'Thank you for playing'; public static function now_plus_x_years($x = 10){ return time()+60*60*24*366*$x; } } ?><file_sep>/functions.php <?php function logout(){ //clear session and cookie session_unset(); //dump_it($_SESSION); session_destroy(); //dump_it($_SESSION); //dump_it(session_id()); session_id(null); //dump_it(session_id()); //clear SID in COOKIES //echo 'You are logged out'; } function show_interesting_facts() { $w = WeightTable::get_instance(); $user = User::get_instance(); $slot = Slot::get_instance($user); $paytable = Paytable::get_instance(); $total_cached_out = Transaction::get_total_cached_out_money(); $slot = Slot::get_instance($user); $total_spin_number = $slot->get_total_spin_number(); $output = " <div id=\"interesting_facts\"> <table class=\"table\" border='2px'> <tr> <td id='total_cached_out'>Cashed out money: $total_cached_out BTC</td> <td id='total_spin_number'>Games played: $total_spin_number </td> </tr> </table> </div> "; echo $output; } function show_generated_total_weight_table() { echo 'generated the number of appearances table'; //$w1 = WeightTable::get_instance(); $w = WeightTable::get_instance(); $user = User::get_instance(); $slot = Slot::get_instance($user); $paytable = Paytable::get_instance(); echo '<table border="1px" style="border-collapse: collapse;">'; echo '<tr>'; echo '<td>'; echo '---'; echo '</td>'; echo '<td>'; echo Symbol::$pyramid; echo '</td>'; echo '<td>'; echo Symbol::$bitcoin; echo '</td>'; echo '<td>'; echo Symbol::$anonymous; echo '</td>'; echo '<td>'; echo Symbol::$onion; echo '</td>'; echo '<td>'; echo Symbol::$anarchy; echo '</td>'; echo '<td>'; echo Symbol::$peace; echo '</td>'; echo '<td>'; echo Symbol::$blank; echo '</td>'; echo '<td>'; echo 'Sum'; echo '</td>'; echo '</tr>'; $number_of_symbol = array(); for ($i = 0; $i < 3; $i++){ $number_of_symbol[$i][Symbol::$pyramid] = 0; $number_of_symbol[$i][Symbol::$bitcoin] = 0; $number_of_symbol[$i][Symbol::$anonymous] = 0; $number_of_symbol[$i][Symbol::$onion] = 0; $number_of_symbol[$i][Symbol::$anarchy] = 0; $number_of_symbol[$i][Symbol::$peace] = 0; $number_of_symbol[$i][Symbol::$blank] = 0; } for($reel_num = 0; $reel_num < 3; $reel_num++){ echo '<tr>'; for ($i = 0; $i < 64; $i++){ //emulate spin and generating new server seeds $slot->generateServerSeeds(); $server_seeds = $slot->getServerSeeds(); //emulate client seed getting $client_seed = mt_rand(0, 2000000000); $hashed_client_seed = sha1($client_seed); if ($reel_num == 0){ $cur_sym = $slot->reel1->get_new_randomly_choosed_symbol($hashed_client_seed, $server_seeds[$reel_num]); } if ($reel_num == 1){ $cur_sym = $slot->reel2->get_new_randomly_choosed_symbol($hashed_client_seed, $server_seeds[$reel_num]); } if ($reel_num == 2){ $cur_sym = $slot->reel3->get_new_randomly_choosed_symbol($hashed_client_seed, $server_seeds[$reel_num]); } foreach ($number_of_symbol[$reel_num] as $key => $value) { //e.g.: if (Symbol::$pyramid == $cur_sym) if ($key == $cur_sym){ //e.g.: $number_of_symbol[$reel_num][Symbol::$bitcoin]++; $number_of_symbol[$reel_num][$key]++; } } } echo '<td>'; echo 'reel #'.$reel_num; echo '</td>'; $sum = 0; foreach ($number_of_symbol[$reel_num] as $key => $value) { //count total weight $sum += $value; echo '<td>'.$value; echo '</td>'; /* *the same as e.g.: *echo '<td>'; *echo $number_of_symbol[$reel_num][Symbol::$onion]; *echo '</td>'; * */ } echo '<td>'; echo $sum; echo '</td>'; echo '</tr>'; } echo '</table>'; } function possible_combinations(){ $w = WeightTable::get_instance(); $user = User::get_instance(); $slot = Slot::get_instance($user); $paytable = Paytable::get_instance(); $number_of_win_lines[Symbol::$pyramid] = 0; $number_of_win_lines[Symbol::$bitcoin] = 0; $number_of_win_lines[Symbol::$anonymous] = 0; $number_of_win_lines[Symbol::$onion] = 0; $number_of_win_lines[Symbol::$anarchy] = 0; $number_of_win_lines[Symbol::$peace] = 0; $number_of_win_lines[Symbol::$blank] = 0; $number_of_win_lines['bitcoin_2'] = 0; $number_of_win_lines['bitcoin_1'] = 0; $number_of_win_lines['lose'] = 0; //$N = 262144; $N = 2000; echo '<br /><table border="1px" style="border-collapse: collapse;">'; for($i = 0; $i < $N; $i++){ $client_seed = mt_rand(0, 2000000); //$hashed_client_seed = sha1($client_seed); //$slot->generateServerSeeds(); //$server_seeds = $w1->getServerSeeds(); $new_payline_and_servers_seeds = $slot->get_new_payline_and_servers_seeds($client_seed); $new_payline = $new_payline_and_servers_seeds['new_payline']; //dump_it($new_payline); $server_seeds = $new_payline_and_servers_seeds['server_seeds']; $result = $paytable->paylines_matching_with_wins($new_payline); //unset($new_payline); echo '<tr> <td> client seed </td> <td>'. $client_seed .'</td> <td> server_seed1 </td> <td>'. $server_seeds[0] .'</td> <td> server_seed2 </td> <td>'. $server_seeds[1] .'</td> <td> server_seed3 </td> <td>'. $server_seeds[2] .'</td> </tr>'; switch ($result){ case 'pyramid_3': $number_of_win_lines[Symbol::$pyramid]++; break; case 'bitcoin_3': $number_of_win_lines[Symbol::$bitcoin]++; break; case 'anonymous_3': $number_of_win_lines[Symbol::$anonymous]++; break; case 'onion_3': $number_of_win_lines[Symbol::$onion]++; break; case 'anarchy_3': $number_of_win_lines[Symbol::$anarchy]++; break; case 'peace_3': $number_of_win_lines[Symbol::$peace]++; break; case 'blank_3': $number_of_win_lines[Symbol::$blank]++; break; case 'bitcoin_2': $number_of_win_lines['bitcoin_2']++; break; case 'bitcoin_1': $number_of_win_lines['bitcoin_1']++; break; case 'lose': $number_of_win_lines['lose']++; break; } } echo '</table>'; //--- Table --- echo 'Table of amount of wins for '.$N.' stops. <br /> Most combinations (excepts bitcoin_2 - any 2 are bitcoins, bitcoin_1 - any 1 is bitcoin and lose) for 3 symbols )'; echo '<br /><table border="1px" style="border-collapse: collapse;">'; echo '<tr>'; echo '<td>'; echo 'win combination'; echo '</td>'; echo '<td>'; echo 'combination occurrence'; echo '</td>'; echo '<td>'; echo 'probability of win combination appears'; echo '</td>'; echo '<td>'; echo '% money returning to player ( probability * payoff)'; echo '</td>'; echo '<td>'; echo 'money (occurrence * bet * payoff - occurrence * bet)'; echo '</td>'; echo '</tr>'; $client_bet = 1; $total_sum = 0; $total_probability_of_apear = 0; $total_money = 0; $probability_of_occur = 0; foreach ($number_of_win_lines as $combination_name => $occurrence) { echo '<tr>'; echo '<td>'.$combination_name.'</td>'; echo '<td>'.$occurrence.'</td>'; //$number_of_win_lines[$combination_name]; $probability_of_occur = $occurrence/$N; echo '<td>'.$occurrence.' / ' .$N. ' = ' .$probability_of_occur.'</td>'; $paytable = Paytable::get_instance(); //get payoff for given combination name (key_...) if ($combination_name == 'bitcoin_2' || $combination_name == 'bitcoin_1'){ $total_probability_of_apear += $probability_of_occur; $payoff = $paytable->payoff_value_by_name($combination_name); } elseif ($combination_name == 'lose'){ $payoff = 0; } elseif ($combination_name == 'blank'){ $payoff = 0; } else{ $total_probability_of_apear += $probability_of_occur; $payoff = $paytable->payoff_value_by_name($combination_name.'_3'); } $res = $probability_of_occur * $payoff; if ($res > 0) $total_sum += $res; echo '<td>'. $probability_of_occur.' * '.$payoff. ' = ' .$res.'</td>'; $money = $occurrence* $client_bet * $payoff - $occurrence * $client_bet; $total_money += $money; echo '<td>'.$occurrence. ' * ' .$client_bet. ' * ' .$payoff. ' - ' .$occurrence. ' * ' .$client_bet. ' = ' .$money.'</td>'; echo '</tr>'; } echo '<tr>'; echo '<td>TOTAL:</td>'; echo '<td>'.$N.'</td>'; echo '<td>'.$total_probability_of_apear. '</td>'; echo '<td>'.$total_sum. ' ~ '. round($total_sum*100, 2) .'% </td>'; echo '<td> profit(deposited - paid) = '.$total_money*(-1).'</td>'; echo '</tr>'; echo '</table>'; //--- Table --- } ?> <file_sep>/__test2.php <?php require_once 'MyBitcoinClient.php'; require_once 'Dumpit.php'; require_once 'User.php'; require_once 'Reel.php'; require_once 'Header.php'; require_once 'Randomizer.php'; require_once 'mersenne_twister.php'; use mersenne_twister\twister; $time_start = microtime(true); $slot = Slot::get_instance(); $user = User::get_instance(); $db = DBconfig::get_instance(); //dump_it($slot); ////echo AppConfig::$domainname; // ////SetCookie("uid", '900b15b28c5dbdb15fb626dbde50861b14274384', AppConfig::now_plus_one_year(), '/', '.bitbandit.eu'); ////SetCookie("uid", $user->uid, AppConfig::now_plus_one_year(), '/', '.bitbandit.eu', true, false); //$user = User::get_instance(); // $options['maxbet'] = $db->mysqli_fetch_array("SELECT option_value FROM slot_options WHERE option_name = 'maxbet' "); //$slot->get_option_from_db(); dump_it($options['maxbet']['option_value']); $twister = new twister(crc32('051461babbcac6fc240ccd709d03f45e038d3bc0')+crc32('e06cc9249329be680f7a5c408538774033425f06')); dump_it($twister->int32()); foreach ($arr as $key => $value) { dump_it($value); //echo Reel::positive_crc32($value); echo "<br />crc32(value) in x64 = "; //dec value echo $crc32 = crc32($value); //echo "<br />hash(crc32b, value) in x64 = "; ////hex value //echo hash("crc32b", $value); echo "<br />dechex(crc32(value)) in x64 = "; //hex value echo dechex(crc32($value)); echo "<br />js value ".$js_arr[$key]; echo "<br />js value (hex) ".dechex($js_arr[$key]); $js_arr[$key] = $js_arr[$key] ^ 0xffffffff00000000; echo "<br />js value (hex) ".dechex($js_arr[$key]); $js_arr[$key] = hexdec($js_arr[$key]); echo "<br />js value (hex) ".dechex($js_arr[$key]); //echo '<br />sprintf("%x", $crc32)'.sprintf("%x", $crc32); //echo '<br />sprintf("%u", $crc32)'.sprintf("%u", $crc32); /* echo $crc32 % 4294967295;//2^32 echo "<br>"; echo "+crc32(value) in x64 = "; echo sprintf("%u", $crc32); echo "<br>"; echo $crc32 % 4294967295;//2^32 echo "<br>"; echo "+crc32(value) in js = "; echo "<br>"; echo $crc32 % 4294967295;//2^32 echo sprintf("%u", $js_arr[$key]); */ } dump_it(PHP_INT_MAX); dump_it(dechex(-1)); dump_it(mt_getrandmax()); $mbc = MyBitcoinClient::get_instance(); for($min_conf = 0; $min_conf < 3; $min_conf++){ echo '<br />All money: '.$mbc->getbalance(NULL,$min_conf).' min_conf = '.$min_conf; echo '<br />Money in SlotBank: '.$mbc->getbalance('SlotBank',$min_conf).' min_conf = '.$min_conf; echo '<br />Current User money: '.$mbc->getbalance($user->uid,$min_conf).' min_conf = '.$min_conf; echo '<br />'; } //$b->move('SlotBank', $user->uid, 0.05, 0,'Move from the user account to the common slot bitcoin account'); ////$amount = $b->getbalance($user->uid); //$amount = $b->getbalance(); //$amount = 0.0195; ////to user //$b->move('SlotBank', $user->uid, $amount, 0,'Move from the user account to the common slot bitcoin account'); ///to SlotBank //$b->move($user->uid, 'SlotBank', $amount, 0,'Move from the user account to the common slot bitcoin account'); //echo '<br />'; //echo '<br />All money: '.$b->getbalance(); //echo '<br />Money in SlotBank: '.$b->getbalance('SlotBank'); //echo '<br />Current User money: '.$b->getbalance($user->uid); //echo '<br /><br />'; ////echo 'SlotBank:'; ////echo 'uid '.$user->uid; //dump_it($b->getaddressesbyaccount($user->uid)); dump_it($user); /* $b = MyBitcoinClient::get_instance(); //todo: get transaction where category == receive!!! //$transactions_list = $b->query("listtransactions", $uid, "1", "0"); //listtransactions, uid = $uid, count = 50, start_from = 0 //$transactions_list = $b->query("listtransactions", $uid, "5", "0"); $transactions_list = $b->query("listtransactions", $user->uid, "10", "0"); // 0, null, false if (!$transactions_list){ echo 'Error. Bitcoin hasn\'t transactions for given user id'; return false; } $transactions_list_size = count($transactions_list); //exactly 1 transcation - where category should be 'receive' if ($transactions_list_size == 1 && isset($transactions_list[0]['receive'])){ $txid = $transactions_list[0]["txid"]; } //if count of transactions in $transactions_list are great than 1 //start to search transaction where 'category' == 'receive' if ($transactions_list_size > 1){ for($i = 0; $i < $transactions_list_size; $i++){ //if transaction has 'category' and 'txid' if (!empty($transactions_list[$i]['category']) && !empty($transactions_list[$i]['txid'])){ $txid = $transactions_list[$i]['txid']; //echo $txid; } foreach ($transactions_list[$i] as $key => $value) { if ($key === 'receive'){ $txid = $transactions_list[0]["txid"]; } } } } //if there are no transactions with 'receive' category if (!isset($txid)){ return false; } //$txid = '4e56ce612c560e8eef187415078aec1e26b89ead41399aa8dd3edce7963d8ea7'; //dump_it($b->getinfo()); //echo $txid; $raw_transaction_arr = $b->query("getrawtransaction", $txid, "1"); if (empty($raw_transaction_arr['vout'])){ echo 'User\'s bitcoin wallet address not found.'; return false; } //user's address placed in 'vout' for($i = 0; $i < count($raw_transaction_arr['vout']); $i++){ //search 'addresses' array in 'scriptPubKey' array if (!empty($raw_transaction_arr['vout'][$i]['scriptPubKey']) && !empty($raw_transaction_arr['vout'][0]['scriptPubKey']['addresses'])){ $addresses_count = count($raw_transaction_arr['vout'][0]['scriptPubKey']['addresses']); //take the last address $user_wallet_address = $raw_transaction_arr['vout'][0]['scriptPubKey']['addresses'][$addresses_count-1]; } } dump_it($raw_transaction_arr); dump_it($user_wallet_address); */ //dump_it($b->query("listaccounts")); //// ////echo 'Account SlotBank has address '.$b->getaccountaddress('SlotBank'); //// //////$transactions_list = $b->query("listtransactions", "SlotBank", "1", "0"); //$transactions_list = $b->query("listtransactions", $user->uid, "10", "0"); ////dump_it($transactions_list[0]); //// //$txid = $transactions_list[0]["txid"]; //echo $txid; //$raw_transaction_arr = $b->query("getrawtransaction", $txid, "1"); //dump_it($raw_transaction_arr); ////$user->user_wallet = $raw_transaction_arr['vout'][1]['scriptPubKey']['addresses'][0]; // //echo '<br>'; //$user->get_user_wallet_by_uid(); echo $user->user_wallet; ////echo $b->sendfrom('SlotBank', '1JedC8gQqfNoP5ykGtTwr567DpGiZcvQ5q', 0.01, 1); //dump_it($b->query("listreceivedbyaddress")); //last values //All money: 0.058 //Money in SlotBank: 0.079 //Current User money: 0 $time_end = microtime(true); $script_time = $time_end-$time_start; printf('Script running time: %.4F s.',$script_time); dump_it($_SESSION); //dump_it($_SESSION['Slot']); dump_it($_SESSION['User']); ?><file_sep>/Cookie.php <?php /** * Description of Cookie * * @author vadim24816 */ require_once 'Appconfig.php'; class Cookie { public static function get_instance(){ if (is_null(self::$cookie)){ self::$cookie = new Cookie(); //self::$cookie->config_filling(); return self::$cookie; } return self::$cookie; } private function __construct(){ } private function __clone(){} private function __wakeup(){} protected static $cookie; public function set_cookie($name, $value, $expire, $path, $domain, $secure, $httponly){ /* $name = htmlentities($name); $value = htmlentities($value); $expire = htmlentities($expire); $path = htmlentities($path); $domain = htmlentities($domain); $secure = htmlentities($secure); $httponly = htmlentities($httponly); */ setcookie($name, $value, $expire, $path, $domain, $secure, $httponly); } public function get_cookie($name){ $name = htmlentities($name); //if there is no cookie with given name if (empty($_COOKIE[$name]) || (!$_COOKIE[$name])){ echo 'no cookie named '.$name; return FALSE; } else { return $_COOKIE[$name]; } } } ?> <file_sep>/__test3.php <?php require_once 'Appconfig.php'; $time_start = microtime(true); //$slot = Slot::get_instance(); $slot = $_SESSION['Slot']; //$_SESSION['Slot'] = $slot; $time_end = microtime(true); $script_time = $time_end-$time_start; printf('Script running time: %.4F s.',$script_time); $user = User::get_instance(); $db = DBconfig::get_instance(); //$m = MyBitcoinClient::get_instance(); $_SESSION['MyBitcoinClient'] = MyBitcoinClient::get_instance(); dump_it($_SESSION['MyBitcoinClient']); dump_it($_SESSION['Slot']); dump_it($_SESSION['User']); ?><file_sep>/README.md slot-machine ============ slot-machine<file_sep>/Dumpit.php <?php //require_once 'Appconfig.php'; function dump_it($var){ echo '<pre>'; echo '<br />var: '; var_dump($var); echo '</pre>'; } ?> <file_sep>/__Instawallet.php <?php class Instawallet { public $wallet_id, $address, $balance; protected $path_new_wallet = 'https://www.instawallet.org/api/v1/new_wallet'; //new_wallet() - Request a new wallet //Parameters: none //Returns: wallet_id /* function new_wallet() { $url = 'https://www.instawallet.org/api/v1/new_wallet'; $json = file_get_contents($url); $data = json_decode($json); echo 'json'; echo $json; if(!$data->successful) { return false; } else { return $data->wallet_id; } } */ function __construct() { $this->wallet_id = $this->new_wallet_curl(); $this->address = $this->address_curl($this->wallet_id); $this->balance = $this->balance_curl($this->wallet_id); } function init_curl($ch, $post, $post_fields){ curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Отключить ошибку "SSL certificate problem, verify that the CA cert is OK" curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //for POST method using curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); curl_setopt($ch, CURLOPT_POST, $post); // Отключить ошибку "SSL: certificate subject name 'hostname.ru' does not match target host name '172.16.58.3'" curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); } //the same function but with cURL function new_wallet_curl() { $ch = curl_init($this->path_new_wallet); //curl_setopt($ch, CURLOPT_POST, 1); $this->init_curl($ch,1,1); $json = curl_exec($ch); $data = json_decode($json); curl_close($ch); if(!$data->successful) { echo $data->message; return false; } else { //$this->wallet_id = $json_obj->wallet_id; return $data->wallet_id; } } //address() - Request the address of an existing wallet //Parameters: wallet_id //Returns: address /* function address($wallet_id = null) { if(empty($wallet_id)) { return false; } else { $url = 'https://www.instawallet.org/api/v1/w/' . $wallet_id . '/address'; $json = file_get_contents($url); $data = json_decode($json); if(!$data->successful) { return false; } else { return $data->address; } } } * */ function address_curl($wallet_id = null) { if(empty($wallet_id)) { return false; } else { $url = 'https://www.instawallet.org/api/v1/w/' . $wallet_id . '/address'; $ch = curl_init($url); $this->init_curl($ch,0,0); $json = curl_exec($ch); $data = json_decode($json); curl_close($ch); if(!$data->successful) { echo $data->message; return false; } else { return $data->address; } } } //balance() - Request the current balance of an existing wallet //Parameters: wallet_id //Returns: balance /* function balance($wallet_id = null) { if(empty($wallet_id)) { return false; } else { $url = 'https://www.instawallet.org/api/v1/w/' . $wallet_id . '/balance'; $json = file_get_contents($url); $data = json_decode($json); if(!$data->successful) { return false; } else { return $data->balance; } } } * */ function balance_curl($wallet_id = null) { if(empty($wallet_id)) { return false; } $url = 'https://www.instawallet.org/api/v1/w/' . $wallet_id . '/balance'; $ch = curl_init($url); $this->init_curl($ch,0,0); $json = curl_exec($ch); $data = json_decode($json); if(!$data->successful) { echo $data->message; return false; } else { return $data->balance; } } //payment() - Request a payment be initiated from an existing wallet /* function payment() { $url = 'https://www.instawallet.org/api/v1/w/' . $wallet_id . '/payment'; $json = file_get_contents($url); return json_decode($json); } * */ function payment_curl($wallet_id = null, $reciever_addres, $amount) { if(empty($wallet_id) || empty($reciever_addres) || empty($amount)) { return false; } $url = 'https://www.instawallet.org/api/v1/w/' . $wallet_id . '/payment'; $ch = curl_init($url); $this->init_curl($ch,1,'address='.$reciever_addres.';amount='.$amount); $json = curl_exec($ch); $data = json_decode($json); if(!$data->successful) { echo $data->message; return false; } echo $data->message; return json_decode($json); } function get_sender_address(){ //http://www.bitcoinforum.com/security-technical-support-and-tutorials/how-to-find-out-the-sender-address/ //http://blockexplorer.com/q/mytransactions/1Cvvr8AsCfbbVQ2xoWiFD1Gb2VRbGsEf28 //https://bitcointalk.org/index.php?topic=112741.0 } } ?><file_sep>/__test4.php <?php //require_once 'MyBitcoinClient.php'; //echo session_start(); //echo phpinfo(); $current_check_connect_time = microtime(true); //require_once 'Dumpit.php'; require_once 'Appconfig.php'; $mbc = $_SESSION['MyBitcoinClient']; dump_it($mbc->can_connect()); for ($i=0; $i<100; $i++){ //sleep(1); //echo $mbc->check_last_connect(); //echo $mbc->getbalance(0,0); } //dump_it($mbc); dump_it($_SESSION); $user = $_SESSION['User']; $user->logout(); dump_it($_SESSION); ?> <file_sep>/User.php <?php require_once 'Appconfig.php'; /** * Description of User * * @author vadim24816 */ ?> <?php class User { //make it singletone protected static $user; private function __construct(){} private function __clone(){} //private function __wakeup(){} public static function get_instance(){ if (is_null( self::$user) ){ self::$user = new User(); // $_SESSION['User'] = self::$user; self::$user->auth(); return self::$user; } /*elseif( !empty($_SESSION['User'])){ self::$user = $_SESSION['User']; return $_SESSION['User']; }*/ return self::$user; } public $uid, $phpsessid, $user_wallet, $bitcoin_receive_address, $money_balance, $affiliateusername, $remote_user_address;//, $bitcoin_receive_address, $money_balance; //private function is_cookie public function auth(){ $file = ''; $line = ''; //check for whether headers was already sent if (headers_sent($file, $line)){ echo 'file: '.$file; echo 'line: '.$line; } //user registered already if ( !empty($_COOKIE['uid']) ){// || !empty($_COOKIE['bitcoin_receive_address'])){ //TODO: escaping by regExp $uid_pattern = '/^[a-zA-Z0-9]{40}&/'; $phpsessid_pattern = '/^[a-zA-Z0-9]{32}&/'; //if wrong $_COOKIE['uid'], clear it if ( !preg_match($uid_pattern, $_COOKIE['uid']) ){ SetCookie("uid", ""); } //if wrong $_COOKIE['PHPSESSID'], clear it if ( !preg_match($phpsessid_pattern, $_COOKIE['PHPSESSID']) ){ SetCookie("PHPSESSID", ""); } $uid = $_COOKIE['uid']; $this->uid = $uid; //search for user by given uid if ($this->get_from_db($uid)){ // $this->phpsessid = session_id(); } //if bitcoin_receive_address didn't set, set it if ( empty($this->bitcoin_receive_address) ){ $this->set_bitcoin_receive_address(); } } //1) user visits first time OR 2) if uid hadn't found in db? else { $this->logout(); if (!$this->reg()){ dump_it($e->getTraceAsString()); //throw new Exception('Can\'t register new user'); } } return $this; } public function logout(){ //from functions.php logout(); //// //clear session and cookie //// $_SESSION = array(); //// dump_it(session_name()); //// //clear SID in COOKIES //// unset($_COOKIE[session_name()]); //// unset($_COOKIE['uid']); //// unset($_COOKIE['bitcoin_receive_address']); //// session_destroy(); //// echo 'You are logged out'; } private function set_bitcoin_receive_address(){ $mbc = MyBitcoinClient::get_instance(); if ( $mbc->check_last_connect() === true ){ try{//to get bitcoin_receive_address $this->bitcoin_receive_address = $mbc->getaccountaddress($this->uid); } catch (BitcoinClientException $e) { //todo: write exceptions to error/exceptions log file dump_it($e->getTraceAsString()); //can't set cookie because of this error echo } } } public function reg(){ if (!empty($_SERVER['REMOTE_ADDR'])){ $remote_user_address = $_SERVER['REMOTE_ADDR']; } // $this->phpsessid = session_id(); //if this uid has had in DB already it generates new uid $this->uid = sha1(uniqid(""));//40 ch while($this->get_from_db($this->uid)){ $this->uid = sha1(uniqid("")); } $this->money_balance = 0; //create the new wallet for new user /* $mbc = MyBitcoinClient::get_instance(); dump_it($mbc); dump_it($mbc->check_new_connect()); dump_it($mbc->check_last_connect()); * */ //no connection with bitcoin server //try to get from bitcoin and set in User address $this->set_bitcoin_receive_address(); $this->user_wallet = 'No_yet'; $this->affiliateusername = 'Nobody'; $this->remote_user_address = $remote_user_address; //e.g.: 04:34:19 11.11.2012 $this->created_at = date('h:i:s d.m.Y'); if ($this->save_in_db()){ $file = ''; $line = ''; //check for whether headers was already sent if (headers_sent($file, $line)){ echo 'file: '.$file; echo 'line: '.$line; } SetCookie("uid", $this->uid, AppConfig::now_plus_x_years(), '/', /*'.bitbandit.eu'*/AppConfig::$domainname, true, false); return true; } else { //throw new Exception('Failed to add to the database.'); echo 'Failed to add to the database.'; return false; } } //get user record from db function get_from_db($uid){ try{ $db = DBconfig::get_instance(); $user = $db->mysqli_fetch_array('SELECT * FROM users WHERE uid = \''.$uid.'\''); //$user = $db->mysqli_fetch_array('SELECT * FROM users WHERE uid = '.$uid); } catch (Exception $e){ dump_it($e->getTraceAsString()); } //if there is no user with given uid if ($user == FALSE){ //echo 'user == false'; return FALSE; } //the user is found else{ $this->uid = $uid; $this->bitcoin_receive_address = $user['bitcoin_receive_address']; $this->money_balance = $user['money_balance']; $this->user_wallet = $user['user_wallet']; $this->remote_user_address = $user['remote_user_address']; $this->affiliateusername = $user['affiliateusername']; return TRUE; } } function is_user_exist($uid){ $db = DBconfig::get_instance(); $user = $db->mysqli_fetch_array('SELECT * FROM users WHERE uid = \''.$uid.'\''); //if there is no user with given uid if ($user == FALSE){ //echo 'user == false'; return FALSE; } //the user is found else{ return TRUE; } } //for updating money balance function update_from_db(){ $this->get_from_db($this->uid); } function save_in_db(){ $db = DBconfig::get_instance(); //escaping party $this->uid = $db->mysqli_link->real_escape_string($this->uid); $this->bitcoin_receive_address = $db->mysqli_link->real_escape_string($this->bitcoin_receive_address); $this->user_wallet = $db->mysqli_link->real_escape_string($this->user_wallet); $this->money_balance = $db->mysqli_link->real_escape_string($this->money_balance); $this->affiliateusername = $db->mysqli_link->real_escape_string($this->affiliateusername); $this->remote_user_address = $db->mysqli_link->real_escape_string($this->remote_user_address); //if user not exist insert in DB if (!$this->is_user_exist($this->uid)){ $res = $db->query( "INSERT INTO users (uid, bitcoin_receive_address, user_wallet, money_balance, affiliateusername, created_at, remote_user_address) VALUES ('$this->uid', '$this->bitcoin_receive_address', '$this->user_wallet', '$this->money_balance', '$this->affiliateusername', NOW(), '$this->remote_user_address')");//NOW() == '$this->created_at', } //if user exists already just update record else { $res = $db->query( "UPDATE users SET `bitcoin_receive_address` = '$this->bitcoin_receive_address', `user_wallet` = '$this->user_wallet', `money_balance` = '$this->money_balance', `affiliateusername` = '$this->affiliateusername', `remote_user_address` = '$this->remote_user_address' WHERE `uid` = '$this->uid' "); } if (!$res){ //echo 'no res'; return FALSE; } //update user after saving $this->get_from_db($this->uid); return true; } // return address from which user sent money public function get_user_wallet_by_uid(){ $db = DBconfig::get_instance(); $b = MyBitcoinClient::get_instance(); $this->uid = $db->mysqli_link->real_escape_string($this->uid); $transactions_list = $b->query("listtransactions", $this->uid, "10", "0"); // 0, null, false if (!$transactions_list){ echo 'Error. Bitcoin hasn\'t transactions for given user id'; return false; } $transactions_list_size = count($transactions_list); //exactly 1 transcation - where category should be 'receive' if ($transactions_list_size == 1 && isset($transactions_list[0]['receive'])){ $txid = $transactions_list[0]["txid"]; } //if count of transactions in $transactions_list are great than 1 //start to search transaction where 'category' == 'receive' if ($transactions_list_size > 1){ for($i = 0; $i < $transactions_list_size; $i++){ //if transaction has 'category' and 'txid' if (!empty($transactions_list[$i]['category']) && !empty($transactions_list[$i]['txid'])){ $txid = $transactions_list[$i]['txid']; //echo $txid; } foreach ($transactions_list[$i] as $key => $value) { if ($key === 'receive'){ $txid = $transactions_list[0]["txid"]; } } } } //if there are no transactions with 'receive' category if (!isset($txid)){ return false; } $raw_transaction_arr = $b->query("getrawtransaction", $txid, "1"); if (empty($raw_transaction_arr['vout'])){ echo 'User\'s bitcoin wallet address not found.'; return false; } //user's address placed in 'vout' for($i = 0; $i < count($raw_transaction_arr['vout']); $i++){ //search 'addresses' array in 'scriptPubKey' array if (!empty($raw_transaction_arr['vout'][$i]['scriptPubKey']) && !empty($raw_transaction_arr['vout'][0]['scriptPubKey']['addresses'])){ $addresses_count = count($raw_transaction_arr['vout'][0]['scriptPubKey']['addresses']); //take the last address $user_wallet_address = $raw_transaction_arr['vout'][0]['scriptPubKey']['addresses'][$addresses_count-1]; } } //$user_wallet_address = $raw_transaction_arr['vout'][0]['scriptPubKey']['addresses'][0]; //dump_it($raw_transaction_arr); $address_and_txid = array('user_wallet_address' => $user_wallet_address, 'txid' => $txid); //return $user_wallet_address; return $address_and_txid; } //one function for cash_in and cash_out public function cash_move($to_where = 'in', $amount = null){ if ($to_where !== 'in' && $to_where !== 'out'){ //little stupid //return -1; return array("amount" => -1, "txid" => -1); } //$mbc = MyBitcoinClient::get_instance(); $mbc = $_SESSION['MyBitcoinClient']; $user = $this; //todo: todo // if (account_not_exist($user->uid)){ // echo 0; // return false; // } //user_bitcoin_money_balance was transfered to SlotBank account, so it's null. //$user_bitcoin_money_balance = $user->money_balance; //$user_bitcoin_money_balance = $m->getbalance($user->uid, 0); //get new connection checking if ( !$mbc->check_last_connect() ){ //return -2; return array("amount" => -2, "txid" => -2); } //payments processing // //all money user has //$user->money_balance = $user_bitcoin_money_balance; if ($to_where == 'in'){ //for 'In' payments we use bitcoind(!) user balance $user_bitcoin_money_balance = $mbc->getbalance($user->uid, 0); if ($user_bitcoin_money_balance == 0){ return array("amount" => 0, "txid" => 0); } //no in/outcoming payments was made if ($user_bitcoin_money_balance < 0){ //return -3; return array("amount" => -3, "txid" => -3); } //move money which was sent by user to the common slot account //(!) Because we move uncomfirmed money (with 0 confirmations and we need 2) //... user balance (in bitcoin) will be negative //... until the moving will be confirmed $mbc->check_and_move($user->uid, Slot::$bitcoin_account_name/*'SlotBank'*/, $user_bitcoin_money_balance, 0/*Appconfig::$min_confirmations_for_cash_out/* == 2*/,'Move from the user account '.$user->uid.' to the common slot bitcoin account '.Slot::$bitcoin_account_name.' Money: '.$user->money_balance); //ADD (+=) new payment to user balance $user->money_balance += $user_bitcoin_money_balance; //find out user's bitcoin wallet address $user_walllet_address_and_txid = $user->get_user_wallet_by_uid(); $wallet_from_which_user_sent_money = $user_walllet_address_and_txid['user_wallet_address']; //find out the input transaction txid $txid = $user_walllet_address_and_txid['txid']; //( txid, all money, deposit = true, uid ) $t = new Transaction($txid, $user_bitcoin_money_balance, true, $user->uid); //keep amount of money was moved for returning $amont_of_money_was_moved = $user_bitcoin_money_balance; //should be not 0 if money was received (there is transaction which has 'received' category) if ($wallet_from_which_user_sent_money !== 0){ $user->user_wallet = $wallet_from_which_user_sent_money; //$user->save_in_db(); } else{ //money was not really received //return -4; return array("amount" => -4, "txid" => -4); } } if ($to_where == 'out'){ //check options are not off for money out $options = Slot::get_option_from_db(); //$options = $slot->get_option_from_db(); //$paying_out = $options['paying_out']; if ($options['paying_out']['option_value'] == 'off'){ return array("amount" => -200, "txid" => -200); } //nothing to out if ($user->money_balance <= 0){ //return -100; return array("amount" => 0, "txid" => 0); } //check that money which user deposited are confirmed (min_conf = 2) //this means that user balance with 2 confirmations should be 0 if ($mbc->getbalance($user->uid, Appconfig::$min_confirmations_for_cash_out /* == 2*/) < 0){ //not enough confirmations //return -101; return array("amount" => -101, "txid" => -101); } //when the cashout amount is more than the wallet amount if ( $user->money_balance > $mbc->getbalance(NULL,$min_conf = 6) ){ //not enough confirmations //return -500; return array("amount" => -500, "txid" => -500); } //1)for cash out only whats on balance not balance+bet or 2) amount not got if ($amount > $user->money_balance || $amount == null){ //amount for cashout > user money balance //return error(?) return array("amount" => -404, "txid" => -404); //cashout all balance //$amount = $user->money_balance; } //first move bitcoins from common account to user account //$m->move(Slot::$bitcoin_account_name/*'SlotBank'*/, $user->uid, $user->money_balance, 0/*Appconfig::$min_confirmations_for_cash_out/*2*/,'Move from the common slot bitcoin account '.Slot::$bitcoin_account_name.' to the user account '.$user->uid.' Money: '.$user->money_balance); //second move bitcoins from user account to user wallet with 2(!) confirmations //$txid = $m->sendfrom($user->uid, $user->user_wallet, (float)$user->money_balance, 2/*Appconfig::$min_confirmations_for_cash_out*/, 'Cash out from user account '.$user->uid.' to user wallet addres '.$user->user_wallet, 'Thank you for playing'/*AppConfig::$message_bitcoin_show_when_user_withdrawn_money*/); //Send amount from the server's available balance $txid = $mbc->sendtoaddress($user->user_wallet, $amount/*cash out only whats on balance not balance+bet /*$user->money_balance*/, 'Cash out from user account '.$user->uid.' to user wallet addres '.$user->user_wallet, 'Thank you for playing'/*AppConfig::$message_bitcoin_show_when_user_withdrawn_money*/); //dump_it($txid); //get amount of fee for withdrawn transaction $arr = $mbc->gettransaction($txid);//$m->query("gettransaction", $txid); //fee is negative! $fee = $arr['fee']; //dump_it($arr); //$m->move(Slot::$bitcoin_account_name/*'SlotBank'*/, $user->uid, abs($fee), 0,"Pay fee for user's transaction of money withdrawal"); //for 'Out' payments we use user balance from DB $t = new Transaction($txid, $amount/*$user->money_balance*/, false, $user->uid); //Send amount from the server's available balance //$m->sendtoaddress($user->user_wallet, $user->money_balance, 'Cash out from user account '.$user->uid.' to user wallet addres '.$user->user_wallet, 'Thank you for playing'/*AppConfig::$message_bitcoin_show_when_user_withdrawn_money*/); //$m->move($user->uid, $user->user_wallet, $user->money_balance, 0/*Appconfig::$min_confirmations_for_cash_out/*2*/,'Move from the user bitcoin account '.$user->uid.' to the user wallet '.$user->user_wallet.' Money: '.$user->money_balance); //keep amount of money was moved for returning $amont_of_money_was_moved = $amount;//$user->money_balance; //user money - amount //$user->money_balance = 0; $user->money_balance -= $amount; } //and SAVE user wallet in DB! $user->save_in_db(); //money was outputed //return $amont_of_money_was_moved; return array("amount" => $amont_of_money_was_moved, "txid" => $txid); } //aliases public function cash_out($amount){ return $this->cash_move($where = 'out', $amount); } public function cash_in(){ return $this->cash_move($where = 'in'); } } ?><file_sep>/fullList.php <?php require_once 'Appconfig.php'; require_once 'Header.php'; ?> <body> <div id="statistic"> <?php if (!empty($_GET['option'])){ $option = $_GET['option']; } else{ $option = 'last'; } switch ($option) { case 'last': Transaction::show_transactions('last', 0, 100); break; case 'biggestwinners': Transaction::show_transactions('biggestwinners', 0, 100); break; default: Transaction::show_transactions('last', 0, 100); break; } ?> </div> <div id="prev_and_next"> <div id="left" style="float: left; display:none;"><a href="#"><<</a></div> <div id="right" style="float: right;"><a href="#">>></a></div> </div> <script type="text/javascript"> $(document).ready(function(){ currentPage = 1; paginationStart = 0; paginationPerPage = 100; totalRecords = $('div.transactions input#total_records').val(); totalPages = Math.ceil(totalRecords / paginationPerPage);// 1.01 => 2 round to greater int number function getParams(){ var tmp = new Array(); var tmp2 = new Array(); GET = new Array(); var get = location.search; if(get != '') { tmp = (get.substr(1)).split('&'); for(var i=0; i < tmp.length; i++) { tmp2 = tmp[i].split('='); GET[tmp2[0]] = tmp2[1]; } } return GET; } function show(){ option = 'last'; GET = getParams(); option = GET['option']; $.post("AjaxRequestsProcessing.php", { slot: "transactions", 'option': option, 'from': (currentPage*paginationPerPage-paginationPerPage), 'to': (currentPage*paginationPerPage)}) .done(function(transactionsTable) { $('div#statistic').html(transactionsTable); //if (window.console) console.log(transactionsTable); pageControl(); }) .fail(function(){ if (window.console) console.log('Client error. Error in ajax admin-->show request, bad response'); }); } $('div#left').on('click',function(){ if (currentPage == 1) return false; currentPage -= 1; show(); }); $('div#right').on('click',function(){ if (currentPage == totalPages) return false; currentPage += 1; show() }); function pageControl(){ if (currentPage == 1){ $('div#left').css('display','none'); } else{ $('div#left').css('display','block'); } if (currentPage == totalPages){ $('div#right').css('display','none'); } else{ $('div#right').css('display','block'); } } pageControl(); }); </script> </body> </html><file_sep>/Paytable.php <?php /** * Description of Paytable * * @author vadim24816 */ require_once 'Appconfig.php'; class Paytable { //make it singletone protected static $paytable; private function __construct(){} private function __clone(){} private function __wakeup(){} public static function get_instance(){ if (is_null(self::$paytable)){ self::$paytable = new Paytable(); self::$paytable->paytable_filling(); return self::$paytable; } return self::$paytable; } //win paylines protected $pyramid_3, $bitcoin_3, $anonymous_3, $onion_3, $anarchy_3, $peace_3, $bitcoin_2, $bitcoin_1; //filling win paylines public function paytable_filling(){ $this->pyramid_3 = new Payline(Symbol::$pyramid, Symbol::$pyramid, Symbol::$pyramid); $this->bitcoin_3 = new Payline(Symbol::$bitcoin, Symbol::$bitcoin, Symbol::$bitcoin); $this->anonymous_3 = new Payline(Symbol::$anonymous, Symbol::$anonymous, Symbol::$anonymous); $this->onion_3 = new Payline(Symbol::$onion, Symbol::$onion, Symbol::$onion); $this->anarchy_3 = new Payline(Symbol::$anarchy, Symbol::$anarchy, Symbol::$anarchy); $this->peace_3 = new Payline(Symbol::$peace, Symbol::$peace, Symbol::$peace); $this->bitcoin_2 = new Payline(Symbol::$bitcoin, Symbol::$bitcoin, Symbol::$any); $this->bitcoin_1 = new Payline(Symbol::$bitcoin, Symbol::$any, Symbol::$any); $this->blank_3 = new Payline(Symbol::$blank, Symbol::$blank, Symbol::$blank); } //compare given payline with win payline public function paylines_matching_with_wins($payline){ switch ($payline){ //3 matches //echo 'pyramid_3'; case $this->pyramid_3: //return 5000; return 'pyramid_3'; break; //echo 'bitcoin_3'; case $this->bitcoin_3: //return 1000; return 'bitcoin_3'; break; //echo 'anonymous_3'; case $this->anonymous_3: //return 200; return 'anonymous_3'; break; //echo 'onion_3'; case $this->onion_3: //return 100; return 'onion_3'; break; //echo 'anarchy_3'; case $this->anarchy_3: //return 50; return 'anarchy_3'; break; //echo 'peace_3'; case $this->peace_3: //return 25; return 'peace_3'; break; case $this->blank_3: //return 0; return 'blank_3'; break; //something else default: //bitcoin_2 //echo 'bitcoin_2'; if ($this->amount_of_symbols_in_payline($payline, Symbol::$bitcoin) == 2){ //return 10; return 'bitcoin_2'; } //bitcoin_1 //echo 'bitcoin_1'; if ($this->amount_of_symbols_in_payline($payline, Symbol::$bitcoin) == 1){ //return 2; return 'bitcoin_1'; } //echo 'you are not win'; //return 0; return 'lose'; } } //return amount of secific symbol in public function amount_of_symbols_in_payline($payline, $symbol){ $amount = 0; $payline_symbols = $payline->get_symbols_array(); for ($i=0; $i<3; $i++){ //found 1 more symbol if ($payline_symbols[$i] == $symbol){ $amount++; } } return $amount; } //return payoffs for given payline public function payoff_value($payline){ switch ($payline){ //3 matches //echo 'pyramid_3'; case $this->pyramid_3: return 5000; break; //echo 'bitcoin_3'; case $this->bitcoin_3: return 1000; break; //echo 'anonymous_3'; case $this->anonymous_3: return 200; break; //echo 'onion_3'; case $this->onion_3: return 100; break; //echo 'anarchy_3'; case $this->anarchy_3: return 50; break; //echo 'peace_3'; case $this->peace_3: return 25; break; case $this->blank_3: return 0; break; //something else default: //bitcoin_2 //echo 'bitcoin_2'; if ($this->amount_of_symbols_in_payline($payline, Symbol::$bitcoin) == 2){ return 10; } //bitcoin_1 //echo 'bitcoin_1'; if ($this->amount_of_symbols_in_payline($payline, Symbol::$bitcoin) == 1){ return 2; } //echo 'you are not win'; return 0; } } public function payoff_value_by_name($combination_name){ switch ($combination_name){ //3 matches //echo 'pyramid_3'; case 'pyramid_3': return 5000; break; //echo 'bitcoin_3'; case 'bitcoin_3': return 1000; break; //echo 'anonymous_3'; case 'anonymous_3': return 200; break; //echo 'onion_3'; case 'onion_3': return 100; break; //echo 'anarchy_3'; case 'anarchy_3': return 50; break; //echo 'peace_3'; case 'peace_3': return 25; break; //echo 'blank_3'; case 'blank_3': return 0; break; //bitcoin_2 //echo 'bitcoin_2'; case 'bitcoin_2': return 10; break; //bitcoin_1 //echo 'bitcoin_1'; case 'bitcoin_1': return 2; break; //something else default: //echo 'you are not win'; return 0; } } } /* $paytable1 = Paytable::get_instance(); $payline1 = new Payline(Symbol::$blank, Symbol::$any, Symbol::$any); $paytable1->paylines_matching_with_wins($payline1); * */ ?> <file_sep>/__test1.php <?php //relocate browser to https //require_once 'relocateToSecureScheme.php'; require_once 'Dumpit.php'; require_once 'DBconfig.php'; ////require_once 'Instawallet.php'; //require_once 'MyBitcoinClient.php'; //require_once 'Randomizer.php'; //require_once 'Symbol.php'; //require_once 'Reel.php'; //require_once 'Payline.php'; //require_once 'Paytable.php'; //require_once 'Cookie.php'; require_once 'User.php'; //require_once 'bitcoin/bitcoin.inc'; require_once 'Slot.php'; //require_once 'Transaction.php'; //require_once 'functions.php'; //Cookies should be enabled $db = DBconfig::get_instance(); //$db->close(); //$db = DBconfig::get_instance(); //$db->close(); //$db = DBconfig::get_instance(); //$db->close(); //$uid = '69d37bef6ba2bb1670d20b49e5e62752391aa6b6'; //$user = $db->mysqli_fetch_array("SELECT * FROM users WHERE uid = '$uid'"); //dump_it($user); $user = User::get_instance(); echo $user->uid; $slot = Slot::get_instance($user); $m = MyBitcoinClient::get_instance(); //$m->move(Slot::$bitcoin_account_name/*'SlotBank'*/, $user->uid, 0.04, 0,'Move from the user account '.$user->uid.' to the common slot bitcoin account'.Slot::$bitcoin_account_name.' Money: '.$user->money_balance); //no incoming payments was made if ($m->check_last_connect() !== true){ return false; } $bitcoin_money_balance = $m->getbalance($user->uid, 0); if ($bitcoin_money_balance <= 0){ echo 0; return false; } //incoming payments processing echo $m->getbalance($user->uid, 0); //all money user have sent $user->money_balance = $bitcoin_money_balance; //( txid, all money, deposit = true, uid ) $t = new Transaction('', $user->money_balance, true, $user->uid); //echo Slot::$bitcoin_account_name; //move money was sent by user to common slot account try{ //$m->move($user->uid, Slot::$bitcoin_account_name/*'SlotBank'*/, $user->money_balance, 0,'Move from the user account '.$user->uid.' to the common slot bitcoin account'.Slot::$bitcoin_account_name.' Money: '.$user->money_balance); $user->user_wallet = $user->get_user_wallet_by_uid(); $user->save_in_db(); } catch (Exception $e){ //$this->reg(); //stack trace show FULL INFO about bitcoin, with login and passwords dump_it($e->getTraceAsString()); } $json = $user->money_balance; echo $json; ?> <file_sep>/MyBitcoinClient.php <?php require_once 'Appconfig.php'; //fill config info class ConfigForMyBitcoinClient{ public function __construct() { if ($_SERVER['HTTP_HOST'] == '172.16.17.32' || $_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '127.0.0.1'){ $this->scheme = 'https'; $this->username = 'bitcoinrpc'; $this->password = '<PASSWORD>'; $this->address = "localhost"; $this->port = 8332; $this->certificate_path = __DIR__ .'/mysitename.crt'; //echo 'path to cert<br/>'; //echo $this->certificate_path; $this->debug_level = 0; //self::$bitcoin = new BitcoinClient($this->scheme, $this->username, $this->password, $this->address, $this->port, $this->certificate_path, $this->debug_level); } else{ $this->scheme = 'https'; $this->username = 'bitcoinrpc'; $this->password = '<PASSWORD>'; $this->address = "172.16.17.32"; //$this->address = "cs1205.mojohost.com"; $this->port = 8332; //$this->certificate_path = "cs1205.crt"; //$this->certificate_path = "server.cert"; $this->certificate_path = __DIR__ .'/mysitename.crt'; //echo $this->certificate_path; $this->debug_level = 0; } } } class MyBitcoinClient extends BitcoinClient{ public $last_check_connect_time, $last_check_connect_status, $check_connect_time_interval; public static function get_instance(){ //echo 'MyBitcoinClient get_instance()'; //make config $config = new ConfigForMyBitcoinClient(); $mbc = new MyBitcoinClient($config->scheme, $config->username, $config->password, $config->address, $config->port, $config->certificate_path, $config->debug_level); $mbc->init(); return $mbc; } public function init(){ //keep the last time when connection was checked $this->last_check_connect_time = microtime(true); $this->last_check_connect_status = true; //interval for bitcoin connection checking $this->check_connect_time_interval = 15; //15sec } public function check_and_move( $fromaccount = "", $toaccount, $amount, $minconf = 0, $comment = NULL ){ if (!is_account_exist($fromaccount) || !is_account_exist($toaccount)){ return false; } $fromaccount_money_balance = $this->getbalance($fromaccount, 0); //for don't make account balance negative! if ($amount > $fromaccount_money_balance){ return false; } $this->move($fromaccount, $toaccount, $amount, $minconf, $comment); } //check bitcoin connection public function _check_last_connect(){ //time now $current_check_connect_time = microtime(true); //if update connection status period is end if ( ($current_check_connect_time - $this->last_check_connect_time) > $this->check_connect_time_interval ){ // $timeout = $current_check_connect_time - $this->last_check_connect_time; // echo ' current_check_connect_time - last_check_connect_time = '.$timeout; // echo ' '; // echo ' > interval = '.$this->check_connect_time_interval.', return last_check_connect_status ' ; $this->last_check_connect_time = $current_check_connect_time; $this->last_check_connect_status = ( $this->can_connect() )? true : false; return $this->last_check_connect_status; } //if period is not finished, return last checked status else{ // echo '<br> current_check_connect_time = '.$current_check_connect_time ; // echo ' last_check_connect_time = '. $this->last_check_connect_time; // $timeout = $current_check_connect_time - $this->last_check_connect_time; // echo ' current_check_connect_time - last_check_connect_time = '.$timeout; // echo ' '; // echo ' < interval = '.$this->check_connect_time_interval.', return last_check_connect_status ' ; return $this->last_check_connect_status; } } // public function is_timeout_expired(){ // //by default check_connect_time_interval = $bictoin_row_from_db['check_connect_time_interval'] // //if ($check_connect_time_interval == null) { // //get check_connect_time_interval and last_check_connect_time // $query = 'SELECT check_connect_time_interval, last_check_connect_time FROM bitcoin WHERE id=1'; // $db = DBconfig::get_instance(); // $res = $db->query($query); // if ( !$res ) // return false; // $bictoin_row_from_db = $db->mysqli_fetch_array_by_result($res); // $this->check_connect_time_interval = $bictoin_row_from_db['check_connect_time_interval']; // $this->last_check_connect_time = $bictoin_row_from_db['last_check_connect_time']; // //$check_connect_time_interval = $this->last_check_connect_time; // //} // //time now // $current_check_connect_time = microtime(true); // //timeout expired // if ( ($current_check_connect_time - $this->last_check_connect_time) > $this->check_connect_time_interval/*$check_connect_time_interval*/ ){ // return $current_check_connect_time; // } // else{ // return false; // } // } public function check_last_connect(){ //get current time $current_check_connect_time = microtime(true); //it make update from DB per every check request $db = DBconfig::get_instance(); $query = 'SELECT `last_check_connect_status` , `check_connect_time_interval` , `last_check_connect_time` FROM bitcoin WHERE id =1'; $res = $db->query($query); if ( !$res ) return 'select error: -1'; $bictoin_row_from_db = $db->mysqli_fetch_array_by_result($res); $this->check_connect_time_interval = $bictoin_row_from_db['check_connect_time_interval']; $this->last_check_connect_time = $bictoin_row_from_db['last_check_connect_time']; $this->last_check_connect_status = $bictoin_row_from_db['last_check_connect_status']; // if last check timeout is expired, save current time in $this->last_check_connect_time if ( ($current_check_connect_time - $this->last_check_connect_time) > $this->check_connect_time_interval ){ $this->last_check_connect_time = $current_check_connect_time; //get current bictoind status $this->last_check_connect_status = ( $this->can_connect() )? true : false; //save it in DB //$query = 'INSERT INTO bitcoin(last_check_connect_status, last_check_connect_time) VALUES('.$this->last_check_connect_status.', '.$this->last_check_connect_time.')'; $query = 'UPDATE bitcoin SET last_check_connect_status = '.$this->last_check_connect_status.', last_check_connect_time = '.$this->last_check_connect_time.' WHERE id=1'; $res = $db->query($query); if ( !$res ) return 'update error: -1'; //and return NEW value of last check //return 'last check timeout is expired '.$this->last_check_connect_status; return $this->last_check_connect_status; } // if NOT expired, get values from DB else{ //and return value of last check from DB //return 'NOT expired '.$this->last_check_connect_status; return $this->last_check_connect_status; } } //todo: public function is_account_exist($account){ return true; } //todo: //can return WRONG address because of bitcoin public function get_sender_bitcoin_address($account){ } public function __destruct() { } } ?> <file_sep>/admin.php <?php require_once 'Appconfig.php'; //require_once 'Header.php.php'; ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Slot admin page</title> <link rel="stylesheet" href="css/jquery-ui.css" /> <script src="js/jquery.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <script src="js/jquery-ui.js"></script> </head> <body> <?php //admin auth function auth(){ if (empty($_SESSION['admin']) || $_SESSION['admin'] != 'true'){ if (empty($_POST['login']) || empty($_POST['password'])){ //echo 'Bad parameters was received. No auth'; exit('Not authorized'); } $login = $_POST['login']; $password_md5 = md5($_POST['password']); $db = DBconfig::get_instance(); $admin = $db->mysqli_fetch_array('SELECT * FROM admin'); //auth == false if (($admin['login'] != $login) || ($admin['password'] != $<PASSWORD>)){ exit('Wrong login or password'); return false; } //auth == true $_SESSION['admin'] = true; //refresh this page echo '<META HTTP-EQUIV="Refresh" Content="0; ">'; } else{ update_login_pass_in_db(); } } //for changing login and pass in db function update_login_pass_in_db(){ if (empty($_POST['login']) || empty($_POST['password']) || empty($_POST['Save'])){ return false; } if (empty($_SESSION['admin']) || $_SESSION['admin'] != 'true' || empty($_POST['Save'])){ echo 'Can\'t change login and password.'; return false; } $login = mysql_real_escape_string($_POST['login']); $password_md5 = md5(mysql_real_escape_string($_POST['password'])); $db = DBconfig::get_instance(); $res = $db->query("UPDATE admin SET login = '$login', password = <PASSWORD>' WHERE ID = 1"); if ($res){ echo 'Login and password updated succesfully<br />'; echo 'Login: '.$login.'<br>'; echo 'md5(password): '.$password_md5; } } ?> <div id="auth_form" style=" width: 200px;"> <form method="POST" action="admin.php" onSubmit="window.location.reload()"> Login:<br /> <input type="text" id="login" name="login" /> <br /> Password:<br /> <input type="password" id="password" name="password" /> <br /> <?php if (empty($_SESSION['admin']) || $_SESSION['admin'] != 'true'){ ?> <input type="submit" id="enter" name="enter" value="Sign in" /> <?php } else{ ?> <input type="submit" id="Save" name="Save" value="Save" /> <br /><br /> <?php } ?> </form> </div> <?php auth(); ?> <div id="slot_power_state">Playing status: on</div> Slot on: <input id="power" checked="checked" type="checkbox" name="power" /> <div id="slot_paying_out_state">Paying out status: on</div> Paying out on: <input id="paying_out" checked="checked" type="checkbox" name="paying_out" /> <!--<div id="slot_max_bet">Maximum bet: </div>--> <br /> Maximum bet: <input id="slot_max_bet" type="text" name="slot_max_bet" /> <br /> <button id="save_slot_state">Save</button> <br /> <br /> <div id="calendar"> <label for="from">From (e.g.: 2012-11-31)</label> <input type="text" id="from" name="from" /> <label for="to">to</label> <input type="text" id="to" name="to" /> <!--<br />--> <button id="show_transactions">Show</button> </div> <div id="transactions"> <!-- tables are loaded via ajax and placed in this div --> </div> <div id="group_by_user"> </div> <script type="text/javascript"> function slotOptions(){ this.options = { 'playing': 'on', 'paying_out': 'on', 'maxbet' : 0.01 }; } $(document).ready(function(){ show(); slotOptions = new slotOptions(); $(function() { $( "#from" ).datepicker({ dateFormat: 'yy-mm-dd', defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onClose: function( selectedDate ) { $( "#to" ).datepicker( "option", "minDate", selectedDate ); } }); $( "#to" ).datepicker({ dateFormat: 'yy-mm-dd', defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onClose: function( selectedDate ) { $( "#from" ).datepicker( "option", "maxDate", selectedDate ); } }); }); getOptionsFromServer(); //fillOptionsOnPage(slotOptions.options); $('button#save_slot_state').on('click',function(){ var options = {"is_power_on" : 'on', "is_payingout" : 'on', "maxbet" : 0.01} options.is_power_on = $('input#power').prop('checked') ? 'on' : 'off' ; options.is_paying_out = $('input#paying_out').prop('checked') ? 'on' : 'off' ; options.maxbet = $('input#slot_max_bet').val(); // var power_on_off = 'on'; // var paying_out = 'on'; // var maxbet = 0.01;//default maxbet /* if (options.is_power_on){ if (window.console) console.log('slot on'); power_on_off = 'on'; } else{ if (window.console) console.log('slot off'); power_on_off = 'off'; } if (options.is_paying_out){ if (window.console) console.log('paying out on'); paying_out = 'on'; } else{ if (window.console) console.log('paying out off'); paying_out = 'off'; } */ //save the values by click $.post("AjaxRequestsProcessing.php", { slot: "options", power: options.is_power_on, paying_out: options.is_paying_out, maxbet: options.maxbet}) .done(function(options) { if (window.console) console.log(options); options = $.parseJSON(options); getOptionsFromServer(); //fillOptionsOnPage(slotOptions.options); }) .fail(function(){ if (window.console) console.log('Client error. Error in ajax admin-->power request, bad response'); }); }); $('button#show_transactions').on('click',function(){ show(); }); //sync with server function getOptionsFromServer(){ $.post("AjaxRequestsProcessing.php", { slot: "options", power: 'check_options'}) .done(function(options) { options = $.parseJSON(options); slotOptions.options.playing = options.playing; slotOptions.options.paying_out = options.paying_out; slotOptions.options.maxbet = options.maxbet; fillOptionsOnPage(slotOptions.options); }) .fail(function(){ if (window.console) console.log('Client error. Error in ajax admin-->checkSlotPowerStatus request, bad response'); }); }; function fillOptionsOnPage(options){ if (window.console) console.log(options); $('div#slot_power_state').text('Playing status: '+options.playing); $('div#slot_paying_out_state').text('Paying out status: '+options.paying_out); $('input#slot_max_bet').val(options.maxbet); if (options.playing == 'on'){ $('input#power').attr('checked', 'checked'); } else{ $('input#power').removeAttr('checked', 'checked'); } if (options.paying_out == 'on'){ $('input#paying_out').attr('checked', 'checked'); } else{ $('input#paying_out').removeAttr('checked', 'checked'); } } function show(){ var fromDate = $('div#calendar > input#from').val(); var toDate = $('div#calendar > input#to').val(); if (!fromDate || !toDate){ if (window.console) console.log('from or to date not specified'); fromDate = '2012-11-01'; toDate = '2052-11-01'; //return false; } $.post("AjaxRequestsProcessing.php", { slot: "transactions", 'fromDate': fromDate, 'toDate': toDate, 'page':'admin'}) .done(function(transactionsTable) { $('div#transactions').html(transactionsTable); }) .fail(function(){ if (window.console) console.log('Client error. Error in ajax admin-->show request, bad response'); }); } }); </script> </body> </html> <file_sep>/Reel.php <?php /** * Description of Reel * * @author vadim24816 */ require_once 'Appconfig.php'; class Reel { public $reel_line = array(),$name; public function __construct($name) { $this->name = $name; } //return new symbol choosed randomly //args - (string $client_seed, string $server_seed) public function get_new_randomly_choosed_symbol($hashed_client_seed, $server_seed){ //real client_seed is crc32(sha1(client_seed)) $client_seed = crc32($hashed_client_seed); //real server_seed is crc32(sha1(mt_rand())) $server_seed = crc32($server_seed); $result_seed = ($client_seed + $server_seed); $randomizer = Randomizer::get_instance(); $rand_num = abs($randomizer->mersenne_twister_int32($result_seed) % 64); $sym = $this->reel_line[$rand_num]; $debug_data = array( 'rand_num' => $rand_num, 'result_seed' => $result_seed, 'client_seed' => $client_seed, 'server_seed' => $server_seed, ); //dump_it($debug_data); return $sym; } // public function filling_by_given_symbol_specifin_number_of_cells($symbol, $number){ for($i = 0; $i < $number; $i++){ array_push($this->reel_line, $symbol); } } } ?> <file_sep>/js/symbols-table.js function weightTable(){ var table = this; //get array (reel1/2/3), symName, N - amount of symbols need to add to this array function fillxN(reel, symName, N){ for(var i=0; i<N; i++){ reel.push(symName); } } this.reels = new Array( //reel1 new Array(), //reel2 new Array(), //reel3 new Array() ); function fillTable(){ var reel1 = table.reels[0]; var reel2 = table.reels[1]; var reel3 = table.reels[2]; fillxN(reel1, 'pyramid', 4); fillxN(reel1, 'bitcoin', 5); fillxN(reel1, 'anonymous', 6); fillxN(reel1, 'onion', 6); fillxN(reel1, 'anarchy', 7); fillxN(reel1, 'peace', 8); fillxN(reel1, 'blank', 28); fillxN(reel2, 'pyramid', 3); fillxN(reel2, 'bitcoin', 4); fillxN(reel2, 'anonymous', 4); fillxN(reel2, 'onion', 5); fillxN(reel2, 'anarchy', 5); fillxN(reel2, 'peace', 6); fillxN(reel2, 'blank', 37); fillxN(reel3, 'pyramid', 1); fillxN(reel3, 'bitcoin', 2); fillxN(reel3, 'anonymous', 3); fillxN(reel3, 'onion', 4); fillxN(reel3, 'anarchy', 6); fillxN(reel3, 'peace', 6); fillxN(reel3, 'blank', 42); } this.getSymNameOnReelByNumber = function(reelN, symN){ return this.reels[reelN][symN]; } fillTable(); }
174693d81f1deeb345b41a82b6773f5fd99c290b
[ "JavaScript", "Markdown", "PHP", "INI" ]
29
PHP
psyvisions/slot-machine-1
d3feca86922a5b8a185489e96a67047f6c9b1ea9
e39c2778b9049f13e94566e39c0838a94c12dea4
refs/heads/master
<file_sep># finance.py # finance flask application import sys from flask import Flask, render_template, request, url_for from financeLib.intradaytools import * from financeLib.charts import * # initialize flask app application = Flask(__name__) # create form @application.route("/finance/") def form(): return render_template('form.html') # get information from form, run volatility calculations @application.route("/finance/volatility/", methods=['POST']) def volatility(): # pull ticker from from ticker = request.form['ticker'] # find market based on ticker (uses google finance) market = findmarket(ticker) ticker = ticker.upper() market = market.upper() # get intraday information for the last 15 days, save to temp file temp(ticker, market) # open tempfile, save lines, delete temp file. with open ('/intradata/temp') as f: templines = f.readlines() os.remove('/intradata/temp') # check for exsisting data files filecheck = os.path.isfile('/intradata/' + ticker) # create new ticker data file if one does not exist or add new lines lines to existing files if filecheck == False: with open('/intradata/' + ticker, 'w') as f: newfile = f.writelines(templines[7:-1]) else: # parse exsiting data files, and new temp data files tempfile, tempdays = parsefile(templines) with open('/intradata/' + ticker) as f: existinglines = f.readlines() existingfile, existingdays = parsefile(existinglines) # merge files, get data older than 15 days from existing file & get data within current 15 days from temp file mergedfile = '' for x in range(len(existingdays)): if existingdays[x] in tempdays: # recent data within the last 15 days - should append from new data (tempfile) pass else: # older data no longer in the last 15 days - append from existing data (existingfile) mergedfile += str(existingfile[str(existingdays[x]) + 'data']) # append all new data (will override old similar data, and keep current day up todate) for x in range(len(tempdays)): mergedfile += str(tempfile[str(tempdays[x]) + 'data']) # overide exsiting file with new data with open('/intradata/' + ticker, 'w') as f: f.write(mergedfile) # open ticker data file and use data with open('/intradata/' + ticker) as f: data = f.readlines() # create dictionary for data storage && store data / run calculations for each min (390 mins per day) intraday = {} average = {} day = 0 for line in data: # every line = 1 min of data split = line.split(',') if str(split[0]).startswith('a'): # replace unix time stamp (which starts with 'a') for new day with 0 split[0] = str(0) # split[0] = int ranging 0 - 390. represents time: 0 = 6:30 (market open) 390 = 13:00 (market close) intraday[str(day) + split[0] + 'high'] = float(split[2]) # split[2] = current min high $ value intraday[str(day) + split[0] + 'low'] = float(split[3]) # split[3] = current min low $ value intraday[str(day) + split[0] + 'open'] = float(split[4]) # split[4] = current min open $ value intraday[str(day) + split[0] + 'close'] = float(split[1]) # split[1] = current min close $ value intraday[str(day) + split[0] + 'vol'] = int(split[5]) # split[5] = current min volume # of shares # volatility formulas intraday[str(day) + split[0] + 'volatilityByMin'] = ((float(split[1]) / float(split[4])) - int(1)) * int(100) intraday[str(day) + split[0] + 'volatilityVsMktOpen'] = ((float(split[1]) / float(intraday[(str(day)) + '0' + 'open'])) - int(1)) * int(100) # create storage locations for averages average[split[0] + 'volatilityByMin'] = 0 average[split[0] + 'volatilityVsMktOpen'] = 0 average[split[0] + 'close'] = 0 # day counter. If at any time current min == 390 mark one complete day if int(split[0]) == int(390): day += 1 # summation for all individual days data for x in range(day): for x2 in range(390): average[str(x2) + 'volatilityByMin'] += float(intraday[str(x) + str(x2) + 'volatilityByMin']) average[str(x2) + 'volatilityVsMktOpen'] += float(intraday[str(x) + str(x2) + 'volatilityVsMktOpen']) average[str(x2) + 'close'] += float(intraday[str(x) + str(x2) + 'close']) # calculate averages based on above summation / # of days of data stored in ticker file for x in range(390): average[str(x) + 'volatilityByMin'] /= int(day) average[str(x) + 'volatilityVsMktOpen'] /= int(day) average[str(x) + 'close'] /= int(day) # get min value / max value / arrays to be used for charting lowvalVBM, lowtimeVBM, lowamountVBM, highvalVBM, hightimeVBM, highamountVBM, allvalsVBM = minmax(average, 'volatilityByMin') lowvalVMO, lowtimeVMO, lowamountVMO, highvalVMO, hightimeVMO, highamountVMO, allvalsVMO = minmax(average, 'volatilityVsMktOpen') graphVBM = createLineGraph('Volatility by Minute', 'volByMin', allvalsVBM) displayVBM = displayLineGraph('volByMin') graphVMO = createLineGraph('Volatility by Minuite Vs. Market Open', 'volVsMktOpen', allvalsVMO) displayVMO = displayLineGraph('volVsMktOpen') return render_template('volatility.html', ticker=ticker, market=market, highamountVBM=highamountVBM, highvalVBM=highvalVBM, hightimeVBM=hightimeVBM, lowamountVBM=lowamountVBM, lowvalVBM=lowvalVBM, lowtimeVBM=lowtimeVBM, highamountVMO=highamountVMO, highvalVMO=highvalVMO, hightimeVMO=hightimeVMO, lowamountVMO=lowamountVMO, lowtimeVMO=lowtimeVMO, lowvalVMO=lowvalVMO, graphVBM=graphVBM, displayVBM=displayVBM, graphVMO=graphVMO, displayVMO=displayVMO) if __name__ == "__main__": application.run(host="0.0.0.0") <file_sep>#!/usr/bin/env python3 # charts.py # library to create charts from flask import Markup def createLineGraph(lname, name, values): string = 'var ' + name + ' = new CanvasJS.Chart("' + name + 'Container",{' string += ' title:{' string += ' text: "' + lname + '"' string += ' },' string += ' axisX:{' string += ' gridThickness: 2, ' string += ' interval: 5,' string += ' labelAngle: -45' string += ' },' string += ' axisY:{' string += ' valueFormatString: "#,##0.####",' string += ' suffix: "%",' string += ' },' string += ' data: [{' string += ' type: "line",' string += ' dataPoints: [' for x in range(len(values)): string += ' { x: new Date(2016,0,1,6,30+' + str(x) + ',0,0), y: ' + str(values[x]) + ' },' string += ' ]' string += ' }]' string += '});' string += '' + name + '.render();' string += '' + name + ' = {};' returnstring = Markup(string) return returnstring def displayLineGraph(name): string = '<div id="' + name + 'Container" style="height: 300px; widthh: 100%;"></div>' returnstring = Markup(string) return returnstring <file_sep># wsgi.py # uWSGI application entry point from finance import application if __name__ == "__main__": application.run() <file_sep># finance.ini # uWSGI config file [uwsgi] module = wsgi master = true processes = 5 socket = finance.sock chmod-socket = 660 vacuum = true die-on-term = true debug = true <file_sep>#!/usr/bin/env python3 # intradaytools.py # library to be used across all analysis scripts import datetime import os import requests import sys from bs4 import BeautifulSoup, NavigableString # scrape website, return html def scrape(website): set_url = website cal_resp = requests.get(set_url) cal_data = cal_resp.text data = BeautifulSoup(cal_data, 'lxml') return data # create a temporary file, will be used to compare to possible exsisting data def temp(ticker, market): data = scrape('https://www.google.com/finance/getprices?q=' + str(ticker.upper()) + '&x=' + str(market.upper()) + '&i=60&p=30d&f=d,c,h,l,o,v') data = str(data) with open('/intradata/temp', 'w') as f: f.write(data) # find the market that the particular ticker is traded on def findmarket(ticker): data = scrape('https://www.google.com/finance?q=' + ticker) title = str(data.title) if 'NASDAQ' in title: return 'NASD' else: return 'NYSE' # input string of comma delimited intraday data, return dict which is ready to be used for calulations def parsefile(lines): tempfile = {} days = [] mins = 0 for x in range(len(lines)): split = lines[x].split(',') if str(split[0]).startswith('a'): currentday = split[0] days.append(currentday) tempfile[currentday + 'days'] = split[0] tempfile[currentday + 'mins'] = mins tempfile[currentday + 'data'] = '' tempfile[currentday + 'data'] += str(lines[x]) else: if len(days) != 0 and x + 1 != len(lines): tempfile[str(currentday) + 'mins'] += 1 tempfile[str(currentday) + 'data'] += str(lines[x]) return tempfile, days # input dict of averaged data, return the highest and lowest points as well as an array to be used for graphs def minmax(dictionary, dataset): lowval = dictionary[str(0) + dataset] lowmin = 0 lowamount = 0 highval = dictionary[str(0) + dataset] highmin = 0 highamount = 0 allvals = [] for x in range(390): if dictionary[str(x) + dataset] < lowval: lowval = dictionary[str(x) + dataset] lowmin = x lowamount = '{:.2f}'.format(dictionary[str(x) + 'close']) if dictionary[str(x) + dataset] > highval: highval = dictionary[str(x) + dataset] highmin = x highamount = '{:.2f}'.format(dictionary[str(x) + 'close']) allvals.append(dictionary[str(x) + dataset]) # calculate times (based on market open (6:30 GMT+8) today = datetime.datetime.today() marketopen = datetime.datetime(today.year, today.month, today.day, 6, 30) lowdelta = datetime.timedelta(minutes = int(lowmin)) highdelta = datetime.timedelta(minutes = int(highmin)) marketlow = marketopen + lowdelta markethigh = marketopen + highdelta marketlow = str(marketlow.strftime("%I:%M%p")) markethigh = str(markethigh.strftime("%I:%M%p")) return lowval, marketlow, lowamount, highval, markethigh, highamount, allvals
9e0d51a1c23684a18dea4f3a06f2c48bd644e964
[ "Python", "INI" ]
5
Python
chriskoh/intraday-flask
e440afa390263e0aaeb40510a72c3abde138512b
e2f5ce076e2e68b4df98fddc022f244ac6d4ab0d
refs/heads/main
<repo_name>KangJialiang/wt_project<file_sep>/weather/weather.py import json from datetime import datetime, timezone import requests params = {'access_key': '5f249e237bea19f2d36c3adeb55ebd03', 'output': 'json', 'language': "zh"} citycode_path = "weather/citycode-2019-08-23.json" with open(citycode_path) as f: citycodes = json.load(f) def get_weather() -> str: try: city_r = requests.get('http://api.ipstack.com/check', params=params) city = city_r.json()["city"] for it in citycodes: if city in it["city_name"] or it["city_name"] in city: city_code = it["city_code"] weather_r = requests.get( f"http://t.weather.itboy.net/api/weather/city/{city_code}") weather = weather_r.json()["data"]["forecast"][0]["type"] return weather else: raise ValueError except: return str() def is_night() -> str: try: city_r = requests.get('http://api.ipstack.com/check', params=params) latitude = city_r.json()["latitude"] longitude = city_r.json()["longitude"] sunset_r = requests.get( 'https://api.sunrise-sunset.org/json', params={"lat": latitude, "lng": longitude, "formatted": 0}) sunrise_time = sunset_r.json()['results']['sunrise'] sunset_time = sunset_r.json()['results']['sunset'] sunrise_time = datetime.strptime(sunrise_time, "%Y-%m-%dT%H:%M:%S%z") sunset_time = datetime.strptime(sunset_time, "%Y-%m-%dT%H:%M:%S%z") if sunrise_time < datetime.now(timezone.utc) < sunset_time: return False else: return True except: return False if __name__ == "__main__": print(get_weather()) print(is_night()) <file_sep>/camera_parameters.py import cv2 import numpy as np import torch if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") fx = 786.356621482640 fy = 785.893340408213 cx = 628.382404554185 cy = 340.808726800420 k1 = -0.364895938951223 k2 = 0.205910153511996 k3 = -0.0835120929150047 p1 = -0.000288373571966727 p2 = 0.000262603352527099 camera_height = 0.6 # rotation_matrix = torch.eye(3) rotation_vector = np.array([[-1.5035], [0.03125], [-0.06]]) rotation_matrix, _ = cv2.Rodrigues(rotation_vector) rotation_matrix = torch.FloatTensor(rotation_matrix) # translation_vector = torch.FloatTensor([[-702.05089465, # 607.54946787, # 3048.32203209]]).t() translation_vector = torch.FloatTensor([[0, 0, 0]]).t() intrinsic_matrix = torch.FloatTensor( [[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) extrinsics_matrix = torch.cat( ( torch.cat((rotation_matrix, translation_vector), dim=1), torch.FloatTensor([[0, 0, 0, 1]]) ), 0) dist_coeffs = np.array((k1, k2, p1, p2, k3)) intrinsic_matrix = intrinsic_matrix.to(device) extrinsics_matrix = extrinsics_matrix.to(device) inv_extrinsics_matrix = extrinsics_matrix.inverse() # u = torch.FloatTensor([1, 2, 3, 4, 5]) # v = torch.FloatTensor([6, 7, 8, 9, 10]) # depth_vector = torch.FloatTensor([11, 12, 13, 14, 15]) # ones = torch.ones(depth_vector.size()) # P_cam = torch.stack((u, v, depth_vector, ones), dim=0).to(device) # P_w = torch.mm(inv_extrinsics_matrix, P_cam) # np.savetxt('P_cam.txt', P_cam.cpu().numpy()) # np.savetxt('P_w.txt', P_w.cpu().numpy()) <file_sep>/safe_or_not/safe_or_not.py def safe_or_not(velocity, distance, weather) -> bool: """Call this only when the ultrasonic sensor detects something""" safe_flag = True possible_weather_conditions = ["小雨", "小到中雨", "中雨", "中到大雨", "大雨", "大到暴雨", "暴雨", "暴雨到大暴雨", "大暴雨", "大暴雨到特大暴雨", "特大暴雨", "冻雨", "阵雨", "雷阵雨", "雨夹雪", "雷阵雨伴有冰雹", "小雪", "小到中雪", "中雪", "中到大雪", "大雪", "大到暴雪", "暴雪", "阵雪", "晴", "多云", "阴", "强沙尘暴", "扬沙", "沙尘暴", "浮尘", "雾", "霾"] reacting_time = 0.2 # static basement_spoting_time = 0.5 # the time before the rider spot the opening door basement_acceleration = 8 # m*s^(-2) if weather not in possible_weather_conditions: weather = "大雨" if weather in ["晴", "多云", "阴", "强沙尘暴", "扬沙", "沙尘暴", "浮尘", "雾", "霾"]: spoting_time = basement_spoting_time acceleration = basement_acceleration elif weather in ["小雨", "小到中雨", "中雨", "阵雨"]: spoting_time = 0.7 acceleration = basement_acceleration/1.7 elif weather in ["中到大雨", "大雨", "雷阵雨"]: spoting_time = 0.9 acceleration = basement_acceleration/1.8 elif weather in ["大到暴雨", "暴雨", "暴雨到大暴雨", "大暴雨", "大暴雨到特大暴雨", "特大暴雨"]: spoting_time = 1 acceleration = basement_acceleration/2 elif weather in ["小雪", "小到中雪", "冻雨", "雨夹雪", "阵雪"]: spoting_time = 1 acceleration = basement_acceleration/3 elif weather in ["雷阵雨伴有冰雹", "中雪", "中到大雪", "大雪", "大到暴雪", "暴雪"]: spoting_time = 1 acceleration = basement_acceleration/4 if (reacting_time+spoting_time)*velocity+velocity**2/(2*acceleration) >= distance: safe_flag = False return safe_flag <file_sep>/safe_or_not/__init__.py from safe_or_not.safe_or_not import safe_or_not <file_sep>/README.md ## References - [ZQPei/deep_sort_pytorch](https://github.com/ZQPei/deep_sort_pytorch) - [AlexeyAB/darknet](https://github.com/AlexeyAB/darknet) - [nianticlabs/monodepth2](https://github.com/nianticlabs/monodepth2)<file_sep>/kalman_filter/KalmanFilter.py import cv2 import numpy as np import json import matplotlib.pyplot as plt class KalmanFilter(): def __init__(self, dynamParams, measureParams, measurementMatrix, transitionMatrix, processNoiseCov, measurementNoiseCov): self.dynamParams = dynamParams self.measureParams = measureParams self.measurementMatrix = measurementMatrix self.transitionMatrix = transitionMatrix self.processNoiseCov = processNoiseCov self.measurementNoiseCov = measurementNoiseCov self.objDict = dict() def update(self, measurement_list, id_list): out_dict = dict() for i in range(len(id_list)): index = id_list[i] measurement = measurement_list[i] measurement = np.array(measurement, dtype=np.float32) if index not in self.objDict: currentKfObj = cv2.KalmanFilter( self.dynamParams, self.measureParams) currentKfObj.measurementMatrix = self.measurementMatrix currentKfObj.transitionMatrix = self.transitionMatrix currentKfObj.processNoiseCov = self.processNoiseCov currentKfObj.measurementNoiseCov = self.measurementNoiseCov init_state = measurement.copy() init_state.resize(self.dynamParams, 1, refcheck=False) currentKfObj.statePre = init_state self.objDict[index] = currentKfObj else: currentKfObj = self.objDict[index] currentKfObj.correct(measurement) predict = currentKfObj.predict() out_dict[index] = list(float(x) for x in predict[:self.measureParams]) return out_dict if __name__ == "__main__": with open("temp.json") as fp: temp_dict = json.load(fp) index = "20" time_stamps = range(235, 247) time_stamps = map(str, time_stamps) temp_list = [] for time in time_stamps: temp_list.append(temp_dict[index][time]) measurement_matrix = np.array( [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0]], np.float32) transition_matrix = np.array( [[1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]], np.float32) process_noise_cov = np.eye(6, dtype=np.float32) * 1e-3 measurement_noise_cov = np.eye(3, dtype=np.float32) * 1e-1 kalman_filter = KalmanFilter(6, 3, measurement_matrix, transition_matrix, process_noise_cov, measurement_noise_cov) y_org = [] y_filt = [] for coord in temp_list: filtered = kalman_filter.update([coord], ["test"]) print(coord, filtered["test"]) y_org.append(coord[1]) y_filt.append(filtered["test"][1]) plt.plot(y_org) plt.plot(y_filt) plt.savefig('temp.png') <file_sep>/main.py import glob import json import os import queue import random import threading import time from ctypes import * import cv2 import matplotlib as mpl import matplotlib.cm as cm import numpy as np import PIL.Image as pil import torch from torchvision import transforms import camera_parameters as params import darknet.darknet as darknet import monodepth2.networks as networks from camera_parameters import * from deep_sort import build_tracker from deep_sort.parser import get_config from kalman_filter import KalmanFilter from monodepth2.layers import disp_to_depth if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") print("CUDA NOT AVALIABLE") def gstreamer_pipeline( capture_width=1280, capture_height=720, display_width=1280, display_height=720, framerate=10, flip_method=0, ): return ( "nvarguscamerasrc ! " "video/x-raw(memory:NVMM), " "width=(int)%d, height=(int)%d, " "format=(string)NV12, framerate=(fraction)%d/1 ! " "nvvidconv flip-method=%d ! " "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! " "videoconvert ! " "video/x-raw, format=(string)BGR ! appsink" % ( capture_width, capture_height, framerate, flip_method, display_width, display_height, ) ) class CameraCapture(cv2.VideoCapture): """Bufferless & Distorted VideoCapture""" def __init__(self, original_options: tuple, intrinsic_matrix, dist_coeffs): super().__init__(*original_options) # self._queue = queue.SimpleQueue() self._queue = queue.Queue() read_camera_thread = threading.Thread(target=self._reader) read_camera_thread.daemon = True read_camera_thread.start() self._intrinsic_matrix = intrinsic_matrix.cpu().numpy() self._dist_coeffs = np.array(dist_coeffs) frame = self._queue.get() self._new_intrinsic_matrix, self._new_xywh = cv2.getOptimalNewCameraMatrix( self._intrinsic_matrix, self._dist_coeffs, frame.shape[:2], 0) self.intrinsic_matrix = torch.tensor( self._new_intrinsic_matrix).to(device) # read frames as soon as they are available, keeping only most recent one def _reader(self): while True: self._success, frame = super().read() if not self._success: break while True: try: self._queue.get_nowait() # discard previous (unprocessed) frame except queue.Empty: break self._queue.put(frame) def _distort_img(self, img): distorted_img = cv2.undistort(img, self._intrinsic_matrix, self._dist_coeffs, None, self._new_intrinsic_matrix) x, y, w, h = self._new_xywh distorted_img = distorted_img[x:x+w, y:y+h] return distorted_img def read(self): return self._success, self._distort_img(self._queue.get()) class FileCapture(): def __init__(self, file_path: str, ext="jpg") -> None: images_list = glob.glob(f'{file_path}/*.{ext}') images_list.sort(key=lambda x: int(x[len(file_path)+1:-len(ext)-1])) self.images = iter(images_list) self.intrinsic_matrix = torch.FloatTensor( [[785.26446533, 0., 627.50964355], [0., 785.27935791, 340.54248047], [0., 0., 1.]]).to(device) def release(self): pass def read(self): success_flag = False try: fname = next(self.images) frame = cv2.imread(fname) success_flag = True except: frame = None pass return success_flag, frame class Trajectory(): def __init__(self, max_age=50, max_error=0.1): self.max_age = max_age self.max_error = max_error self.objects = dict() self.index = 0 def __delete_out_dated(self): to_be_deleted = [] for obj_id, coords_dict in self.objects.items(): last_index = max([key for key in coords_dict.keys()]) if self.index-last_index > self.max_age: to_be_deleted.append(obj_id) for index in to_be_deleted: self.objects.pop(index) def update(self, coords, ids): self.__delete_out_dated() for i, id in enumerate(ids): if id not in self.objects.keys(): self.objects[id] = {self.index: coords[i]} else: if self.index-1 in self.objects[id]: self.objects[id][self.index] = coords[i] else: last_index = max([key for key in self.objects[id].keys()]) for index in range(last_index+1, self.index+1): last_coord = self.objects[id][last_index] current_coord = coords[i] self.objects[id][index] = [last_coord[coord]+(current_coord[coord]-last_coord[coord])*( index-last_index)/(self.index-last_index) for coord in range(len(coords[i]))] self.index += 1 def get_nearest(self, distance) -> dict: distance_dict = dict() min_delta = float("inf") for obj_id, coords_dict in self.objects.items(): last_index = max([key for key in coords_dict.keys()]) current_coord = coords_dict[last_index] current_distance = (sum(x**2 for x in current_coord))**.5 distance_dict[obj_id] = current_distance for obj_id, obj_distance in distance_dict.items(): if abs(obj_distance-distance) < min_delta: min_delta = abs(obj_distance-distance) best_match = obj_id if min_delta < self.max_error: return self.objects[best_match] return None def init_monodepth_model(model_name): """Function to predict for a single image or folder of images """ model_path = os.path.join("./monodepth2/models", model_name) print("-> Loading model from ", model_path) encoder_path = os.path.join(model_path, "encoder.pth") depth_decoder_path = os.path.join(model_path, "depth.pth") # LOADING PRETRAINED MODEL print(" Loading pretrained encoder") encoder = networks.ResnetEncoder(18, False) loaded_dict_enc = torch.load(encoder_path, map_location=device) # extract the height and width of image that this model was trained with feed_height = loaded_dict_enc['height'] feed_width = loaded_dict_enc['width'] filtered_dict_enc = { k: v for k, v in loaded_dict_enc.items() if k in encoder.state_dict()} encoder.load_state_dict(filtered_dict_enc) encoder.to(device) encoder.eval() print(" Loading pretrained decoder") depth_decoder = networks.DepthDecoder( num_ch_enc=encoder.num_ch_enc, scales=range(4)) loaded_dict = torch.load(depth_decoder_path, map_location=device) depth_decoder.load_state_dict(loaded_dict) depth_decoder.to(device) depth_decoder.eval() return feed_height, feed_width, encoder, depth_decoder def get_relative_depth(frame, feed_height, feed_width, encoder, depth_decoder): input_image = pil.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) # PREDICTING ON EACH IMAGE IN TURN with torch.no_grad(): # Load image and preprocess original_width, original_height = input_image.size input_image = input_image.resize( (feed_width, feed_height), pil.LANCZOS) input_image = transforms.ToTensor()(input_image).unsqueeze(0) # PREDICTION input_image = input_image.to(device) features = encoder(input_image) outputs = depth_decoder(features) disp = outputs[("disp", 0)] disp_resized = torch.nn.functional.interpolate( disp, (original_height, original_width), mode="bilinear", align_corners=False) # 插值成源图像大小 _, depth = disp_to_depth(disp_resized, 0.1, 100) return depth def pixelcoord_to_worldcoord(depth_matrix, intrinsic_matrix, inv_extrinsics_matrix, pixel_indexs): cx = intrinsic_matrix[0, 2] cy = intrinsic_matrix[1, 2] fx = intrinsic_matrix[0, 0] fy = intrinsic_matrix[1, 1] v = pixel_indexs[0, :] u = pixel_indexs[1, :] depth_vector = depth_matrix.view(-1) v = (v-cy)*depth_vector/fy u = (u-cx)*depth_vector/fx ones = torch.ones(depth_vector.size()).to(device) P_cam = torch.stack((u, v, depth_vector, ones), dim=0) # [x: crosswise ,y: -lengthwise, z: vertical, 1] P_w = torch.mm(inv_extrinsics_matrix, P_cam) # np.savetxt('P_cam.txt', P_cam.cpu().numpy()[:, :10]) # np.savetxt('P_w.txt', P_w.cpu().numpy()[:, :10]) return P_w def get_mask(x_left, y_top, x_right, y_bottom, to_size, portion=1): """Edges all included""" if portion > 0 and portion < 1: mask = torch.bernoulli( torch.ones(y_bottom-y_top+1, x_right-x_left+1)*portion) else: mask = torch.ones(y_bottom-y_top+1, x_right-x_left+1) padding = ( x_left, # padding in left to_size[1]-x_right-1, # padding in right y_top, # padding in top to_size[0]-y_bottom-1 # padding in bottom ) mask = torch.nn.functional.pad( mask, padding, mode="constant", value=0).type(torch.bool).to(device) return mask def find_diff(last_frame, current_frame, threshold=10): diff = cv2.absdiff(last_frame, current_frame) diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) static_points = torch.from_numpy((diff < threshold)).to(device) return static_points def get_scale(relative_disp: torch.tensor, intrinsic_matrix: torch.tensor, inv_extrinsics_matrix: torch.tensor, camera_height: float, pixel_indexs, current_frame, last_frame, last_true_disp, portion=1): mask = get_mask(relative_disp.size()[1]*3//8, relative_disp.size()[0]*27//40, relative_disp.size()[1]*5//8, relative_disp.size()[0]*37//40, relative_disp.size(), portion=portion) road_points = relative_disp*mask P_w = pixelcoord_to_worldcoord(road_points, intrinsic_matrix, inv_extrinsics_matrix, pixel_indexs) rel_heights = torch.masked_select(P_w[2, :], mask.view(-1)) # 选取z坐标 std = torch.std(rel_heights) mean = torch.mean(rel_heights) threshold_mask = torch.lt(torch.abs(rel_heights-mean), std) rel_heights = torch.masked_select(rel_heights, threshold_mask.view(-1)) scale_camera_height_based = camera_height / \ (rel_heights.sum()/rel_heights.shape[0]) if last_frame is not None and last_true_disp is not None: static_points = find_diff(last_frame, current_frame) scale_static_points_based = torch.sum(last_true_disp*static_points.reshape_as(last_true_disp)) /\ torch.sum(relative_disp*static_points.reshape_as(relative_disp)) scale = .1*scale_camera_height_based+0.9*scale_static_points_based # print(torch.sum(static_points) / last_true_disp.numel()) else: scale = scale_camera_height_based return scale def init_darknet_network(config_file: str, data_file: str, weights_file: str,): network, class_names, class_colors = darknet.load_network( config_file, data_file, weights_file, batch_size=1) return network, class_names, class_colors def detection(darknet_network, class_names, class_colors, frame, confidence_thresh=0.25): original_height = frame.shape[0] original_width = frame.shape[1] network_width = darknet.network_width(darknet_network) network_height = darknet.network_height(darknet_network) frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_resized = cv2.resize(frame_rgb, (network_width, network_height), interpolation=cv2.INTER_LINEAR) img_for_detect = darknet.make_image(network_width, network_height, 3) darknet.copy_image_from_bytes(img_for_detect, frame_resized.tobytes()) detections = darknet.detect_image( darknet_network, class_names, img_for_detect, thresh=confidence_thresh) darknet.free_image(img_for_detect) detections_resized = [] for label, confidence, bbox in detections: x, y, w, h = bbox bbox = (x*original_width/network_width, y*original_height/network_height, w*original_width/network_width, h*original_height/network_height,) detections_resized.append((label, confidence, bbox)) return detections_resized def get_coordinates(P_w, outputs, frame): measurement_list = [] id_list = [] for output in outputs: x1, y1, x2, y2, id = output # mask = get_mask(x1+(x2-x1)//10, y1+(y2-y1)//10, # x2-(x2-x1)//10, y2-(y2-y1)//10, frame.shape) mask = get_mask(x1, y1, x2, y2, frame.shape) x_coords = torch.masked_select(P_w[0, :], mask.view(-1)) y_coords = torch.masked_select(P_w[1, :], mask.view(-1)) z_coords = torch.masked_select(P_w[2, :], mask.view(-1)) coords = torch.stack((x_coords, y_coords, z_coords), dim=0) distance_w = torch.norm(coords, p=2, dim=0) min_distance = torch.min(distance_w) index = (distance_w == min_distance).nonzero().flatten()[0] x_distance = float(coords[0, index]) y_distance = float(coords[1, index]) z_distance = float(coords[2, index]) measurement_list.append([x_distance, y_distance, z_distance]) id_list.append(id) return measurement_list, id_list # @profile def main(): # # read form camera # intrinsic_matrix = params.intrinsic_matrix # camera = CameraCapture((0,), intrinsic_matrix, dist_coeffs) # camera = CameraCapture( # (gstreamer_pipeline(), cv2.CAP_GSTREAMER), intrinsic_matrix, dist_coeffs) # read form file camera = FileCapture("./img") intrinsic_matrix = camera.intrinsic_matrix # cv2.namedWindow("Test camera") # cv2.namedWindow("Result") # cv2.namedWindow("MultiTracker") # choices = ["mono_640x192", # "stereo_640x192", # "mono+stereo_640x192", # "mono_no_pt_640x192", # "stereo_no_pt_640x192", # "mono+stereo_no_pt_640x192", # "mono_1024x320", # "stereo_1024x320", # "mono+stereo_1024x320"] # initiate monodepth feed_height, feed_width, encoder, depth_decoder = init_monodepth_model( "mono_640x192") # initiate yolo darknet_network, class_names, class_colors = init_darknet_network(config_file="./darknet/yolo-obj.cfg", data_file="./darknet/data/obj.data", weights_file="./darknet/yolo-obj.weights") # initiate deep track cfg = get_config() cfg.merge_from_file("deep_sort/configs/deep_sort.yaml") deepsort = build_tracker(cfg, use_cuda=torch.cuda.is_available()) # initiate Kalman filter measurement_matrix = np.array( [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0]], np.float32) transition_matrix = np.array( [[1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]], np.float32) process_noise_cov = np.eye(6, dtype=np.float32) * 1e-3 measurement_noise_cov = np.eye(3, dtype=np.float32) * 1e-1 kalman_filter = KalmanFilter(6, 3, measurement_matrix, transition_matrix, process_noise_cov, measurement_noise_cov) # initiate trajectory recorder trajectory_recorder = Trajectory() success, frame = camera.read() pixel_indexs = torch.tensor([[v, u] for v in range(frame.shape[0]) for u in range(frame.shape[1])]).t().to(device) last_frame = None last_true_disp = None last_y = dict() time_serial_index = 0 while success: last_run_time = time.time() # key = cv2.waitKey(1) # # if key == 27 or not success or\ # # cv2.getWindowProperty("Test camera", cv2.WND_PROP_AUTOSIZE) < 1 or\ # # cv2.getWindowProperty("Result", cv2.WND_PROP_AUTOSIZE) < 1 or\ # # cv2.getWindowProperty("MultiTracker", cv2.WND_PROP_AUTOSIZE) < 1: # if key == 27 or not success: # break # if key == ord(']'): # continue # do depth estimation rel_disp = get_relative_depth( frame, feed_height, feed_width, encoder, depth_decoder) scale = get_scale(rel_disp, intrinsic_matrix, inv_extrinsics_matrix, camera_height, pixel_indexs, frame, last_frame, last_true_disp) true_disp = rel_disp*scale P_w = pixelcoord_to_worldcoord(true_disp, intrinsic_matrix, inv_extrinsics_matrix, pixel_indexs) last_frame = frame last_true_disp = true_disp # do detection detections = detection( darknet_network, class_names, class_colors, frame) detections = np.array(detections, dtype=object) if detections.size > 0: bbox_xywh = np.array([np.array(xywh) for xywh in detections[:, 2]]) cls_conf = detections[:, 1].astype(np.float) else: bbox_xywh = np.array([[], [], [], []]).T cls_conf = np.array([[], [], [], []]).T # do tracking outputs = deepsort.update(bbox_xywh, cls_conf, frame) # get coordinates coords, ids = get_coordinates(P_w, outputs, frame) # do kalman filting filtered = kalman_filter.update(coords, ids) # record trajectory trajectory_recorder.update([filtered[index] for index in ids], ids) # # get depth image # disp_resized_np = -P_w[1, :].cpu().numpy().reshape( # frame.shape[0], frame.shape[1]) # # Saving colormapped depth image # vmax = np.percentile(disp_resized_np, 95) # # normalizer = mpl.colors.Normalize( # # vmin=disp_resized_np.min(), vmax=vmax) # normalizer = mpl.colors.Normalize(vmin=0, vmax=20) # # print(f"min: {disp_resized_np.min()}\tmax: {vmax}") # mapper = cm.ScalarMappable(norm=normalizer, cmap='magma') # colormapped_im = (mapper.to_rgba(disp_resized_np)[ # :, :, :3] * 255).astype(np.uint8) # im = pil.fromarray(colormapped_im) # # im.save(f'./temp/{temp_index}_disp.jpg') # plot result font = cv2.FONT_HERSHEY_DUPLEX font_thickness = 1 for output in outputs: x1, y1, x2, y2, id = output random.seed(id) color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) x_distance, y_distance, z_distance = filtered[id] if id in last_y: speed = (last_y[id]+y_distance)/0.1244 else: speed = 0 last_y[id] = -y_distance text_line1 = f"y:{-y_distance:0.2f}m" text_line2 = f"speed:{speed:0.2f}m/s" font_scale = 0.8 cv2.putText(frame, text_line1, (x2, y1), font, font_scale, color, font_thickness, cv2.LINE_AA) size_line1 = cv2.getTextSize( text_line1, font, font_scale, font_thickness)[0] cv2.putText(frame, text_line2, (x2, y1+size_line1[1]), font, font_scale, color, font_thickness, cv2.LINE_AA) font_scale = 2 fps_text = f"FPS:{1/(time.time()-last_run_time):0.1f}" size_fps_text = cv2.getTextSize( fps_text, font, font_scale, font_thickness)[0] cv2.putText(frame, fps_text, (frame.shape[0]-size_fps_text[0], size_fps_text[1]), font, font_scale, (0, 0, 255), font_thickness, cv2.LINE_AA) # cv2.imshow("MultiTracker", frame) # cv2.imwrite(f'./temp/{temp_index}.jpg', frame) print(f"index: {time_serial_index}") # if time_serial_index == 50: # break success, frame = camera.read() time_serial_index += 1 camera.release() cv2.destroyAllWindows() if __name__ == "__main__": main() <file_sep>/read_radar/__init__.py from read_radar.read_radar import read_radar <file_sep>/weather/__init__.py from weather.weather import get_weather, is_night
09bc6324bf5a1ece34ea69e4aa7859d21a42701c
[ "Markdown", "Python" ]
9
Python
KangJialiang/wt_project
5dfa14e0fed0d6c42feefdec5df256cfad86ad46
f9c7e0f1e28ad7b6a48484d521e6a562e29cfeb8
refs/heads/master
<repo_name>jbiddulph/moveme<file_sep>/database/seeds/DatabaseSeeder.php <?php use App\PropertyType; use Illuminate\Database\Seeder; use App\Category; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { // $this->call(UsersTableSeeder::class); factory('App\User', 20)->create(); factory('App\Company', 20)->create(); factory('App\Property', 20)->create(); $categories = [ 'Sold', 'Under Offer', 'Sold STC', 'For Sale' ]; foreach ($categories as $category){ Category::create(['name'=>$category]); } $propertytypes = [ 'House', 'Bungalow', 'Flat' ]; foreach ($propertytypes as $proptype){ PropertyType::create(['name'=>$proptype]); } } } <file_sep>/app/Http/Controllers/CompanyController.php <?php namespace App\Http\Controllers; use App\Company; use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class CompanyController extends Controller { public function __construct() { $this->middleware('company', ['except'=>array('index')]); } // public function index($id, Company $company){ return view('company.index', compact('company')); } public function create() { return view('company.create'); } public function store(Request $request) { $user_id = auth()->user()->id; $request->validate([ 'address' => 'required', 'telephone' => 'required', 'website' => 'required', 'slogan' => 'required', 'description' => 'required', ]); Company::where('user_id', $user_id)->update([ 'address'=>request('address'), 'telephone'=>request('telephone'), 'website'=>request('website'), 'slogan'=>request('slogan'), 'description'=>request('description') ]); return redirect()->back()->with('message','Company Successfully Updated!'); } public function coverPhoto(Request $request) { $user_id = auth()->user()->id; $request->validate([ 'cover_photo' => 'required:mimes:jpeg,jpg,png,gif', ]); if($request->hasFile('cover_photo')){ $file = $request->file('cover_photo'); $ext = $file->getClientOriginalExtension(); $filename = time().'.'.$ext; $file->move('uploads/coverphoto/', $filename); Company::where('user_id',$user_id)->update([ 'cover_photo'=>$filename ]); } return redirect()->back()->with('message','Cover Photo Successfully Updated!'); } public function companyLogo(Request $request) { $user_id = auth()->user()->id; // Log::info('FILE: '.$user_id); $request->validate([ 'company_logo' => 'required:mimes:jpeg,jpg,png,gif', ]); if($request->hasFile('company_logo')){ $file = $request->file('company_logo'); $ext = $file->getClientOriginalExtension(); $filename = time().'.'.$ext; $file->move('uploads/logo/', $filename); Company::where('user_id',$user_id)->update([ 'logo'=>$filename ]); } return redirect()->back()->with('message','Logo Successfully Updated!'); } public function companyBrand(Request $request) { $user_id = auth()->user()->id; $request->validate([ 'primary_color' => 'required', 'secondary_color' => 'required', ]); Company::where('user_id', $user_id)->update([ 'primary_color'=>'#'.request('primary_color'), 'secondary_color'=>'#'.request('secondary_color') ]); return redirect()->back()->with('message','Company Branding Successfully Updated!'); } } <file_sep>/app/Http/Controllers/UserAPIController.php <?php namespace App\Http\Controllers; use App\Http\Resources\UserResource; use App\Http\Resources\UserResourceCollection; use App\User; use Illuminate\Http\Request; class UserAPIController extends Controller { /** * @return UserResourceCollection */ public function index(): UserResourceCollection { return new UserResourceCollection(User::paginate(100)); } /** * @param User $user * @return UserResource */ public function show(User $user): UserResource { return new UserResource($user); } /** * @param Request $request * @return UserResource */ public function store(Request $request) { $request->validate([ 'name'=>'required', 'email'=>'required', ]); $user = User::create($request->all()); return new UserResource($user); } public function update(User $user, Request $request): UserResource { //update our user $user->update($request->all()); return new UserResource($user); } /** * @param User $user * @return \Illuminate\Http\JsonResponse * @throws \Exception */ public function destroy(User $user) { $user->delete(); return response()->json(); } } <file_sep>/app/Http/Controllers/EventAPIController.php <?php namespace App\Http\Controllers; use App\Http\Resources\EventResource; use App\Http\Resources\EventResourceCollection; use App\Event; use Illuminate\Http\Request; class EventAPIController extends Controller { /** * @return EventResourceCollection */ public function index(): EventResourceCollection { return new EventResourceCollection(Event::paginate(100)); } /** * @param Event $event * @return EventResource */ public function show(Event $event): EventResource { return new EventResource($event); } /** * @param Request $request * @return EventResource */ public function store(Request $request) { $request->validate([ // 'venue_id'=>'required', 'eventName'=>'required', // 'slug'=>'required', // 'eventPhoto'=>'required', 'eventDate'=>'required', 'eventTimeStart'=>'required', 'eventTimeEnd'=>'required', 'eventType'=>'required', 'eventCost'=>'required' // 'is_live'=>'required' ]); $event = Event::create($request->all()); return new EventResource($event); } public function update(Event $event, Request $request): EventResource { //update our event $event->update($request->all()); return new EventResource($event); } /** * @param Event $event * @return \Illuminate\Http\JsonResponse * @throws \Exception */ public function destroy(Event $event) { $event->delete(); return response()->json(); } } <file_sep>/app/Venue.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Spatie\Activitylog\Traits\LogsActivity; class Venue extends Model { use Notifiable, LogsActivity; protected $fillable = ['id', 'venuename', 'venuetype', 'address', 'address2', 'town', 'county', 'postcode', 'postalsearch', 'telephone', 'latitude', 'longitude', 'website', 'photo', 'is_live']; public function events() { return $this->hasMany('App\Event'); } public function user() { return $this->belongsTo('App\User'); } public function tagins() { return $this->hasMany('App\Tagin'); } } <file_sep>/app/Http/Controllers/LandlordRegisterController.php <?php namespace App\Http\Controllers; use App\Event; use App\User; use App\Venue; use Mapper; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; class LandlordRegisterController extends Controller { public function landlordRegister() { $venue = Venue::findOrFail(request('selectedVenueID')); $user = User::create([ 'name' => $venue->venuename, 'venue_id' => $venue->id, 'email' => request('email'), 'user_type' => request('user_type'), 'password' => <PASSWORD>(request('password')), ]); $venue->user_id = $user->id; $venue->email = $user->email; $venue->save(); return redirect()->to('login'); } public function registerClaim() { $venue = Venue::findOrFail(request('venue_id')); $venue_id = $venue->id; $venue_name = $venue->venuename; return view('register-claim', compact( 'venue_id', 'venue_name')); } public function viewVenue(Request $request) { $venueid = Auth::user()->venue_id; $thevenue = Venue::findOrFail($venueid); $towns = Venue::select('town')->distinct()->get(); $events = Event::latest()->where("venue_id", "=", "$venueid")->get(); Mapper::map($thevenue->latitude,$thevenue->longitude, [ 'zoom' => 16, 'marker' => true, 'cluster' => false ]); Mapper::informationWindow($thevenue->latitude, $thevenue->longitude, '<a href="/venues/' . str_slug($thevenue->town) . '/' . str_slug($thevenue->venuename) . '/'. $thevenue->id .'">' . $thevenue->venuename . '</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); $venues = Venue::get(); $venueslist = Venue::latest()->where('is_live',1)->paginate(52); return view('venues.venue', compact( 'venues', 'venueslist', 'thevenue','towns', 'events')); } } <file_sep>/resources/docs/source/.compare.md --- title: API Reference language_tabs: - bash - javascript includes: search: true toc_footers: - <a href='http://github.com/mpociot/documentarian'>Documentation Powered by Documentarian</a> --- <!-- START_INFO --> # Info Welcome to the generated API reference. [Get Postman Collection](http://moveme.test/docs/collection.json) <!-- END_INFO --> #general <!-- START_f7b7ea397f8939c8bb93e6cab64603ce --> ## Display Swagger API page. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/documentation" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/documentation" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET api/documentation` <!-- END_f7b7ea397f8939c8bb93e6cab64603ce --> <!-- START_1ead214f30a5e235e7140eb2aaa29eee --> ## Dump api-docs content endpoint. Supports dumping a json, or yaml file. > Example request: ```bash curl -X GET \ -G "http://moveme.test/docs/" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/docs/" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json { "swagger": "2.0", "info": { "title": "L5 Swagger API", "description": "L5 Swagger API description", "contact": { "email": "<EMAIL>" }, "version": "1.0.0" }, "host": "movemeapi.test", "basePath": "", "schemes": [ "http", "https" ], "paths": { "\/api\/testing\/{mytest}": { "get": { "summary": "Get Testing", "operationId": "testing", "parameters": [ { "name": "mytest", "in": "path", "required": true, "type": "string" } ], "responses": { "200": { "description": "successful operation" }, "406": { "description": "not acceptable" }, "500": { "description": "internal server error" } } } } }, "definitions": {}, "securityDefinitions": { "bearer_token": { "type": "apiKey", "description": "Enter token in format (Bearer <token>)", "name": "Authorization", "in": "header" } } } ``` ### HTTP Request `GET docs/{jsonFile?}` `POST docs/{jsonFile?}` `PUT docs/{jsonFile?}` `PATCH docs/{jsonFile?}` `DELETE docs/{jsonFile?}` `OPTIONS docs/{jsonFile?}` <!-- END_1ead214f30a5e235e7140eb2aaa29eee --> <!-- START_1a23c1337818a4de9e417863aebaca33 --> ## docs/asset/{asset} > Example request: ```bash curl -X GET \ -G "http://moveme.test/docs/asset/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/docs/asset/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "(1) - this L5 Swagger asset is not allowed" } ``` ### HTTP Request `GET docs/asset/{asset}` <!-- END_1a23c1337818a4de9e417863aebaca33 --> <!-- START_a2c4ea37605c6d2e3c93b7269030af0a --> ## Display Oauth2 callback pages. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/oauth2-callback" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/oauth2-callback" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET api/oauth2-callback` <!-- END_a2c4ea37605c6d2e3c93b7269030af0a --> <!-- START_e4c20ab9c4727524c3daa74a53e56200 --> ## Display the form to gather additional payment verification for the given payment. > Example request: ```bash curl -X GET \ -G "http://moveme.test/stripe/payment/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/stripe/payment/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET stripe/payment/{id}` <!-- END_e4c20ab9c4727524c3daa74a53e56200 --> <!-- START_15ae8ca17c014b55868e68dc48ee5047 --> ## Handle a Stripe webhook call. > Example request: ```bash curl -X POST \ "http://moveme.test/stripe/webhook" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/stripe/webhook" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST stripe/webhook` <!-- END_15ae8ca17c014b55868e68dc48ee5047 --> <!-- START_56f0a9e2603f1ee851384158a3a2bc34 --> ## api/venue > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/venue" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/venue" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json { "data": [ { "id": 1148987, "user_id": 0, "email": null, "venuename": "The Marquis Of Granby", "slug": "the-marquis-of-granby", "venuetype": "Public Houses", "address": "West Street", "address2": "", "town": "Lancing", "county": "West Sussex", "postcode": "BN150AP", "postalsearch": "BN15", "telephone": "01903 231102", "latitude": "50.834524", "longitude": "-0.3531344", "website": "", "photo": "venues\/venue-default.png", "is_live": 0, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-10-10 21:45:55" }, { "id": 1149078, "user_id": 0, "email": null, "venuename": "The Marine", "slug": "the-marine", "venuetype": "Public Houses", "address": "Selborne Road", "address2": "", "town": "Littlehampton", "county": "West Sussex", "postcode": "BN175NN", "postalsearch": "BN17", "telephone": "01903721476", "latitude": "50.8051908", "longitude": "-0.5332891", "website": "", "photo": "venues\/venue-default.png", "is_live": 0, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 15:08:22" }, { "id": 1149079, "user_id": 33, "email": "<EMAIL>", "venuename": "The Marine", "slug": "the-marine", "venuetype": "Public Houses", "address": "61 Seaside", "address2": "", "town": "Eastbourne", "county": "East Sussex", "postcode": "BN227NE", "postalsearch": "BN22", "telephone": "01323720464", "latitude": "50.7715121", "longitude": "0.2952365", "website": "", "photo": "public\/venues\/photos\/AeegKGFyBYoVndROG1ZlsnBsfP3qXnT3d7FVmcwD.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-09-21 19:30:31" }, { "id": 1149188, "user_id": 0, "email": null, "venuename": "<NAME>", "slug": "the-mashtun", "venuetype": "Public Houses", "address": "1 Church Street", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN11UE", "postalsearch": "BN1", "telephone": "01273684951", "latitude": "50.82347450", "longitude": "-0.13847680", "website": "https:\/\/www.mashtun.pub\/", "photo": "public\/venues\/photos\/bpHgwKtvMWhvotXeKZUKSV0PXXa8mgk6OTgbuLwb.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 13:55:06" }, { "id": 1149243, "user_id": 0, "email": null, "venuename": "The Marlborough Hotel", "slug": "the-marlborough-hotel", "venuetype": "Public Houses", "address": "4 Princes Street", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN21RD", "postalsearch": "BN2", "telephone": "01273 570028", "latitude": "50.8223086", "longitude": "-0.1359947", "website": "", "photo": "public\/venues\/photos\/MmqjXeHbD8RjEmTV8o9wFSytxD6Gx4bqgTUpBMYM.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 13:57:03" }, { "id": 1149305, "user_id": 0, "email": null, "venuename": "The Market Inn", "slug": "the-market-inn", "venuetype": "Public Houses", "address": "1 Market Street", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN11HH", "postalsearch": "BN1", "telephone": "01273329483", "latitude": "50.8214604", "longitude": "-0.1397625", "website": "", "photo": "public\/venues\/photos\/L1igcRRQMtZuDgisF3oLEqymyDjBIUhDFnOzJ0ru.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 13:57:54" }, { "id": 1149381, "user_id": 0, "email": null, "venuename": "The Marine Tavern", "slug": "the-marine-tavern", "venuetype": "Public Houses", "address": "13 Broad Street", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN21TJ", "postalsearch": "BN2", "telephone": "01273681284", "latitude": "50.8204832", "longitude": "-0.134889", "website": "", "photo": "public\/venues\/photos\/Q7WFVSHUSdCAtKqWvtX4tSazs8FFX53yX3CLUStV.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 13:58:48" }, { "id": 1149568, "user_id": 0, "email": null, "venuename": "<NAME>", "slug": "white-star-inn", "venuetype": "Public Houses", "address": "36 Lansdown Place", "address2": "", "town": "Lewes", "county": "East Sussex", "postcode": "BN72JU", "postalsearch": "BN7", "telephone": "01273480623", "latitude": "50.871791", "longitude": "0.0118211", "website": "", "photo": "public\/venues\/photos\/TdP3JMrC1erCTfhM7iU0MAXkLHnaZgkQxZdP47nG.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 14:00:00" }, { "id": 1149696, "user_id": 0, "email": null, "venuename": "<NAME>", "slug": "leone-d'oori", "venuetype": "Public Houses", "address": "76 Preston Street", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN12HG", "postalsearch": "BN1", "telephone": "01273722214", "latitude": "50.8227313", "longitude": "-0.1512552", "website": "", "photo": "venues\/venue-default.png", "is_live": 0, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 15:08:59" }, { "id": 1149715, "user_id": 0, "email": null, "venuename": "<NAME>", "slug": "mrs-fitzherberts", "venuetype": "Public Houses", "address": "25 New Road", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN11UG", "postalsearch": "BN1", "telephone": "01273682401", "latitude": "50.8237068", "longitude": "-0.1390769", "website": "www.fitzherberts.com", "photo": "public\/venues\/photos\/2t7glHspAFKRczHJIGBqi70bbsEkrxpX3OpDYsf7.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 14:03:50" }, { "id": 1149717, "user_id": 30, "email": "<EMAIL>", "venuename": "<NAME>", "slug": "st-george-inn", "venuetype": "Public Houses", "address": "29 High Street", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN412LH", "postalsearch": "BN41", "telephone": "01273424933", "latitude": "50.8433788", "longitude": "-0.2194018", "website": "", "photo": "public\/venues\/photos\/TebIvhxdKn1wV6uP4ebjkdaBt3vE3gWngSgdthJ3.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-09-21 18:38:56" }, { "id": 1149924, "user_id": 0, "email": null, "venuename": "<NAME>", "slug": "albion-tavern", "venuetype": "Public Houses", "address": "13-15 Fishersgate Terrace", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN411PH", "postalsearch": "BN41", "telephone": "01273411256", "latitude": "50.8309695", "longitude": "-0.2183261", "website": "", "photo": "public\/venues\/photos\/RYfXMhU0EawsScYq1SlLpKppOtGMlHxs5YjzD8Ic.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-09-20 11:29:12" }, { "id": 1149969, "user_id": 0, "email": null, "venuename": "<NAME>", "slug": "preston-park-tavern", "venuetype": "Public Houses", "address": "88 Havelock Road", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN16GF", "postalsearch": "BN1", "telephone": "01273542271", "latitude": "50.8405665", "longitude": "-0.1405794", "website": "", "photo": "public\/venues\/photos\/tfo4BbrrgbT1Mg46NotUXctPEcM98ebjFsUq4ZU6.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 14:07:27" }, { "id": 1150066, "user_id": 0, "email": null, "venuename": "The Open House", "slug": "the-open-house", "venuetype": "Public Houses", "address": "146 Springfield Road", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN16BZ", "postalsearch": "BN1", "telephone": "01273550000", "latitude": "50.8371361", "longitude": "-0.1369521", "website": "", "photo": "public\/venues\/photos\/OYznVn2ywj12LikjWTTxMp2SlQlDJ3idEZCnpdP4.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 14:08:05" }, { "id": 1150071, "user_id": 0, "email": null, "venuename": "The Earth & Stars", "slug": "the-earth-&-stars", "venuetype": "Public Houses", "address": "8 Queens Road", "address2": "", "town": "Brighton", "county": "East Sussex", "postcode": "BN13WA ", "postalsearch": "BN1", "telephone": "01273737770", "latitude": "50.8246098", "longitude": "-0.143258", "website": "", "photo": "public\/venues\/photos\/Ki0u1mzQPvMNXBQ55AJGiFVh8cNaVsRWiyfAi6dU.jpeg", "is_live": 1, "created_at": "2020-03-15 18:37:54", "updated_at": "2020-04-15 14:08:45" } ], "links": { "first": "http:\/\/localhost\/api\/venue?page=1", "last": "http:\/\/localhost\/api\/venue?page=36", "prev": null, "next": "http:\/\/localhost\/api\/venue?page=2" }, "meta": { "current_page": 1, "from": 1, "last_page": 36, "path": "http:\/\/localhost\/api\/venue", "per_page": 15, "to": 15, "total": 529 } } ``` ### HTTP Request `GET api/venue` <!-- END_56f0a9e2603f1ee851384158a3a2bc34 --> <!-- START_190cbe4357f56179064a8caab827d3f2 --> ## api/venue > Example request: ```bash curl -X POST \ "http://moveme.test/api/venue" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/venue" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST api/venue` <!-- END_190cbe4357f56179064a8caab827d3f2 --> <!-- START_ee94771b70d97e6ae2f1a42bb08ca085 --> ## api/venue/{venue} > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/venue/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/venue/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Venue] 1" } ``` ### HTTP Request `GET api/venue/{venue}` <!-- END_ee94771b70d97e6ae2f1a42bb08ca085 --> <!-- START_892be4345d8797ab237ba7869c41c7d8 --> ## api/venue/{venue} > Example request: ```bash curl -X PUT \ "http://moveme.test/api/venue/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/venue/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "PUT", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `PUT api/venue/{venue}` `PATCH api/venue/{venue}` <!-- END_892be4345d8797ab237ba7869c41c7d8 --> <!-- START_097b01f88d51f1c0cf2fe832e6ab5654 --> ## api/venue/{venue} > Example request: ```bash curl -X DELETE \ "http://moveme.test/api/venue/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/venue/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "DELETE", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `DELETE api/venue/{venue}` <!-- END_097b01f88d51f1c0cf2fe832e6ab5654 --> <!-- START_c3fa189a6c95ca36ad6ac4791a873d23 --> ## api/login > Example request: ```bash curl -X POST \ "http://moveme.test/api/login" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/login" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST api/login` <!-- END_c3fa189a6c95ca36ad6ac4791a873d23 --> <!-- START_d7b7952e7fdddc07c978c9bdaf757acf --> ## api/register > Example request: ```bash curl -X POST \ "http://moveme.test/api/register" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/register" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST api/register` <!-- END_d7b7952e7fdddc07c978c9bdaf757acf --> <!-- START_61739f3220a224b34228600649230ad1 --> ## api/logout > Example request: ```bash curl -X POST \ "http://moveme.test/api/logout" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/logout" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST api/logout` <!-- END_61739f3220a224b34228600649230ad1 --> <!-- START_4227b9e5e54912af051e8dd5472afbce --> ## Display a listing of the resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/tasks" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/tasks" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET api/tasks` <!-- END_4227b9e5e54912af051e8dd5472afbce --> <!-- START_77cebd77d4e11b47656dcb7c358c782e --> ## Show the form for creating a new resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/tasks/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/tasks/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET api/tasks/create` <!-- END_77cebd77d4e11b47656dcb7c358c782e --> <!-- START_4da0d9b378428dcc89ced395d4a806e7 --> ## Store a newly created resource in storage. > Example request: ```bash curl -X POST \ "http://moveme.test/api/tasks" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/tasks" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST api/tasks` <!-- END_4da0d9b378428dcc89ced395d4a806e7 --> <!-- START_5297efa151ae4fd515fec2efd5cb1e9a --> ## Display the specified resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/tasks/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/tasks/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET api/tasks/{task}` <!-- END_5297efa151ae4fd515fec2efd5cb1e9a --> <!-- START_78152b9305f9bb5329902097d70e99d3 --> ## Show the form for editing the specified resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/tasks/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/tasks/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET api/tasks/{task}/edit` <!-- END_78152b9305f9bb5329902097d70e99d3 --> <!-- START_546f027bf591f2ef4a8a743f0a59051d --> ## Update the specified resource in storage. > Example request: ```bash curl -X PUT \ "http://moveme.test/api/tasks/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/tasks/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "PUT", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `PUT api/tasks/{task}` `PATCH api/tasks/{task}` <!-- END_546f027bf591f2ef4a8a743f0a59051d --> <!-- START_8b8069956f22facfa8cdc67aece156a8 --> ## Remove the specified resource from storage. > Example request: ```bash curl -X DELETE \ "http://moveme.test/api/tasks/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/tasks/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "DELETE", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `DELETE api/tasks/{task}` <!-- END_8b8069956f22facfa8cdc67aece156a8 --> <!-- START_96ed66d9e6531df9b49e02d84ca5a619 --> ## Display a listing of the resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/customers" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/customers" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET api/customers` <!-- END_96ed66d9e6531df9b49e02d84ca5a619 --> <!-- START_089467e7ea475fb2aca445b2d23f6e7d --> ## Store a newly created resource in storage. > Example request: ```bash curl -X POST \ "http://moveme.test/api/customers" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/customers" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST api/customers` <!-- END_089467e7ea475fb2aca445b2d23f6e7d --> <!-- START_51260396e2d6bf23a957126f249c5ee9 --> ## Display the specified resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/customers/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/customers/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET api/customers/{customer}` <!-- END_51260396e2d6bf23a957126f249c5ee9 --> <!-- START_9c3d56ca438bc61f264f75d157cf51bd --> ## Update the specified resource in storage. > Example request: ```bash curl -X PUT \ "http://moveme.test/api/customers/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/customers/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "PUT", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `PUT api/customers/{customer}` `PATCH api/customers/{customer}` <!-- END_9c3d56ca438bc61f264f75d157cf51bd --> <!-- START_92d13d95887bbc9f105182378dcca720 --> ## Remove the specified resource from storage. > Example request: ```bash curl -X DELETE \ "http://moveme.test/api/customers/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/customers/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "DELETE", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `DELETE api/customers/{customer}` <!-- END_92d13d95887bbc9f105182378dcca720 --> <!-- START_6e5ce4acf3e28e7792c2a6f443fdd941 --> ## api/testing/{mytest} > Example request: ```bash curl -X GET \ -G "http://moveme.test/api/testing/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/api/testing/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `GET api/testing/{mytest}` <!-- END_6e5ce4acf3e28e7792c2a6f443fdd941 --> <!-- START_53be1e9e10a08458929a2e0ea70ddb86 --> ## / > Example request: ```bash curl -X GET \ -G "http://moveme.test/" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET /` <!-- END_53be1e9e10a08458929a2e0ea70ddb86 --> <!-- START_66e08d3cc8222573018fed49e121e96d --> ## Show the application&#039;s login form. > Example request: ```bash curl -X GET \ -G "http://moveme.test/login" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/login" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET login` <!-- END_66e08d3cc8222573018fed49e121e96d --> <!-- START_ba35aa39474cb98cfb31829e70eb8b74 --> ## Handle a login request to the application. > Example request: ```bash curl -X POST \ "http://moveme.test/login" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/login" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST login` <!-- END_ba35aa39474cb98cfb31829e70eb8b74 --> <!-- START_e65925f23b9bc6b93d9356895f29f80c --> ## Log the user out of the application. > Example request: ```bash curl -X POST \ "http://moveme.test/logout" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/logout" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST logout` <!-- END_e65925f23b9bc6b93d9356895f29f80c --> <!-- START_ff38dfb1bd1bb7e1aa24b4e1792a9768 --> ## Show the application registration form. > Example request: ```bash curl -X GET \ -G "http://moveme.test/register" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/register" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET register` <!-- END_ff38dfb1bd1bb7e1aa24b4e1792a9768 --> <!-- START_d7aad7b5ac127700500280d511a3db01 --> ## Handle a registration request for the application. > Example request: ```bash curl -X POST \ "http://moveme.test/register" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/register" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST register` <!-- END_d7aad7b5ac127700500280d511a3db01 --> <!-- START_d72797bae6d0b1f3a341ebb1f8900441 --> ## Display the form to request a password reset link. > Example request: ```bash curl -X GET \ -G "http://moveme.test/password/reset" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/password/reset" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET password/reset` <!-- END_d72797bae6d0b1f3a341ebb1f8900441 --> <!-- START_feb40f06a93c80d742181b6ffb6b734e --> ## Send a reset link to the given user. > Example request: ```bash curl -X POST \ "http://moveme.test/password/email" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/password/email" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST password/email` <!-- END_feb40f06a93c80d742181b6ffb6b734e --> <!-- START_e1605a6e5ceee9d1aeb7729216635fd7 --> ## Display the password reset view for the given token. If no token is present, display the link request form. > Example request: ```bash curl -X GET \ -G "http://moveme.test/password/reset/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/password/reset/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET password/reset/{token}` <!-- END_e1605a6e5ceee9d1aeb7729216635fd7 --> <!-- START_cafb407b7a846b31491f97719bb15aef --> ## Reset the given user&#039;s password. > Example request: ```bash curl -X POST \ "http://moveme.test/password/reset" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/password/reset" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST password/reset` <!-- END_cafb407b7a846b31491f97719bb15aef --> <!-- START_b77aedc454e9471a35dcb175278ec997 --> ## Display the password confirmation view. > Example request: ```bash curl -X GET \ -G "http://moveme.test/password/confirm" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/password/confirm" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (401): ```json { "message": "Unauthenticated." } ``` ### HTTP Request `GET password/confirm` <!-- END_b77aedc454e9471a35dcb175278ec997 --> <!-- START_54462d3613f2262e741142161c0e6fea --> ## Confirm the given user&#039;s password. > Example request: ```bash curl -X POST \ "http://moveme.test/password/confirm" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/password/confirm" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST password/confirm` <!-- END_54462d3613f2262e741142161c0e6fea --> <!-- START_cb859c8e84c35d7133b6a6c8eac253f8 --> ## Show the application dashboard. > Example request: ```bash curl -X GET \ -G "http://moveme.test/home" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/home" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (401): ```json { "message": "Unauthenticated." } ``` ### HTTP Request `GET home` <!-- END_cb859c8e84c35d7133b6a6c8eac253f8 --> <!-- START_d3905b9b0262f05da393514eee95b2ea --> ## company/{id}/{company} > Example request: ```bash curl -X GET \ -G "http://moveme.test/company/1/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/company/1/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Company] 1" } ``` ### HTTP Request `GET company/{id}/{company}` <!-- END_d3905b9b0262f05da393514eee95b2ea --> <!-- START_2c83b922439896837b1ea278563ede93 --> ## company/create > Example request: ```bash curl -X GET \ -G "http://moveme.test/company/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/company/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (302): ```json null ``` ### HTTP Request `GET company/create` <!-- END_2c83b922439896837b1ea278563ede93 --> <!-- START_885ae7fd77c5fc3955320367f2a83644 --> ## company/create > Example request: ```bash curl -X POST \ "http://moveme.test/company/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/company/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST company/create` <!-- END_885ae7fd77c5fc3955320367f2a83644 --> <!-- START_29fda587a4e2c32f615742e5f7396e73 --> ## company/coverphoto > Example request: ```bash curl -X POST \ "http://moveme.test/company/coverphoto" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/company/coverphoto" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST company/coverphoto` <!-- END_29fda587a4e2c32f615742e5f7396e73 --> <!-- START_30d495046d565928568c58b2af4731b5 --> ## company/logo > Example request: ```bash curl -X POST \ "http://moveme.test/company/logo" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/company/logo" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST company/logo` <!-- END_30d495046d565928568c58b2af4731b5 --> <!-- START_d0f00297a5a590089131b75037a3f361 --> ## company/branding > Example request: ```bash curl -X POST \ "http://moveme.test/company/branding" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/company/branding" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST company/branding` <!-- END_d0f00297a5a590089131b75037a3f361 --> <!-- START_ef808664c80bc38fd1707571729e14c7 --> ## Invoke the controller method. > Example request: ```bash curl -X GET \ -G "http://moveme.test/register/company" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/register/company" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET register/company` <!-- END_ef808664c80bc38fd1707571729e14c7 --> <!-- START_23fa7a44420a89776d537bb69af70b6d --> ## company/register > Example request: ```bash curl -X POST \ "http://moveme.test/company/register" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/company/register" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST company/register` <!-- END_23fa7a44420a89776d537bb69af70b6d --> <!-- START_9fc0bdc56864baa96b568dd71e6755c6 --> ## Invoke the controller method. > Example request: ```bash curl -X GET \ -G "http://moveme.test/register/landlord" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/register/landlord" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET register/landlord` <!-- END_9fc0bdc56864baa96b568dd71e6755c6 --> <!-- START_e6833a73ffb0b9d2940e8849d6ffa4a1 --> ## register/claim > Example request: ```bash curl -X GET \ -G "http://moveme.test/register/claim" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/register/claim" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Venue]." } ``` ### HTTP Request `GET register/claim` <!-- END_e6833a73ffb0b9d2940e8849d6ffa4a1 --> <!-- START_1c73c29f8335a0fff34dafb39c2c1167 --> ## landlord/register > Example request: ```bash curl -X POST \ "http://moveme.test/landlord/register" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/landlord/register" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST landlord/register` <!-- END_1c73c29f8335a0fff34dafb39c2c1167 --> <!-- START_38ac90367d9a366bade5ee15d317c0f7 --> ## venue/events/create > Example request: ```bash curl -X GET \ -G "http://moveme.test/venue/events/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venue/events/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET venue/events/create` <!-- END_38ac90367d9a366bade5ee15d317c0f7 --> <!-- START_ae6581004d0fd2594d026e5a9d3474d4 --> ## venue/events/create > Example request: ```bash curl -X POST \ "http://moveme.test/venue/events/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venue/events/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST venue/events/create` <!-- END_ae6581004d0fd2594d026e5a9d3474d4 --> <!-- START_ec380f982745bfcba04810c0c2268e14 --> ## venue/view > Example request: ```bash curl -X GET \ -G "http://moveme.test/venue/view" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venue/view" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET venue/view` <!-- END_ec380f982745bfcba04810c0c2268e14 --> <!-- START_3e8d5f4de3e3bd52a4b7ccb199f36ab7 --> ## venue/{id}/{now}/tagin/stats > Example request: ```bash curl -X GET \ -G "http://moveme.test/venue/1/1/tagin/stats" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venue/1/1/tagin/stats" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Venue] 1" } ``` ### HTTP Request `GET venue/{id}/{now}/tagin/stats` <!-- END_3e8d5f4de3e3bd52a4b7ccb199f36ab7 --> <!-- START_e6d6662e3a2a9b9f269a6144cd3382c3 --> ## subscribe > Example request: ```bash curl -X GET \ -G "http://moveme.test/subscribe" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/subscribe" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (401): ```json { "message": "Unauthenticated." } ``` ### HTTP Request `GET subscribe` <!-- END_e6d6662e3a2a9b9f269a6144cd3382c3 --> <!-- START_7cd1c92845723362129d03191c93e958 --> ## subscribe > Example request: ```bash curl -X POST \ "http://moveme.test/subscribe" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/subscribe" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST subscribe` <!-- END_7cd1c92845723362129d03191c93e958 --> <!-- START_7ed318e6b30fcb9d0f2ec4b79bd46b6c --> ## venue/{id}/edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/venue/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venue/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Venue] 1" } ``` ### HTTP Request `GET venue/{id}/edit` <!-- END_7ed318e6b30fcb9d0f2ec4b79bd46b6c --> <!-- START_ac5fa200290ce6a460fe3b0a4e707351 --> ## venue/{id}/edit > Example request: ```bash curl -X POST \ "http://moveme.test/venue/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venue/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST venue/{id}/edit` <!-- END_ac5fa200290ce6a460fe3b0a4e707351 --> <!-- START_10c700a1a5173f595c341e34abcd27fb --> ## user/profile > Example request: ```bash curl -X GET \ -G "http://moveme.test/user/profile" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/user/profile" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET user/profile` <!-- END_10c700a1a5173f595c341e34abcd27fb --> <!-- START_1f2aac652dd3d6ba648d6bdc7065d960 --> ## user/profile/create > Example request: ```bash curl -X POST \ "http://moveme.test/user/profile/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/user/profile/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST user/profile/create` <!-- END_1f2aac652dd3d6ba648d6bdc7065d960 --> <!-- START_7714c2131ee44a7c0351265c232a7552 --> ## user/coverletter > Example request: ```bash curl -X POST \ "http://moveme.test/user/coverletter" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/user/coverletter" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST user/coverletter` <!-- END_7714c2131ee44a7c0351265c232a7552 --> <!-- START_bd95bb8bd0371ac6272779b7eba0f3b3 --> ## user/identification > Example request: ```bash curl -X POST \ "http://moveme.test/user/identification" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/user/identification" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST user/identification` <!-- END_bd95bb8bd0371ac6272779b7eba0f3b3 --> <!-- START_210b1af6995fdbf20255888917c7208e --> ## user/avatar > Example request: ```bash curl -X POST \ "http://moveme.test/user/avatar" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/user/avatar" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST user/avatar` <!-- END_210b1af6995fdbf20255888917c7208e --> <!-- START_6ff495e092650c9f0e765b17fe9b4ae7 --> ## properties/{id}/edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/properties/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (302): ```json null ``` ### HTTP Request `GET properties/{id}/edit` <!-- END_6ff495e092650c9f0e765b17fe9b4ae7 --> <!-- START_826676f2989592434e6b036ae5528332 --> ## properties/{id}/edit > Example request: ```bash curl -X POST \ "http://moveme.test/properties/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST properties/{id}/edit` <!-- END_826676f2989592434e6b036ae5528332 --> <!-- START_606dc10f46efe291772f5baae3bc61a5 --> ## changeStatus > Example request: ```bash curl -X GET \ -G "http://moveme.test/changeStatus" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/changeStatus" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (302): ```json null ``` ### HTTP Request `GET changeStatus` <!-- END_606dc10f46efe291772f5baae3bc61a5 --> <!-- START_55a9af37993fe0257326419de5cecaa2 --> ## properties/{id}/uploads-edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/properties/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (302): ```json null ``` ### HTTP Request `GET properties/{id}/uploads-edit` <!-- END_55a9af37993fe0257326419de5cecaa2 --> <!-- START_56b96b8503d9430c44f429501a8e80e1 --> ## properties/{id}/uploads-edit > Example request: ```bash curl -X POST \ "http://moveme.test/properties/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST properties/{id}/uploads-edit` <!-- END_56b96b8503d9430c44f429501a8e80e1 --> <!-- START_1e0cd94333c99e320a68deb1c3af0c5b --> ## properties/{id}/{property} > Example request: ```bash curl -X GET \ -G "http://moveme.test/properties/1/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/1/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Property] 1" } ``` ### HTTP Request `GET properties/{id}/{property}` <!-- END_1e0cd94333c99e320a68deb1c3af0c5b --> <!-- START_9ed54d1b8269897e0c5cdebd629ba1a7 --> ## properties/{id}/{property}/addphotos > Example request: ```bash curl -X GET \ -G "http://moveme.test/properties/1/1/addphotos" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/1/1/addphotos" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Property] 1" } ``` ### HTTP Request `GET properties/{id}/{property}/addphotos` <!-- END_9ed54d1b8269897e0c5cdebd629ba1a7 --> <!-- START_788ff9e045e2f928be437c8c4a9c3754 --> ## propertyphoto/add > Example request: ```bash curl -X POST \ "http://moveme.test/propertyphoto/add" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/propertyphoto/add" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST propertyphoto/add` <!-- END_788ff9e045e2f928be437c8c4a9c3754 --> <!-- START_76f0ec380a08045b21faee92f63c3a7b --> ## property/create > Example request: ```bash curl -X GET \ -G "http://moveme.test/property/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/property/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (401): ```json { "message": "Unauthenticated." } ``` ### HTTP Request `GET property/create` <!-- END_76f0ec380a08045b21faee92f63c3a7b --> <!-- START_f2070d0136dbbc1dc09afc4af6113e73 --> ## property/my-property > Example request: ```bash curl -X GET \ -G "http://moveme.test/property/my-property" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/property/my-property" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (302): ```json null ``` ### HTTP Request `GET property/my-property` <!-- END_f2070d0136dbbc1dc09afc4af6113e73 --> <!-- START_6c4a69cc1a64b687f2516563eefb30c3 --> ## properties/all-properties > Example request: ```bash curl -X GET \ -G "http://moveme.test/properties/all-properties" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/all-properties" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET properties/all-properties` <!-- END_6c4a69cc1a64b687f2516563eefb30c3 --> <!-- START_24b3fda3b1b1dc04342b799f42e992af --> ## property/create > Example request: ```bash curl -X POST \ "http://moveme.test/property/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/property/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST property/create` <!-- END_24b3fda3b1b1dc04342b799f42e992af --> <!-- START_eb77607a6c2804d029dc185e0428dbb6 --> ## property/interest/{id} > Example request: ```bash curl -X POST \ "http://moveme.test/property/interest/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/property/interest/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST property/interest/{id}` <!-- END_eb77607a6c2804d029dc185e0428dbb6 --> <!-- START_9eff7267b8482bf012b629476a18498b --> ## properties/applications > Example request: ```bash curl -X GET \ -G "http://moveme.test/properties/applications" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/properties/applications" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (302): ```json null ``` ### HTTP Request `GET properties/applications` <!-- END_9eff7267b8482bf012b629476a18498b --> <!-- START_a171dd5f4f0f913ba53d4d66a1df5ada --> ## Display a listing of the resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/events/all" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/events/all" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET events/all` <!-- END_a171dd5f4f0f913ba53d4d66a1df5ada --> <!-- START_7ca4f7024d6374f6e3d789b34fba7874 --> ## events/{id} > Example request: ```bash curl -X GET \ -G "http://moveme.test/events/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/events/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Event] 1" } ``` ### HTTP Request `GET events/{id}` <!-- END_7ca4f7024d6374f6e3d789b34fba7874 --> <!-- START_80f70a8e35dbbf277522c4ddfe649f31 --> ## venues/all > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/all" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/all" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET venues/all` <!-- END_80f70a8e35dbbf277522c4ddfe649f31 --> <!-- START_986824100e1a6390e8895da876e294cb --> ## venues/all > Example request: ```bash curl -X POST \ "http://moveme.test/venues/all" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/all" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST venues/all` <!-- END_986824100e1a6390e8895da876e294cb --> <!-- START_e8757e3b68e8dc18ab32bb7d0ecdef10 --> ## venues/towns/{town} > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/towns/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/towns/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET venues/towns/{town}` <!-- END_e8757e3b68e8dc18ab32bb7d0ecdef10 --> <!-- START_c4114fcfe186590889b851748266b416 --> ## venues/{town}/{name}/{id} > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/1/1/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/1/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Venue] 1" } ``` ### HTTP Request `GET venues/{town}/{name}/{id}` <!-- END_c4114fcfe186590889b851748266b416 --> <!-- START_de85f195eb2e05a3203592b3263330e6 --> ## venues/{id}/tagin > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/1/tagin" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/tagin" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Venue] 1" } ``` ### HTTP Request `GET venues/{id}/tagin` <!-- END_de85f195eb2e05a3203592b3263330e6 --> <!-- START_f7750d054a278f319238a44a6a071770 --> ## venues/{id}/tagin/add > Example request: ```bash curl -X POST \ "http://moveme.test/venues/1/tagin/add" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/tagin/add" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST venues/{id}/tagin/add` <!-- END_f7750d054a278f319238a44a6a071770 --> <!-- START_d9afb6a754e2fb1d61cb859a7e340ea0 --> ## venues/{id}/uploads-edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Venue] 1" } ``` ### HTTP Request `GET venues/{id}/uploads-edit` <!-- END_d9afb6a754e2fb1d61cb859a7e340ea0 --> <!-- START_426fe28536b519c9b9335ad97c49d1a8 --> ## venues/{id}/uploads-edit > Example request: ```bash curl -X POST \ "http://moveme.test/venues/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST venues/{id}/uploads-edit` <!-- END_426fe28536b519c9b9335ad97c49d1a8 --> <!-- START_910bfcc4e69212f7976cec2af85b85cd --> ## venues/{town}/pdfs > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/1/pdfs" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/pdfs" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (500): ```json { "message": "Server Error" } ``` ### HTTP Request `GET venues/{town}/pdfs` <!-- END_910bfcc4e69212f7976cec2af85b85cd --> <!-- START_d5b211d39c66b6fc35447689817f6886 --> ## venues/{town}/address-labels > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/1/address-labels" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/address-labels" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET venues/{town}/address-labels` <!-- END_d5b211d39c66b6fc35447689817f6886 --> <!-- START_89c8dece483cc94efab30b22722efc86 --> ## venues/{town}/qrcode-labels > Example request: ```bash curl -X GET \ -G "http://moveme.test/venues/1/qrcode-labels" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/venues/1/qrcode-labels" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (200): ```json null ``` ### HTTP Request `GET venues/{town}/qrcode-labels` <!-- END_89c8dece483cc94efab30b22722efc86 --> <!-- START_659d897ca9e21fc71f49ade4b8c9a53b --> ## saveproperty/{id} > Example request: ```bash curl -X POST \ "http://moveme.test/saveproperty/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/saveproperty/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST saveproperty/{id}` <!-- END_659d897ca9e21fc71f49ade4b8c9a53b --> <!-- START_d2be89a0404b3a9d05e217ea3b6c7940 --> ## unsaveproperty/{id} > Example request: ```bash curl -X POST \ "http://moveme.test/unsaveproperty/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/unsaveproperty/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST unsaveproperty/{id}` <!-- END_d2be89a0404b3a9d05e217ea3b6c7940 --> <!-- START_8d6b1d7a8d2c648cf9764f807f460854 --> ## admin/searchvenues > Example request: ```bash curl -X POST \ "http://moveme.test/admin/searchvenues" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/searchvenues" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/searchvenues` <!-- END_8d6b1d7a8d2c648cf9764f807f460854 --> <!-- START_2fb5718ba335cb7d5b6a2bb3b67b4951 --> ## admin/searchvenuetowns > Example request: ```bash curl -X POST \ "http://moveme.test/admin/searchvenuetowns" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/searchvenuetowns" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/searchvenuetowns` <!-- END_2fb5718ba335cb7d5b6a2bb3b67b4951 --> <!-- START_249c33237ac808c68decd4efff488216 --> ## admin/properties/{id}/{property}/addphotos > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/properties/1/1/addphotos" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/properties/1/1/addphotos" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (404): ```json { "message": "No query results for model [App\\Property] 1" } ``` ### HTTP Request `GET admin/properties/{id}/{property}/addphotos` <!-- END_249c33237ac808c68decd4efff488216 --> <!-- START_e40bc60a458a9740730202aaec04f818 --> ## admin > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin` <!-- END_e40bc60a458a9740730202aaec04f818 --> <!-- START_03e266f5d4d4b8f68612eeec7fa8c6ae --> ## admin/property > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/property" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/property" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/property` <!-- END_03e266f5d4d4b8f68612eeec7fa8c6ae --> <!-- START_c5c8bacafac86b1e68a66fac811e8733 --> ## admin/venue > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/venue" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/venue" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/venue` <!-- END_c5c8bacafac86b1e68a66fac811e8733 --> <!-- START_69f00dbddcd7762458c3d423a545206d --> ## admin/event > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/event" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/event" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/event` <!-- END_69f00dbddcd7762458c3d423a545206d --> <!-- START_b1e084c9ad3ddeb3f7a7058a4c5f8687 --> ## admin/town > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/town" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/town" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/town` <!-- END_b1e084c9ad3ddeb3f7a7058a4c5f8687 --> <!-- START_83279d6155c1499f6c34a50595cae12c --> ## Display a listing of the resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/permission" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/permission" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/permission` <!-- END_83279d6155c1499f6c34a50595cae12c --> <!-- START_ceb7a75690d365dd64967ceaf36dae81 --> ## Show the form for creating a new resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/permission/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/permission/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/permission/create` <!-- END_ceb7a75690d365dd64967ceaf36dae81 --> <!-- START_deeb2b5a20a84b3aba5132baaf0b9d1f --> ## Store a newly created resource in storage. > Example request: ```bash curl -X POST \ "http://moveme.test/admin/permission" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/permission" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/permission` <!-- END_deeb2b5a20a84b3aba5132baaf0b9d1f --> <!-- START_11101f22e3cefe1b2df0ba6e676d4d40 --> ## Display the specified resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/permission/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/permission/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/permission/{permission}` <!-- END_11101f22e3cefe1b2df0ba6e676d4d40 --> <!-- START_9e9ecbeef32a6f6dfb84cc17d6f01300 --> ## Show the form for editing the specified resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/permission/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/permission/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/permission/{permission}/edit` <!-- END_9e9ecbeef32a6f6dfb84cc17d6f01300 --> <!-- START_9dc2feebeb72ff08beaba6c6323f7fba --> ## Update the specified resource in storage. > Example request: ```bash curl -X PUT \ "http://moveme.test/admin/permission/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/permission/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "PUT", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `PUT admin/permission/{permission}` `PATCH admin/permission/{permission}` <!-- END_9dc2feebeb72ff08beaba6c6323f7fba --> <!-- START_a00b2a629713d7b654e2f5aa0659ada4 --> ## Remove the specified resource from storage. > Example request: ```bash curl -X DELETE \ "http://moveme.test/admin/permission/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/permission/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "DELETE", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `DELETE admin/permission/{permission}` <!-- END_a00b2a629713d7b654e2f5aa0659ada4 --> <!-- START_82f68f2b49601191068d2a3e52f6bc8b --> ## Display a listing of the resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/role" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/role" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/role` <!-- END_82f68f2b49601191068d2a3e52f6bc8b --> <!-- START_13259a0edd4278fbb67d6176d6efeea9 --> ## Show the form for creating a new resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/role/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/role/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/role/create` <!-- END_13259a0edd4278fbb67d6176d6efeea9 --> <!-- START_64c5083082f51f02e9c59f23549e1341 --> ## Store a newly created resource in storage. > Example request: ```bash curl -X POST \ "http://moveme.test/admin/role" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/role" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/role` <!-- END_64c5083082f51f02e9c59f23549e1341 --> <!-- START_d05bc13bf03325fe0912623be4c78b25 --> ## Display the specified resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/role/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/role/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/role/{role}` <!-- END_d05bc13bf03325fe0912623be4c78b25 --> <!-- START_31bad7bd8379b0fff4dc61933b3899bf --> ## Show the form for editing the specified resource. > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/role/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/role/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/role/{role}/edit` <!-- END_31bad7bd8379b0fff4dc61933b3899bf --> <!-- START_06c4eb4f0da941a29b2da741c4339aad --> ## Update the specified resource in storage. > Example request: ```bash curl -X PUT \ "http://moveme.test/admin/role/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/role/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "PUT", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `PUT admin/role/{role}` `PATCH admin/role/{role}` <!-- END_06c4eb4f0da941a29b2da741c4339aad --> <!-- START_4acd49ff83e61527371e78c2982b2667 --> ## Remove the specified resource from storage. > Example request: ```bash curl -X DELETE \ "http://moveme.test/admin/role/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/role/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "DELETE", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `DELETE admin/role/{role}` <!-- END_4acd49ff83e61527371e78c2982b2667 --> <!-- START_bd487ab94d8034c2d13644bb1772fdfa --> ## admin/user > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/user" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/user" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/user` <!-- END_bd487ab94d8034c2d13644bb1772fdfa --> <!-- START_85482a73dd59bd3ef1adaab154cc5407 --> ## admin/user/create > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/user/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/user/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/user/create` <!-- END_85482a73dd59bd3ef1adaab154cc5407 --> <!-- START_71dba47ec1215d1147a3f8e59c55751a --> ## admin/user > Example request: ```bash curl -X POST \ "http://moveme.test/admin/user" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/user" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/user` <!-- END_71dba47ec1215d1147a3f8e59c55751a --> <!-- START_3b3de25d21f37e1748b345027c37ce73 --> ## admin/user/{user} > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/user/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/user/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/user/{user}` <!-- END_3b3de25d21f37e1748b345027c37ce73 --> <!-- START_8dbd3c8dace74c8cc20dbdadc3a61eed --> ## admin/user/{user}/edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/user/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/user/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/user/{user}/edit` <!-- END_8dbd3c8dace74c8cc20dbdadc3a61eed --> <!-- START_7bc8a51548d7c6e9ac5bc7dda1263ba7 --> ## admin/user/{user} > Example request: ```bash curl -X PUT \ "http://moveme.test/admin/user/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/user/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "PUT", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `PUT admin/user/{user}` `PATCH admin/user/{user}` <!-- END_7bc8a51548d7c6e9ac5bc7dda1263ba7 --> <!-- START_b8a25da15b804e04ecaa4bf05806041e --> ## admin/user/{user} > Example request: ```bash curl -X DELETE \ "http://moveme.test/admin/user/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/user/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "DELETE", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `DELETE admin/user/{user}` <!-- END_b8a25da15b804e04ecaa4bf05806041e --> <!-- START_4240f67a0da95f5d725a063d58c67810 --> ## changePropertyStatus > Example request: ```bash curl -X GET \ -G "http://moveme.test/changePropertyStatus" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/changePropertyStatus" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET changePropertyStatus` <!-- END_4240f67a0da95f5d725a063d58c67810 --> <!-- START_b8bf488f2513fc2ff329eff5ca14d8bd --> ## changeVenueStatus > Example request: ```bash curl -X GET \ -G "http://moveme.test/changeVenueStatus" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/changeVenueStatus" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET changeVenueStatus` <!-- END_b8bf488f2513fc2ff329eff5ca14d8bd --> <!-- START_f740a1c1b06aed255343b83267c5fb09 --> ## admin/venues/create > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/venues/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/venues/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/venues/create` <!-- END_f740a1c1b06aed255343b83267c5fb09 --> <!-- START_5d0dc3587fc8e4b2eb095ba6a1657a36 --> ## admin/venues/create > Example request: ```bash curl -X POST \ "http://moveme.test/admin/venues/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/venues/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/venues/create` <!-- END_5d0dc3587fc8e4b2eb095ba6a1657a36 --> <!-- START_44bf94ab8d6d949bd54987c0d92d2e3e --> ## admin/venues/{id}/edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/venues/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/venues/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/venues/{id}/edit` <!-- END_44bf94ab8d6d949bd54987c0d92d2e3e --> <!-- START_ba768473438477a4eb942f4351378efd --> ## admin/venues/{id}/edit > Example request: ```bash curl -X POST \ "http://moveme.test/admin/venues/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/venues/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/venues/{id}/edit` <!-- END_ba768473438477a4eb942f4351378efd --> <!-- START_be677fdc7fdfa2c2591bce0fbfa6ddef --> ## admin/venues/{id}/uploads-edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/venues/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/venues/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/venues/{id}/uploads-edit` <!-- END_be677fdc7fdfa2c2591bce0fbfa6ddef --> <!-- START_0e2981bbee2b8a61e9a5cc0c9a37ab72 --> ## admin/venues/{id}/uploads-edit > Example request: ```bash curl -X POST \ "http://moveme.test/admin/venues/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/venues/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/venues/{id}/uploads-edit` <!-- END_0e2981bbee2b8a61e9a5cc0c9a37ab72 --> <!-- START_b9bcdc142b61fd13be7a640a1b8f1888 --> ## admin/charts > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/charts" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/charts" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/charts` <!-- END_b9bcdc142b61fd13be7a640a1b8f1888 --> <!-- START_2000017e8f22b8914d503292c2107059 --> ## Fetch the particular company details > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/charts/chart" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/charts/chart" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/charts/chart` <!-- END_2000017e8f22b8914d503292c2107059 --> <!-- START_eceeee62f7792c3f49c89123e82bb181 --> ## admin/events/create > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/events/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/events/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/events/create` <!-- END_eceeee62f7792c3f49c89123e82bb181 --> <!-- START_cf17a57542fb400d4eadfbbec4610699 --> ## admin/events/create > Example request: ```bash curl -X POST \ "http://moveme.test/admin/events/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/events/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/events/create` <!-- END_cf17a57542fb400d4eadfbbec4610699 --> <!-- START_ae6e9e26db71a68a33369e171c1e1f92 --> ## admin/events/{id}/edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/events/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/events/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/events/{id}/edit` <!-- END_ae6e9e26db71a68a33369e171c1e1f92 --> <!-- START_4201ba7ec46e33b9e590b438cc40457c --> ## admin/events/{id}/edit > Example request: ```bash curl -X POST \ "http://moveme.test/admin/events/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/events/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/events/{id}/edit` <!-- END_4201ba7ec46e33b9e590b438cc40457c --> <!-- START_47af33db986554ea6dfd7d67df1f86c3 --> ## admin/events/{id}/uploads-edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/events/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/events/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/events/{id}/uploads-edit` <!-- END_47af33db986554ea6dfd7d67df1f86c3 --> <!-- START_a4c0e7abc8318e986a48261bdb39a085 --> ## admin/events/{id}/uploads-edit > Example request: ```bash curl -X POST \ "http://moveme.test/admin/events/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/events/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/events/{id}/uploads-edit` <!-- END_a4c0e7abc8318e986a48261bdb39a085 --> <!-- START_af39cbccabb255b364d6f0f9f375262f --> ## admin/event/delete/{id} > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/event/delete/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/event/delete/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/event/delete/{id}` <!-- END_af39cbccabb255b364d6f0f9f375262f --> <!-- START_4c2f674ed85f3c7e530dbe45d33da5de --> ## admin/event/withsoftdelete > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/event/withsoftdelete" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/event/withsoftdelete" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/event/withsoftdelete` <!-- END_4c2f674ed85f3c7e530dbe45d33da5de --> <!-- START_a76abc340e356b21acfa65fc3b8a5a47 --> ## admin/event/softdeleted > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/event/softdeleted" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/event/softdeleted" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/event/softdeleted` <!-- END_a76abc340e356b21acfa65fc3b8a5a47 --> <!-- START_de59d0052532e063cc993d78b8ebf9e7 --> ## admin/event/{id} > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/event/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/event/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/event/{id}` <!-- END_de59d0052532e063cc993d78b8ebf9e7 --> <!-- START_2bd0bc54b11d67264cf4e5528460a7ee --> ## admin/event/deletesoft/{id} > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/event/deletesoft/1" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/event/deletesoft/1" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/event/deletesoft/{id}` <!-- END_2bd0bc54b11d67264cf4e5528460a7ee --> <!-- START_1e18f902259f1f674f1228597096fb17 --> ## admin/properties/create > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/properties/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/properties/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/properties/create` <!-- END_1e18f902259f1f674f1228597096fb17 --> <!-- START_f7470d45e4dc091ec12e4c494a5578b4 --> ## admin/properties/create > Example request: ```bash curl -X POST \ "http://moveme.test/admin/properties/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/properties/create" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/properties/create` <!-- END_f7470d45e4dc091ec12e4c494a5578b4 --> <!-- START_1c7fd5b710bead40ae3eaab3f64a7ce8 --> ## admin/properties/{id}/edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/properties/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/properties/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/properties/{id}/edit` <!-- END_1c7fd5b710bead40ae3eaab3f64a7ce8 --> <!-- START_2467dc4444701c7874458b0c4d7be5e8 --> ## admin/properties/{id}/edit > Example request: ```bash curl -X POST \ "http://moveme.test/admin/properties/1/edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/properties/1/edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/properties/{id}/edit` <!-- END_2467dc4444701c7874458b0c4d7be5e8 --> <!-- START_154e8d53b369f4e47641f57e8484854a --> ## admin/propertyphoto/add > Example request: ```bash curl -X POST \ "http://moveme.test/admin/propertyphoto/add" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/propertyphoto/add" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/propertyphoto/add` <!-- END_154e8d53b369f4e47641f57e8484854a --> <!-- START_e8b7625a5a69d470246295bc8564e9ba --> ## admin/properties/{id}/uploads-edit > Example request: ```bash curl -X GET \ -G "http://moveme.test/admin/properties/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/properties/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "GET", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` > Example response (403): ```json { "message": "User is not logged in." } ``` ### HTTP Request `GET admin/properties/{id}/uploads-edit` <!-- END_e8b7625a5a69d470246295bc8564e9ba --> <!-- START_84a446a9bb1f5ee0666e043bd4e3c28a --> ## admin/properties/{id}/uploads-edit > Example request: ```bash curl -X POST \ "http://moveme.test/admin/properties/1/uploads-edit" \ -H "Content-Type: application/json" \ -H "Accept: application/json" ``` ```javascript const url = new URL( "http://moveme.test/admin/properties/1/uploads-edit" ); let headers = { "Content-Type": "application/json", "Accept": "application/json", }; fetch(url, { method: "POST", headers: headers, }) .then(response => response.json()) .then(json => console.log(json)); ``` ### HTTP Request `POST admin/properties/{id}/uploads-edit` <!-- END_84a446a9bb1f5ee0666e043bd4e3c28a --> <file_sep>/app/Http/Controllers/VenueAPIController.php <?php namespace App\Http\Controllers; use App\Http\Resources\VenueResource; use App\Http\Resources\VenueResourceCollection; use App\Venue; use Illuminate\Http\Request; class VenueAPIController extends Controller { /** * @return VenueResourceCollection */ public function index(): VenueResourceCollection { return new VenueResourceCollection(Venue::paginate(100)); } /** * @param Venue $venue * @return VenueResource */ public function show(Venue $venue): VenueResource { return new VenueResource($venue); } /** * @param Request $request * @return VenueResource */ public function store(Request $request) { $request->validate([ 'venuename'=>'required', 'venuetype'=>'required', 'address'=>'required', 'town'=>'required', 'county'=>'required', 'postcode'=>'required', 'latitude'=>'required', 'longitude'=>'required', 'telephone'=>'required' ]); $venue = Venue::create($request->all()); return new VenueResource($venue); } public function update(Venue $venue, Request $request): VenueResource { //update our venue $venue->update($request->all()); return new VenueResource($venue); } /** * @param Venue $venue * @return \Illuminate\Http\JsonResponse * @throws \Exception */ public function destroy(Venue $venue) { $venue->delete(); return response()->json(); } } <file_sep>/app/Http/Controllers/PropertyController.php <?php namespace App\Http\Controllers; use App\Company; use App\PropertyPhotos; use Auth; use Illuminate\Http\Request; use App\Property; use Validator; use Illuminate\Support\Facades\Log; use App\Http\Requests\PropertyPostRequest; use Mapper; class PropertyController extends Controller { public function __construct() { $this->middleware('company', ['except'=>array('index','show','interest','allProperties')]); } public function index() { $properties = Property::where('is_live',1)->inRandomOrder()->paginate(8); $allproperties = Property::all(); Mapper::map(50.8319292,-0.3155225, [ 'zoom' => 12, 'marker' => false, 'cluster' => false ]); foreach ($allproperties as $p) { Mapper::marker($p->latitude, $p->longitude); Mapper::informationWindow($p->latitude, $p->longitude, '<a href="/properties/'.$p->id.'/'.$p->slug.'">'.$p->propname.'</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); } // Mapper::marker($properties->latitude, $properties->longitude); $companies = Company::inRandomOrder()->paginate(4); if (Auth::check()) { $loggedin = true; } else { $loggedin = false; } return view('welcome', compact('properties', 'allproperties', 'companies', 'loggedin')); } public function myProperty() { $properties = Property::where('user_id',auth()->user()->id)->get(); return view('properties.myproperty', compact('properties')); } public function edit($id) { $property = Property::findOrFail($id); return view('properties.edit', compact('property')); } public function update(Request $request, $id) { $property = Property::findOrFail($id); $property->update($request->all()); return redirect()->back()->with('message','Property successfully updated!'); } public function propuploadsedit($id) { $property = Property::findOrFail($id); return view('properties.uploads-edit', compact('property')); } public function propImageUpdate(Request $request, $id) { $property = Property::findOrFail($id); Log::info('This Property: '.$property.''); $propertyphoto = $request->file('propimage')->store('public/property/photos'); $property->update([ 'propimage'=>$propertyphoto, ]); return redirect()->back()->with('message','Property image updated!'); } public function show($id,Property $property) { Mapper::map($property->latitude,$property->longitude, ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); if (Auth::check()) { $loggedin = true; } else { $loggedin = false; } return view('properties.show',compact('property', 'loggedin')); } public function addphotos($id, Property $property) { $propertyPhotos = PropertyPhotos::where('property_id', '=', $id) ->get(); $params = array_merge(['propertyId' => $id, 'photos' => $propertyPhotos], compact('property')); return view('properties.addphotos', $params); } public function propertyPhoto(Request $request) { $rules = array( // 'file' => 'required' ); $error = Validator::make($request->all(), $rules); if($error->fails()) { return response()->json(['errors' => $error->errors()->all()]); } $user_id = auth()->user()->id; $propertyphoto = $request->file('property_photo')->store('public/property/photos'); PropertyPhotos::create([ 'user_id'=>$user_id, 'property_id'=>request('property_id'), 'photo_title'=>request('photo_title'), 'photo'=>$propertyphoto ]); return redirect()->back()->with('message','Photo Added to property!'); } public function create() { return view('properties.create'); } public function store(PropertyPostRequest $request) { $user_id = auth()->user()->id; $company = Company::where('user_id',$user_id)->first(); $company_id = $company->id; $propertyphoto = $request->file('propimage')->store('public/property/photos'); $floorplan = $request->file('floorplan')->store('public/property/brochure'); $brochure = $request->file('brochure')->store('public/property/floorplan'); $requestedtown = request('town'); if($requestedtown == ''){ $requestedtown = request('othertown'); } Property::create([ 'user_id'=>$user_id, 'company_id'=>$company_id, 'propname'=>request('propname'), 'slug'=>str_slug(request('propname')), 'propcost'=>request('propcost'), 'proptype_id'=>request('proptype_id'), 'propimage'=>$propertyphoto, 'bedroom'=>request('bedroom'), 'bathroom'=>request('bathroom'), 'kitchen'=>request('kitchen'), 'garage'=>request('garage'), 'reception'=>request('reception'), 'conservatory'=>request('conservatory'), 'outbuilding'=>request('outbuilding'), 'address'=>request('address'), 'town'=>$requestedtown, 'county'=>request('county'), 'postcode'=>request('postcode'), 'latitude'=>request('latitude'), 'longitude'=>request('longitude'), 'short_summary'=>request('short_summary'), 'summary'=>request('summary'), 'description'=>request('description'), 'floorplan'=>$floorplan, 'brochure'=>$brochure, 'last_date'=>request('last_date'), 'category_id'=>request('category_id'), 'is_featured'=>request('is_featured'), 'is_live'=>request('is_live') ]); //LOGGING Log::info('Property Name: '.request('propname').''); return redirect()->back()->with('message','Property added successfully!'); } public function uploadImage(Request $request) { if($request->hasFile('upload')) { //get filename with extension $filenamewithextension = $request->file('upload')->getClientOriginalName(); //get filename without extension $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME); //get file extension $extension = $request->file('upload')->getClientOriginalExtension(); //filename to store $filenametostore = $filename.'_'.time().'.'.$extension; //Upload File $request->file('upload')->storeAs('public/uploads', $filenametostore); $CKEditorFuncNum = $request->input('CKEditorFuncNum'); $url = asset('storage/uploads/'.$filenametostore); $msg = 'Image successfully uploaded'; $re = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>"; // Render HTML output @header('Content-type: text/html; charset=utf-8'); echo $re; } } public function interest(Request $request, $id) { $propertyid = Property::findOrFail($id); $propertyid->users()->attach(Auth::user()->id); return redirect()->back()->with('message','Interest was sent!'); } public function applicant() { $applicants = Property::has('users')->where('user_id', auth()->user()->id)->get(); return view('properties.applicants', compact('applicants')); } public function allProperties(Request $request) { $propname = request('propname'); $minbeds = request('bedroom'); $proptype_id = request('proptype_id'); $category_id = request('category_id'); $town = request('town'); if (Auth::check()) { $loggedin = true; } else { $loggedin = false; } $query = Property::query(); $query->paginate(20); if($propname||$minbeds||$proptype_id||$category_id||$town) { $properties = Property::when($propname, function ($query) use ($propname) { return $query->orWhere('propname', 'LIKE', "%".$propname."%"); }) ->when($proptype_id, function ($query) use ($proptype_id) { return $query->orWhere('proptype_id', $proptype_id); }) ->when($minbeds, function ($query) use ($minbeds) { return $query->orWhere('bedroom', $minbeds); }) ->when($category_id, function ($query) use ($category_id) { return $query->orWhere('category_id', $category_id); }) ->when($town, function ($query) use ($town) { return $query->orWhere('town', $town); })->paginate(20); // dd($properties); Mapper::map(50.8319292,-0.3155225, [ 'zoom' => 12, 'marker' => false, 'cluster' => false ]); foreach ($properties as $p) { Mapper::marker($p->latitude, $p->longitude); Mapper::informationWindow($p->latitude, $p->longitude, '<a href="/properties/'.$p->id.'/'.$p->slug.'">'.$p->propname.'</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); } return view('properties.allproperties', compact('properties','loggedin')); } else { $properties = Property::latest()->where('is_live',1)->paginate(20); Mapper::map(50.8319292,-0.3155225, [ 'zoom' => 12, 'marker' => false, 'cluster' => false ]); foreach ($properties as $p) { Mapper::marker($p->latitude, $p->longitude); Mapper::informationWindow($p->latitude, $p->longitude, '<a href="/properties/'.$p->id.'/'.$p->slug.'">'.$p->propname.'</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); } return view('properties.allproperties', compact('properties','loggedin')); } } public function toggleLive(Request $request) { $property = Property::find($request->id); $property->is_live = $request->is_live; $property->save(); return redirect()->back(); } } <file_sep>/app/Http/Controllers/EventController.php <?php namespace App\Http\Controllers; use App\Event; use App\Http\Requests\EventPostRequest; use App\Http\Resources\EventResource; use App\Http\Resources\EventResourceCollection; use App\Venue; use Illuminate\Support\Facades\Auth; use Mapper; use Illuminate\Http\Request; class EventController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $eventslist = Event::latest()->where('is_live',1)->paginate(52); $events = Event::get(); $towns = Venue::select('town')->distinct()->get(); Mapper::map(50.8319292,-0.3155225, [ 'zoom' => 12, 'marker' => false, 'cluster' => false ]); foreach ($eventslist as $e) { Mapper::marker($e->venue->latitude, $e->venue->longitude); Mapper::informationWindow($e->venue->latitude, $e->venue->longitude, '<a href="/venues/' . str_slug($e->venue->town) . '/' . str_slug($e->venue->venuename) . '/'. $e->venue->id .'">' . $e->venue->venuename . '</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/secondary_map_marker.png', 'scale' => 100]]); } return view('events.all', compact( 'events', 'towns', 'eventslist')); } /** * @param Event $event * @return EventResource */ public function show(Event $event): EventResourceCollection { return new EventResource($event); } // public function show($id) // { // $event = Event::findOrFail($id); // $venueid = $event->venue_id; // $thevenue = Venue::findOrFail($venueid); // return view('events.show', compact( // 'event', // 'venueid', // 'thevenue' // )); // } private function notFoundMessage() { return [ 'code' => 404, 'message' => 'Note not found', 'success' => false, ]; } private function successfulMessage($code, $message, $status, $count, $payload) { return [ 'code' => $code, 'message' => $message, 'success' => $status, 'count' => $count, 'data' => $payload, ]; } public function permanentDelete($id) { $event = Event::destroy($id); if ($event) { $response = $this->successfulMessage(200, 'Successfully deleted', true, 0, $event); } else { $response = $this->notFoundMessage(); } //return response($response); return redirect('admin/event/softdeleted'); } public function eventsWithSoftDelete() { $events = Event::withTrashed()->get(); $response = $this->successfulMessage(200, 'Successfully', true, $events->count(), $events); // return response($response); return redirect('admin/event'); } public function softDeleted() { $events = Event::onlyTrashed()->get(); $response = $this->successfulMessage(200, 'Successfully', true, $events->count(), $events); // return response($response); return view('administration.admineventsdeleted', compact('events')); } public function restoreDeletedEvent($id) { $event = Event::onlyTrashed()->find($id); $events = Event::onlyTrashed()->get(); if (!is_null($event)) { $event->restore(); $response = $this->successfulMessage(200, 'Successfully restored', true, $event->count(), $event); } else { return response($response); } return redirect('admin/event'); // return view('administration.admineventsdeleted', compact('events')); } public function permanentDeleteSoftDeleted($id) { $event = Event::onlyTrashed()->find($id); if (!is_null($event)) { $event->forceDelete(); $response = $this->successfulMessage(200, 'Successfully deleted', true, 0, $event); } else { return response($response); } // return response($response); return redirect('admin/event'); } public function eventCreate() { $venueid = Auth::user()->venue_id; $thevenue = Venue::findOrFail($venueid); //dd($thevenue); return view('events.create', compact('venueid', 'thevenue')); } public function eventStore(EventPostRequest $request) { $eventphoto = $request->file('eventPhoto')->store('public/events/photos'); Event::create([ 'venue_id'=>request('venue_id'), 'eventName'=>request('eventName'), 'slug'=>str_slug(request('eventName')), 'eventPhoto'=>$eventphoto, 'eventDate'=>request('eventDate'), 'eventTimeStart'=>request('eventTimeStart'), 'eventTimeEnd'=>request('eventTimeEnd'), 'eventType'=>request('eventType'), 'eventCost'=>request('eventCost') ]); return redirect()->back()->with('message','Event added successfully!'); } public function eventEdit($id) { $event = Event::findOrFail($id); return view('events.edit', compact('event')); } public function eventUpdate(Request $request, $id) { $event = Event::findOrFail($id); if ($request->file('eventPhoto') != ''){ $eventphoto = $request->file('eventPhoto')->store('public/events/photos'); $event->update([ 'eventPhoto'=>$eventphoto, ]); } $event->update([ 'venue_id'=>request('venue_id'), 'eventName'=>request('eventName'), 'slug'=>str_slug(request('eventName')), 'eventDate'=>request('eventDate'), 'eventTimeStart'=>request('eventTimeStart'), 'eventTimeEnd'=>request('eventTimeEnd'), 'eventType'=>request('eventType'), 'eventCost'=>request('eventCost') ]); return redirect()->back()->with('message','Event successfully updated!'); } public function eventuploadsedit($id) { $event = Event::findOrFail($id); return view('events.uploads-edit', compact('event')); } public function eventImageUpdate(Request $request, $id) { $event = Venue::findOrFail($id); $eventphoto = $request->file('eventPhoto')->store('public/events/photos'); $event->update([ 'eventPhoto'=>$eventphoto, ]); return redirect()->back()->with('message','Event image updated!'); } } <file_sep>/database/migrations/2020_03_15_172208_create_venues_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVenuesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('venues', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('venuename'); $table->string('venuetype')->nullable(); $table->string('address'); $table->string('address2')->nullable(); $table->string('town'); $table->string('county')->nullable(); $table->string('postcode'); $table->string('postalsearch'); $table->string('telephone')->nullable(); $table->string('latitude'); $table->string('longitude'); $table->string('website')->nullable(); $table->string('photo')->default('venue-default.png'); $table->integer('is_live')->default('1'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('venues'); } } <file_sep>/app/Tagin.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Spatie\Activitylog\Traits\LogsActivity; class Tagin extends Model { use Notifiable, LogsActivity; protected $guarded = []; public function venue() { return $this->belongsTo(Venue::class); } } <file_sep>/database/migrations/2020_02_10_202332_create_properties_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePropertiesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('properties', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('slug'); $table->integer('user_id'); $table->integer('company_id'); $table->string('propname'); $table->integer('propcost'); $table->integer('proptype_id'); $table->string('propimage'); $table->integer('bedroom')->default(0); $table->integer('bathroom')->default(0); $table->integer('kitchen')->default(0); $table->integer('garage')->default(0); $table->integer('reception')->default(0); $table->integer('conservatory')->default(0); $table->integer('outbuilding')->default(0); $table->string('address'); $table->string('town'); $table->string('county'); $table->string('postcode'); $table->string('latitude'); $table->string('longitude'); $table->string('description'); $table->string('floorplan'); $table->string('brochure'); $table->date('last_date'); $table->integer('category_id'); $table->integer('is_featured')->default(0); $table->integer('is_live')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('properties'); } } <file_sep>/app/Console/Commands/ScrapeConcorde.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; use Goutte\Client; use Symfony\Component\HttpClient\HttpClient; class ScrapeConcorde extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'scraper:c2'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // // $client = new Client(); // $crawler = $client->request('GET', 'https://www.allgigs.co.uk/view/venue/140/Concorde-2-Brighton.html'); // // $links = $crawler->filter('a.url')->each(function($node) { // $href = $node->attr('href'); // return $href; // }); // // foreach($links as $key => $link){ $client = new Client(); $crawler = $client->request('GET', 'https://www.ents24.com/brighton-events/concorde-2'); $crawler->filter('img, .when, .what')->each(function ($node) { $image = $node->attr('src'); $date = $node->attr('datetime'); $output = $node->text()."\n"; print_r($date); print_r($image); print_r($output); }); // } } } <file_sep>/app/Console/Commands/everyDay.php <?php namespace App\Console\Commands; use App\Event; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class everyDay extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'day:delete'; /** * The console command description. * * @var string */ protected $description = 'This will clean the events table daily of past events'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $currentDate = Carbon::now(); DB::table('events')->where('eventDate','<=',$currentDate->toDateString())->update(['deleted_at' => $currentDate]); echo $currentDate->toDateString(); } } <file_sep>/app/Property.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Spatie\Activitylog\Traits\LogsActivity; class Property extends Model { use Notifiable, LogsActivity; protected $fillable = ['user_id', 'company_id', 'propname', 'slug', 'propcost', 'proptype_id', 'propimage', 'bedroom', 'bathroom', 'kitchen', 'garage', 'reception', 'conservatory', 'outbuilding', 'address', 'town', 'othertown', 'county', 'postcode', 'latitude', 'longitude', 'short_summary', 'description', 'summary', 'floorplan', 'brochure', 'category_id', 'is_featured', 'is_live']; public function getRouteKeyName() { return 'slug'; } public function company() { return $this->belongsTo('App\Company'); } public function propertyphotos() { return $this->hasMany('App\PropertyPhotos'); } public function users() { return $this->belongsToMany(User::class)->withTimestamps(); } public function checkInterest() { return \DB::table('property_user')->where('user_id', auth()->user()->id) ->where('property_id', $this->id)->exists(); } public function favourites() { return $this->belongsToMany(Property::class, 'favourites', 'prop_id', 'user_id')->withTimestamps(); } public function checkSaved() { return \DB::table('favourites')->where('user_id', auth()->user()->id) ->where('prop_id', $this->id)->exists(); } } <file_sep>/app/Http/Controllers/FavouriteController.php <?php namespace App\Http\Controllers; use App\Property; use Illuminate\Http\Request; class FavouriteController extends Controller { public function saveProperty($id) { $propertyID = Property::find($id); $propertyID->favourites()->attach(auth()->user()->id); return redirect()->back(); } public function unsaveProperty($id) { $propertyID = Property::find($id); $propertyID->favourites()->detach(auth()->user()->id); return redirect()->back(); } } <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use App\Profile; use App\User; use Illuminate\Http\Request; class UserController extends Controller { // public function __construct() // { // $this->middleware('seeker')->except('users'); // } public function index(Request $request) { $keyword = $request->get('search'); $perPage = 25; if (!empty($keyword)) { $user = User::where('name','LIKE',"%$keyword%")->paginate($perPage); } else { $user = User::paginate($perPage); } return view('admin.user.index', compact('user')); } public function profile() { return view('profile.index'); } public function create() { return view('admin.user.create'); } public function show($id) { $user = User::findOrFail($id); return view('admin.user.show', compact('user')); } public function edit($id) { $user = User::findOrFail($id); return view('admin.user.edit', compact('user')); } public function profilestore(Request $request) { $this->validate($request,[ 'address'=>'required', 'phone_number'=>'required|min:10|numeric', ]); $user_id = auth()->user()->id; Profile::where('user_id', $user_id)->update([ 'address'=>request('address'), 'phone_number'=>request('phone_number'), 'experience'=>request('experience'), 'bio'=>request('bio'), ]); return redirect()->back()->with('message','Profile Successfully Updated!'); } public function store(Request $request) { $requestData = $request->except('roles'); $roles=$request->roles; $user = User::create($requestData); $user->assignRole($roles); return redirect('admin/user')->with('flash_message', 'User added!'); } public function update(Request $request, $id) { $requestData = $request->all(); $user = User::findOrFail($id); $user->update($requestData); $user->syncRoles($request->roles); return redirect('admin/user')->with('flash_message', 'User updated!'); } public function coverletter(Request $request) { $this->validate($request,[ 'cover_letter'=>'required|mimes:pdf,doc,docx|max:20000' ]); $user_id = auth()->user()->id; $cover = $request->file('cover_letter')->store('public/files/'); Profile::where('user_id', $user_id)->update([ 'cover_letter'=>$cover ]); return redirect()->back()->with('message','Cover Successfully Updated!'); } public function identification(Request $request) { $this->validate($request,[ 'identification'=>'required' ]); $user_id = auth()->user()->id; $identification = $request->file('identification')->store('public/files/'); Profile::where('user_id', $user_id)->update([ 'identification'=>$identification ]); return redirect()->back()->with('message','Identification Successfully Updated!'); } public function avatar(Request $request) { $this->validate($request,[ 'avatar'=>'required|mimes:png,jpeg,jpg,gif|max:20000' ]); $user_id = auth()->user()->id; if($request->hasFile('avatar')){ $file = $request->file('avatar'); $ext = $file->getClientOriginalExtension(); $filename = time().'.'.$ext; $file->move('uploads/avatar/', $filename); Profile::where('user_id', $user_id)->update([ 'avatar'=>$filename ]); return redirect()->back()->with('message','Profile Successfully Updated!'); } } public function destroy($id) { User::destroy($id); return redirect('admin/user')->with('flash_message', 'User deleted!'); } } <file_sep>/app/Http/Requests/PropertyPostRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class PropertyPostRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'user_id'=>'required', 'propname'=>'required|max:45', 'propcost'=>'required', 'proptype_id'=>'required', 'propimage'=>'required', 'address'=>'required', 'county'=>'required', 'postcode'=>'required', 'latitude'=>'required', 'longitude'=>'required', 'description'=>'required', 'floorplan'=>'required', 'brochure'=>'required', 'category_id'=>'required' ]; } } <file_sep>/app/Company.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Laravel\Cashier\Billable; use Spatie\Activitylog\Traits\LogsActivity; use Spatie\Permission\Traits\HasRoles; class Company extends Model { use Notifiable, LogsActivity, Billable, HasRoles; protected $fillable = [ 'cname', 'user_id', 'slug', 'address', 'telephone', 'website', 'logo', 'cover_photo', 'slogan', 'description', ]; public function getRouteKeyName() { return 'slug'; } public function properties() { return $this->hasMany('App\Property'); } } <file_sep>/app/Http/Controllers/TaginController.php <?php namespace App\Http\Controllers; use App\Tagin; use App\Venue; use Illuminate\Http\Request; class TaginController extends Controller { public function index() { return view('tagins.index'); } /** * Fetch the particular company details * @return json response */ public function chart() { $result = Venue::groupBy('town') ->selectRaw('count(*) as total, town') ->get(); return response()->json($result); } } <file_sep>/app/Http/Controllers/SubscriptionController.php <?php namespace App\Http\Controllers; use App\User; use App\Venue; use Illuminate\Http\Request; class SubscriptionController extends Controller { // public function __construct() { $this->middleware('auth'); } public function index() { return view('subscribe'); } public function payment() { $availablePlans = [ 'price_1HTPqPB9HABsmFZYYSALtKrp'=>"Monthly - £5.00", 'price_1HTQB9B9HABsmFZYy4mQYXWF'=>"Ever 3 months - £15.00" ]; $user = auth()->user(); $data = [ 'intent' => $user->createSetupIntent(), 'plans' => $availablePlans ]; return view('subscribe')->with($data); } public function subscribe(Request $request) { $user = auth()->user(); $venueid = $user->venue_id; $paymentMethod = $request->payment_method; $planId = $request->plan; $user->newSubscription('main', $planId)->create($paymentMethod); // $venueid = Venue::where('user_id',$userid)->get(); // return redirect()->intended('/home')->getTargetUrl(); // return response([ // // 'success_url'=>redirect()->intended('/venue/'.$venueid.'/edit')->getTargetUrl(), // 'message'=>'success' // ]); return response([ 'success' => redirect()->intended('/venue/'.$venueid.'/edit')->getTargetUrl(), 'message' => 'success' ]); } // public function store() // { // return true; // } } <file_sep>/app/Http/Middleware/Authenticate.php <?php namespace App\Http\Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware; class Authenticate extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ protected function redirectTo($request) { if (! $request->expectsJson()) { return route('login'); } } /** * @OA\SecurityScheme( * type="http", * description="Login with email and password to get the authentication token", * name="Token based Based", * in="header", * scheme="bearer", * bearerFormat="JWT", * securityScheme="apiAuth", * ) */ /** * @OA\Get( * path="/resources", * summary="Get the list of resources", * tags={"Resource"}, * @OA\Response(response=200, description="Return a list of resources"), * security={{ "apiAuth": {} }} * ) */ } <file_sep>/app/Profile.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Spatie\Activitylog\Traits\LogsActivity; class Profile extends Model { use Notifiable, LogsActivity; protected $guarded = []; } <file_sep>/resources/js/custom-scripts.js $( document ).ready(function() { $('.date').datepicker({ format: 'yyyy-mm-dd' }); var colorpickerOptions1 = { parts: ['map', 'bar', 'hex', 'hsv', 'rgb', 'alpha', 'preview', 'footer'], altProperties: 'background-color', altField: '.colorpicker1', color: 'cccccc', select: function (event, color) { var color_in_hex_format = color.formatted; console.log(color_in_hex_format); } ,inline: false }; var colorpickerOptions2 = { parts: ['map', 'bar', 'hex', 'hsv', 'rgb', 'alpha', 'preview', 'footer'], altProperties: 'background-color', altField: '.colorpicker2', color: 'cccccc', select: function (event, color) { var color_in_hex_format = color.formatted; console.log(color_in_hex_format); } ,inline: false }; $('.colorpicker1').colorpicker(colorpickerOptions1).prepend('#'); $('.colorpicker2').colorpicker(colorpickerOptions2).prepend('#'); $('.toggle-class').change(function() { var is_live = $(this).prop('checked') == true ? 1 : 0; var property_id = $(this).data('id'); $.ajax({ type: "GET", dataType: "json", url: '/changeStatus', data: {'is_live': is_live, 'id': property_id}, success: function(data){ console.log(data.success) } }); }) $('.toggle-live-property').change(function() { var is_live = $(this).prop('checked') == true ? 1 : 0; var property_id = $(this).data('id'); $.ajax({ type: "GET", dataType: "json", url: '/changePropertyStatus', data: {'is_live': is_live, 'id': property_id}, success: function(data){ console.log(data.success) } }); }) $('.toggle-live-venue').change(function() { var is_live = $(this).prop('checked') == true ? 1 : 0; var venue_id = $(this).data('id'); $.ajax({ type: "GET", dataType: "json", url: '/changeVenueStatus', data: {'is_live': is_live, 'id': venue_id}, success: function(data){ console.log(data.success) } }); }) $("#mapswitchform input:checkbox").change( function() { if( $(this).is(":checked") ) { $("#mapswitchform").submit(); } else { $("#mapswitchform").submit(); } } ) $('#subscription-plan').on('change', function() { if ( this.value == 'price_1HTQB9B9HABsmFZYy4mQYXWF') { $("#three-option").show(); $("#monthly-option").hide(); } else if ( this.value == 'price_1HTPqPB9HABsmFZYYSALtKrp') { $("#three-option").hide(); $("#monthly-option").show(); } }); // $('.grid').masonry({ // // options... // itemSelector: '.grid-item', // columnWidth: 200 // }); }); <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //Route::get('/', 'PropertyController@index'); Route::get('/', 'VenueController@welcome'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); //company Route::get('/company/{id}/{company}', 'CompanyController@index')->name('company.index'); Route::get('/company/create', 'CompanyController@create')->name('company.view'); Route::post('/company/create', 'CompanyController@store')->name('company.store'); Route::post('/company/coverphoto', 'CompanyController@coverPhoto')->name('cover.photo'); Route::post('/company/logo', 'CompanyController@companyLogo')->name('company.logo'); Route::post('/company/branding', 'CompanyController@companyBrand')->name('company.branding'); // Company View Route::View('register/company','register-company')->name('register.company'); Route::post('company/register', 'CompanyRegisterController@companyRegister')->name('company.register'); // Landlord View Route::View('register/landlord','register-landlord')->name('register.landlord'); //Route::View('register/claim','register-claim')->name('register.claim'); Route::get('register/claim','LandlordRegisterController@registerClaim')->name('register.claim'); Route::post('landlord/register', 'LandlordRegisterController@landlordRegister')->name('landlord.register'); Route::get('venue/events/create', 'EventController@eventCreate')->name('event.create'); Route::post('venue/events/create', 'EventController@eventStore')->name('event.store'); Route::get('venue/view', 'LandlordRegisterController@viewVenue')->name('view.venue'); Route::get('venue/{id}/{now}/tagin/stats', 'VenueController@venueTaginstats')->name('venue.venuetaginstats'); //Subscribe Route::get('/subscribe', 'SubscriptionController@payment'); Route::post('/subscribe', 'SubscriptionController@subscribe'); // Landlord Edit Venue Route::get('/venue/{id}/edit', 'VenueController@venueEdit')->name('venue.edit'); Route::post('/venue/{id}/edit', 'VenueController@venueUpdate')->name('venue.update'); // User Profile Route::get('user/profile', 'UserController@profile')->name('user.view'); Route::post('user/profile/create', 'UserController@profilestore')->name('profile.create'); Route::post('user/coverletter', 'UserController@coverletter')->name('cover.letter'); Route::post('user/identification', 'UserController@identification')->name('identification'); Route::post('user/avatar', 'UserController@avatar')->name('avatar'); // Properties Route::get('/properties/{id}/edit', 'PropertyController@edit')->name('property.edit'); Route::post('/properties/{id}/edit', 'PropertyController@update')->name('property.update'); //Route::post('/properties/{id}/edit', 'PropertyController@toggleLive')->name('property.togglelive'); Route::get('/changeStatus', 'PropertyController@toggleLive')->name('property.togglelive'); Route::get('/properties/{id}/uploads-edit', 'PropertyController@propuploadsedit')->name('property.uploadsedit'); Route::post('/properties/{id}/uploads-edit', 'PropertyController@propImageUpdate')->name('property.propImageUpdate'); //Route::post('/properties/{id}/uploads-edit', 'PropertyController@brochureUpdate')->name('property.brochureUpdate'); //Route::post('/properties/{id}/uploads-edit', 'PropertyController@floorplanUpdate')->name('property.floorplanUpdate'); Route::get('/properties/{id}/{property}', 'PropertyController@show')->name('properties.show'); Route::get('/properties/{id}/{property}/addphotos', 'PropertyController@addphotos')->name('properties.addphotos'); Route::post('/propertyphoto/add', 'PropertyController@propertyPhoto')->name('property.photo'); Route::get('/property/create', 'PropertyController@create')->name('property.create')->middleware(['auth','check-subscription']); Route::get('/property/my-property', 'PropertyController@myProperty')->name('property.myproperty'); Route::get('/properties/all-properties', 'PropertyController@allProperties')->name('allproperties'); Route::post('/property/create', 'PropertyController@store')->name('property.store'); Route::post('/property/interest/{id}', 'PropertyController@interest')->name('property.interest'); Route::get('/properties/applications', 'PropertyController@applicant')->name('applicants'); //Events Route::get('/events/all', 'EventController@index')->name('events.show'); Route::get('/events/{id}', 'EventController@show')->name('events.event'); Route::get('qr-code-g', function () { \QrCode::size(500) ->format('png') ->generate('ItSolutionStuff.com', public_path('images/qrcode.png')); return view('qrCode'); }); //Venues Route::get('/venues/all', 'VenueController@index')->name('venues.show'); Route::post('/venues/all', 'VenueController@index')->name('venues'); Route::get('/venues/towns/{town}', 'VenueController@town')->name('venues.town'); Route::get('/venues/{town}/{name}/{id}', 'VenueController@venue')->name('venue.name'); Route::get('/venues/{id}/tagin', 'VenueController@venueTagin')->name('venue.venuetagin'); Route::post('/venues/{id}/tagin/add', 'VenueController@tagin')->name('venue.tagin'); //Route::get('/venues/{id}/edit', 'AdministrationController@venueEdit')->name('venue.edit'); //Route::post('/venues/{id}/edit', 'AdministrationController@venueUpdate')->name('venue.update'); Route::get('/venues/{id}/uploads-edit', 'AdministrationController@venueuploadsedit')->name('venue.uploadsedit'); Route::post('/venues/{id}/uploads-edit', 'AdministrationController@venueImageUpdate')->name('venue.venueImageUpdate'); Route::get('/venues/{town}/pdfs', 'VenueController@pdf')->name('venues.pdf'); Route::get('/venues/{town}/address-labels', 'VenueController@addressLabels')->name('venues.addressLabels'); Route::get('/venues/{town}/qrcode-labels', 'VenueController@qrcodeLabels')->name('venues.qrcodeLabels'); //Save and unsave property Route::post('/saveproperty/{id}', 'FavouriteController@saveProperty'); Route::post('/unsaveproperty/{id}', 'FavouriteController@unsaveProperty'); Route::post('/admin/searchvenues', 'VenueController@searchVenues')->name('search.venues'); Route::post('/admin/searchvenuetowns', 'VenueController@searchVenueTowns')->name('search.venuetowns'); Route::group(['middleware'=>'role:super-agent'], function () { Route::get('/admin/properties/{id}/{property}/addphotos', 'AdministrationController@addphotos')->name('adminproperty.addphotos'); }); Route::group(['middleware'=>'role:super-admin'], function (){ Route::get('/admin', 'AdministrationController@index'); Route::get('/admin/property', 'AdministrationController@property')->name('admin.property'); Route::get('/admin/venue', 'AdministrationController@venue')->name('admin.venue'); Route::get('/admin/event', 'AdministrationController@event')->name('admin.event'); Route::get('/admin/town', 'AdministrationController@town')->name('admin.town'); Route::resource('admin/permission', 'Admin\\PermissionController'); Route::resource('admin/role', 'Admin\\RoleController'); Route::resource('admin/user', 'UserController'); Route::get('/changePropertyStatus', 'AdministrationController@togglePropertyLive')->name('adminproperty.togglelive'); Route::get('/changeVenueStatus', 'AdministrationController@toggleVenueLive')->name('adminvenue.togglelive'); //Edit Venues Route::get('/admin/venues/create', 'AdministrationController@venueCreate')->name('adminvenue.create'); Route::post('/admin/venues/create', 'AdministrationController@venueStore')->name('adminvenue.store'); Route::get('/admin/venues/{id}/edit', 'AdministrationController@venueEdit')->name('adminvenue.edit'); Route::post('/admin/venues/{id}/edit', 'AdministrationController@venueUpdate')->name('adminvenue.update'); Route::get('/admin/venues/{id}/uploads-edit', 'AdministrationController@venueuploadsedit')->name('adminvenue.uploadsedit'); Route::post('/admin/venues/{id}/uploads-edit', 'AdministrationController@venueImageUpdate')->name('adminvenue.venueImageUpdate'); //Charts Route::get('/admin/charts','TaginController@index'); Route::get('/admin/charts/chart','TaginController@chart'); //Edit Events Route::get('/admin/events/create', 'AdministrationController@eventCreate')->name('adminevent.create'); Route::post('/admin/events/create', 'AdministrationController@eventStore')->name('adminevent.store'); Route::get('/admin/events/{id}/edit', 'AdministrationController@eventEdit')->name('adminevent.edit'); Route::post('/admin/events/{id}/edit', 'AdministrationController@eventUpdate')->name('adminevent.update'); Route::get('/admin/events/{id}/uploads-edit', 'AdministrationController@eventuploadsedit')->name('adminevent.uploadsedit'); Route::post('/admin/events/{id}/uploads-edit', 'AdministrationController@eventImageUpdate')->name('adminevent.eventImageUpdate'); //Delete Events Route::get('/admin/event/delete/{id}', 'EventController@permanentDelete')->name('perm.delete'); Route::get('/admin/event/soft/{id}', 'EventController@softDelete'); Route::get('/admin/event/withsoftdelete','EventController@eventsWithSoftDelete'); Route::get('/admin/event/softdeleted','EventController@softDeleted')->name('events.deleted'); Route::get('/admin/event/{id}','EventController@restoreDeletedEvent')->name('event.restoredelete'); Route::get('/admin/event/deletesoft/{id}','EventController@permanentDeleteSoftDeleted')->name('event.permdelete'); //Edit Properties Route::get('/admin/properties/create', 'AdministrationController@propertyCreate')->name('adminproperty.create'); Route::post('/admin/properties/create', 'AdministrationController@propertyStore')->name('adminproperty.store'); Route::get('/admin/properties/{id}/edit', 'AdministrationController@propertyEdit')->name('adminproperty.edit'); Route::post('/admin/properties/{id}/edit', 'AdministrationController@propertyUpdate')->name('adminproperty.update'); Route::get('/admin/properties/{id}/{property}/addphotos', 'AdministrationController@addphotos')->name('adminproperty.addphotos'); Route::post('/admin/propertyphoto/add', 'AdministrationController@propertyPhoto')->name('adminproperty.photo'); Route::get('/admin/properties/{id}/uploads-edit', 'AdministrationController@propuploadsedit')->name('adminproperty.uploadsedit'); Route::post('/admin/properties/{id}/uploads-edit', 'AdministrationController@propImageUpdate')->name('adminproperty.propImageUpdate'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); <file_sep>/README.md <p align="center"><img src="https://github.com/jbiddulph/moveme/blob/master/public/logo/secondary_marker.png" width="400"></p> ## About BN Here BN Here is a web service for people who live in the BN postalcode area who and are interested in local News, Events and Property. <file_sep>/app/Http/Controllers/VenueController.php <?php namespace App\Http\Controllers; use App\Company; use App\Event; use App\Http\Controllers\PDF_Label; use App\Http\Requests\TaginPostRequest; use App\Http\Requests\VenuePostRequest; use App\Http\Resources\VenueResource; use App\Http\Resources\VenueResourceCollection; use App\Property; use App\Tagin; use App\Venue; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Mapper; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; class VenueController extends Controller { /** * @param Venue $venue * @return VenueResource */ public function show(Venue $venue): VenueResourceCollection { return new VenueResource($venue); } public function getVenue(Venue $venue) { return $venue; } public function index(Request $request) { $mapswitch = request('mapswitch'); if($mapswitch == 'on') { $cluster = true; $checked = 'checked'; } else { $cluster = false; $checked = ''; } $venueslist = Venue::latest()->where('is_live',1)->paginate(52); $venues = Venue::get(); $towns = Venue::select('town')->distinct()->get(); Mapper::map(50.8319292,-0.3155225, [ 'zoom' => 12, 'marker' => false, 'cluster' => $cluster ]); if($mapswitch == 'on') { foreach ($venues as $v) { Mapper::marker($v->latitude, $v->longitude); Mapper::informationWindow($v->latitude, $v->longitude, '<a href="/venues/' . str_slug($v->town) . '/' . str_slug($v->venuename) . '/'. $v->id .'">' . $v->venuename . '</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/secondary_map_marker.png', 'scale' => 60]]); } } else { foreach ($venueslist as $v) { Mapper::marker($v->latitude, $v->longitude); Mapper::informationWindow($v->latitude, $v->longitude, '<a href="/venues/' . str_slug($v->town) . '/' . str_slug($v->venuename) . '/'. $v->id .'">' . $v->venuename . '</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/secondary_map_marker.png', 'scale' => 60]]); } } return view('venues.all', compact( 'venues', 'venueslist', 'towns', 'checked')); } public function welcome() { $venues = Venue::where('is_live',1)->inRandomOrder()->paginate(24); $allvenues = Venue::paginate(38); Mapper::map(50.8319292,-0.3155225, [ 'zoom' => 12, 'marker' => false, 'cluster' => false ]); foreach ($allvenues as $p) { Mapper::marker($p->latitude, $p->longitude); Mapper::informationWindow($p->latitude, $p->longitude, '<a href="/venues/'.str_slug($p->town).'/'.str_slug($p->town).'/'.$p->id.'">'.$p->venuename.'</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); } // Mapper::marker($properties->latitude, $properties->longitude); // if (Auth::check()) { // $loggedin = true; // } else { // $loggedin = false; // } return view('welcome', compact('venues', 'allvenues')); } public function searchVenueTowns(Request $request) { $query = $request->get('query'); $data = DB::table('venues')->where('town','LIKE','%'.$query.'%')->get(); // Log::info('Venue Query Here: '.$query.''); // Log::info('Venue Data Here: '.$data.''); $output = '<ul class="dropdown-menu" style="padding:10px; display:block; position:relative; height: 300px; overflow-y: scroll;">'; foreach ($data as $row){ $output .= '<li> <div class="form-check"> <input class="form-check-input" type="radio" name="selectedVenueID" id="'.$row->slug.'" value="'.$row->id.'"> <label class="form-check-label" for="'.$row->slug.'"> '.$row->venuename.', '.$row->town.' </label> </div></li>'; } $output .= '</ul>'; return $output; // return response()->json($data); } public function searchVenues(Request $request) { $query = $request->get('query'); $data = DB::table('venues')->where('venuename','LIKE','%'.$query.'%')->get(); // Log::info('Venue Query Here: '.$query.''); // Log::info('Venue Data Here: '.$data.''); $output = '<ul class="dropdown-menu" style="padding:10px; display:block; position:relative; height: 300px; overflow-y: scroll;">'; foreach ($data as $row){ $output .= '<li> <div class="form-check"> <input class="form-check-input" type="radio" name="selectedVenueID" id="'.$row->slug.'" value="'.$row->id.'"> <label class="form-check-label" for="'.$row->slug.'"> '.$row->venuename.', '.$row->town.' </label> </div></li>'; } $output .= '</ul>'; return $output; } public function town(Request $request, $town) { $venueslist = Venue::latest()->where('is_live',1)->where('town', $town)->paginate(52); $venues = Venue::get(); $towns = Venue::select('town')->distinct()->get(); if($town == 'brighton'){ $town = 'Brighton Sussex'; } elseif($town == 'Brighton') { $town = 'Brighton Sussex'; } if($town == 'Peacehaven'){ $town = 'Peacehaven Sussex'; } Mapper::location($town); Mapper::location($town)->map([ 'zoom' => 14, 'center' => true, 'marker' => false, 'cluster' => false, 'type' => 'ROADMAP']); foreach ($venueslist as $v) { Mapper::marker($v->latitude, $v->longitude); Mapper::informationWindow($v->latitude, $v->longitude, '<a href="/venues/' . str_slug($v->town) . '/' . str_slug($v->venuename) . '/'. $v->id .'">' . $v->venuename . '</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); } return view('venues.town', compact( 'venues', 'venueslist', 'towns')); } public function venue($town, $venue, $id) { $towns = Venue::select('town')->distinct()->get(); $thevenue = Venue::findOrFail($id); $events = Event::latest()->where("venue_id", "=", "$id")->get(); Mapper::map($thevenue->latitude,$thevenue->longitude, [ 'zoom' => 16, 'marker' => true, 'cluster' => false ]); Mapper::informationWindow($thevenue->latitude, $thevenue->longitude, '<a href="/venues/' . str_slug($thevenue->town) . '/' . str_slug($thevenue->venuename) . '/'. $thevenue->id .'">' . $thevenue->venuename . '</a>', ['icon' => ['url' => 'https://bnhere.co.uk/logo/primary_map_marker.png', 'scale' => 100]]); return view('venues.venue', compact( 'towns', 'town', 'venue', 'id', 'thevenue', 'events')); } public function venueTagin($id) { $thevenue = Venue::findOrFail($id); $venue = $thevenue->name; return view('venues.tagin', compact( 'id', 'thevenue', 'venue')); } public function tagin(TaginPostRequest $request) { Tagin::create([ 'venue_id'=>request('venue_id'), 'phone_number'=>request('phone_number'), 'email_address'=>request('email_address'), 'reason_visit'=>request('reason_visit'), 'marketing'=>request('marketing') ]); //LOGGING //Log::info('Phone number: '.request('phone_number').''); return redirect()->back()->with('message','Tagged in successfully!'); } public function pdf($town){ $venueslist = Venue::latest()->where('is_live',1)->where('town', $town)->paginate(52); foreach ($venueslist as $v) { //create pdf document $pdf = app('Fpdf'); $pdf->AddPage(); $pdf->SetFont('Arial','B',14); $qrtagin = "qrcodes/".$v->town."/customers/tagin-".$v->id.".png"; $qrvenue = "qrcodes/".$v->town."/venues/qrcode-".$v->id.".png"; // $address = $v->venuename.'<br />'.$v->address.'<br />'.$v->address2.'<br />'.$v->town.'<br />'.$v->county.'<br />'.$v->postcode.'<br />'.date('Y-m-d').'<br />'; $pdf->Cell(150,8,"\n"); $pdf->Cell(50, 40, $pdf->Image($qrtagin, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'C' ); $pdf->Cell(150,8,$v->venuename."\n"); $pdf->Ln(); $pdf->Cell(150,8,$v->venuename."\n"); $pdf->Ln(); $pdf->Cell(150,8,$v->address."\n"); if($v->address2){ $pdf->Ln(); $pdf->Cell(150,8,$v->address2."\n"); } $pdf->Ln(); $pdf->Cell(150,8,$v->town."\n"); $pdf->Ln(); $pdf->Cell(150,8,$v->county."\n"); $pdf->Ln(); $pdf->Cell(150,8,date("F j, Y")."\n"); // $pdf->Cell( 160, 10, $pdf->Image($qrvenue, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'R', false ); // $pdf->Ln(); // $pdf->Cell(160,8,'Venue QR-Code'."\n", 0, 0, 'R', false); // $pdf->Ln(); // $pdf->Cell(160,20,'Tagin QR-Code'."\n", 1, 1, 'R', false); $pdf->SetFont('Arial','',12); // set some text for example $txt = $v->venuename . ' is currently listed on https://www.bnhere.co.uk. A website directory of venues in Sussex (the BN district) helping these venues with the NHS Test and Trace system. We make it easy for your customers to submit their details privately upon arrival and with their consent. For customer with NFC enabled smart phones, NFC tags (included) can be tapped allowing the customer to easily fill out their details for test and trace. Scanning the QR code of your venue with the a smart phones camera will also allow yoru customer to enter their details. And for just 5 pounds per month, you can claim your venue on https://bnhere.co.uk, edit your venue details, view visitor/customer statistics, add additional photos of your venue and add future events. Have fun and stay safe with a safe distance whilst socialising. BNHERE.CO.UK - Local Track & Trace.'; // print a blox of text using multicell() $pdf->setX(20); $pdf->setY(80); // $pdf->MultiCell(184, 6, $txt."\n",0,0,'L'); $pdf->MultiCell(184, 6, $txt, 0, 'L', 0, 0, '', '', false); //save file Storage::put('/public/letters/'.$town.'/'.$v->venuename.'.pdf', $pdf->Output('S')); } return view('venues.pdf', compact( 'pdf')); } public function qrcodeLabels($town) { $pdf = new PDF_Label('L7163'); $pdf->AddPage(); $venueslist = Venue::latest()->where('is_live',1)->where('town', $town)->paginate(1000); // Print labels foreach ($venueslist as $v) { $qrtagin = "qrcodes/".$v->town."/customers/tagin-".$v->id.".png"; $qrcode = sprintf("%s\n", $pdf->Cell(50, 40, $pdf->Image($qrtagin, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'C' )); $pdf->Add_Label($qrcode); } Storage::put('/public/labels/'.$town.'/qrcodes.pdf', $pdf->Output('S')); return view('venues.addresses', compact( 'pdf')); } public function addressLabels($town) { $pdf = new PDF_Label('L7163'); $pdf->AddPage(); $venueslist = Venue::latest()->where('is_live',1)->where('town', $town)->paginate(1000); // Print labels foreach ($venueslist as $v) { $text = sprintf("%s\n%s%s\n%s\n%s\n%s", "$v->venuename", "$v->address", "$v->address2", "$v->town", "$v->county", "$v->postcode"); $pdf->Add_Label($text); } Storage::put('/public/labels/'.$town.'/addresses.pdf', $pdf->Output('S')); return view('venues.addresses', compact( 'pdf')); } public function venueEdit($id) { $venue = Venue::findOrFail($id); return view('venues.edit', compact('venue')); } public function venueUpdate(Request $request, $id) { $venue = Venue::findOrFail($id); $venue->update($request->all()); return redirect()->back()->with('message','Venue successfully updated!'); } public function venueTaginstats($id, $date) { $selecteddate = $date; $tagins = Tagin::latest()->where('venue_id',$id)->where('created_at', 'like', '%' . $date . '%')->paginate(1000); $data = Tagin::select(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d") as taginDate'))->distinct()->where('venue_id',$id)->orderBy('created_at', 'DESC')->get(); $thevenue = Venue::findOrFail($id); return view('venues.tagins', compact( 'tagins','thevenue', 'data', 'selecteddate')); } } <file_sep>/database/factories/UserFactory.php <?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\User; use Faker\Generator as Faker; use Illuminate\Support\Str; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | This directory should contain each of the model factory definitions for | your application. Factories provide a convenient way to generate new | model instances for testing / seeding your application's database. | */ $factory->define(User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'user_type' => 'seeker', 'email_verified_at' => now(), 'password' => <PASSWORD>', // password 'remember_token' => Str::random(10), ]; }); $factory->define(App\Company::class, function (Faker $faker) { return [ 'user_id' => App\User::all()->random()->id, 'cname'=>$name=$faker->company, 'slug'=>Str::slug($name), 'address'=>$faker->address, 'telephone'=>$faker->phoneNumber, 'website'=>$faker->domainName, 'logo'=>'logo/company-logo.png', 'cover_photo'=>'cover/pier_header.png', 'slogan'=>'letting agents', 'description'=>$faker->paragraph(rand(2,10)) ]; }); $factory->define(App\Property::class, function (Faker $faker) { return [ 'user_id' => App\User::all()->random()->id, 'company_id'=>App\Company::all()->random()->id, 'propname'=>$prop_name=$faker->text(60), 'slug'=>Str::slug($prop_name), 'propcost'=>'399,000', 'proptype_id'=>'1', 'propimage'=>'property/pantiles.jpg', 'address'=>$faker->address, 'town'=>$faker->city, 'postcode'=>$faker->postcode, 'latitude'=>$faker->latitude, 'longitude'=>$faker->longitude, 'description'=>$faker->paragraph(rand(2,10)), 'floorplan'=>'floorplan/penfold.jpg', 'brochure'=>'brochure/penfold.pdf', 'category_id'=>rand(1,5), 'is_live'=>'1', 'description'=>$faker->paragraph(rand(2,10)), 'last_date'=>$faker->dateTime ]; }); <file_sep>/app/Http/Requests/EventPostRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class EventPostRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'eventName'=>'required', 'venue_id'=>'required', 'eventPhoto'=>'required', 'eventDate'=>'required', 'eventTimeStart'=>'required', 'eventTimeEnd'=>'required', 'eventType'=>'required', 'eventCost'=>'required' ]; } } <file_sep>/app/Http/Controllers/AdministrationController.php <?php namespace App\Http\Controllers; use App\Company; use App\Event; use App\Http\Requests\PropertyPostRequest; use App\Http\Requests\VenuePostRequest; use App\Http\Requests\EventPostRequest; use App\Property; use App\PropertyPhotos; use App\User; use App\Profile; use App\Venue; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; class AdministrationController extends Controller { // public function __construct() // { // $this->middleware('admin'); // } public function index() { return view('administration.dashboard'); } public function property() { $properties = Property::all(); return view('administration.adminproperty', compact('properties')); } public function venue() { // Generate QR CODE // ini_set('max_execution_time', 300); // $venueslist = Venue::where('town','Worthing')->get(); // foreach ($venueslist as $v) { // \QrCode::size(500) // ->format('png') // ->generate('https://www.bnhere.co.uk/venues/'.$v->id.'/tagin', public_path('qrcodes/Worthing/customers/tagin-'.$v->id.'.png')); // } $venues = Venue::paginate(52); return view('administration.adminvenue', compact('venues')); } public function event() { $events = Event::paginate(52); return view('administration.adminevent', compact('events')); } public function town() { $towns = Venue::select('town')->distinct()->get(); return view('administration.admintown', compact('towns')); } public function eventCreate() { return view('events.create'); } public function eventStore(EventPostRequest $request) { $eventphoto = $request->file('eventPhoto')->store('public/events/photos'); Event::create([ 'venue_id'=>request('venue_id'), 'eventName'=>request('eventName'), 'slug'=>str_slug(request('eventName')), 'eventPhoto'=>$eventphoto, 'eventDate'=>request('eventDate'), 'eventTimeStart'=>request('eventTimeStart'), 'eventTimeEnd'=>request('eventTimeEnd'), 'eventType'=>request('eventType'), 'eventCost'=>request('eventCost') ]); return redirect()->back()->with('message','Event added successfully!'); } public function eventEdit($id) { $event = Event::findOrFail($id); return view('events.edit', compact('event')); } public function eventUpdate(Request $request, $id) { $event = Event::findOrFail($id); if ($request->file('eventPhoto') != ''){ $eventphoto = $request->file('eventPhoto')->store('public/events/photos'); $event->update([ 'eventPhoto'=>$eventphoto, ]); } $event->update([ 'venue_id'=>request('venue_id'), 'eventName'=>request('eventName'), 'slug'=>str_slug(request('eventName')), 'eventDate'=>request('eventDate'), 'eventTimeStart'=>request('eventTimeStart'), 'eventTimeEnd'=>request('eventTimeEnd'), 'eventType'=>request('eventType'), 'eventCost'=>request('eventCost') ]); return redirect()->back()->with('message','Event successfully updated!'); } public function eventuploadsedit($id) { $event = Event::findOrFail($id); return view('events.uploads-edit', compact('event')); } public function eventImageUpdate(Request $request, $id) { $event = Venue::findOrFail($id); $eventphoto = $request->file('eventPhoto')->store('public/events/photos'); $event->update([ 'eventPhoto'=>$eventphoto, ]); return redirect()->back()->with('message','Event image updated!'); } public function venueCreate() { return view('venues.create'); } public function venueStore(VenuePostRequest $request) { $venuephoto = $request->file('photo')->store('public/venues/photos'); Venue::create([ 'venuename'=>request('venuename'), 'slug'=>str_slug(request('venuename')), 'venuetype'=>request('venuetype'), 'address'=>request('address'), 'photo'=>$venuephoto, 'address2'=>request('address2'), 'town'=>request('town'), 'county'=>request('county'), 'postcode'=>request('postcode'), 'postalsearch'=>request('postalsearch'), 'telephone'=>request('telephone'), 'latitude'=>request('latitude'), 'longitude'=>request('longitude'), 'website'=>request('website') ]); //LOGGING Log::info('Venue Name: '.request('venuename').''); return redirect()->back()->with('message','Venue added successfully!'); } public function venueEdit($id) { $venue = Venue::findOrFail($id); return view('venues.edit', compact('venue')); } public function venueUpdate(Request $request, $id) { $venue = Venue::findOrFail($id); $venue->update($request->all()); return redirect()->back()->with('message','Venue successfully updated!'); } public function venueuploadsedit($id) { $venue = Venue::findOrFail($id); return view('venues.uploads-edit', compact('venue')); } public function venueImageUpdate(Request $request, $id) { $venue = Venue::findOrFail($id); Log::info('This Venue: '.$venue.''); $venuephoto = $request->file('photo')->store('public/venues/photos'); $venue->update([ 'photo'=>$venuephoto, ]); return redirect()->back()->with('message','Venue image updated!'); } public function propertyCreate() { return view('properties.create'); } public function propertyStore(PropertyPostRequest $request) { $user_id = $request->user_id; $company = Company::where('user_id',$user_id)->first(); $company_id = $company->id; $propertyphoto = $request->file('propimage')->store('public/property/photos'); $floorplan = $request->file('floorplan')->store('public/property/brochure'); $brochure = $request->file('brochure')->store('public/property/floorplan'); $requestedtown = request('town'); if($requestedtown == ''){ $requestedtown = request('othertown'); } Property::create([ 'user_id'=>$user_id, 'company_id'=>$company_id, 'propname'=>request('propname'), 'slug'=>str_slug(request('propname')), 'propcost'=>request('propcost'), 'proptype_id'=>request('proptype_id'), 'propimage'=>$propertyphoto, 'bedroom'=>request('bedroom'), 'bathroom'=>request('bathroom'), 'kitchen'=>request('kitchen'), 'garage'=>request('garage'), 'reception'=>request('reception'), 'conservatory'=>request('conservatory'), 'outbuilding'=>request('outbuilding'), 'address'=>request('address'), 'town'=>$requestedtown, 'county'=>request('county'), 'postcode'=>request('postcode'), 'latitude'=>request('latitude'), 'longitude'=>request('longitude'), 'short_summary'=>request('short_summary'), 'summary'=>request('summary'), 'description'=>request('description'), 'floorplan'=>$floorplan, 'brochure'=>$brochure, 'last_date'=>request('last_date'), 'category_id'=>request('category_id'), 'is_featured'=>request('is_featured'), 'is_live'=>request('is_live') ]); //LOGGING Log::info('Property Name: '.request('propname').''); return redirect()->back()->with('message','Property added successfully!'); } public function addphotos($id, Property $property) { $propertyPhotos = PropertyPhotos::where('property_id', '=', $id) ->get(); $params = array_merge(['propertyId' => $id, 'photos' => $propertyPhotos], compact('property')); return view('properties.addphotos', $params); } public function propertyPhoto(Request $request) { $rules = array( // 'file' => 'required' ); $error = Validator::make($request->all(), $rules); if($error->fails()) { return response()->json(['errors' => $error->errors()->all()]); } $user_id = auth()->user()->id; $propertyphoto = $request->file('property_photo')->store('public/property/photos'); PropertyPhotos::create([ 'user_id'=>$user_id, 'property_id'=>request('property_id'), 'photo_title'=>request('photo_title'), 'photo'=>$propertyphoto ]); return redirect()->back()->with('message','Photo Added to property!'); } public function propertyEdit($id) { $property = Property::findOrFail($id); return view('properties.edit', compact('property')); } public function propertyUpdate(Request $request, $id) { $property = Property::findOrFail($id); $property->update($request->all()); return redirect()->back()->with('message','Property successfully updated!'); } public function propuploadsedit($id) { $property = Property::findOrFail($id); return view('properties.uploads-edit', compact('property')); } public function propImageUpdate(Request $request, $id) { $property = Property::findOrFail($id); Log::info('This Property: '.$property.''); $propertyphoto = $request->file('propimage')->store('public/property/photos'); $property->update([ 'propimage'=>$propertyphoto, ]); return redirect()->back()->with('message','Property image updated!'); } public function togglePropertyLive(Request $request) { $property = Property::find($request->id); $property->is_live = $request->is_live; $property->save(); return redirect()->back(); } public function toggleVenueLive(Request $request) { $Venue = Venue::find($request->id); $Venue->is_live = $request->is_live; $Venue->save(); return redirect()->back(); } } <file_sep>/app/Event.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Notifications\Notifiable; use Spatie\Activitylog\Traits\LogsActivity; class Event extends Model { use Notifiable, LogsActivity, SoftDeletes; protected $fillable = ['id', 'venue_id', 'eventName', 'slug', 'eventPhoto', 'eventDate', 'eventTimeStart', 'eventTimeEnd', 'eventType', 'eventCost', 'is_live']; public function venue() { return $this->belongsTo(Venue::class); } }
567d6efcd9376e8db6b87435bf485cbbcfd95f23
[ "Markdown", "JavaScript", "PHP" ]
32
PHP
jbiddulph/moveme
0ee76910ccfc837df49fe5e1674fbdd0ef2b9801
a39f3ab8475273dca24e15bd4dd5d2b2fb0fb1dc
refs/heads/master
<file_sep>package com.rnkrsoft.config; import com.rnkrsoft.config.properties.PropertiesConfigProvider; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; /** * Created by <EMAIL> on 2019/1/6. */ public abstract class ConfigProviderFactory { private ConfigProviderFactory(){ } private final static Map<String, ConfigProvider> INSTANCES = new HashMap<String, ConfigProvider>(); /** * 构建属性文件的实例 * @param name 配置文件名称 * @return 配置提供者 */ public synchronized static ConfigProvider getPropertiesInstance(String name){ return getInstance(PropertiesConfigProvider.class.getName(), name); } /** * 构建指定实现配置提供者的实例 * @param clazz 配置提供者实现类 * @param name 配置文件名称 * @return 配置提供者 */ public synchronized static ConfigProvider getInstance(Class clazz, String name){ if (INSTANCES.containsKey(name)) { return INSTANCES.get(name); } else { ConfigProvider instance = null; try { Constructor constructor = clazz.getConstructor(String.class); instance = (ConfigProvider) constructor.newInstance(name); } catch (Exception e) { throw new RuntimeException("构建配置提供者发生异常", e); } INSTANCES.put(name, instance); return instance; } } /** * 构建指定实现配置提供者的实例 * @param className 配置提供者实现类 * @param name 配置文件名称 * @return 配置提供者 */ public synchronized static ConfigProvider getInstance(String className, String name){ Class clazz = null; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("构建配置提供者发生异常", e); } return getInstance(clazz, name); } } <file_sep>package com.rnkrsoft.config.properties; import com.rnkrsoft.config.AbstractConfigProvider; import java.io.*; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Created by <EMAIL> on 2019/1/6. */ public class PropertiesConfigProvider extends AbstractConfigProvider implements Runnable { final Properties properties = new Properties(); String name; long lastModified = 0L; File file; ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1); public PropertiesConfigProvider(String name) { this.name = name; } /** * 初始化配置 * * @param configDir 配置目录 * @param reloadInterval 监控配置变换间隔 */ public void init(String configDir, int reloadInterval) { this.file = new File(configDir, this.name + ".properties"); init(reloadInterval); } @Override public void init(int reloadInterval) { reload(); //如果重新加载的时间间隔大于0,则启动定时任务 if (reloadInterval > 0) { scheduledThreadPool.scheduleWithFixedDelay(this, reloadInterval, reloadInterval, TimeUnit.SECONDS); } } @Override public void reload() { InputStream is = null; try { System.out.println("reload config : " + file.getCanonicalPath()); if (!file.exists()) { System.err.println(file.getCanonicalPath() + " is not found!"); save(); lastModified = file.lastModified(); return; } is = new FileInputStream(file); properties.load(is); lastModified = file.lastModified(); } catch (IOException e) { if (is != null) { try { is.close(); } catch (IOException e1) { ; } } } } public void save() { FileOutputStream fos = null; try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } fos = new FileOutputStream(file); properties.store(fos, name); } catch (Exception e) { if (fos != null) { try { fos.close(); } catch (IOException e1) { e.printStackTrace(); } } } } public void param(String name, String value) { properties.setProperty(name, value); } public <T> T getParam(String paramName, Class<T> paramClass) { Object value = properties.getProperty(paramName); return convert(value, paramClass); } @Override public void run() { if (file.lastModified() > lastModified){ reload(); } } } <file_sep># 配置文件库 [![Maven central](https://maven-badges.herokuapp.com/maven-central/com.rnkrsoft.config/config/badge.svg)](http://search.maven.org/#search|ga|1|g%3A%22com.rnkrsoft.config%22%20AND%20a%3A%22config%22) ```xml <dependency> <groupId>com.rnkrsoft.config</groupId> <artifactId>config</artifactId>    <version>最新版本号</version> </dependency> ``` 配置文件提供者 ```java package com.rnkrsoft.config; /** * Created by <EMAIL> on 2019/1/6. * 配置提供者 */ public interface ConfigProvider { /** * 初始化配置提供者 * @param configDir 配置文件目录 * @param reloadInterval 重新加载时间间隔 */ void init(String configDir, int reloadInterval); /** * 初始化配置提供者 * @param reloadInterval 重新加载时间间隔 */ void init(int reloadInterval); /** * 重新加载 */ void reload(); /** * 保存配置 */ void save(); /** * 设置参数值 * @param name 参数名 * @param value 参数值 */ void param(String name, String value); /** * 获取参数 * @param name 参数名 * @param paramClass 参数值类型 * @param <T> 参数值类型 * @return 参数值 */ <T> T getParam(String name, Class<T> paramClass); /** * 获取指定参数名的数组值 * @param name 参数名 * @return 参数值 */ String[] getArray(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ String getString(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ String getString(String name, String defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Integer getInteger(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Integer getInteger(String name, Integer defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Long getLong(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Long getLong(String name, Long defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Double getDouble(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Double getDouble(String name, Double defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Boolean getBoolean(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Boolean getBoolean(String name, Boolean defaultValue); } ``` 通过工厂类构建实现 ```java //构建配置提供者test.properties final ConfigProvider configProvider = ConfigProviderFactory.getPropertiesInstance("test"); configProvider.param("MONITOR_APPLICATIONID", "default"); configProvider.param("MONITOR_ENVIRONMENTID", "1"); //每隔2秒钟热加载一次 configProvider.init("src/test/resources", 2); Thread t = new Thread(){ @Override public void run() { while (true){ Long value = configProvider.getLong("MONITOR_ENVIRONMENTID", 0L); System.out.println(value); try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.start(); Thread.sleep(60 * 1000); ``` <file_sep>package com.rnkrsoft.config; /** * Created by <EMAIL> on 2019/1/6. */ public abstract class AbstractConfigProvider implements ConfigProvider { protected <T> T convert(Object value, Class<T> paramClass) { try { if (paramClass == String.class) { return (T) (value == null ? null : value.toString()); } if (paramClass == Integer.class || paramClass == Integer.TYPE) { if (value == null) { return null; } else { return (T) new Integer(value.toString()); } } if (paramClass == Long.class || paramClass == Long.TYPE) { if (value == null) { return null; } else { return (T) new Long(value.toString()); } } if (paramClass == Double.class || paramClass == Double.TYPE) { if (value == null) { return null; } else { return (T) new Double(value.toString()); } } if (paramClass == Boolean.class || paramClass == Boolean.TYPE) { if (value == null) { return null; } else { return (T) new Boolean(value.toString()); } } throw new IllegalArgumentException("无效参数类型'" + paramClass + "'"); } catch (Exception e) { return null; } } public String[] getArray(String paramName) { String value = getString(paramName, ""); if (value.isEmpty()) { return new String[0]; } String[] str = value.split(";"); return str; } public String getString(String name, String defaultValue) { String value = getParam(name, String.class); if (value == null) { value = defaultValue; } return value; } public Integer getInteger(String name, Integer defaultValue) { Integer value = getParam(name, Integer.class); if (value == null) { value = defaultValue; } return value; } @Override public Long getLong(String name, Long defaultValue) { Long value = getParam(name, Long.class); if (value == null) { value = defaultValue; } return value; } @Override public Double getDouble(String name, Double defaultValue) { Double value = getParam(name, Double.class); if (value == null) { value = defaultValue; } return value; } @Override public String getString(String name) { return getString(name, null); } @Override public Integer getInteger(String name) { return getInteger(name, 0); } @Override public Long getLong(String name) { return getLong(name, 0L); } @Override public Double getDouble(String name) { return getDouble(name, 0D); } @Override public Boolean getBoolean(String name) { return getBoolean(name, false); } public Boolean getBoolean(String name, Boolean defaultValue) { Boolean value = getParam(name, Boolean.class); if (value == null) { value = defaultValue; } return value; } } <file_sep>package com.rnkrsoft.config; /** * Created by <EMAIL> on 2019/1/6. * 配置提供者 */ public interface ConfigProvider { /** * 初始化配置提供者 * @param configDir 配置文件目录 * @param reloadInterval 重新加载时间间隔 */ void init(String configDir, int reloadInterval); /** * 初始化配置提供者 * @param reloadInterval 重新加载时间间隔 */ void init(int reloadInterval); /** * 重新加载 */ void reload(); /** * 保存配置 */ void save(); /** * 设置参数值 * @param name 参数名 * @param value 参数值 */ void param(String name, String value); /** * 获取参数 * @param name 参数名 * @param paramClass 参数值类型 * @param <T> 参数值类型 * @return 参数值 */ <T> T getParam(String name, Class<T> paramClass); /** * 获取指定参数名的数组值 * @param name 参数名 * @return 参数值 */ String[] getArray(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ String getString(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ String getString(String name, String defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Integer getInteger(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Integer getInteger(String name, Integer defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Long getLong(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Long getLong(String name, Long defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Double getDouble(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Double getDouble(String name, Double defaultValue); /** * 获取指定参数名的字符串值 * @param name 参数名 * @return 参数值 */ Boolean getBoolean(String name); /** * 获取指定参数名的字符串值 * @param name 参数名 * @param defaultValue 如果为null时返回默认值 * @return 参数值 */ Boolean getBoolean(String name, Boolean defaultValue); }
3a459abd59319f7d82b44274a6de700b9516b433
[ "Markdown", "Java" ]
5
Java
rnkrsoft/config
9464b64a813c11cc6d6fa124f702b0ac73d86049
389194035ea9217cf92d25dd956f82ee23d64d8f
refs/heads/master
<repo_name>IUTInfoMontp-M4103C/td1-CemSARISOY<file_sep>/README.md # ![](ressources/logo.jpeg) Prog web client riche - JavaScript ### IUT Montpellier-Sète – Département Informatique ## TD1 #### _Thème : dynamiser une page web_ Cliquez sur le lien ci-dessous pour faire, dans un dossier public_html/JS/TD1, votre fork privé du TD1 (**attention, pas de fork à la main !**): https://classroom.github.com/a/1pEh7RIt la version [pdf](ressources/td1.pdf) ## INTRODUCTION Vos TD et projets de S1 (Conception Doc) vous ont appris à créer des sites web statiques, où les pages ne varient pas. Leur seul aspect dynamique était apporté pas le css qui permettait des effets (media querries, transitions, etc). En S3 vous avez appris à réellement dynamiser vos sites web en utilisant des appels au serveur web, avec des pages web construites par le serveur, en fonction de données recueillies sur la base de données ou par le biais de formulaires, et au moyen du langage PHP. L’aspect dynamique de ces sites tient donc au fait que le serveur web construit la page sur demande (en fonction de l’utilisateur, des données d’un formulaire, etc). La page construite est donc fonction des circonstances, et c’est ce qui lui donne son caractère dynamique. JavaScript permet de rendre dynamique une page web par l’utilisation de scripts, en réponse à des sollicitations côté client. Par exemple, des événements comme un clic de souris, une action au clavier, etc. Ici l’aspect dynamique est indépendant d’un appel serveur. Dans certains cas, il peut être excessif de faire des appels permanents au serveur. Dans ce TD1 vous allez devoir modifier une page web qui pour le moment est en partie remplie via PHP, par des appels exagérés au serveur web. Créez dans votre `public_html` un dossier `JS/TD`. C'est ce dossier qui accueillera le dépôt local en lien avec votre fork du TD1. Il est nécessaire que ce dépôt local soit dans votre `public_html` car le fichier index.php aura besoin d'un serveur web qui produira la page web bien construite. Dans ce TD1, vous commencez à coder en JavaScript, sans cours préalable. Pas d’inquiétude, vous avez déjà un passé de prog objet, et même s’il faut se méfier de pas mal de choses intuitives avec ce langage, cela ne vous empêchera pas de faire vos premiers pas en JavaScript ! ## EXERCICE 1 - mécanisme client serveur 1. Appelez la page **index.php?fleur=rose** et expliquez le rôle de chaque instruction PHP de cette page (lignes 1 à 12, lignes 26 et 30, lignes 48 à 55). <p align="center"> <img src="ressources/img3.png" width="800"> </p> 2. En cliquant sur un des 4 items du menu, on fait une requête http au serveur, en lui passant en GET une valeur de fleur. Expliquez ce qui est actualisé sur la page quand on clique sur un item du menu. ## EXERCICE 2 - dynamiser le menu 1. Excluez tous les appels au serveur dans les liens du menu en remplaçant les `href="index.php?fleur=…"` par des `href="#"`. Vérifiez que le menu n’agit plus (ne lance plus de requête http). 2. Excluez de la partie PHP initiale (lignes 1 à 12) les lignes qui affectent une valeur à la variable `$fleur`. 3. Réactualisez la page web. Expliquez ce que vous constatez. 4. Pour corriger l’erreur, modifiez le contenu de la balise html `<div class='galerie'>` pour que par défaut elle affiche les roses, en remplaçant les évocations au PHP par ce qu’il faut. 5. Modifiez les balises `<a>` du menu pour les transformer ainsi : <nav> <ul> <li><a href="#" onclick="adapter_galerie('rose');">rose</a></li> <li><a href="#" onclick="adapter_galerie('hortensia');">hortensia</a></li> <li><a href="#" onclick="adapter_galerie('fruitier');">fruitier</a></li> <li><a href="#" onclick="adapter_galerie('autre');">autre</a></li> </ul> </nav> 6. Ouvrez l’examinateur d’élément, menu « console » (F12), rafraîchissez la page, cliquez sur un item du menu et expliquez le message d’erreur qui apparaît. L’attribut `onclick` des balises `<a>` a pour valeur une chaîne de caractères qui évoque l’exécution d’une fonction `adapter_galerie` avec un paramètre propre à chaque balise `<a>`. Cet attribut `onclick` permet un appel à un script JavaScript quand le lien est cliqué. 7. Juste avant la balise `</body>`, ajoutez le code suivant, et vérifiez que l’erreur précédente ne se produit plus. <script type="text/javascript"> function adapter_galerie(nom) { // à compléter } </script> 8. Essayez, à la place du commentaire `// à compléter`, les divers codes suivants, et décrivez ce qu’ils font : console.log("bonjour de la part du menu !"); console.log(nom); 9. On souhaite essayer le code suivant : <script type="text/javascript"> function adapter_galerie(nom) { for(let i = 1; i <= 6; i++) { let image = document.getElementById('fleur' + i); image.src = 'img/fleurs/' + nom + '/' + nom + i + '.jpg'; } } </script> Avant de l'essayer, d'après vous : + Que renvoie `document.getElementById('fleur' + i)` ? + Que fait `image.src = …` ? Copiez le nouveau code de `adapter_galerie`, puis vérifiez vos réponses par l’inspecteur d’éléments après les clics sur les items du menu. Vous prendrez le temps d'inspecter les images et de constater que les attributs `src` ont été adaptés. 10. Au survol d’une image de fleur, un titre s’affiche, car l’attribut `title` a été renseigné. Mais si on passe des roses à une autre catégorie de fleurs, on voit que le script n’a pas actualisé ce `title`. Corrigez le script en complétant la fonction `adapter_galerie` (inspirez-vous de la commande `image.src = …`) et vérifiez que le `title` est devenu dynamique. 11. Si une image n’est pas trouvée par le serveur, l’attribut `alt` joue son rôle et affiche un texte de remplacement à l’image. Vérifiez ce rôle en changeant le nom de certains fichiers images (par exemple renommez l'image `rose1.jpg` en `roseUn.jpg`) et réactualisez la page (`CTRL` `F5` par exemple) Observez ce qui se passe au niveau des attributs `alt` quand on choisit les différents items du menu. Ils sont encore statiques... Corrigez le script pour que les attributs `alt` soient construits comme ceux des roses : "hortensia1", "fruitier2" etc. Vérifiez le bon fonctionnement du script puis redonnez leur nom d’origine aux images modifiées. ## EXERCICE 3 - dynamiser la banière On va maintenant dynamiser la banière. Pour le moment, l'image est choisie au hasard parmi 6 possibles, lors de la requête initiale, grâce à une variable PHP. Modifiez la banière en incorporant toutes les images de cette façon : <div id="baniere"> <img id="1" class="img_baniere visible" alt="baniere" src="img/baniere/baniere1.jpg"> <img id="2" class="img_baniere cachee" alt="baniere" src="img/baniere/baniere2.jpg"> <img id="3" class="img_baniere cachee" alt="baniere" src="img/baniere/baniere3.jpg"> <img id="4" class="img_baniere cachee" alt="baniere" src="img/baniere/baniere4.jpg"> <img id="5" class="img_baniere cachee" alt="baniere" src="img/baniere/baniere5.jpg"> <img id="6" class="img_baniere cachee" alt="baniere" src="img/baniere/baniere6.jpg"> </div> Supprimez aussi les dernières lignes PHP en début de fichier. La nouvelle structure html de la banière montre qu’il y a 6 images, dont une de classe « visible » et 5 de classe « cachee ». Derrière ces deux classes il y a une valeur différente de l’opacité de l’image (0 pour cachée et 1 pour visible, voir le css). Ces images sont superposées. Vous allez créer deux effets différents de succession d’images. 1. Créez, dans la partie `<script>`, après le code de `adapter_galerie(nom)`, une fonction `cacher(im)` qui cache l’image `im` passée en paramètre. Pour cela vous pourrez : - retirer la classe `visible` à l’image `im` - ajouter la classe `cachee` à l’image `im` Aide : - `im.classList` désigne la liste de classes attribuées à `im` - `im.classList.add('nom_classe')` ajoute la classe `nom_classe` à `im` - `im.classList.remove('nom_classe')` la lui retire 2. Actualisez votre page. Dans la console, testez votre nouvelle fonction en entrant les instructions suivantes : let img_ban_1 = document.getElementById('1'); cacher(img_ban_1); Si votre fonction est opérationnelle, l'image de la banière a dû disparaître... 2. Créez de même une fonction `afficher(im)`, rafraîchissez la page (pour charger le script complété) et testez la nouvelle fonction dans la console. let img_ban_1 = document.getElementById('1'); let img_ban_2 = document.getElementById('2'); cacher(img_ban_1); afficher(img_ban_2); cacher(img_ban_2); afficher(img_ban_1); 3. Créez ensuite une fonction `suivant(n)` qui retourne l’entier suivant n (au sens 1=>2, 2=>3, 3=>4, 4=>5, 5=>6 et 6=>1). En effet, il y a 6 images de banières et on va passer d’une banière à la suivante de façon naturelle sauf si on est à la sixième auquel cas on revient à la première. 4. On va maintenant créer une fonction `change_baniere_v1()` qui : - récupère la banière visible ; - récupère l’`id` de cette banière ; - calcule le suivant de cet `id` ; - cache la banière actuellement visible ; - affiche la banière suivante. Pour récupérer la banière visible (qui n’est pas forcément la banière n°1, même si au chargement de la page, c’est le cas), on va se servir non pas de l’identifiant, mais du fait que la banière visible est LA SEULE banière qui a la classe visible. Or JavaScript permet de récupérer, sous forme de tableau, les éléments html de la page qui sont munis d’une certaine classe. Cela se fait par la méthode `document.getElementsByClassName` qui gère un argument chaîne de caractères. Dans le cas présent on pourra utiliser l’instruction `let tab = document.getElementsByClassName('visible');` Remarque : vous pouvez lancer cette instruction dans la console de l’explorateur de document. Vous aurez alors en direct le tableau résultat de cette commande, affecté dans une variable nommée ici `tab`. En affichant `tab` (tab puis Entrée dans la console) vous aurez le résultat. Comme attendu, `tab` n’a qu’un seul élément, qui est accessible par `tab[0]`. Essayez dans la console. Dans le codage de la fonction `change_baniere_v1`, vous avez donc maintenant les moyens de récupérer la banière visible, puis son `id`, puis … Just do it. Une fois que c’est fait, testez dans la console votre fonction en lançant l’instruction `change_baniere_v1();` (sans oublier les parenthèses). **ATTENTION : JavaScript peut avoir un comportement surprenant. Par exemple, l’opération `"3" + 1` donne `"31"`. Ne soyez donc pas étonné si `suivant("3")` retourne `"31"`. Par contre, `3 + 1` donne bien `4`. Il peut donc être utile de transformer une chaîne de caractères (l’identifiant de la banière) en nombre. Pour cela, une multiplication par `1` fera l’affaire. Par exemple, `"3"*1 + 1` donne `4` car `"3"*1` est interprété en `3*1`.** 5. Pour que la banière soit mise à jour automatiquement et à intervalles réguliers, et non pas à la main comme à la question précédente, ajoutez en fin de script (hors des fonctions) l’instruction `let chb = setInterval(change_baniere_v1,6000);` Ceci permet de créer une variable `chb` de type **timer**. Réactualisez la page. L’instruction précédente lance en boucle la fonction `change_baniere_v1` à intervalles réguliers de 6000 ms. 6. Récupérez l’ensemble de votre script, qui commence à être imposant, sauvegardez-le dans un fichier `scripts_td1.js` du répertoire `public_html/JS/TD/TD1/js` et incorporez dans le html, à la place du script déplacé, la balise suivante, qui permet d’insérer l’ensemble du script : <script type="text/javascript" src="js/scripts_td1.js"></script> Enlevez aussi l’instruction PHP qui annonce l’appel au serveur. Vous avez compris qu’il n’y avait qu’un seul appel maintenant, et que tout est dynamisé côté client. Remarque importante : le chargement du script est bloquant pour le chargement des balises html. Il est donc important que les éléments html soient chargés avant que le script n’agisse. C’est pourquoi ce script est inséré juste avant la balise `</body>`. 7. On va maintenant programmer une transition plus douce entre les différentes images de la banière. Pour cela, c’est très simple : il suffit d’ajouter une transition sur l’opacité quand on passe de la classe cachee à la classe visible et aussi de la classe visible à la classe cachee. Cela se fait par des instructions comme : `maBaniere.style.transition = "opacity 3s";` Cette instruction JavaScript agit sur le css en écrivant un style « inline » pour la balise, comme vous pouvez le constater par l’inspecteur d’objets. Créez une fonction `change_baniere_v2` (sur la même base que `change_baniere_v1`) qui réalisera cette nouvelle transition, et que vous utiliserez à la place de `change_baniere_v1` dans le `setInterval`. ## EXERCICE 4 - dynamiser le titre de la galerie On peut aussi dynamiser le titre « Galerie de fleurs ». Ainsi, quand on cliquera sur l’item **hortensia** du menu, le titre sera mis à jour en « **Galerie d’hortensias** » et de même pour les autres items. 1. Au même niveau que la variable `chb` (c’est-à-dire avec un statut de variable globale), créez un tableau nommé `tabTitres` de la façon suivante : let tabTitres = new Array(); tabTitres['rose'] = 'Galerie de roses'; tabTitres['hortensia'] = 'Galerie d\’hortensias'; tabTitres['fruitier'] = 'Galerie de fruitiers'; tabTitres['autre'] = 'Galerie de fleurs diverses'; 2. Créez une fonction `adapter_titre(nom)` qui modifie le contenu de la balise `<span>`. Cette fonction utilisera le tableau `tabTitres`. L’appel de cette fonction sera inséré dans la fonction `adapter_galerie`. Indications : on peut modifier le contenu d’une balise comme `<span>` en changeant la valeur de son attribut `innerHTML`, avec une instruction similaire à : monParagraphe.innerHTML = 'Hello world !'; Remarque : il serait plus cohérent que, par défaut, le titre de la galerie soit "Galerie de roses". Vous pouvez le changer dans le html. ## EXERCICE 5 - compléments pour la banière 1. On peut annuler le défilement de la banière par une instruction `clearInterval(chb);`. Testez cette instruction dans la console. 2. Comme `chb` est une variable « globale », on peut l’évoquer dans le corps d’une fonction. Créez une fonction `stopper_defilement` qui annulera le défilement de la banière, et programmez le lancement de cette fonction au clic sur la banière (attribut `onclick`). Vous pourrez vous inspirer des attributs `onclick` des items du menu. 3. Créez une fonction `lancer_defilement` qui attribue à `chb` la valeur `setInterval(change_baniere_v2,6000)`. Programmer la réactivation du défilement de la banière quand on double-clique dessus (associé à l’attribut `ondblclick`). ## EXERCICE 6 - création d'une info-bulle Vous devez maintenant créer une info-bulle toute simple qui apparaît au survol du **footer** et disparaît après ce survol. La création et la destruction de cette bulle reposent sur trois méthodes intéressantes de l’objet `document`. Nous reviendrons sur ces méthodes plus tard dans le cours, mais vous pouvez en avoir un premier aperçu : 1. Voici le code de la fonction `construit_infobulle()` : function construit_infobulle() { let info = document.createElement('div'); info.innerHTML = "<p>c'est moi la bulle !</p>"; info.id = "bulle"; info.style.position = "fixed"; info.style.top = "100px"; info.style.right = "150px"; info.style.backgroundColor = "darkblue"; info.style.color = "white"; document.body.appendChild(info); } Décrivez ce que fait chaque ligne. Vous creuserez en particulier la première et la dernière ligne. Copiez ce code dans votre fichier `scripts_td1.js`. Lancez dans la console la commande `construit_infobulle();` Observez ce qui se passe par l’inspecteur d’objet. 2. Stylisez un peu votre bulle en ajoutant quelques lignes à la fonction `construit_infobulle`. Vous pouvez ajouter du *padding*, un *border-radius* et un *box-shadow*, etc. Remarque : on aurait bien sûr pu isoler toutes les lignes `info.style....` dans un fichier css et ne garder que les autres lignes pour le JavaScript. Ici l'objectif est de montrer qu'on peut agir sur le css d'un élément en injectant du style `inline` (ce qui est plutôt déconseillé en général). 3. Voici maintenant le code d’une fonction `detruit_bulle` : function detruit_infobulle() { var info = document.getElementById('bulle'); document.body.removeChild(info); } Que fait chaque ligne ? Copiez ce code dans votre script et lancez-le depuis la console. Observez ce qui se passe dans l’inspecteur d’objet quand on alterne cette commande et la précédente. 4. On peut renseigner d’autres attributs que `onclick` ou `ondblclick`. Par exemple, les attributs `onmouseover` et `onmouseout` existent aussi. Soyez malin et faites en sorte que l’info-bulle apparaisse au survol du **footer** et disparaisse à la fin de ce survol. ## EXERCICE 7 - Et pour quelques minutes de plus... 1. Renseignez l'attribut `onclick` de la balise `<img id="parametres"...>` pour permettre le lancement, au clic, de l'instruction `changer_parametres()` correspondant à une fonction que vous allez écrire. 2. codez la fonction en question pour qu'elle : + génère un nombre entier aléatoire entre 1 et 4; + modifie l'image de fond du `body` en lui donnant comme nouvelle url celle correspondant au fichier image dont le nom correspond au nombre aléatoire ci-dessus (il y a dans le dossier `img/background` 4 fichiers `bg-1.jpg`, ..., `bg-4.jpg`) 3. comme le nombre généré peut être répété, on peut parfois avoir l'impression que la fonction est inopérante, alors qu'elle a juste remplacé une image par elle-même. Débrouillez-vous pour éviter ce petit inconvénient. <file_sep>/src/js/scripts_td1.js function adapter_galerie(nom) { adapter_titre(nom); for(let i = 1; i <= 6; i++) { let image = document.getElementById('fleur' + i); image.src = 'img/fleurs/' + nom + '/' + nom + i + '.jpg'; image.title = nom+i; image.alt = nom+i; } } function cacher(im) { im.classList.remove('visible'); im.classList.add('cachee'); } function afficher(im) { im.classList.remove('cachee'); im.classList.add('visible'); } function suivant(n) { if(n%6===0) { return 1; } else { return n+1; } } function change_banniere_v1() { let ban = document.getElementsByClassName('visible')[0]; let id = ban.id; cacher(ban); let suiv = document.getElementById(suivant(id*1)); afficher(suiv); } function change_banniere_v2() { let ban = document.getElementsByClassName('visible')[0]; ban.style.transition = "opacity 3s"; let id = ban.id; cacher(ban); let suiv = document.getElementById(suivant(id*1)); suiv.style.transition = "opacity 3s"; afficher(suiv); } function adapter_titre(nom) { let titre = document.getElementById('titre'); titre.innerHTML = tabTitres[nom]; } function stopper_defilement() { clearInterval(chb); } function lancer_defilement() { chb = setInterval(change_banniere_v2, 6000); } function construit_infobulle() { let info = document.createElement('div'); info.innerHTML = "<p>c'est moi la bulle !</p>"; // On crée la bulle avec le message apparant info.id = "bulle"; // on lui donne un id info.style.position = "fixed"; info.style.top = "100px"; info.style.right = "150px"; info.style.backgroundColor = "darkblue"; info.style.color = "white"; // on lui donne le style que l'on veut document.body.appendChild(info); //On le rend enfant de body } function detruit_infobulle() { var info = document.getElementById('bulle'); //On cherche l'élément dans la page document.body.removeChild(info); // Il n'est plus enfant de body et donc disparait } function changer_parametres() { let url = document.body.style.backgroundImage; let nbImgActu = url[url.length-7]; let rnd; do { rnd = Math.floor(Math.random() * (5 - 1)) + 1; }while(nbImgActu*1===rnd*1); document.body.style.backgroundImage = 'url("./img/background/bg-' + rnd + '.jpg")'; } let chb = setInterval(change_banniere_v2,6000); let tabTitres = new Array(); tabTitres['rose'] = 'Galerie de roses'; tabTitres['hortensia'] = 'Galerie d\’hortensias'; tabTitres['fruitier'] = 'Galerie de fruitiers'; tabTitres['autre'] = 'Galerie de fleurs diverses';
58f6c469dade2d7a3cd9c6c39b6b132e465794ca
[ "Markdown", "JavaScript" ]
2
Markdown
IUTInfoMontp-M4103C/td1-CemSARISOY
83456caba6e26e564c0a18e3cacbe617a782e048
f0eab3934213ab646569ab8ca064991894f71f3d
refs/heads/master
<file_sep>GlitchBooth =========== NPoole 10/23/14 GlitchBooth Demo for the pcDuino3 and CSI Camera Module Featured on Sparkfun.com 10/24/14 New Product Friday Based on the jpglitch project found at https://github.com/Kareeeeem/jpglitch (included here in full) Description: This project uses the pcDuino3 (https://www.sparkfun.com/products/12856) and 2MP Camera Module (https://www.sparkfun.com/products/13100) to capture a photo and artistically corrupt it. A button press on D2 will capture an image, save it to the disk and display it using Feh (http://feh.finalrewind.org/). A button press on D3 will process the last image captured using the jpglitch method, save the output to the disk and display it using Feh. Using the "cam_to_glitch_tweepy" script allows the GlitchBooth to post glitched images to the Twitter stream of your choice using the Tweepy (http://www.tweepy.org/) framework. This action is triggered by a button press on D4. In order for Tweepy to work properly, you will need to register a Twitter App and insert your API Keys into the script. The GlitchBooth will also require a relatively stable internet connection. Simply connect the camera module to your pcDuino3 and run the Python script! Enjoy! <file_sep>#jpglitch A command line tool to create glitchart from jp[e]g's. The script will save the glitched *image.jpg* as *image_glitched.png*. The reason to save the result as png is for stability and to make sure the result looks the same on different platforms. It uses elements of this javascript implementation. https://github.com/snorpey/glitch-canvas/ ##Usage ``` python jpglitch.py image.jpg ``` There are three optional parameters 1.Amount (This determines the hex value that is used to overwrite original values in the image data. Value from 1 to 99) 1.Seed (This determines where in the image data the script starts overwriting data. Value from 1 to 99) 1.Iterations (This determines how many times the script overwrites data. Value from 1-110) When the optional parameters are not given it generates random values in the allowed ranges. This is closer to the original purpose. Glitches are technically not engineered but they just happen. ``` python jpglitch.py image.jpg -a 70 -s 4 -i 31 ``` ##Example ![alt text](http://imgur.com/bUvNMaQ.jpg "example") <file_sep>import os import random from PIL import Image import tweepy import subprocess import time import pygame import pygame.camera from pygame.locals import * pygame.init() pygame.camera.init() cam = pygame.camera.Camera("/dev/video0",(640,480)) cam.start() #Oauth keys and secrets consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' #Oauth Process auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) #Create Interface api = tweepy.API(auth) def getBytes(image): with open(image, 'rb') as im: data = im.read() bytes = bytearray(data) return bytes def getJpgHeaderLength(image_bytes): for i in (range(len(image_bytes)-1)): if (image_bytes[i] == 255) & (image_bytes[i+1] == 218): result = i break return result def glitchJpgBytes(image, amount=None, seed=None, iterations=None): if amount is None: amount = random.randint(0, 99) elif amount > 99: amount = 99 if seed is None: seed = random.randint(1, 99) elif seed > 99: seed = 99 elif seed < 1: seed = 1 if iterations is None: iterations = random.randint(1, 110) parameters = {'amount': amount, 'seed': seed, 'iterations': iterations} print parameters amount = float(amount)/100 seed = float(seed)/100 bytes = getBytes(image) headerlength = getJpgHeaderLength(bytes) for i in (range(iterations)): max_index = len(bytes) - headerlength - 4 px_min = int((max_index / iterations) * i) px_max = int((max_index / iterations) * (i + 1)) delta = (px_max - px_min) * 0.8 px_i = int(px_min + (delta * seed)) if (px_i > max_index): px_i = max_index byte_index = headerlength + px_i bytes[byte_index] = int(amount * 256.0) new_name = 'new_' + image new_name = image.rsplit('.')[0] + '_glitched.jpg' with open(new_name, 'wb') as output: output.write(bytes) return (new_name, image, parameters) def savetoPNG(glitched_image): image = glitched_image[0] old_image = glitched_image[1] parameters = glitched_image[2] png_name = image.rsplit('.')[0] + '.png' while True: try: im = Image.open(image) im.save(png_name) os.remove(image) print 'succes' break except IOError: print 'oops' parameters['iterations'] -= 1 second_attempt = ( glitchJpgBytes(old_image, amount=parameters['amount'], seed=parameters['seed'], iterations=(parameters['iterations']))) image = second_attempt[0] def glitchJpg(image, amount=None, seed=None, iterations=None): glitched_image = glitchJpgBytes(image, amount, seed, iterations) savetoPNG(glitched_image) def snapDisp(): subprocess.call('killall feh', shell=True) image = cam.get_image() image = cam.get_image() image = cam.get_image() pygame.image.save(image,'temp.jpg') pygame.image.save(image,'temp.jpg') pygame.image.save(image,'temp.jpg') viewPng = subprocess.Popen("feh temp.jpg -F -Z", shell=True) def glitchDisp(): subprocess.call('killall feh', shell=True) glitchJpg('temp.jpg') viewPng = subprocess.Popen("feh temp_glitched.png -F -Z", shell=True) def tweetDisp(): im = Image.open("temp_glitched.png") im.save("temp_glitched_jpg.jpg") photo_path = 'temp_glitched_jpg.jpg' status = 'Testing a Python/Tweepy App' + time.strftime("%Y-%m-%d %H:%M") api.update_with_media(photo_path, status=status) viewPng = subprocess.Popen("feh sharescreen.png -F -Z", shell=True) def buttons(): while '0' not in tempa[0] and '0' not in tempb[0] and '0' not in tempc[0]: file1.seek(0) tempa[0] = file1.read() file2.seek(0) tempb[0] = file2.read() file3.seek(0) tempc[0] = file3.read() time.sleep(.1) if '0' in tempa[0]: snapDisp() if '0' in tempb[0]: glitchDisp() if '0' in tempc[0]: tweetDisp() GPIO_MODE_PATH= os.path.normpath('/sys/devices/virtual/misc/gpio/mode/') GPIO_PIN_PATH=os.path.normpath('/sys/devices/virtual/misc/gpio/pin/') GPIO_FILENAME="gpio" pinMode = [] pinData = [] HIGH = "1" LOW = "0" INPUT = "0" OUTPUT = "1" INPUT_PU = "8" for i in range(0,18): pinMode.append(os.path.join(GPIO_MODE_PATH, 'gpio'+str(i))) pinData.append(os.path.join(GPIO_PIN_PATH, 'gpio'+str(i))) file = open(pinMode[2], 'r+') file.write(INPUT_PU) file.close() file = open(pinMode[3], 'r+') file.write(INPUT_PU) file.close() file = open(pinMode[4], 'r+') file.write(INPUT_PU) file.close() tempa = [''] tempb = [''] tempc = [''] while True: file1 = open(pinData[2], 'r') file2 = open(pinData[3], 'r') file3 = open(pinData[4], 'r') tempa[0] = file1.read() tempb[0] = file2.read() tempc[0] = file3.read() buttons() <file_sep>import os import random from PIL import Image def getBytes(image): with open(image, 'rb') as im: data = im.read() bytes = bytearray(data) return bytes def getJpgHeaderLength(image_bytes): for i in (range(len(image_bytes)-1)): if (image_bytes[i] == 255) & (image_bytes[i+1] == 218): result = i break return result def glitchJpgBytes(image, amount=None, seed=None, iterations=None): if amount is None: amount = random.randint(0, 99) elif amount > 99: amount = 99 if seed is None: seed = random.randint(1, 99) elif seed > 99: seed = 99 elif seed < 1: seed = 1 if iterations is None: iterations = random.randint(1, 110) parameters = {'amount': amount, 'seed': seed, 'iterations': iterations} print parameters amount = float(amount)/100 seed = float(seed)/100 bytes = getBytes(image) headerlength = getJpgHeaderLength(bytes) for i in (range(iterations)): max_index = len(bytes) - headerlength - 4 px_min = int((max_index / iterations) * i) px_max = int((max_index / iterations) * (i + 1)) delta = (px_max - px_min) * 0.8 px_i = int(px_min + (delta * seed)) if (px_i > max_index): px_i = max_index byte_index = headerlength + px_i bytes[byte_index] = int(amount * 256.0) new_name = 'new_' + image new_name = image.rsplit('.')[0] + '_glitched.jpg' with open(new_name, 'wb') as output: output.write(bytes) return (new_name, image, parameters) def savetoPNG(glitched_image): image = glitched_image[0] old_image = glitched_image[1] parameters = glitched_image[2] png_name = image.rsplit('.')[0] + '.png' while True: try: im = Image.open(image) im.save(png_name) os.remove(image) print 'succes' break except IOError: print 'oops' parameters['iterations'] -= 1 second_attempt = ( glitchJpgBytes(old_image, amount=parameters['amount'], seed=parameters['seed'], iterations=(parameters['iterations']))) image = second_attempt[0] def glitchJpg(image, amount=None, seed=None, iterations=None): glitched_image = glitchJpgBytes(image, amount, seed, iterations) savetoPNG(glitched_image) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("jpg", help="you need to provide a jpg image") parser.add_argument('-a', metavar="amount", type=int, help="a number used to replace data in the image file. \ must be between 0 and 99") parser.add_argument('-s', metavar="seed", type=int, help="a number used to determine which data gets replaced. \ Must be between 0 and 99") parser.add_argument('-i', metavar="iterations", type=int, help="how many times over do you want to glitch the image. \ must be between 0 and 110") args = parser.parse_args() glitchJpg(args.jpg, amount=args.a, seed=args.s, iterations=args.i)
92736b6792fdf19dec12666c2abe743a0550f71d
[ "Markdown", "Python" ]
4
Markdown
sparkfun/GlitchBooth
225d54ede9570e090363a8ec88a6815e68536534
a3eea10e34de80657c5487ba7b9c810713886638
refs/heads/master
<repo_name>balta2ar/ncm2-jira<file_sep>/pythonx/ncm2_jira.py # -*- coding: utf-8 -*- from datetime import datetime from operator import itemgetter from os.path import expanduser, expandvars import vim from ncm2 import getLogger, Ncm2Source logger = getLogger(__name__) def log(msg): now = str(datetime.now()) with open('/tmp/ncm2-jira.log', 'a') as file_: file_.write('%s %s\n' % (now, msg)) def load_lines(filename): # 0 - key # 1 - subject # 2 - status # 3 - owner # 4 - last updated filename = expanduser(expandvars(filename)) get_subset = itemgetter(0, 1, 4) with open(filename) as file_: lines = [get_subset(line.strip().split('\t')) for line in file_.readlines()] log('load_lines: #: %s' % len(lines)) return lines def get_jira_candidates(candidates, _current_prefix, matcher_key): max_ticket_len = max(len(ticket) for ticket, _title, _last_updated in candidates) ticket_formatter = '%' + str(max_ticket_len) + 's' return [{ 'word': ticket, 'abbr': ticket_formatter % ticket + ' ' + title, #matcher_key: current_prefix + title, matcher_key: 'JI' + title, 'last_updated': last_updated, } for ticket, title, last_updated in candidates] class Source(Ncm2Source): def __init__(self, nvim): super(Source, self).__init__(nvim) self.executable_look = nvim.call('executable', 'look') def on_complete(self, ctx): query = ctx['base'] candidates_filename = '~/.cache/jira/jira.candidates.tsv' candidates = load_lines(candidates_filename) matches = get_jira_candidates(candidates, query, 'custom') self.complete(ctx, ctx['startccol'], matches) source = Source(vim) on_complete = source.on_complete <file_sep>/pythonx/ncm2_sorter/custom.py import sys def log(msg): from datetime import datetime now = str(datetime.now()) with open('/tmp/ncm2-jira.log', 'a') as file_: file_.write('%s %s\n' % (now, msg)) def Sorter(**kargs): def key(e): w = e['word'] ud = e['user_data'] hl = ud['match_highlight'] # prefer less pieces pieces = len(hl) # prefer earlier match first_match = sys.maxsize if len(hl): first_match = hl[0][0] # prefer shorter span span = sys.maxsize if len(hl): span = hl[-1][1] - hl[0][0] # alphanum scw = w.swapcase() return [pieces, first_match, span, scw] def sort(matches: list): # log('matches: %s' % matches) # raise RuntimeError('CUSTOM SORTER: %s' % matches) matches.sort(key=key) return matches return sort <file_sep>/pythonx/ncm2_filter/fuzzybydate.py from ncm2_filter.abbr_ellipsis import Filter as EllipsisFilter from datetime import datetime from operator import itemgetter def log(msg): now = str(datetime.now()) with open('/tmp/ncm2-jira.log', 'a') as file_: file_.write('%s %s\n' % (now, msg)) ellipses_filter = EllipsisFilter(limit=120, ellipsis='…') def Filter(**kargs): def filt(data, sr, sctx, sccol, matches): typed = data['context']['typed'] # When query is empty, sort candidates by their last_updated field # in descending order so that recently updated items are first in the # list #log('FILTER TYPED: %s' % typed) result = matches if typed.endswith('JI'): result = sorted(matches, key=itemgetter('last_updated'), reverse=True) return ellipses_filter(data, sr, sctx, sccol, result) return filt <file_sep>/README.md # ncm2-look.vim Port of the [neco-look] plugin for [NCM2] Using `look` to complete words in english ![](https://user-images.githubusercontent.com/48519/42656561-0748c44e-85f6-11e8-8f68-aeacda42876b.gif) ## Requirements - [ncm2] - [nvim-yarp] (required by ncm2) - `look` binary. run `which look` on your terminal to see if it's available; ## Installation Use your favorite plugin manager. I recommend [vim-plug]: ```vim " NCM and it's requirements Plug 'ncm2/ncm2' Plug 'roxma/nvim-yarp' " Look.vim completion plugin Plug 'filipekiss/ncm2-look.vim' " enable ncm2 for all buffer autocmd BufEnter * call ncm2#enable_for_buffer() " note that must keep noinsert in completeopt, the others is optional set completeopt=noinsert,menuone,noselect ``` ## Usage By default, look.vim will be disabled. After all, if you're writing code you don't want the completion popup jumping at you everytime you type something that remotely looks like a word. #### To enable it globally Put this in your `.vimrc` ```vim let g:ncm2_look_enabled = 1 ``` #### To enable it on a per-buffer basis ```vim :let b:ncm2_look_enabled = 1 ``` #### To enable it on a pre-filetype basis Let's say you want to enable it for markdown files. - Create a file in `~/.vim/ftplugin/markdown.vim` - Put `let b:ncm2_look_enabled = 1` on the file - Save and open a markdown file [neco-look]: https://github.com/ujihisa/neco-look [ncm2]: https://github.com/ncm2/ncm2 [nvim-yarp]: https://github.com/roxma/nvim-yarp [vim-plug]: https://github.com/junegunn/vim-plug # ncm2-jira
9911a097f8f2c20efeefaabe0f7077ff1763d378
[ "Markdown", "Python" ]
4
Python
balta2ar/ncm2-jira
a67d243f56b011579c0632f277c7bc1e2fd8f1d8
ce364ec5ce430e98a2de01be1dbee09fe5e794ba