language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
454
3.234375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { int i,ram[5]={1,2,3,4,5},sum=0; int temp; printf("Name\t Value\t Address\n"); for(i=0;i<5;i++) { int *ptr= ram[i]; printf("ram[%d]\t %d\t%p\n",i,ram[i],ptr); } printf("Another method\n"); for(i=0;i<5;i++) { temp= *(ram+i); sum=sum+temp; } printf("The sum of the data is :%d",sum); return 0; }
Python
UTF-8
1,876
2.734375
3
[ "Apache-2.0" ]
permissive
"""A material template.""" from gemd.entity.template.base_template import BaseTemplate from gemd.entity.template.has_property_templates import HasPropertyTemplates class MaterialTemplate(BaseTemplate, HasPropertyTemplates): """ A material template. Material templates are collections of property templates that constrain the values of a material's property attributes, and provide a common structure for describing similar materials. Parameters ---------- name: str, optional The name of the material template. description: str, optional Long-form description of the material template. uids: Map[str, str], optional A collection of `unique IDs <https://citrineinformatics.github.io/gemd-documentation/ specification/unique-identifiers/>`_. tags: List[str], optional `Tags <https://citrineinformatics.github.io/gemd-documentation/specification/tags/>`_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. properties: List[:class:`PropertyTemplate \ <gemd.entity.template.property_template.PropertyTemplate>`] or \ List[:class:`PropertyTemplate <gemd.entity.template.property_template.PropertyTemplate>`,\ :py:class:`BaseBounds <gemd.entity.bounds.base_bounds.BaseBounds>`], optional Templates for associated properties. Each template can be provided by itself, or as a list with the second entry being a separate, *more restrictive* Bounds object that defines the limits of the value for this property. """ typ = "material_template" def __init__(self, name=None, description=None, properties=None, uids=None, tags=None): BaseTemplate.__init__(self, name, description, uids, tags) HasPropertyTemplates.__init__(self, properties)
Java
UTF-8
29,191
1.53125
2
[]
no_license
package com.hlnwl.auction.ui.goods; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.view.View; import android.webkit.WebView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.allen.library.SuperButton; import com.bakerj.rxretrohttp.RxRetroHttp; import com.bakerj.rxretrohttp.subscriber.ApiObserver; import com.blankj.utilcode.util.StringUtils; import com.hlnwl.auction.R; import com.hlnwl.auction.base.BaseDialog; import com.hlnwl.auction.base.MyActivity; import com.hlnwl.auction.bean.NoDataBean; import com.hlnwl.auction.bean.goods.GoodsDetailBean; import com.hlnwl.auction.bean.goods.OfferBean; import com.hlnwl.auction.message.LoginMessage; import com.hlnwl.auction.ui.common.ImagePagerActivity; import com.hlnwl.auction.ui.common.LoginActivity; import com.hlnwl.auction.ui.shop.ShopHomeAcitivity; import com.hlnwl.auction.ui.user.bid.BidRecordActivity; import com.hlnwl.auction.utils.CountdownUtils; import com.hlnwl.auction.utils.StringsUtils; import com.hlnwl.auction.utils.http.Api; import com.hlnwl.auction.utils.http.MessageUtils; import com.hlnwl.auction.utils.my.MyLinearLayoutManager; import com.hlnwl.auction.utils.my.PhoneUtil; import com.hlnwl.auction.utils.photo.ImageLoaderUtils; import com.hlnwl.auction.utils.sp.SPUtils; import com.hlnwl.auction.view.banner.GlideImageLoader; import com.hlnwl.auction.view.dialog.BidRecordDialog; import com.hlnwl.auction.view.dialog.BondDialog; import com.hlnwl.auction.view.dialog.PayDialog; import com.sackcentury.shinebuttonlib.ShineButton; import com.youth.banner.Banner; import com.youth.banner.BannerConfig; import com.youth.banner.Transformer; import com.youth.banner.listener.OnBannerListener; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import cn.iwgang.countdownview.CountdownView; /** * 版权:hlnwl 版权所有 * * @author yougui * 版本:1.0 * 创建日期:2019/9/19 13:59 * 描述: */ public class GoodsDetailActivity extends MyActivity { @BindView(R.id.goods_detail_banner) Banner mBanner; @BindView(R.id.goods_detail_price_start) TextView mPriceStart; @BindView(R.id.goods_detail_price_add_once) TextView mAddOnce; @BindView(R.id.goods_detail_title) TextView mTitle; @BindView(R.id.goods_detail_introduce) TextView mIntroduce; @BindView(R.id.goods_detail_weight) TextView mWeight; @BindView(R.id.goods_detail_from) TextView mFrom; @BindView(R.id.goods_detail_style) TextView mStyle; @BindView(R.id.goods_detail_bid_record) RecyclerView mGoodsBidRecord; @BindView(R.id.goods_detail_shop_img) ImageView mShopImg; @BindView(R.id.goods_detail_shop_name) TextView mShopName; @BindView(R.id.goods_detail_phone) TextView mPhone; @BindView(R.id.goods_detail_time_count) TextView mTimeCount; @BindView(R.id.goods_detail_like_tv) TextView mLikeNum; @BindView(R.id.goods_detail_see_tv) TextView mSeeNum; @BindView(R.id.good_detail_web) WebView mWeb; @BindView(R.id.goods_detail_is_j) TextView mIsJp; @BindView(R.id.goods_detail_attribute) RecyclerView mGoodsDetailAttribute; @BindView(R.id.offer_message) TextView mOfferMessage; @BindView(R.id.goods_detail_make_price) TextView mGoodsDetailMakePrice; @BindView(R.id.chujia_liebiao) LinearLayout liebiao; @BindView(R.id.countdownView1) CountdownView countdownView1; @BindView(R.id.ll_count) LinearLayout llCount; @BindView(R.id.ll_price) LinearLayout llPrice; @BindView(R.id.goods_detail_shop_in) SuperButton goodsDetailShopIn; @BindView(R.id.ll_shop) LinearLayout llShop; @BindView(R.id.goods_detail_like) LinearLayout goodsDetailLike; @BindView(R.id.tv_exhibition) TextView tvExhibition; @BindView(R.id.goods_detail_normal) LinearLayout goodsDetailNormal; @BindView(R.id.buy_layout) LinearLayout buyLayout; private String good_id = ""; private GoodsDetailBean.DataBean mGoodsDetailData; private TimeCount time;//倒计时 private GoodsAttrAdapter mAttrAdapter; private OfferAdapter mOfferAdapter; private static boolean flag = true; private ShineButton shineButton; private String price = ""; @Override protected int getLayoutId() { return R.layout.activity_goods_detail; } @Override protected int getTitleBarId() { return R.id.title_tb; } @Override protected void initView() { shineButton = (ShineButton) findViewById(R.id.shine_button); if (shineButton != null) shineButton.init(this); shineButton.setClickable(false); shineButton.setFocusable(false); } @Subscribe(threadMode = ThreadMode.MAIN) public void loginEventBus(LoginMessage update) { getData(); setTimer(); } @Override protected void initData() { good_id = getIntent().getStringExtra("id"); showLoading(); getData(); setTimer(); if (getIntent().getIntExtra("tag", 0) == 1) { llCount.setVisibility(View.VISIBLE); llPrice.setVisibility(View.GONE); llShop.setVisibility(View.GONE); tvExhibition.setText(getResources().getString(R.string.exhibition1)); mGoodsDetailMakePrice.setText(getResources().getString(R.string.display1)); mTimeCount.setText(getResources().getString(R.string.call_customer1)); } else if (getIntent().getIntExtra("tag", 0) == 2) { llCount.setVisibility(View.GONE); goodsDetailNormal.setVisibility(View.GONE); buyLayout.setVisibility(View.VISIBLE); } else { llCount.setVisibility(View.GONE); llPrice.setVisibility(View.VISIBLE); } } private void getData() { if (getIntent().getIntExtra("tag", 0) == 2) { RxRetroHttp.composeRequest(RxRetroHttp.create(Api.class) .getGoodsData2(good_id, StringUtils.null2Length0(SPUtils.getUserId())), this) .subscribe(new ApiObserver<GoodsDetailBean>() { @Override protected void success(GoodsDetailBean data) { boolean isSuccess = MessageUtils.setCode(getActivity(), data.getStatus() + "", data.getMsg()); if (!isSuccess) { showError(); return; } if (data.getData().get(0) != null) { mGoodsDetailData = data.getData().get(0); initUI(data.getData().get(0)); } } @Override public void onError(Throwable t) { super.onError(t); showError(); toast(t.getMessage()); } } ); } else { RxRetroHttp.composeRequest(RxRetroHttp.create(Api.class) .getGoodsData(SPUtils.getLanguage(), good_id, StringUtils.null2Length0(SPUtils.getUserId())), this) .subscribe(new ApiObserver<GoodsDetailBean>() { @Override protected void success(GoodsDetailBean data) { boolean isSuccess = MessageUtils.setCode(getActivity(), data.getStatus() + "", data.getMsg()); if (!isSuccess) { showError(); return; } if (data.getData().get(0) != null) { mGoodsDetailData = data.getData().get(0); initUI(data.getData().get(0)); } } @Override public void onError(Throwable t) { super.onError(t); showError(); toast(t.getMessage()); } } ); } } private void initUI(GoodsDetailBean.DataBean dataBean) { // 倒计时 CountdownUtils.getCounDown(countdownView1, StringsUtils.getStrTime(String.valueOf(dataBean.getEndtime()))); mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR); //设置图片加载器 mBanner.setImageLoader(new GlideImageLoader()); //设置图片集合 mBanner.setImages(dataBean.getPic()); //设置banner动画效果 mBanner.setBannerAnimation(Transformer.Default); //设置标题集合(当banner样式有显示title时) // banner.setBannerTitles(titles); //设置自动轮播,默认为true mBanner.isAutoPlay(true); //设置轮播时间 mBanner.setDelayTime(3500); //设置指示器位置(当banner模式中有指示器时) mBanner.setIndicatorGravity(BannerConfig.CENTER); ArrayList<String> imgUrls = new ArrayList<>(); imgUrls.addAll(dataBean.getPic()); mBanner.setOnBannerListener(new OnBannerListener() { @Override public void OnBannerClick(int position) { Intent intent = new Intent(GoodsDetailActivity.this, ImagePagerActivity.class); intent.putStringArrayListExtra("imageUrls", imgUrls); intent.putExtra("position", position + ""); startActivity(intent); } }); //banner设置方法全部调用完毕时最后调用 mBanner.start(); log(mGoodsDetailData.getStatus()); if (!StringUtils.isEmpty(mGoodsDetailData.getIs_bid()) && mGoodsDetailData.getIs_bid().equals("1")) { mPriceStart.setVisibility(View.VISIBLE); mAddOnce.setVisibility(View.VISIBLE); mPriceStart.setText(getResources().getString(R.string.price_start) + getResources().getString(R.string.money) + dataBean.getLow_price()); mAddOnce.setText(getResources().getString(R.string.add_once) + getResources().getString(R.string.money) + dataBean.getBid_price()); if (mGoodsDetailData.getStatus().equals("0")) { Date date = new Date(); long timestamp = date.getTime(); //时间戳 long midTime = mGoodsDetailData.getEndtime() * 1000 - timestamp; // long mytime=TimeUtils.getMillisByNow(mGoodsDetailData.getEndtime(),); if (midTime > 0) { log(midTime + ""); // time = new TimeCount(this, midTime, 1000, mTimeCount); // time.start(); } //mGoodsDetailMakePrice.setBackgroundColor(ColorUtils.getColor(R.color.main)); } else { // mGoodsDetailMakePrice.setBackgroundColor(ColorUtils.getColor(R.color.gray)); // mTimeCount.setText(StringsUtils.getString(R.string.auction_over)); } liebiao.setVisibility(View.VISIBLE); } else { mPriceStart.setVisibility(View.INVISIBLE); mAddOnce.setVisibility(View.INVISIBLE); // mTimeCount.setText(StringsUtils.getString(R.string.goods_zhanshi)); // mGoodsDetailMakePrice.setBackgroundColor(ColorUtils.getColor(R.color.gray)); //mGoodsDetailMakePrice.setText(StringsUtils.getString(R.string.zhanshi)); liebiao.setVisibility(View.GONE); } mTitle.setText(dataBean.getName()); // String css = "<style type=\"text/css\"> img {" + // "width:100%;" + // "height:auto;" + // "}" + // "body {" + // "margin-right:15px;" + // "margin-left:15px;" + // "margin-top:15px;" + // "font-size:15px;" + // "}" + // "</style>"; // String url = goodsDetailData.getGoods_content(); // url = url.replaceAll("<img src=\"", "<img src=\"" + CONFIG.URL); // String html = "<html><header>" + css + "</header><body>" + url + "</body></html>"; // goodsWeb.loadDataWithBaseURL("file://", html, "text/html", "UTF-8", "about:blank"); mWeb.loadDataWithBaseURL("file://", dataBean.getContent(), "text/html", "utf-8", "about:blank"); if (dataBean.getSpeci().size() > 0) { log(dataBean.getSpeci().get(0).toString()); mGoodsDetailAttribute.setLayoutManager(new LinearLayoutManager(getActivity())); mAttrAdapter = new GoodsAttrAdapter(); mAttrAdapter.setNewData(dataBean.getSpeci()); mGoodsDetailAttribute.setAdapter(mAttrAdapter); } ImageLoaderUtils.display(this, mShopImg, dataBean.getSpic()); mShopName.setText(dataBean.getSname()); mPhone.setText(getResources().getString(R.string.hotline) + " " + dataBean.getSphone()); if (dataBean.getGenre().equals("1")) { mIsJp.setVisibility(View.VISIBLE); } else { mIsJp.setVisibility(View.GONE); } log(mGoodsDetailData.getStatus() + " " + mGoodsDetailData.getIs_bid()); if (mGoodsDetailData.getGive().equals("0")) { shineButton.setChecked(false); } else { shineButton.setChecked(true); } mLikeNum.setText(mGoodsDetailData.getBang()); mSeeNum.setText(mGoodsDetailData.getViews()); getOfferList(); showComplete(); } private void setTimer() { mHandler.postDelayed(runnable, 30000); } private Handler mHandler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { //在这里执行定时需要的操作 getOfferList(); if (flag) { mHandler.postDelayed(this, 30000); } } }; private void getOfferList() { RxRetroHttp.composeRequest(RxRetroHttp.create(Api.class) .getOfferList(SPUtils.getLanguage(), 1, good_id), this) .subscribe(new ApiObserver<OfferBean>() { @Override protected void success(OfferBean data) { boolean isSuccess = MessageUtils.setCode(getActivity(), data.getStatus() + "", data.getMsg()); if (!isSuccess) { return; } initOffer(data.getData()); } @Override public void onError(Throwable t) { super.onError(t); toast(t.getMessage()); } } ); } private void initOffer(List<OfferBean.DataBean> data) { List<OfferBean.DataBean> offerList = new ArrayList<>(); offerList.clear(); if (data.size() > 4) { for (int i = 0; i < 5; i++) { offerList.add(data.get(i)); } } else { offerList.addAll(data); } if (offerList.size() > 0) { price = Double.parseDouble(offerList.get(0).getPrice()) + Double.parseDouble(mGoodsDetailData.getBid_price()) + ""; } else { price = mGoodsDetailData.getLow_price(); } mGoodsBidRecord.setLayoutManager(new MyLinearLayoutManager(getActivity())); if (mOfferAdapter == null) { mOfferAdapter = new OfferAdapter(); mGoodsBidRecord.setAdapter(mOfferAdapter); } else { mOfferAdapter.notifyDataSetChanged(); } mOfferAdapter.setNewData(offerList); //第一页如果不够一页就不显示没有更多数据布局 if (offerList.size() < 5) { mOfferMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toast(getResources().getString(R.string.no_more_offer)); } }); } else { mOfferMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(GoodsDetailActivity.this, OfferRecordActivity.class) .putExtra("good_id", good_id)); } }); } if (offerList.size() == 0) { mOfferMessage.setText(getResources().getString(R.string.null_offer)); } else if (offerList.size() > 2) { mOfferMessage.setText(getResources().getString(R.string.see_more)); } } private void stopTimer() { flag = false; } @OnClick({R.id.goods_detail_back, R.id.goods_detail_shop_in, R.id.goods_detail_like, R.id.goods_detail_make_price, R.id.goods_detail_phone}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.goods_detail_back: finish(); break; case R.id.goods_detail_shop_in: startActivity(new Intent(this, ShopHomeAcitivity.class) .putExtra("name", mGoodsDetailData.getSname()) .putExtra("pic", mGoodsDetailData.getSpic()) .putExtra("id", mGoodsDetailData.getSid())); break; case R.id.goods_detail_like: if (SPUtils.getLogin().length() == 0 || SPUtils.getLogin() == null) { startActivity(LoginActivity.class); } else { if (shineButton.isChecked()) { like(false); } else { like(true); } } break; case R.id.goods_detail_make_price: if (mGoodsDetailData.getIs_bid().equals("2")) { toast(StringUtils.getString(R.string.goods_zhanshi)); } else { if (mGoodsDetailData.getStatus().equals("0")) { if (SPUtils.getLogin().length() == 0 || SPUtils.getLogin() == null) { startActivity(LoginActivity.class); } else { getIfOffer(); } } else { toast(StringUtils.getString(R.string.auction_over)); } } break; case R.id.goods_detail_phone: PhoneUtil.callPhone(this, mGoodsDetailData.getSphone()); break; } } private void like(boolean islike) { RxRetroHttp.composeRequest(RxRetroHttp.create(Api.class) .islike(SPUtils.getLanguage(), SPUtils.getUserId(), SPUtils.getToken(), good_id), this) .subscribe(new ApiObserver<NoDataBean>() { @Override protected void success(NoDataBean data) { boolean isSuccess = MessageUtils.setCode(GoodsDetailActivity.this, data.getStatus(), data.getMsg()); if (!isSuccess) { return; } if (islike) { shineButton.setChecked(true, true); mLikeNum.setText(Integer.parseInt(mLikeNum.getText().toString()) + 1 + ""); } else { shineButton.setChecked(false, true); mLikeNum.setText(Integer.parseInt(mLikeNum.getText().toString()) - 1 + ""); } } @Override public void onError(Throwable t) { super.onError(t); toast(t.getMessage()); } } ); } private BaseDialog payOffer() { return new PayDialog.Builder(GoodsDetailActivity.this, "pay") .setPrice(StringUtils.getString(R.string.chujia) + " " + price + StringUtils.getString(R.string.money_unit)) .setListener(new PayDialog.OnPayListener() { @Override public void onSelected(Dialog dialog, String pay_style) { if (pay_style.equals("weChat")) { } else if (pay_style.equals("alipay")) { } else { offer("1"); } } @Override public void onCancel(Dialog dialog) { dialog.dismiss(); } }).show(); } private void offer(String paytype) { RxRetroHttp.composeRequest(RxRetroHttp.create(Api.class) .offer(SPUtils.getLanguage(), StringUtils.null2Length0(SPUtils.getUserId()), StringUtils.null2Length0(SPUtils.getToken()), good_id, paytype), this) .subscribe(new ApiObserver<NoDataBean>() { @Override protected void success(NoDataBean data) { boolean isSuccess = MessageUtils.setCode(getActivity(), data.getStatus() + "", data.getMsg()); if (!isSuccess) { return; } EventBus.getDefault().post(new LoginMessage("update")); getOfferList(); toast(data.getMsg()); getBidRecord(); } @Override public void onError(Throwable t) { super.onError(t); toast(t.getMessage()); } } ); } private BaseDialog getBidRecord() { return new BidRecordDialog.Builder(GoodsDetailActivity.this) .setListener(new BidRecordDialog.OnClickListener() { @Override public void setOnClick(View v) { startActivity(BidRecordActivity.class); } }).show(); } private void getIfOffer() { RxRetroHttp.composeRequest(RxRetroHttp.create(Api.class) .getGoodsData(SPUtils.getLanguage(), good_id, StringUtils.null2Length0(SPUtils.getUserId())), this) .subscribe(new ApiObserver<GoodsDetailBean>() { @Override protected void success(GoodsDetailBean data) { boolean isSuccess = MessageUtils.setCode(getActivity(), data.getStatus() + "", data.getMsg()); if (!isSuccess) { return; } if (data.getData().get(0) != null) { log(data.getData().get(0).getOffer()); if (data.getData().get(0).getOffer().equals("0")) { new BondDialog.Builder(GoodsDetailActivity.this, data.getData().get(0).getPrice()) .setListener(new BondDialog.OnClickListener() { @Override public void setOnClick(View v) { payOffer(); } }) // .setGravity(Gravity.BOTTOM) // .setAnimStyle(BaseDialog.AnimStyle.BOTTOM) .show(); } else { payOffer(); } } } @Override public void onError(Throwable t) { super.onError(t); toast(t.getMessage()); } } ); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } private class TimeCount extends CountDownTimer { private TextView getVerCode; private Context mContext; public TimeCount(Context context, long millisInFuture, long countDownInterval, TextView getVerCode) { super(millisInFuture, countDownInterval); this.getVerCode = getVerCode; this.mContext = context; } @Override public void onTick(long millisUntilFinished) { getVerCode.setEnabled(false); getVerCode.setText(mContext.getResources().getString(R.string.goods_detail_time_count) + " " + secToTime(millisUntilFinished)); } @Override public void onFinish() { getVerCode.setText(mContext.getResources().getString(R.string.auction_over)); getVerCode.setEnabled(true); } } public String secToTime(long time) { int ss = 1000; int mi = ss * 60; int hh = mi * 60; int dd = hh * 24; long day = time / dd; long hour = (time - day * dd) / hh; long minute = (time - day * dd - hour * hh) / mi; long second = (time - day * dd - hour * hh - minute * mi) / ss; long milliSecond = time - day * dd - hour * hh - minute * mi - second * ss; String strDay = day < 10 ? "0" + day : "" + day; //天 String strHour = hour < 10 ? "0" + hour : "" + hour;//小时 String strMinute = minute < 10 ? "0" + minute : "" + minute;//分钟 String strSecond = second < 10 ? "0" + second : "" + second;//秒 String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;//毫秒 strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond; return strDay + getResources().getString(R.string.day) + " " + strHour + " : " + strMinute + " : " + strSecond; } @Override protected void onDestroy() { super.onDestroy(); if (time != null) { time.cancel(); } mHandler.removeCallbacks(runnable); stopTimer(); } }
Markdown
UTF-8
1,128
2.515625
3
[]
no_license
# SpeedPack (toàn bộ ý tưởng và hình ảnh đều của lumosity-speedpack game) Yêu cầu màn hình FullHD (do window co size 1000x1000) Gõ "./make" trong cửa sổ Shell hoặc cmd để compile code Gõ "./make run" trong cửa sổ Shell hoặc cmd để chơi Giới thiệu về game SpeedPack: Thời gian 1 lượt chơi: 2 phút Mục tiêu: Tối đa số điểm đạt được (Sẽ có thông báo khác nhau theo điểm người chơi đạt được khi gameover) Người chơi cần chọn vị trí để đặt camera vào vali sao cho khi vali đóng lại, camera không bị đè lên bởi vật khác trong vali Hiện chỉ có 2 lọai vali tương ứng với 10 điểm và 15 điểm nếu người chơi chọn đúng Người chơi có thể nhận thêm điểm trên mỗi vali chọn đúng nếu chọn đúng liên tiếp nhiều lần Có thể nhấn Esc để tạm dừng và hiện Menu trong lúc chơi Có thể điều khiển trên menu bằng chuột hoặc bàn phím Hiện lựa chọn Option trong menu chưa khả dụng # DEMO ![](demo.gif)
Markdown
UTF-8
862
2.578125
3
[]
no_license
# MyReads Project This is my 6th project with Udacity for the Front End Development Nanodegree.A static example of the CSS and HTML markup was provided and was used to write React code that was needed to complete the project. Progressively, added interactivity to the app by refactoring the static code. Getting Started Download this repo Install all project dependencies with npm install Start the development server with npm start Highlights: Created a new JS file for each component. Component state is passed down from parent to child component. SetState() is used to modify the state of the component. Resources React-router-dom. (n.d.). Retrieved from https://www.npmjs.com/package/react-router-dom Waite, R. (2018, September 22). Tutorial Requests: FEND Project 6 - Walk Through (LONG). Retrieved from https://www.youtube.com/watch?v=acJHkd6K5kI
Markdown
UTF-8
1,921
2.546875
3
[]
no_license
--- title: "CBioPortal and cgdsr: An Introduction" header: teaser: "post_teasers/cbioportal_900x450.jpg" image: "post_teasers/cbioportal_1600x450.jpg" categories: - r author: Augustin Luna --- The [cBio Cancer Genomics Portal](http://cbioportal.org/) is an open-access resource for interactive exploration of multidimensional cancer genomics data sets, currently providing access to data from more than 100 cancer studies. The cBio Cancer Genomics Portal significantly lowers the barriers between complex genomic data and cancer researchers who want rapid, intuitive, and high-quality access to molecular profiles and clinical attributes from large-scale cancer genomics projects and empowers researchers to translate these rich data sets into biologic insights and clinical applications. The slides below preview many of the website features found on the CBioPortal website, including view genomic alterations as [oncoprints](http://www.cbioportal.org/faq.jsp#what-are-oncoprints) (a compact way of viewing genomic alterations across a large number of study patients), viewing study summaries, and accessing details patient data, such as, histology images and pathology reports. Additionally, the slides provide introductory material for the usage of CBioPortal from R using the cgdsr package. cgdsr simplifies access to the [web application programming interface (API)](http://www.cbioportal.org/web_api.jsp) provided by the project. This is a REST-based API, that allows software to query the database using parameters appended onto the URL. Using the cgdsr package mirrors closely the way a user would manually interact with the CBioPortal website by searching and selecting the cancer studies of interest, the genetic profiles for a given study, and the case sets for the cancer study. Slides: cBioPortal: [http://slides.lunean.com/uspWorkshop/cbioportal.pdf](http://slides.lunean.com/uspWorkshop/cbioportal.pdf)
Java
UTF-8
498
2.4375
2
[]
no_license
package state.freundin.v2; public abstract class AbstrakteZustand implements Zustand{ protected Freundin freundin; public AbstrakteZustand(Freundin freundin){ this.freundin = freundin; } @Override public void unterhalten() { throw new IllegalStateException(); } @Override public void kussGeben() { throw new IllegalStateException(); } @Override public void verärgern() { throw new IllegalStateException(); } }
Python
UTF-8
3,725
2.671875
3
[]
no_license
import pandas as pd import models from models import Input, PolarityOutput # test each aspect: def load_polarity_data(path, aspectId): """ :param path: :return: :rtype: list of models.Input """ inputs = [] outputs = [] df = pd.read_csv(path) for _, r in df.iterrows(): if r['aspect{}'.format(aspectId)] != 0: t = r['text'].strip() inputs.append(Input(t)) score = r['aspect{}'.format(aspectId)] label = 'aspect{}'.format(aspectId) + (' -' if score == -1 else ' +') aspect = 'aspect{}'.format(aspectId) outputs.append(PolarityOutput(label, aspect, score)) return inputs, outputs def preprocess(inputs): return inputs # def load_stopword(path): # """ # load stopword from path, # :param path: # :return: pd.DataFrame # """ # return pd.read_csv(path, sep=',', header=None, names=["stopword"]) # # # def load_acronym(path): # """ # load vietnamese acronyms in comments, maybe missing # :param path: # :return: pd.DataFrame # """ # return pd.read_csv(path, sep=',', header=None, names=["acronym", "meaning"]) # # def preprocess(inputs, stopword=None, acronym=None, break_sentence=True, stopword_filter=True, acronym_filter=True, tokenizer: models.Tokenizer=None): # """ # :param tokenizer: pretrain model # :param acronym_filter: using acronym converter or not # :param acronym: pd.DataFrame acronym: list of acronym # :param inputs: list of models.Input: inputs # :param break_sentence: True if break the sentence into words # :param stopword_filter: True if filter stopword # :param stopword: pd.DataFrame of stopword # :return: list of models.Input: output # """ # # using VnCoreNLP for sentence segmentation # # default path: # tokenizer = models.PivyTokenizer() # ans = inputs # # if break_sentence: # ans = tokenizer.tokenizer(ans) # # ans = word_filter(ans, acronym_filter, stopword_filter, acronym, stopword) # # return ans # # # def word_filter(inputs, use_dup_letter_filter, use_len_filter, use_acronym, use_stopword, acronyms : pd.DataFrame = None, stopword : pd.DataFrame = None): # """ # Multi function filter # :param inputs: list of models.Input # :param use_dup_letter_filter: True if remove duplicated last letter. ex: hiiiii -> hi # :param use_len_filter: True, remove word that longer than 7 # :param use_acronym: True, replace acronym with meaning # :param use_stopword: True, remove stopword # :param acronyms: DataFrame of acronyms # :param stopword: DataFrame of stopwords # :return: # """ # outputs = [] # for input in inputs: # texts = input.text.split(' ') # ans = [] # for text in texts: # # remove duplicate last letter # while use_dup_letter_filter and len(text) > 1 and text[-1] == text[-2]: # text = text[:-1] # # remove too long or null word # if use_len_filter: # if len(text) > 7 or len(text) < 1: # continue # # replace acronym with corresponding word # if use_acronym and text in acronyms["acronym"].values: # text = acronyms[acronyms["acronym"] == text].iloc[0, 1] # # remove stopword # if use_stopword and text in stopword.values: # continue # # ans.append(text) # outputs.append(models.Input(" ".join(ans))) # return outputs # # # def examinate(inputs): # print("Len: ", len(inputs)) # for input in inputs: # print(input.text) # print()
Markdown
UTF-8
1,487
3.234375
3
[]
no_license
# 자바의 메모리 구조 및 구성 ![자바 메모리 구조](images/java_memory_structure.png) ## Data - global, static variables가 저장되는 영역이다. - 프로그램의 시작과 함께 할당되며, 프로그램이 종료되면 소멸한다. ## Stack - 프로그램의 실행 과정에서 임시로 할당되는 변수(local variables)가 저장된다. - variable이 primitive type(int, char, boolean ...)라면 실제 값이 저장된다. - 객체라면 reference value가 저장되며, 실제 데이터는 heap 영역에 저장된다. - 런 타임에 그 크기가 결정된다. - 메소드가 호출됧 때마다 그 메소드의 로컬 변수를 준비하고, 메소드 호출이 끝나면 메소드 내 local variables가 스택에서 제거된다. ## Heap - 동적 데이터를 보관하는 저장소로, 런 타임에 그 크기가 결정된다. - 힙 영역에 보관되는 메모리는 메소드 호출이 끝나도 사라지지 않고 유지된다. - GB에 의해 지워지거나 JVM이 종료되면 사라진다. - 'new'를 통해 생성된 Reference type의 실제 데이터가 저장되는 공간이다. ```java public void blahblah() { int[] arr = new int[2]; arr[0] = 1; arr[1] = 2; } // 실제 데이터(1, 2)는 heap 영역에 저장되고, 이 영역을 가르키는 참조값(reference value)이 stack 영역에 저장된다. ``` ![자바 heap과 stack](images/java_stack_heap.png) <hr/> ## Reference - http://wanzargen.tistory.com/17
C#
UTF-8
476
2.875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CompositionOverInheritance { public class Toyota : IManufacturer { private static IManufacturer instance; private Toyota() { } public string Name { get { return "Toyota"; } } public static IManufacturer GetInstance() { return instance ?? (instance = new Toyota()); } } }
C#
UTF-8
1,850
2.828125
3
[]
no_license
class Program { public delegate bool WindowEnumDelegate(IntPtr hwnd, int lParam); [DllImport("user32.dll")] public static extern int EnumChildWindows(IntPtr hwnd, WindowEnumDelegate del, int lParam); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hwnd, StringBuilder bld, int size); static void Main(string[] args) { var mainWindowHandle = Process.GetProcessesByName("mpc-hc").First().MainWindowHandle; var list = new List<string>(); EnumChildWindows(mainWindowHandle, (hwnd, param) => { var bld = new StringBuilder(256); GetWindowText(hwnd, bld, 256); var text = bld.ToString(); if (!string.IsNullOrEmpty(text)) list.Add(text); return true; }, 0); Console.WriteLine("length={0}", list[0]); Console.WriteLine("state={0}", list[1]); Console.WriteLine("bitrate={0}", list[5]); Console.WriteLine("name={0}", list[7]); Console.WriteLine("Press enter to exit"); Console.ReadLine(); } }
TypeScript
UTF-8
2,581
2.90625
3
[ "MIT" ]
permissive
import { describe, expect, it } from 'vitest'; import { EventID, PublicKey } from '@/utils/Hex/Hex.ts'; describe('PublicKey', () => { it('should convert npub bech32 to hex', () => { const bech32 = 'npub1g53mukxnjkcmr94fhryzkqutdz2ukq4ks0gvy5af25rgmwsl4ngq43drvk'; const hex = '4523be58d395b1b196a9b8c82b038b6895cb02b683d0c253a955068dba1facd0'; const publicKey = new PublicKey(bech32); expect(publicKey.hex).toEqual(hex); expect(publicKey.npub).toEqual(bech32); }); it('should init from hex', () => { const hex = '4523be58d395b1b196a9b8c82b038b6895cb02b683d0c253a955068dba1facd0'; const publicKey = new PublicKey(hex); expect(publicKey.hex).toEqual(hex); expect(publicKey.npub).toEqual( 'npub1g53mukxnjkcmr94fhryzkqutdz2ukq4ks0gvy5af25rgmwsl4ngq43drvk', ); }); it('should fail with too long hex', () => { const hex = '4523be58d395b1b196a9b8c82b038b6895cb02b683d0c253a955068dba1facd04523be58d395b1b196a9b8c82b038b6895cb02b683d0c253a955068dba1facd0'; expect(() => new PublicKey(hex)).toThrow(); }); it('equals(hexStr)', () => { const hex = '4523be58d395b1b196a9b8c82b038b6895cb02b683d0c253a955068dba1facd0'; const publicKey = new PublicKey(hex); expect(publicKey.equals(hex)).toEqual(true); }); it('equals(PublicKey)', () => { const hex = '4523be58d395b1b196a9b8c82b038b6895cb02b683d0c253a955068dba1facd0'; const publicKey = new PublicKey(hex); const publicKey2 = new PublicKey(hex); expect(publicKey.equals(publicKey2)).toEqual(true); }); it('equals(bech32)', () => { const bech32 = 'npub1g53mukxnjkcmr94fhryzkqutdz2ukq4ks0gvy5af25rgmwsl4ngq43drvk'; const publicKey = new PublicKey(bech32); expect(publicKey.equals(bech32)).toEqual(true); }); }); describe('EventID', () => { it('should convert note id bech32 to hex', () => { const noteBech32 = 'note1wdyajan9c9d72wanqe2l34lxgdu3q5esglhquusfkg34fqq6462qh4cjd5'; const noteHex = '7349d97665c15be53bb30655f8d7e6437910533047ee0e7209b22354801aae94'; const eventId = new EventID(noteBech32); expect(eventId.hex).toEqual(noteHex); expect(eventId.note).toEqual(noteBech32); }); it('should init from hex', () => { const hex = '7349d97665c15be53bb30655f8d7e6437910533047ee0e7209b22354801aae94'; const eventId = new EventID(hex); expect(eventId.hex).toEqual(hex); expect(eventId.note).toEqual('note1wdyajan9c9d72wanqe2l34lxgdu3q5esglhquusfkg34fqq6462qh4cjd5'); }); it('should fail with too long hex', () => { const hex = '7349d97665c15be53bb30655f8d7e6437910533047ee0e7209b22354801aae947349d97665c15be53bb30655f8d7e6437910533047ee0e7209b22354801aae94'; expect(() => new EventID(hex)).toThrow(); }); it('equals(hexStr)', () => { const hex = '7349d97665c15be53bb30655f8d7e6437910533047ee0e7209b22354801aae94'; const eventId = new EventID(hex); expect(eventId.equals(hex)).toEqual(true); }); it('equals(EventID)', () => { const hex = '7349d97665c15be53bb30655f8d7e6437910533047ee0e7209b22354801aae94'; const eventId = new EventID(hex); const eventId2 = new EventID(hex); expect(eventId.equals(eventId2)).toEqual(true); }); it('equals(bech32)', () => { const bech32 = 'note1wdyajan9c9d72wanqe2l34lxgdu3q5esglhquusfkg34fqq6462qh4cjd5'; const eventId = new EventID(bech32); expect(eventId.equals(bech32)).toEqual(true); }); });
Python
UTF-8
383
3.171875
3
[]
no_license
a = 100 b = 'Male' c = ['a','b','c'] d = (10, 20, 30, 40) e = { 2020, 2021, 2022, 2023 } std = { "name" : "Somkiat Jaidee", "age" : 25, "major" : "Computer", "gpa" : 2.56 } print(a); print(type(a)) print(b); print(type(b)) print(c); print(type(c)) print(d); print(type(d)) print(e); print(type(e)) print(std); print(type(std))
Python
UTF-8
1,675
2.71875
3
[]
no_license
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d np.random.seed(101) tf.set_random_seed(101) learning_rate=0.02 epochs=1000 n_samples=200 train_x=np.linspace(0,50,n_samples*2).reshape(n_samples,2) train_y=np.linspace(0,50,n_samples) train_x[:,0]+=np.random.uniform(-4,4,n_samples) train_x[:,1]+=np.random.uniform(-4,4,n_samples) ones=np.ones(shape=[n_samples,1],dtype='float32') train_x=np.append(train_x,ones,1) train_y+=np.random.uniform(-4,4,n_samples) B0=tf.Variable(np.random.randn()) B1=tf.Variable(np.random.randn()) B2=tf.Variable(np.random.randn()) X1=tf.placeholder(tf.float32) X2=tf.placeholder(tf.float32) Y=tf.placeholder(tf.float32) pred=B0+B1*X1+B2*X2 cost=tf.reduce_sum((Y-pred)**2)/(2*n_samples) optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) init=tf.global_variables_initializer() #print(train_x) input('x') with tf.Session() as sess: sess.run(init) print(sess.run(B0)) print(sess.run(B1)) print(sess.run(B2)) for epoch in range(epochs): print(epoch) for x1,x2,y in zip(train_x[:,0],train_x[:,1],train_y): sess.run(optimizer,feed_dict={ X1 : x1, X2 : x2 , Y : y }) cb0=sess.run(B0) cb1=sess.run(B1) cb2=sess.run(B2) print(cb0) print(cb1) print(cb2) fig = plt.figure() ax = plt.axes(projection='3d') ax.scatter3D(train_x[:, 0], train_x[:, 1], train_y,'gray') ax.scatter3D(train_x[:, 0], train_x[:, 1], train_x[:,0]*cb1+train_x[:,1]*cb2+cb0,'red') plt.show()
Python
UTF-8
330
3.671875
4
[ "MIT" ]
permissive
def calculate(command, num_a, num_b): if command == "multiply": return num_a * num_b elif command == "divide": return num_a // num_b elif command == "add": return num_a + num_b elif command == "subtract": return num_a - num_b print(calculate(input(), int(input()), int(input())))
Python
UTF-8
4,203
2.90625
3
[]
no_license
import urllib2 import sqlite3 from BeautifulSoup import * from urlparse import urljoin from sqlite3 import dbapi2 as sqlite # Create a list of words to ignore ignorewords={'the':1,'of':1,'to':1,'and':1,'a':1,'in':1,'is':1,'it':1} class crawler: # Initialize the crawler with the name of database def __init__(self,dbname): self.con=sqlite.connect(dbname) def __del__(self): self.con.close() def dbcommit(self): self.con.commit() # Auxilliary function for getting an entry id and adding # it if it's not present def getentryid(self,table,field,value,createnew=True): cur=self.con.execute( "select rowid from %s where %s='%s'" % (table,field,value)) res=cur.fetchone( ) if res==None: cur=self.con.execute( "insert into %s (%s) values ('%s')" % (table,field,value)) return cur.lastrowid else: return res[0] # Index an individual page def addtoindex(self,url,soup): if self.isindexed(url): return print 'Indexing '+url # Get the individual words text=self.gettextonly(soup) words=self.separatewords(text) # Get the URL id urlid=self.getentryid('urllist','url',url) # Link each word to this url for i in range(len(words)): word=words[i] if word in ignorewords: continue wordid=self.getentryid('wordlist','word',word) self.con.execute("insert into wordlocation(urlid,wordid,location) \ values (%d,%d,%d)" % (urlid,wordid,i)) # Extract the text from an HTML page (no tags) def gettextonly(self,soup): v=soup.string if v==None: c=soup.contents resulttext='' for t in c: subtext=self.gettextonly(t) resulttext+=subtext+'\n' return resulttext else: return v.strip( ) # Separate the words by any non-whitespace character def separatewords(self,text): splitter=re.compile('\\W*') return [s.lower( ) for s in splitter.split(text) if s!=''] # Return true if this url is already indexed def isindexed(self,url): u=self.con.execute("select rowid from urllist where url='%s'" % url).fetchone( ) if u!=None: # Check if it has actually been crawled v=self.con.execute('select * from wordlocation where urlid=%d' % u[0]).fetchone( ) if v!=None: return True return False # Add a link between two pages def addlinkref(self,urlFrom,urlTo,linkText): pass # Starting with a list of pages, do a breadth # first search to the given depth, indexing pages # as we go def crawl(self,pages,depth=2): pass # Create the database tables def createindextables(self): pass # Starting with a list of pages, do a breadth # first search to the given depth, indexing pages # as we go def crawl(self,pages,depth=2): for i in range(depth): newpages=set() for page in pages: try: c=urllib2.urlopen(page) except: print "Could not open %s" % page continue soup=BeautifulSoup(c.read()) self.addtoindex(page,soup) links=soup('a') for link in links: if ('href' in dict(link.attrs)): url=urljoin(page,link['href']) if url.find("'")!=-1: continue url=url.split('#')[0] # remove location portion if url[0:4]=='http' and not self.isindexed(url): newpages.add(url) linkText=self.gettextonly(link) self.addlinkref(page,url,linkText) self.dbcommit() pages=newpages def createindextables(self): self.con.execute('create table urllist(url)') self.con.execute('create table wordlist(word)') self.con.execute('create table wordlocation(urlid,wordid,location)') self.con.execute('create table link(fromid integer,toid integer)') self.con.execute('create table linkwords(wordid,linkid)') self.con.execute('create index wordidx on wordlist(word)') self.con.execute('create index urlidx on urllist(url)') self.con.execute('create index wordurlidx on wordlocation(wordid)') self.con.execute('create index urltoidx on link(toid)') self.con.execute('create index urlfromidx on link(fromid)') self.dbcommit( )
Java
UTF-8
359
1.882813
2
[ "Apache-2.0" ]
permissive
package org.eno.bot.scene; import org.treblereel.gwt.xml.mapper.api.annotation.XMLMapper; @XMLMapper public class Style { private String backgroundColor; public String getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; } }
Python
UTF-8
1,447
3.3125
3
[ "MIT" ]
permissive
from lxml import etree as ET from subprocess import call def process_news(): root = ET.parse("results/news.xml") print("Count of images for pages:") for page in ET.XPath("//data/page")(root): print("(", ET.XPath("@url")(page)[0], ") : ", int(ET.XPath("count(fragment[@type=\"image\"])")(page)), "images") def process_bikes(): dom = ET.parse("results/bikes.xml") xslt = ET.parse("xslscripts/bikes.xsl") transform = ET.XSLT(xslt) result = transform(dom) result.write_output("results/bikes.html") def print_menu(): print(30 * "-", "MENU", 30 * "-") print("1. Scrapy News") print("2. Scrapy Bikes") print("3. Process News") print("4. Process Bikes") print("5. Exit") print(67 * "-") loop = True while loop: ## While loop which will keep going until loop = False print_menu() ## Displays menu choice = int(input("Enter your choice [1-5]: ")) if choice == 1: call("scrapy crawl news".split()) elif choice == 2: call("scrapy crawl bikes".split()) elif choice == 3: process_news() elif choice == 4: process_bikes() elif choice == 5: loop = False # This will make the while loop to end as not value of loop is set to False else: # Any integer inputs other than values 1-5 we print an error message print("Wrong option selection. Enter any key to try again..")
Java
UTF-8
7,212
2.328125
2
[]
no_license
package com.test720.grasshoppercollege.module.peiYin.bean; import java.util.List; /** * 佛祖保佑 永无BUG * 佛曰: * 程序园里程序天,程序天里程序员; * 程序猿人写程序,又拿程序换肉钱。 * 肉饱继续桌前坐,饱暖还是桌前眠; * 半迷半醒日复日,码上码下年复年。 * 但愿叱咤互联世,不愿搬砖码当前; * 诸葛周瑜算世事,我算需求得加钱。 * 别人笑我忒直男,我说自己是程猿; * 但见成都府国内,处处地地程序员。 * 作者:水东流 编于 2018/8/29 */ public class PeiYinData { /** * code : 1 * msg : 成功 * data : {"collection":"0","info":{"con_id":"1","album_id":"1","video_name":"围追堵截1","video_path":"https://www.hzggedu.com/oldggxy/Uploads/dubbing_file/video/yixingji/chuanxuezidemao1_weizhuidujie.mp4","desc":""},"list":[{"pei_id":"1","thumb_up_count":"0","header":"https://www.hzggedu.com/ggxy/Uploads/popup_ads/2018-02-23/5a8fde9fee502.jpg","uid":"1252","nickname":"虚空恶犬二千","level":"1","vip":0,"vip_time":"13000000"}],"is_share":"0","share_points":"10"} */ private int code; private String msg; private DataBean data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { /** * collection : 0 * info : {"con_id":"1","album_id":"1","video_name":"围追堵截1","video_path":"https://www.hzggedu.com/oldggxy/Uploads/dubbing_file/video/yixingji/chuanxuezidemao1_weizhuidujie.mp4","desc":""} * list : [{"pei_id":"1","thumb_up_count":"0","header":"https://www.hzggedu.com/ggxy/Uploads/popup_ads/2018-02-23/5a8fde9fee502.jpg","uid":"1252","nickname":"虚空恶犬二千","level":"1","vip":0,"vip_time":"13000000"}] * is_share : 0 * share_points : 10 */ private String collection; private InfoBean info; private String is_share; private String share_points; private List<ListBean> list; public String getCollection() { return collection; } public void setCollection(String collection) { this.collection = collection; } public InfoBean getInfo() { return info; } public void setInfo(InfoBean info) { this.info = info; } public String getIs_share() { return is_share; } public void setIs_share(String is_share) { this.is_share = is_share; } public String getShare_points() { return share_points; } public void setShare_points(String share_points) { this.share_points = share_points; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class InfoBean { /** * con_id : 1 * album_id : 1 * video_name : 围追堵截1 * video_path : https://www.hzggedu.com/oldggxy/Uploads/dubbing_file/video/yixingji/chuanxuezidemao1_weizhuidujie.mp4 * desc : */ private String con_id; private String album_id; private String video_name; private String video_path; private String desc; private String level; public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getCon_id() { return con_id; } public void setCon_id(String con_id) { this.con_id = con_id; } public String getAlbum_id() { return album_id; } public void setAlbum_id(String album_id) { this.album_id = album_id; } public String getVideo_name() { return video_name; } public void setVideo_name(String video_name) { this.video_name = video_name; } public String getVideo_path() { return video_path; } public void setVideo_path(String video_path) { this.video_path = video_path; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } } public static class ListBean { /** * pei_id : 1 * thumb_up_count : 0 * header : https://www.hzggedu.com/ggxy/Uploads/popup_ads/2018-02-23/5a8fde9fee502.jpg * uid : 1252 * nickname : 虚空恶犬二千 * level : 1 * vip : 0 * vip_time : 13000000 */ private String pei_id; private String thumb_up_count; private String header; private String uid; private String nickname; private String level; private int vip; private String vip_time; public String getPei_id() { return pei_id; } public void setPei_id(String pei_id) { this.pei_id = pei_id; } public String getThumb_up_count() { return thumb_up_count; } public void setThumb_up_count(String thumb_up_count) { this.thumb_up_count = thumb_up_count; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public int getVip() { return vip; } public void setVip(int vip) { this.vip = vip; } public String getVip_time() { return vip_time; } public void setVip_time(String vip_time) { this.vip_time = vip_time; } } } }
C++
UTF-8
3,325
2.5625
3
[]
no_license
#include "StdAfx.h" #include "RunCodeProcess.h" namespace BrainthreadIDE { bool RunCodeProcess::Launch() { if(worker->IsBusy) return false; this->OnStart(this, EventArgs::Empty); processWorkContext->outputLister->AddOutputWithTimestamp(String::Format("Running {0} with args: {1}", Path::GetFileName(startInfo->FileName), startInfo->Arguments)); worker->RunWorkerAsync(); return true; } void RunCodeProcess::Stop() { worker->CancelAsync(); this->OnComplete(this, EventArgs::Empty); } void RunCodeProcess::worker_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) { try { process = gcnew Process; process->StartInfo = this->startInfo; process->Start(); //positioning process window this->MoveProcessWindow(); } catch(Exception ^ ex) { String ^msg = String::Format("Cannot run the program. Reason: {0}", ex->Message); processWorkContext->outputLister->AddOutputWithTimestamp(msg); MessageBox::Show(msg, "Launch error", MessageBoxButtons::OK, MessageBoxIcon::Error); e->Result = cli::safe_cast<int>( -1 ); process->Close(); return; } while(!process->HasExited) { if(worker->CancellationPending) { e->Cancel = true; try { process->Kill(); process->WaitForExit(); } catch(Exception ^ ex) { String ^msg = String::Format("Cannot cancel the process now. Reason: {0}", ex->Message); processWorkContext->outputLister->AddOutputWithTimestamp(msg); MessageBox::Show(msg, "Cancellation error", MessageBoxButtons::OK, MessageBoxIcon::Error); } break; } Thread::Sleep(115); } e->Result = cli::safe_cast<int>( process->ExitCode ); process->WaitForExit(); } void RunCodeProcess::worker_RunWorkerCompleted(System::Object^ sender, System::ComponentModel::RunWorkerCompletedEventArgs^ e) { if(e->Cancelled) { processWorkContext->outputLister->AddOutputWithTimestamp("Program stopped by user"); } else { if(false == GlobalOptions::Instance->PauseProgramAfterRun && process->HasExited) processWorkContext->outputLister->AddOutputWithTimestamp(String::Format("Program exited with code {0}", cli::safe_cast<int>(e->Result) )); else //program not exited processWorkContext->outputLister->AddOutputWithTimestamp("Execution completed"); processWorkContext->outputLister->AddIDEOutput(this->GetProcessStatistics()); } process->Close(); this->OnComplete(this, EventArgs::Empty); } String ^ RunCodeProcess::GetProcessStatistics() { String ^ machineName = Environment::MachineName; String ^ msg = "Process statistics cannot be displayed "; try { if(process && process->HasExited == true) { int cpu_time = (int)process->TotalProcessorTime.TotalMilliseconds; int proc_time = (int)(process->ExitTime - process->StartTime).TotalMilliseconds; if(String::Compare(machineName, process->MachineName) && String::Compare(".", process->MachineName)) machineName = process->MachineName; return String::Format("@{0} {1} ms, CPU time: {2} ms", machineName, proc_time, cpu_time); } else return msg; } catch(InvalidOperationException ^ e) { return msg + e->Message; } } }
Java
UTF-8
2,407
2.65625
3
[ "Apache-2.0" ]
permissive
package wang.yeting.wtp.core.enums; import lombok.Getter; import wang.yeting.wtp.core.concurrent.ResizableCapacityLinkedBlockingDeque; import wang.yeting.wtp.core.concurrent.ResizableCapacityLinkedBlockingQueue; import java.util.*; import java.util.concurrent.*; /** * @author : weipeng * @date : 2020-07-25 10:35 */ @Getter public enum QueueEnums { /** * Dynamically modifiable {@link LinkedBlockingQueue} */ resizableCapacityLinkedBlockIngQueue("ResizableCapacityLinkedBlockingQueue", ResizableCapacityLinkedBlockingQueue.class), /** * Dynamically modifiable {@link LinkedBlockingDeque} */ resizableCapacityLinkedBlockingDeque("ResizableCapacityLinkedBlockingDeque", ResizableCapacityLinkedBlockingDeque.class), /** * details {@link LinkedBlockingQueue} */ linkedBlockingQueue("LinkedBlockingQueue", LinkedBlockingQueue.class), /** * details {@link LinkedBlockingDeque} */ linkedBlockingDeque("LinkedBlockingDeque", LinkedBlockingDeque.class), /** * details {@link PriorityBlockingQueue} */ priorityBlockingQueue("PriorityBlockingQueue", PriorityBlockingQueue.class), /** * details {@link ArrayBlockingQueue} */ arrayBlockingQueue("ArrayBlockingQueue", ArrayBlockingQueue.class), /** * details {@link SynchronousQueue} */ synchronousQueue("SynchronousQueue", SynchronousQueue.class), /** * details {@link LinkedTransferQueue} */ linkedTransferQueue("LinkedTransferQueue", LinkedTransferQueue.class); private final String queueName; private final Class<?> queueClass; QueueEnums(String queueName, Class<?> queueClass) { this.queueName = queueName; this.queueClass = queueClass; } private static final Map<String, QueueEnums> ENUM_MAP = new HashMap<>(QueueEnums.values().length); static { for (QueueEnums e : QueueEnums.values()) { ENUM_MAP.put(e.getQueueName(), e); } } /** * 根据 {@queueName queueName} 获取枚举类 * * @param queueName 枚举类的值 * @return 枚举类 */ public static QueueEnums getByQueueName(String queueName) { return ENUM_MAP.get(queueName); } public static List<String> getAllQueueName() { Set<String> keySet = ENUM_MAP.keySet(); return new ArrayList<>(keySet); } }
PHP
UTF-8
314
2.546875
3
[]
no_license
<?php namespace Application\Form; class GradeForm extends HorizontalForm { public function __construct() { parent::__construct(); $this->addText('code', 'Code') ->addText('description', 'Description') ->addButton('submit', 'Add', 'btn-primary'); } }
Java
UTF-8
47
2.046875
2
[]
no_license
public enum ItemType { damage,healing; }
Java
UTF-8
331
2.09375
2
[]
no_license
package com.herscher.cribbage.scoring; import android.support.annotation.Nullable; import com.herscher.cribbage.Card; import java.util.List; /** * TODO add comments * * Implement this for all scoring types, then add to PlayScoreProcessor * */ public interface PlayScorer { @Nullable ScoreUnit score(List<Card> cards); }
Markdown
UTF-8
3,796
2.6875
3
[]
no_license
十五 爱丽丝有点畏怯地缩回紧抱著他腰背的手,动作缓慢,予人难舍难离的深切感受。 凌渡宇眼中脑际填满她诱人的神态,一对有力的手条件反射般把她反楼向自己,肉体的磨擦和紧挤,把怀中的美女弄得“嗯”的一声,全身软靠著他。 爱丽丝抬起飞红的俏面,一对美目抵受不住凌渡宇深注的眼神,眯成两线。 凌渡宇忘记了两人外的一切,重重吻上她的樱唇。 爱丽丝软弱地一声樱咛,沉醉在两性相触的世界内,像梦湖的湖水,溶流合运,内里却有激冲的暗涌。 天地在那一刻停顿下来。 车辆驶近的声音从左方的路上传来。 凌渡宇首先惊醒。 爱丽丝轻轻推开他,转过了身,高耸的胸口强烈起伏。 车辆在他们左方十多码处停下,一名大汉走出车来,打开后座的侧门。 爱丽丝当先走了过去。 两人并排坐在车尾,车子向玻璃屋的方向驶去。 直到抵达玻璃屋,爱丽丝仍是垂著头,一言不发。 车子在一所平房前停下,凌渡宇认得是他昨晚休息的地方。 爱丽丝望向他,一触他灼灼的眼神,立时别过头去,才道:“你先休息一会吧,博士将与你共进午膳,我待会才来接你。” 凌渡宇摇头道:“我不需要任何休息,我要求见见雅黛妮。” 爱丽丝几乎是立时道:“不!你不可以见她。” 凌渡宇冷笑道:“为甚么?” 爱丽丝转过俏面来,情绪很不稳定,道:“她一切很好,你为甚么要见她,难道不信任我吗?” 凌渡宇看到她眼中的嫉妒,不禁哑然失笑,柔声道:“当我是探望一个朋友,见她一面,谈上几句,行吗。” 爱丽丝横蛮无理地道:“不!”凌渡宇为之气结。 巴极博士的声音在车内响起,道:“爱丽丝!让凌先生去见雅黛妮吧!不过要照足保安的规则。” 凌渡宇乍闻巴极的声音,吓了一跳,才醒悟巴极是通过车内的传音系统说话,由此可见,他的一举一动,一言一语,全在这魔王的监视下。 爱丽丝咬著嘴唇低头,道:“是,博士!” 凌渡宇见到爱丽丝如此遵从巴极,心中大不是味儿,这种心理,微妙异常。 车子再次开出。 爱丽丝俯身过来。 凌渡宇吓了一跳,难道她忽尔来个一百八十度的转变,要和他当著司机亲热。不过他很快知道原因,爱丽丝面无表情地给他戴上一个眼罩。 这就是巴极刚才提到的保安措施。 巴极令人害怕的地方,就是一切事物,外表都和平宁静,骨子里却是严刻之极。一步也不放松,幸好他还未处于完全的劣势。 他一言不发,把精神集中,默记车行的路线。 多年禅坐的修行,使他身体内有一个无形的时钟,能精确地把握时间的短长。 车子左弯右拐,时快时慢。 凌渡宇估计对方蓄意绕上几个弯子,使他迷失去向。 二十五分钟后,车子停下。 凌渡宇像盲人一样,由爱丽丝把他拖出车外,进入了一所建筑物内。 眼罩除下。 这是一个大厅模样的地方,除了他和爱丽丝外,一个人也没有,但凌渡宇的第六感告诉他,最少有两对眼睛,通过隐蔽的电视眼,监视他的行动。 爱丽丝面无表情,指著一道房门道:“她在里面,你自己进去吧!” 凌渡宇伸手轻薄地拧了她面蛋一下,在她未及抗议前,大步向房门走去。 房门自动缩入墙内,又是一道电子控制的电闸。 凌渡宇走了进去。
PHP
UTF-8
1,037
2.765625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace App\Repository; use App\Entity\GuessAttempt; use Doctrine\DBAL\Connection; class PDOGuessAttemptRepository implements GuessAttemptRepository { /** * @var Connection */ private $connection; /** * @param Connection $connection */ public function __construct(Connection $connection) { $this->connection = $connection; } /** * @param GuessAttempt $guessAttempt * @return GuessAttempt * @throws \Doctrine\DBAL\DBALException */ public function save(GuessAttempt $guessAttempt): GuessAttempt { $insertQuery = <<<SQL INSERT INTO guess_attempt (game_id, uuid, player_guess, feedback) VALUES (?, ?, ?, ?) SQL; $this->connection->executeQuery($insertQuery, [ $guessAttempt->gameId(), $guessAttempt->uuid()->toString(), $guessAttempt->playerAttempt()->toString(), $guessAttempt->feedback()->toString() ]); return $guessAttempt; } }
Java
UTF-8
1,191
2.5625
3
[]
no_license
import java.util.*; public class SensitiveDataVariable { public String scope; public String name; public String shortMessage; public String message; public boolean memoryLocked; public boolean valueSet; public boolean valueCleared; public boolean isSecure; public boolean[] stepsApplied = new boolean[UIUtils.SD_EV_MEMORYUNLOCKED+1]; public SensitiveDataVariable() { } public SensitiveDataVariable(String scopeIn, String nameIn) { scope = scopeIn; name = nameIn; memoryLocked = valueSet = valueCleared = false; isSecure = true; // message = "Declared variable"; // shortMessage = "Declared"; for (int n = 0; n <= UIUtils.SD_EV_MEMORYUNLOCKED; ++n) stepsApplied[n] = false; } public SensitiveDataVariable newInstance() { SensitiveDataVariable var = new SensitiveDataVariable(); var.scope = scope; var.name = name; var.shortMessage = ""; var.message = ""; var.memoryLocked = memoryLocked; var.valueSet = valueSet; var.valueCleared = valueCleared; var.isSecure = isSecure; for (int n = 0; n <= UIUtils.SD_EV_MEMORYUNLOCKED; ++n) var.stepsApplied[n] = stepsApplied[n]; return var; } }
Python
UTF-8
160
3.625
4
[]
no_license
#номер наибольшего числа из 2 x1 = int(input()) x2 = int(input()) if x2 < x1: print(1) elif x2 > x1: print(2) else: print(0)
C
UTF-8
1,229
3.421875
3
[]
no_license
/* ** display.c for display in /home/tran_-/Documents/rendu/PSU_2015_navy ** ** Made by Guillaume TRAN ** Login <tran_-@epitech.net> ** ** Started on Thu Dec 10 20:32:53 2015 Guillaume TRAN ** Last update Fri Dec 18 23:30:32 2015 Guillaume TRAN */ #include <unistd.h> #include <stdlib.h> #include "navy.h" #include "my.h" char **my_fill_grid(char **grid) { int i; int k; int n; i = 0; n = 0; while (i < 8) { k = 0; while (k < 8) { grid[i][k] = '.'; n++; k++; } i++; } return (grid); } char **my_initialize_grid() { int i; char **grid; i = 0; if ((grid = malloc(sizeof(*grid) * 8)) == NULL) return (NULL); while (i < 8) { if ((grid[i] = malloc(sizeof(*grid) * 8)) == NULL) return (NULL); i++; } return (grid); } void display_line(int number, char **grid) { int i; i = 0; while (i < 8) { my_printf("%c", grid[number][i]); if (i + 1 <= 8) my_putchar(' '); i++; } } void my_display(char **grid) { int i; i = 0; my_printf("\n |A B C D E F G H\n"); my_printf("-+---------------\n"); while (i < 8) { my_printf("%d|", i + 1); display_line(i, grid); my_printf("\n"); i++; } }
Python
UTF-8
1,152
4.25
4
[]
no_license
# Faça um programa que receba dois inteiros x e n, com x, n > 0 e x < n, e conte # o número de múltplos de x menores do que n. # DICA 1: Os múltiplos de um número são obtidos multiplicando-se esse número pelos # números naturais (1, 2, 3, 4, 5, ...) # DICA 2: No primeiro exemplo, os múltiplos de são: 7*1, 7*2, 7*3, 7*4, 7*5, .... --> 7, 14, 21, 28, 35, # ... Sendo assim, temos 3 múltiplos que são estritamente menores que 28, já que o quarto múltiplo é o # próprio 28 (portanto = e não < ). # DICA 3: Use um laço de repetição para ir percorrendo os números inteiros e um acumulador # para contar +1 para cada múltiplo encontrado, parando quando o múltiplo da vez for igual # ao número limite dado (ou seja, deve executar enquando ele for menor). # A entrada consiste em dois números inteiros x e n, nessa ordem, não é necessário validar a entrada. numX = int(input("Número Menor: ")); numN = int(input("Número Maior: ")); cont = 1; mult = 0; while (mult < numN): mult = numX * cont; if mult < numN: cont = cont + 1; print("O numero {} tem {} multiplos menores que {}.".format(numX, (cont-1), numN))
JavaScript
UTF-8
1,621
3.109375
3
[]
no_license
var mainApp = angular.module("mainApp", []); mainApp.controller('gameController',function() { var vm = this; var emptyCell = '-'; vm.board = [ [{value: '-'}, {value: '-'}, {value: '-'}], [{value: '-'}, {value: '-'}, {value: '-'}], [{value: '-'}, {value: '-'}, {value: '-'}] ]; vm.reset = function() { vm.currentPlayer = 'X'; vm.winner = false; vm.cat = false; vm.board.forEach(function(row){ row.forEach(function(cell){ cell.value = emptyCell; }); }); vm.currentPlayer = 'X'; vm.winner = false; vm.cat = false; }; vm.reset(); var checkForMatch = function(cell1, cell2, cell3) { return cell1.value === cell2.value && cell1.value === cell3.value && cell1.value !== emptyCell; }; var checkEndOFGame = function(){ var rowMatch = [0, 1, 2].reduce(function(memo, row) { return memo, checkForMatch(vm.board[row][0], vm.board[row][1], vm.board[row][2]); }, false); var colMatch = [0, 1, 2].reduce(function(memo, col) { return memo, checkForMatch(vm.board[0][col], vm.board[1][col], vm.board[2][col]); }, false); var diagonalMatch = checkForMatch(vm.board[0][0], vm.board[1][1], vm.board[2][2]) || checkForMatch(vm.board[0][2], vm.board[1][1], vm.board[2][0]); vm.winner = rowMatch || colMatch || diagonalMatch; return vm.winner; }; vm.isTaken = function(cell) { return cell.value !== '-'; }; vm.populateValue = function(cell) { cell.value = vm.currentPlayer; if(checkEndOFGame() === false) { vm.currentPlayer = vm.currentPlayer === 'X'? '0' : 'X'; } }; });
C++
UTF-8
310
2.578125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int dp_xor(int n,int start,int k){ if(k==0){ return 0; } if(start==n){ return start; } return min(start^dp_xor(n,start+1,k-1),dp_xor(n,start,k)); } int main(){ int n,k; cin>>n>>k; cout<<dp_xor(n,1,k); return 0; }
PHP
UTF-8
1,976
2.734375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Hash; class UserController extends Controller { public function login(Request $request) { $user = User::where('username',$request->username)->first(); if ($user) { if (Hash::check($request->password, $user->password)) { $token = rand(111111, 999999); User::where('username',$request->username)->update(['api_token' => $token]); return response()->json([ 'name' => $user->username, 'email' => $user->email, 'access_token' => $token, ]); } else { return response()->json([ 'message' => 'Invalid password' ], 200); } } else { return response()->json([ 'message' => 'Invalid username' ], 401); } } public function register(Request $request) { $validated = $request->validate([ 'username' => 'required|unique:users|max:255', 'password' => 'required|min:6|max:32|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&.,])[A-Za-z\d@$!%*?&.,]{6,}$/', 'fullname' => 'required', 'email' => 'required', 'birthday' => 'required' ]); $user = new User; $user->username = $request->username; $user->password = Hash::make($request->password); $user->fullname = $request->fullname; $user->email = $request->email; $user->birthday = $request->birthday; $user->save(); return response()->json([ 'name' => $user->username, 'email' => $user->email, 'fullname' => $user->fullname, 'birthday' => $user->birthday, ], 201); } }
PHP
UTF-8
1,378
3.59375
4
[]
no_license
<?php //Tạo ngẫu nhiên một số nguyên a có giá trị trong khoảng [1,5] và một số nguyên btrong khoảng [10,100]. $a = rand(1,5); $b = rand(10,100); echo 'a = '.$a.' <br>'; echo 'b = '.$b.' <br>'; //Khai báo hằng cho số pi define('soPI', 3.14); switch ($a) { case 1: //Nếu số a là 1: Tính chu vi và diện tích của hình vuông có cạnh là b. echo 'Chu vi hình vuông '.($b*4).' <br>'; echo "Diện tích hình vuông ".pow($b,2)."<br>"; break; case 2: //Nếu số a là 2: Tính chu vi và diện tích của hình tròn có bán kính là b. echo "Chu vi hình tròn ".$b*2*soPI."<br>"; echo "Diện tích hình tròn ".pow($b,2)*soPI."<br>"; break; case 3: //Nếu số a là 3: Tính chu vi và diện tích của hình tam giác đều có cạnh là b. echo 'Chu vi tam giác đều '.($b*3).' <br>'; echo "Diện tích tam giác đều ".pow($b,2)*sqrt(3/4)."<br>"; break; case 4: //Nếu số a là 4: Tính chu vi và diện tích của hình chữ nhật có 2 cạnh là a và b. echo 'Chu vi hình chữ nhật '.(($a+$b)*2).' <br>'; echo "Diện tích tam giác đều ".$a*$b."<br>"; break; default: echo "Số ngẫu nhiên $a không nằm trong phạm vi từ 1 đến 4, đề nghị bạn Reload lại web lấy số ngẫu nhiên khác"; } ?>
C#
UTF-8
2,520
3.03125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public abstract class Producto { protected int _codigoDeBarra; protected EMarcaProducto _marca; protected float _precio; public enum EMarcaProducto { Manaos, Pitusas, Naranjú, Diversión, Swift, Favorita } public enum ETipoProducto { Harina, Galletita, Gaseosa, Jugo, Todos } public virtual float CalcularCostoDeProduccion { get { return 0f; } } public EMarcaProducto Marca { get { return this._marca; } } public float Precio { get { return this._precio; } } public Producto(int codigoBarra, EMarcaProducto marca, float precio) { this._precio = precio; this._marca = marca; this._codigoDeBarra = codigoBarra; } private static string MostrarProducto(Producto p) { return " el codigo de barra es " + p._codigoDeBarra + " marca " + p._marca + " precio " + p._precio; } public static bool operator ==(Producto p1, Producto p2) { bool ret = false; if (p1.GetType() == p2.GetType() && p1._marca == p2._marca && p1._codigoDeBarra == p2._codigoDeBarra) { ret = true; } return ret; } public static bool operator !=(Producto p1, Producto p2) { return !(p1 == p2); } public static bool operator ==(Producto p, EMarcaProducto m) { bool ret = false; if (p._marca == m) { ret = true; } return ret; } public static bool operator !=(Producto p, EMarcaProducto m) { return !(p == m); } public static explicit operator int(Producto p) { return p._codigoDeBarra; } public static implicit operator string(Producto p) { return Producto.MostrarProducto(p); } public override bool Equals(Object obj) { return this.GetType()==obj.GetType(); } public virtual string Consumir() { return " Parte de una mezcla "; } } }
JavaScript
UTF-8
567
3.140625
3
[]
no_license
/** * @description Check url is valid * @param {string} inputUrl - url to analyze */ function checkUrl(inputUrl) { console.log('::: Running checkUrl :::', inputUrl); const expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi; const regex = new RegExp(expression); if (!inputUrl.match(regex)) { return 'Invalid URL'; } else { return 'Ok'; } } export { checkUrl };
C
UTF-8
5,055
2.84375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* ----------------------------------------------------------------------------- * denseSift3d.c * ----------------------------------------------------------------------------- * Copyright (c) 2015-2016 Blaine Rister et al., see LICENSE for details. * ----------------------------------------------------------------------------- * This file contains a command-line tool to extract dense SIFT3D features from * an image. * ----------------------------------------------------------------------------- */ #include <stdio.h> #include <string.h> #include <math.h> #include "immacros.h" #include "imutil.h" #include "sift.h" #define BUF_SIZE (1 << 10) /* The log tag */ const char tag[] = "denseSift3d"; /* The help message */ const char help_msg[] = "Usage: denseSift3D [input.nii] [descriptors%.nii] \n" "\n" "Extracts a dense gradient histogram image from the input file. The \n" "output is a set of 12 images, each representing a channel or \n" "histogram bin. The last '%' character in the output filename is \n" "replaced by the channel index.\n" "\n" "Supported image formats: \n" " .dcm (DICOM) \n" " .nii (nifti-1) \n" " .nii.gz (gzip-compressed nifti-1) \n" " directory containing .dcm files \n" "\n" "Example: \n" " denseSift3d in.nii.gz out%.nii.gz \n" "\n" "Upon completion, the output would be the following 12 images: \n" " -out0.nii.gz \n" " -out1.nii.gz \n" " ... \n" " -out11.nii.gz \n" "\n"; /* Print an error message. */ void err_msg(const char *msg) { SIFT3D_ERR("%s: %s \n" "Use \"denseSift3d --help\" for more information. \n", tag, msg); } /* Report an unexpected error. */ void err_msgu(const char *msg) { err_msg(msg); print_bug_msg(); } int main(int argc, char **argv) { char out_name[BUF_SIZE], chan_str[BUF_SIZE]; Image im, desc, chan; SIFT3D sift3d; char *in_path, *out_path, *marker; size_t len; int c, marker_pos; /* Parse the GNU standard options */ switch (parse_gnu(argc, argv)) { case SIFT3D_HELP: puts(help_msg); return 0; case SIFT3D_VERSION: return 0; } /* Parse the arguments */ if (argc < 3) { err_msg("Not enough arguments."); return 1; } else if (argc > 3) { err_msg("Too many arguments."); return 1; } in_path = argv[1]; out_path = argv[2]; /* Initialize data */ init_im(&im); init_im(&desc); init_im(&chan); if (init_SIFT3D(&sift3d)) { err_msgu("Failed to initialize SIFT3D data."); return 1; } /* Read the image */ if (im_read(in_path, &im)) { char msg[BUF_SIZE]; snprintf(msg, BUF_SIZE, "Failed to read input image \"%s\".", in_path); err_msg(msg); return 1; } /* Ensure the output file name has a % character */ if ((marker = strrchr(out_path, '%')) == NULL) { err_msg("output filename must contain '%'."); return 1; } marker_pos = marker - out_path; /* Get the output file name length */ len = strlen(out_path) + (int) ceil(log10((double) im.nc)) - 1; if (len > BUF_SIZE) { char msg[BUF_SIZE]; snprintf(msg, BUF_SIZE, "Ouput filename cannot exceed %d " "characters.", BUF_SIZE); err_msg(msg); return 1; } /* Extract the descriptors */ if (SIFT3D_extract_dense_descriptors(&sift3d, &im, &desc)) { err_msgu("Failed to extract descriptors."); return 1; } /* Write each channel as a separate image */ for (c = 0; c < desc.nc; c++) { /* Get the channel */ if (im_channel(&desc, &chan, c)) { err_msgu("Failed to extract the channel."); return 1; } /* Form the output file name */ out_name[0] = '\0'; snprintf(chan_str, BUF_SIZE, "%d", c); strncat(out_name, out_path, marker_pos); strcat(out_name, chan_str); strcat(out_name, marker + 1); /* Write the channel */ if (im_write(out_name, &chan)) { char msg[BUF_SIZE]; snprintf(msg, BUF_SIZE, "Failed to write output image " "\"%s\".", out_name); err_msg(msg); return 1; } } return 0; }
TypeScript
UTF-8
2,531
3.390625
3
[ "MIT" ]
permissive
/** * index.ts * Copyright (C) 2020 Editora Sanar * * Distributed under terms of the MIT license. * @author Edgard Leal <edgard.leal@sanar.com> * @module index.ts */ /** * isArray * Check if a given parameter is an valid array * * @author edgardleal@gmail.com * @since 07.01.21 */ export function isArray(param: any): boolean { if (!param) { return false; } if (param.length !== undefined) { return true; } return false; } /** * Return a range sort for a givem list */ export function shuffleList<T = any>(params: T[]): T[] { const copy = [...params]; const result: T[] = []; while (copy.length) { const index = Math.floor(Math.random() * copy.length); const value = copy[index]; copy.splice(index, 1); result.push(value); } return result; } /** * Delete a field from given object */ export function actionDeleteField<T = any>(fieldName: string, obj: T): T { delete (obj as any)[fieldName]; // eslint-disable-line return obj; } export type ActionTypes = 'delete' | 'randomString'; const ACTIONS: { [key: string]: (field: string, obj: any) => void, } = {}; ACTIONS.delete = actionDeleteField; export interface ThanosParameter { action?: ActionTypes; } export const DEFAULT_CONFIGURATION: ThanosParameter = { action: 'delete', }; /** * Random delte half of object properties */ export default function thanos<T = any>(param: T, parameters: ThanosParameter = {}): T { if (isArray(param)) { if ((param as unknown as any[]).length === 1) { if (Math.round(Math.random() * 1)) { return [] as unknown as T; } return param; } const arrayResult = shuffleList(param as unknown as any[]); const halfCount = Math.round(arrayResult.length / 2); return (arrayResult.splice(0, halfCount)) as unknown as T; } const keys: string[] = Object.keys(param); const halfCount = Math.round(keys.length / 2); const shuffledFields = shuffleList(keys).splice(0, halfCount); const result: T = { ...param, }; const { action } = { ...DEFAULT_CONFIGURATION, ...parameters, }; const actionFunction = ACTIONS[action!]; for (let i = 0; i < shuffledFields.length; i += 1) { const item = shuffledFields[i]; actionFunction(item, result as any); } const remainingFields = Object.keys(param); for (let i = 0; i < remainingFields.length; i += 1) { const field = remainingFields[i]; if (typeof (param as any)[field] === 'object') { (result as any)[field] = thanos((param as any)[field]); } } return result; }
Java
UTF-8
1,650
3.453125
3
[]
no_license
package Commands; import java.io.File; import java.util.ArrayList; import java.util.Objects; public class CommandParser { private final ArrayList<Command> commands; // list of commands possible /** * constructs CommandParser */ public CommandParser() { commands = getCommands(); } /** * does the command * @param response the response/command of which to do * @return a command which you can execute */ public Command parser(String response) { response = response.trim(); for (Command command : commands) { if (command.getName().equalsIgnoreCase(response)) return command; } return null; } /** * gets the commands from the Commands Pakage * @return a list of Commands */ private ArrayList<Command> getCommands() { ArrayList<Command> commands = new ArrayList<>(); File file = new File("src/Commands"); for (String f : Objects.requireNonNull(file.list())) { try { Object object = Class.forName("Commands." + f.substring(0, f.length() - 5)).getConstructor().newInstance(); if (object instanceof Command && !f.equals("Command.java")) { Command command = (Command) object; commands.add(command); } } catch (Exception e) { } } return commands; } /** * displays all the possible commands */ public void displayCommands() { for (Command command : commands) { command.displayCommandInfo(); } } }
Java
UTF-8
1,522
2.0625
2
[]
no_license
package com.huilong.zhang.mobilesafe117.Receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.telephony.SmsMessage; import android.util.Log; import com.huilong.zhang.mobilesafe117.R; import com.huilong.zhang.mobilesafe117.Service.LocationService; public class SmsReceiver extends BroadcastReceiver { private static final String TAG ="SmsReceiver" ; public SmsReceiver() { } @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. // Object[] objectses = (Object[]) intent.getExtras().get("pdus"); // for (Object object:objectses // ) { //短信最多140个字节 // SmsMessage fromPdu = SmsMessage.createFromPdu((byte[])object); // String originationAddress = fromPdu.getOriginatingAddress(); // String messageBody = fromPdu.getMessageBody(); //Log.v(TAG,"originationAddress is " + originationAddress + " messageBody is " + messageBody); //if ("#*alarm*#".equals(messageBody)) { MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs); player.setVolume(1f, 1f); player.setLooping(true); player.start(); //} //} context.startService(new Intent(context,LocationService.class)); } }
Java
UTF-8
100
1.703125
2
[]
no_license
package sk.ehr.learning.course.domain.entity; public enum DwellingType { // Commute, Boarding }
C++
UTF-8
503
2.6875
3
[]
no_license
#include "Increment.hpp" Increment::Increment() { } Increment::Increment(Increment &) { } Increment::~Increment() { } Increment &Increment::operator=(Increment &) { return *this; } void Increment::execute(ExecutionHandler &exec) { unsigned char **data_ptr; unsigned char *data_start; data_ptr = exec.getEnviron().getDataPointer(); data_start = exec.getEnviron().getDataStart(); if (*data_ptr == data_start + exec.getEnviron().getN() - 1) *data_ptr = data_start; else (*data_ptr)++; }
Swift
UTF-8
416
2.890625
3
[]
no_license
// // ReceiverData.swift // Transfer // // Created by Rizky Saputra on 29/05/21. // import Foundation public struct ReceiverData { public var id: Int public var name: String public var phone: String public var image: String init(id: Int, name: String, phone: String, image: String) { self.id = id self.name = name self.phone = phone self.image = image } }
C#
UTF-8
3,285
3.5625
4
[]
no_license
using System; using System.Collections.Generic; public class Program { static void Main(string[] args) { var input = Console.ReadLine(); Animal type = null; var countInputLines = 0; var animals = new List<Animal>(); while (input != "End") { var com = input.Split(); if (countInputLines % 2 == 0) { type = Animals(com, type); } else { Foods(com, type); animals.Add(type); } countInputLines++; input = Console.ReadLine(); } Print(animals); } private static void Print(List<Animal> animals) { foreach (var x in animals) { Console.WriteLine(x.ToString()); } } private static void Foods(string[] com, Animal type) { var foodType = com[0]; var foodQuantity = double.Parse(com[1]); if (type.IsEat(foodType) == false) { Console.WriteLine($"{type.GetType().Name} does not eat {foodType}!"); } type.FoodEat = type.AnimalWeight(type.Weight, foodQuantity, foodType); type.FoodQvn = type.FoodEaten(foodType, foodQuantity); } private static Animal Animals(string[] com, Animal type) { if (com[0] == "Hen" || com[0] == "Owl") { var animalName = com[1]; var animalWeight = double.Parse(com[2]); var wingSize = double.Parse(com[3]); if (com[0] == "Hen") { type = new Hen(animalName, animalWeight, wingSize); Console.WriteLine($"{((Hen)type).ProducingSound}"); } else if (com[0] == "Owl") { type = new Owl(animalName, animalWeight, wingSize); Console.WriteLine($"{((Owl)type).ProducingSound}"); } } else if (com[0] == "Cat" || com[0] == "Tiger") { var animalName = com[1]; var animalWeight = double.Parse(com[2]); var livingRegion = com[3]; var breed = com[4]; if (com[0] == "Cat") { type = new Cat(animalName, animalWeight, livingRegion, breed); Console.WriteLine($"{((Cat)type).ProducingSound}"); } else if (com[0] == "Tiger") { type = new Tiger(animalName, animalWeight, livingRegion, breed); Console.WriteLine($"{((Tiger)type).ProducingSound}"); } } else if (com[0] == "Mouse" || com[0] == "Dog") { var animalName = com[1]; var animalWeight = double.Parse(com[2]); var livingRegion = com[3]; if (com[0] == "Mouse") { type = new Mouse(animalName, animalWeight, livingRegion); Console.WriteLine($"{((Mouse)type).ProducingSound}"); } else if (com[0] == "Dog") { type = new Dog(animalName, animalWeight, livingRegion); Console.WriteLine($"{type.ProducingSound}"); } } return type; } }
Java
UTF-8
1,665
1.882813
2
[]
no_license
package com.wallet.crypto.trustapp.ui.transfer.factory; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider.Factory; import com.wallet.crypto.trustapp.interact.HandleTransactionInteract; import com.wallet.crypto.trustapp.repository.assets.AssetsController; import com.wallet.crypto.trustapp.repository.network.BlockchainRepository; import com.wallet.crypto.trustapp.repository.session.SessionRepository; import com.wallet.crypto.trustapp.service.ApiService; import com.wallet.crypto.trustapp.ui.transfer.viewmodel.ConfirmationViewModel; import javax.inject.Inject; public class ConfirmationViewModelFactory implements Factory { /* renamed from: a */ private final BlockchainRepository f19997a; /* renamed from: b */ private final AssetsController f19998b; /* renamed from: c */ private final SessionRepository f19999c; /* renamed from: d */ private final HandleTransactionInteract f20000d; /* renamed from: e */ private final ApiService f20001e; @Inject public ConfirmationViewModelFactory(BlockchainRepository blockchainRepository, AssetsController assetsController, SessionRepository sessionRepository, HandleTransactionInteract handleTransactionInteract, ApiService apiService) { this.f19997a = blockchainRepository; this.f19998b = assetsController; this.f19999c = sessionRepository; this.f20000d = handleTransactionInteract; this.f20001e = apiService; } public <T extends ViewModel> T create(Class<T> cls) { return (T) new ConfirmationViewModel(this.f19997a, this.f19998b, this.f19999c, this.f20000d, this.f20001e); } }
TypeScript
UTF-8
1,313
2.53125
3
[]
no_license
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { AngularFireAuth } from "@angular/fire/auth"; import { Router } from "@angular/router"; import { map } from 'rxjs/operators' import { isNullOrUndefined } from 'util'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor( private AFauth: AngularFireAuth, private router: Router) { } /** * Dado el estado de la sesion de authentication si es nulo, redirige al login * y si hay una sesion activa(loggeado) permite acceder al home (true). * @param next * @param state * @returns true si tiene acceso a la pantalla (home), falso caso contrario. */ canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.AFauth.authState.pipe(map(auth => { console.log(auth) if (isNullOrUndefined(auth)) { this.router.navigate(['/login']) return false } else { console.log(auth.email) console.log(auth.uid) return true } })) } }
Java
UTF-8
12,264
2.53125
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2018-2021, ranke (213539@qq.com). * * 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 top.klw8.alita.validator.utils; import org.apache.commons.lang3.StringUtils; /** * 密码检测工具类 * 2019/11/6 11:12 */ public class PasswordCheckUtil { private static String[] KEYBOARD_SLOPE_ARR = { "!qaz", "1qaz", "@wsx", "2wsx", "#edc", "3edc", "$rfv", "4rfv", "%tgb", "5tgb", "^yhn", "6yhn", "&ujm", "7ujm", "*ik,", "8ik,", "(ol.", "9ol.", ")p;/", "0p;/", "+[;.", "=[;.", "_pl,", "-pl,", ")okm", "0okm", "(ijn", "9ijn", "*uhb", "8uhb", "&ygv", "7ygv", "^tfc", "6tfc", "%rdx", "5rdx", "$esz", "4esz" }; private static String[] KEYBOARD_HORIZONTAL_ARR = { "01234567890-=", "!@#$%^&*()_+", "qwertyuiop[]", "QWERTYUIOP{}", "asdfghjkl;'", "ASDFGHJKL:", "zxcvbnm,./", "ZXCVBNM<>?", }; private static String SPECIAL_CHAR = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; /** * 检测密码长度是否符合要求 * 2019/11/6 11:13 * @param: password * @param: minLength 最小长度 * @param: maxLength 最大长度 * @return boolean */ public static boolean checkPasswordLength(String password, int minLength, int maxLength) { int pwdLength = password.length(); if (minLength > pwdLength || maxLength < pwdLength) { return false; } return true; } /** * 检测密码是否是纯数字 * 2019/11/6 14:09 * @param: spassword * @return boolean */ public static boolean checkOnlyContainDigit(String spassword) { if (StringUtils.isNotBlank(spassword)) return spassword.matches("^[0-9]*$"); else return false; } /** * 检测密码中是否包含数字 * 2019/11/6 11:15 * @param: password * @return boolean */ public static boolean checkContainDigit(String password) { char[] chPass = password.toCharArray(); boolean flag = false; int num_count = 0; for (int i = 0; i < chPass.length; i++) { if (Character.isDigit(chPass[i])) { num_count++; } } if (num_count >= 1) { flag = true; } return flag; } /** * 检测密码中是否包含字母(不区分大小写) * 2019/11/6 11:16 * @param: password * @return boolean */ public static boolean checkContainCase(String password) { char[] chPass = password.toCharArray(); boolean flag = false; int char_count = 0; for (int i = 0; i < chPass.length; i++) { if (Character.isLetter(chPass[i])) { char_count++; } } if (char_count >= 1) { flag = true; } return flag; } /** * 检测密码中是否包含小写字母 * 2019/11/6 11:16 * @param: password * @return boolean */ public static boolean checkContainLowerCase(String password) { char[] chPass = password.toCharArray(); boolean flag = false; int char_count = 0; for (int i = 0; i < chPass.length; i++) { if (Character.isLowerCase(chPass[i])) { char_count++; } } if (char_count >= 1) { flag = true; } return flag; } /** * 检测密码中是否包含大写字母 * 2019/11/6 11:17 * @param: password * @return boolean */ public static boolean checkContainUpperCase(String password) { char[] chPass = password.toCharArray(); boolean flag = false; int char_count = 0; for (int i = 0; i < chPass.length; i++) { if (Character.isUpperCase(chPass[i])) { char_count++; } } if (char_count >= 1) { flag = true; } return flag; } /** * 检测密码中是否包含特殊符号 * 2019/11/6 11:17 * @param: password * @return boolean */ public static boolean checkContainSpecialChar(String password) { char[] chPass = password.toCharArray(); boolean flag = false; int special_count = 0; for (int i = 0; i < chPass.length; i++) { if (SPECIAL_CHAR.indexOf(chPass[i]) != -1) { special_count++; } } if (special_count >= 1) { flag = true; } return flag; } /** * 是否包含键盘横向连续字符 * 2019/11/6 11:17 * @param: password * @param: repetitions 连续个数 * @param: isLower 是否区分大小写 true:区分大小写, false:不区分大小写 * @return boolean */ public static boolean checkLateralKeyboardSite(String password, int repetitions, boolean isLower) { String t_password = new String(password); //将所有输入字符转为小写 t_password = t_password.toLowerCase(); int n = t_password.length(); /** * 键盘横向规则检测 */ boolean flag = false; int arrLen = KEYBOARD_HORIZONTAL_ARR.length; int limit_num = repetitions; for (int i = 0; i + limit_num <= n; i++) { String str = t_password.substring(i, i + limit_num); String distinguishStr = password.substring(i, i + limit_num); for (int j = 0; j < arrLen; j++) { String configStr = KEYBOARD_HORIZONTAL_ARR[j]; String revOrderStr = new StringBuffer(KEYBOARD_HORIZONTAL_ARR[j]).reverse().toString(); //检测包含字母(区分大小写) if (isLower) { //考虑 大写键盘匹配的情况 String UpperStr = KEYBOARD_HORIZONTAL_ARR[j].toUpperCase(); if ((configStr.indexOf(distinguishStr) != -1) || (UpperStr.indexOf(distinguishStr) != -1)) { flag = true; return flag; } //考虑逆序输入情况下 连续输入 String revUpperStr = new StringBuffer(UpperStr).reverse().toString(); if ((revOrderStr.indexOf(distinguishStr) != -1) || (revUpperStr.indexOf(distinguishStr) != -1)) { flag = true; return flag; } } else { if (configStr.indexOf(str) != -1) { flag = true; return flag; } //考虑逆序输入情况下 连续输入 if (revOrderStr.indexOf(str) != -1) { flag = true; return flag; } } } } return flag; } /** * 是否包含键盘纵向连续字符 * 2019/11/6 11:20 * @param: password * @param: repetitions 连续个数 * @param: isLower 是否区分大小写 true:区分大小写, false:不区分大小写 * @return boolean */ public static boolean checkKeyboardSlantSite(String password, int repetitions, boolean isLower) { String t_password = new String(password); t_password = t_password.toLowerCase(); int n = t_password.length(); /** * 键盘斜线方向规则检测 */ boolean flag = false; int arrLen = KEYBOARD_SLOPE_ARR.length; int limit_num = repetitions; for (int i = 0; i + limit_num <= n; i++) { String str = t_password.substring(i, i + limit_num); String distinguishStr = password.substring(i, i + limit_num); for (int j = 0; j < arrLen; j++) { String configStr = KEYBOARD_SLOPE_ARR[j]; String revOrderStr = new StringBuffer(KEYBOARD_SLOPE_ARR[j]).reverse().toString(); //检测包含字母(区分大小写) if (isLower) { //考虑 大写键盘匹配的情况 String UpperStr = KEYBOARD_SLOPE_ARR[j].toUpperCase(); if ((configStr.indexOf(distinguishStr) != -1) || (UpperStr.indexOf(distinguishStr) != -1)) { flag = true; return flag; } //考虑逆序输入情况下 连续输入 String revUpperStr = new StringBuffer(UpperStr).reverse().toString(); if ((revOrderStr.indexOf(distinguishStr) != -1) || (revUpperStr.indexOf(distinguishStr) != -1)) { flag = true; return flag; } } else { if (configStr.indexOf(str) != -1) { flag = true; return flag; } //考虑逆序输入情况下 连续输入 if (revOrderStr.indexOf(str) != -1) { flag = true; return flag; } } } } return flag; } /** * 是否包含字母表连续字符 * 2019/11/6 11:21 * @param: password * @param: repetitions 连续个数 * @param: isLower 是否区分大小写 true:区分大小写, false:不区分大小写 * @return boolean */ public static boolean checkSequentialChars(String password, int repetitions, boolean isLower) { String t_password = new String(password); boolean flag = false; int limit_num = repetitions; int normal_count = 0; int reversed_count = 0; //检测包含字母(区分大小写) if (!isLower) { t_password = t_password.toLowerCase(); } int n = t_password.length(); char[] pwdCharArr = t_password.toCharArray(); for (int i = 0; i + limit_num <= n; i++) { normal_count = 0; reversed_count = 0; for (int j = 0; j < limit_num - 1; j++) { if (pwdCharArr[i + j + 1] - pwdCharArr[i + j] == 1) { normal_count++; if (normal_count == limit_num - 1) { return true; } } if (pwdCharArr[i + j] - pwdCharArr[i + j + 1] == 1) { reversed_count++; if (reversed_count == limit_num - 1) { return true; } } } } return flag; } /** * 是否包含连续相同字符, 如 aaa,qqq,!!! * 2019/11/6 11:23 * @param: password * @param: repetitions 连续次数 * @return boolean */ public static boolean checkSequentialSameChars(String password, int repetitions) { String t_password = new String(password); int n = t_password.length(); char[] pwdCharArr = t_password.toCharArray(); boolean flag = false; int limit_num = repetitions; int count = 0; for (int i = 0; i + limit_num <= n; i++) { count = 0; for (int j = 0; j < limit_num - 1; j++) { if (pwdCharArr[i + j] == pwdCharArr[i + j + 1]) { count++; if (count == limit_num - 1) { return true; } } } } return flag; } }
Markdown
UTF-8
3,845
3.703125
4
[]
no_license
目录 [TOC] # 写在前面 日常开发中,我们经常会遇到判断数据类型的需求,简单的有判断数字还是字符串,进阶一点的有判断数组还是对象等等。 JS 用来检测数据类型的方式有: - typeof - instanceof - constructor - Object.prototype.toString.call() # typeof >- 语法:typeof [value] >- 返回值:使用 typeof 检测出来的结果是一个`字符串`,比如:"number"/"string"/"boolean"/"undefined"/"object"/"function",`小写` typeof 的 BUG: ```js let a; // typeof a //=>"undefined" const s = Symbol('s'); // typeof a //=>"symbol" typeof null //=>"object" typeof console.log //=>'function' ``` typeof 可以**识别除了 null 所有的值类型**,也可以**识别函数**,但**无法识别 null 和引用类型,返回的都是 "object"**。 面试题: ```js typeof typeof typeof [] //=>typeof "object" //=>"string" ``` # instanceof 检测某一个`对象实例是否隶属于这个类`,这个类的原型对象只要出现在它的 __proto__ 线上就返回 true。 >语法:obj instanceof constructor 原理:基于原型链进行检测,只要在实例的原型链上有这个类,就返回 true。 ```js 1 instanceof Number //=>false [] instanceof Array //=>true Array instanceof Function //=>true [] instanceof Function //=>false,[]和Function属于两条不同的原型链上 ``` 局限性: 无法检测基本类型值 ```js let num1 = 12, num2 = new Number(12); typeof num1; //=>'number' typeof num2; //=>'object' num1 instanceof Number; //=>false num2 instanceof Number; //=>true ``` # constructor 所有对象都会从它的原型上继承一个 constructor 属性 ```js {}.constructor === Object //=>true [].constructor === Array //=>true ``` 局限性:原型对象必须是默认的,一旦被重写就没有 constructor 属性了 # Object.prototype.toString.call([value]) > Object.prototype 上的 toString 方法执行,会返回`当前值的内部类型`,格式:`"[object 所属的类型]"`。 我们要检测谁,就用 call 借用 Object.prototype.toString 方法,把 this 变为需要检测的值。返回一个由 "object " 和 class 组成的字符串,而 \[[class]] 是要判断的值的内部属性。 可以识别至少 12 种: ```js // 以下是 11 种:基本数据类型和引用数据类型 Object.prototype.toString.call(undefined);// [object Undefined] Object.prototype.toString.call(null);// [object Null] var number = 1; // [object Number] var string = '123'; // [object String] var boolean = true; // [object Boolean] var obj = {a: 1} // [object Object] var array = [1, 2, 3]; // [object Array] var date = new Date(); // [object Date] var error = new Error(); // [object Error] var reg = /a/g; // [object RegExp] var func = function a(){}; // [object Function] //内置的对象 Object.prototype.toString.call(Math); // [object Math] Object.prototype.toString.call(JSON); // [object JSON] Object.prototype.toString.call(arguments); // [object Arguments] //DOM Object.prototype.toString.call(document); // [object HTMLDocument] ``` # 结束 ***重学 JS 系列*** 预计 25 篇左右,这是一个旨在帮助大家,其实也是帮助我自己捋顺 JavaScript 底层知识的系列。主要包括变量和类型、执行上下文、作用域及闭包、原型和继承、单线程和异步、JS Web API、渲染和优化几个部分,将重点讲解如执行上下文、作用域、闭包、this、call、apply、bind、原型、继承、Event-loop、宏任务和微任务等比较难懂的部分。让我们一起拥抱整个 JavaScript 吧。 大家或有疑问、或指正、或鼓励、或感谢,尽管留言回复哈!非常欢迎 star 哦! [点击返回博客主页](https://github.com/chenchen0224/webfrontend-space)
C
UTF-8
2,331
3.15625
3
[ "Apache-2.0" ]
permissive
#include<stdio.h> #include<string.h> #include<malloc.h> #define NULL 0 #define len sizeof(struct stu) char s[10]; struct stu{ char name[31]; struct stu *next; }; struct stu *ins(struct stu *head,int num,struct stu *head1){ struct stu *p1; if(head==NULL){ head=head1; head1->next=NULL; return head; } int n; n=1; p1=head; if(head!=NULL&&num==1){ head1->next=p1; head=head1; return head; } while(p1->next!=NULL&&n!=num-1){ p1=p1->next; n++; } if(n==num-1){ head1->next=p1->next; p1->next=head1; } return head; }; void print(struct stu *head){ struct stu *p; int i; if(head==NULL){ printf("\n"); } else{ p=head; while(p!=NULL){ for(i=0;i<strlen(p->name);i++){ printf("%c",p->name[i]); } p=p->next; if(p!=NULL) printf(" "); } printf("\n"); } } void se(struct stu *head){ struct stu *p; char b[31]; scanf("%s",b); int n=1; p=head; while(p!=NULL){ if(strcmp(p->name,b)==0){ printf("%d\n",n); break; } p=p->next; n++; } } struct stu *del(struct stu *head){ struct stu *p1; struct stu *p2; char b[31]; scanf("%s",b); if(head==NULL){ return head; } p1=head; while(p1->next!=NULL&&strcmp(p1->name,b)!=0){ p2=p1; p1=p1->next; } if(strcmp(p1->name,b)==0){ if(p1==head){ head=p1->next; } else{ p2->next=p1->next; } free(p1); p1==NULL; } return head; }; int main(){ struct stu *head; struct stu *head1; head=NULL; int num; char b[20]; while(~scanf("%s",s)){ if(strcmp(s,"insert")==0){ head1=(struct stu *)malloc(len); scanf("%d %s",&num,&head1->name); head=ins(head,num,head1); //print(head); } else if(strcmp(s,"show")==0){ print(head); } else if(strcmp(s,"search")==0){ se(head); } else if(strcmp(s,"delete")==0){ head=del(head); } } return 0; }
Python
UTF-8
1,209
3.890625
4
[]
no_license
# coding=utf-8 """ Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle node remains unchanged. """ from G4G.Problems.linked_list.linked_list import create_linked_list, print_ll def count_nodes(head): n = 0 while head is not None: n += 1 head = head.nxt return n def modify_first_half(node, complement, n): if node is None: return complement else: first = modify_first_half(node.nxt, complement, n) if n[0] < n[1]: first.data = first.data - node.data n[0] += 1 return first.nxt def modify_list(head): cnt = count_nodes(head) n = [0, cnt // 2] modify_first_half(head, head, n) return head if __name__ == '__main__': h = create_linked_list([10, 4, 5, 3, 6]) modify_list(h) print_ll(h) h = create_linked_list([2, 9, 8, 12, 7, 10]) modify_list(h) print_ll(h)
Ruby
UTF-8
1,644
3.1875
3
[]
no_license
#1 def pet_shop_name(pet_shop) return pet_shop[:name] end #2 def total_cash(pet_shop) return pet_shop[:admin][:total_cash] end #3 def add_or_remove_cash(pet_shop, sum) pet_shop[:admin][:total_cash] += sum end #4 def remove_cash(pet_shop, sum) pet_shop[:admin][:total_cash] -= sum end #5 def pets_sold(pet_shop) return pet_shop[:admin][:pets_sold] end #6 def increase_pets_sold(pet_shop, sum) pet_shop[:admin][:pets_sold] += sum end #7 def stock_count(pet_shop) pet_shop[:pets].count end #8,9 def pets_by_breed(pet_shop, search) found = [] for pet in pet_shop[:pets] if pet[:breed] == search found.push(pet) end end return found end #10 def find_pet_by_name(pet_shop, search) find_pet = nil for pet in pet_shop[:pets] if pet[:name] == search return pet end end return find_pet end #11 # def remove_pet_by_name(pet_shop, search) # find_pet = nil # for pet in pet_shop[:pets] # if pet[:name] == search # pet.each() # end # return find_pet # end # end #12 def add_pet_to_stock(pet_shop, new_pet) pet_shop[:pets].push(new_pet) end #13 def customer_cash(customers) return customers[:cash] end #14 def remove_customer_cash(customers, amount) return customers[:cash] -= amount end #15 def customer_pet_count(customers) return customers[:pets].count end #16 def add_pet_to_customer(customers, new_pet) customers[:pets].push(new_pet) end #optional def customer_can_afford_pet(customer, new_pet) can_buy_pet = true for person in customer if customer[:cash] >= new_pet[:price] return can_buy_pet end end return false end
JavaScript
UTF-8
3,395
2.859375
3
[]
no_license
/** * 默认xmlhttprequest请求 */ import EventEmitter from 'events' import { noop } from './utils' export default class Transport extends EventEmitter { constructor () { super(); this.xhr = new XMLHttpRequest(); this._data = null; this._reqHeaders = null; } _ajax (form) { let headers = this._reqHeaders; if (headers) { for (let header in headers) { if (headers[header] !== undefined) { this.xhr.setRequestHeader(header, headers[header]); } } } var xhr = this.xhr; xhr.upload.onprogress = e => { this.emit('progress', e); }; this.xhr.onerror = e => { this.callback('error', e); }; this.xhr.onabort = e => { this.callback('abort', e); }; xhr.onreadystatechange = e => { if (xhr.readyState !== 4 ) { return; } if (xhr.status >= 200 && xhr.status < 300 ) { this.callback('complete', e); } else { this.callback('error', e); } }; xhr.send(form); } /** * first set has higher priority * * @param {object} headers */ _mergeHeader(headers) { for (let header in headers) { if (!this._reqHeaders[header]) { this._reqHeaders[header] = headers[header]; } } } /** * @param: {object} data 发送选项 * headers {object} 请求头 * binary {boolean} 使用二进制开发 * formData {array|function} 发送的formData(非FormData实例) * field 文件表单名字 * name 文件名 如果为空使用file.name * file 文件 */ send (data) { this._data = data; this._reqHeaders = data.headers || {}; // 默认为post请求async必须为true this.xhr.open(data.method || 'POST', data.url || '', true); this._mergeHeader({ 'X-Requested-With': 'XMLHttpRequest' }); if (data.binary) { return this.sendAsBinary(data); } else { return this.sendAsFormData(data); } } /** * 使用二进制流发送 * 不会自动处理formData 如果需传递参数请通过url */ sendAsBinary (data) { // 接收头为octet-stream this._mergeHeader({ 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="' + encodeURI(data.filename) + '"' }); return this._ajax(data.file); } /** * 使用formdata发送 如果有formdata则会处理formData里面的数据 */ sendAsFormData (data) { var forms; if (data.formData) { if (typeof data.formData === 'function') { forms = data.formData(); } else { forms = data.formData; } } if (!forms) { forms = []; } var formData = new FormData(); for (let i = 0, l = forms.length; i > l; i++) { let form = formData[i]; formData.append(form.name, form.value); } if (data.file) { formData.append(data.field, data.file, data.name); } return this._ajax(formData); } abort () { this.xhr.onreadystatechange = null; this.xhr.abort(); } callback(type, e) { let x = this.xhr; x.onreadystatechange = x.upload.onerror = x.onprogress = x.onabort = null; this.emit(type, e); } getResponse () { return this.xhr.response; } getText () { return this.xhr.responseText; } getJson () { return JSON.parse(this.xhr.responseText); } }
JavaScript
UTF-8
914
2.921875
3
[]
no_license
const d=document; d.addEventListener("DOMContentLoaded",e=> { const seleccionarDeCargo=()=>{ const $cargo=d.getElementById("id_cargo"); let xhr=new XMLHttpRequest(); const $fragment=d.createDocumentFragment(); xhr.open('GET','../php/procesar.php?numero=cargo'); xhr.onload=function(){ if(xhr.readyState!==4)return; if(xhr.status>=200 && xhr.status<300) { let json=JSON.parse(xhr.responseText); json.forEach(el=>{ let opt=d.createElement("option"); opt.textContent=el.cargo; opt.value=el.id_cargo; $fragment.appendChild(opt); }); $cargo.appendChild($fragment); } else{ console.log('existe un error'); } } xhr.send(); }; seleccionarDeCargo(); });
Markdown
UTF-8
7,341
2.921875
3
[]
no_license
--- layout: post title: 这一年:2017 category: 随想 --- 忘记自己之存在而存在的人会越来越心不在焉 —— 克尔凯郭尔 这是略微纠结的一年,这是反复折叠的一年,这是貌似幸福的一年。 一切似乎都是刚刚好,无论是幸福快乐,还是悲伤痛苦。一切似乎都还不够,比如说幸福快乐,或者悲伤痛苦。我常常是一个很矛盾的人:希望能保持专注,但同时又兴趣广泛,分身乏术;希望能重情重义,但有时又难抵诱惑,心猿意马;希望能心存善良,但偶尔也会自大刻薄,心生厌恶。 这一年,工作已经进入完全的舒适区,不再有初入职场的新奇感、兴奋感和挑战感,也渐渐地对自我的成长和价值开始产生了质疑。同时面对团队成员功利性的离职、新人招募的不易,以及越来越发现身边大部分人的得过且过不思进取,有了比较强烈的挫败感和厌恶感。似乎自己用心去构建、经营和期盼的一切都得到了否认。 这一年,发现最悲伤的事情莫过于,在揪心揪肺地做出艰难的决定之后,发现自己原来根本就没有选择,于是乎开始怀疑自己是不是就是那个命中注定被诅咒的悲惨角色。然而大概人生的剧本是为了刻意制造起伏吧,跌入谷底之后,又峰回路转,进入另一个极端的世界。原本以为从此这就是终点,最终发现事情的发展远不是自己当初所预料,又生枝节开始期盼走向看似更美好的旅程。总之,世界上不只有一朵玫瑰花,而我也不会是一位多了不起的小王子。 一直有一个三年期限的假设,自从离开出生和成长的家乡,在黄浦江上的城市度过三年的大学时光,之后又在六边形的国度经历了三年的成长之旅,如今是在这个新生而又朝气的南方城市工作和生活,在这一年即将满三年。离开,意味着能立马改变,抛下一切的不如意,去寻找一个全新的开始,这也正是我一直所认同的自由的生活方式。然后,生活并不总是只有这一面呐,终究三年的期限已经逾越,而现在的我,决定放弃急切要离开的念头,继续在这里扎根和生长。 本来以为对于技术的热爱是团队工程师文化的基石,后来发现技术虽然有天然的吸引力,但是它的感染力还是不能统领一切,团队的管理还是要回到人,也就是团队成员上来。慢慢地试着不轻易对别人做道德评判,也不轻易对自己做道德评判。很喜欢一句话:“对于足够了解的,你是无法讨厌的”,我想,对事物如此,对人也是如此。只是这样的境界太高太宏大,也太完美。但这不失为一个指引我的遥远灯塔,让我明白,人生最重要的使命,就是去了解。而回望这一年,最大的收获,大概就是在更多的学会管理别人的同时,也更多的学会了管理自己,在更多的了解了别人的同时,也更多的了解了自己。 在别人的眼睛里,也在自己的内心里,看到或体会过喜悦、幸福、疑虑、悲伤和恐惧。我想我的精神洁癖彻底终结了,慢慢地能接受他人和自己的不完美,也不再有莫名的优越感,对于他人和自身的期待会更加务实。遇到了或者更了解了一些言而无信、冷漠麻木、不懂装懂、任性粗鲁甚至品行恶劣的人,一开始会深受冲击而倍感痛苦,后来不知是因为自己开始麻木,还是因为更成熟,内心不再会有大的波澜。开始能看清一点别人的心思,不再惊讶于各种莫测的行为。更多的时候是会告诉自己,世界本来就是如此,而我要引以为戒,不能让未来的自己拥有现在所讨厌的特质。相反,我应该要更加一言九鼎、热情善良、睿智诚实、温柔体贴。虽然在迷茫的时候希望能有人指引,但同时也明白,每个人的人生都是第一次,只有自己才最有资格决定自己的人生选择。在此同时也认识了或者更了解了一些生活不只是金钱、地位和荣耀,而是只是想做一些事情的人;常为他人着想又对自己有所要求的人;绝顶聪明又心地善良的人。而这些人,对于我自己,不需要他们对我说什么,本身就是很好的启示和指引。有人说,每个人都是一本书。确实如此,认识的人越多,就越明白人和人之间的差异,自然也越认识到自己和他人,他人和自己的不同。 常常做着自己在飞翔的梦,飞得自在又从容,轻松但是虚幻。而年少时却有过很多真实的梦:有一个绘画的梦,有一个物理学家的梦,有一个世界首富的梦,有一个无所不知的智者的梦,有一个计算机天才的梦。现在,我又有一个梦,一个关于知识,关于爱好,关于信念、关于未来的梦,这个梦在这一年变得越来越显著,越来越清晰。于是遵从内心的想法,在经历了从犹豫到坚定到恐慌再到释然的心路历程之后,决定放弃确定的安稳,踏上自己想要走的路。不过也明白,再远再高的梦,也需要从现实出发,一步一步往前往上走。越来越意识到,学生生涯里学的所有东西,都是人类千年来积累的知识和智慧,学校教育里的内容是帮助人思考的重要工具,现在想想当时没有丝毫的理由不认真对待。好在当时也没有太荒废,好在现在是一个富足而又自由的时代,好在自己未来可能还有很多可以支配的时光。 以前总想着如果自己要是能不睡觉,要是能有一大段可以自由支配的时间就好了。这样的话可以让自己更优秀,也能去做一些更伟大的事情。但是现在明白了,这样的看法是让自己和这个世界对立起来的。有人说,战场上冲锋杀敌虽然算是英雄,但是比这个更难做到的,是平淡生活中的坚守。所以这一年我在继续慢慢抛弃年少时的英雄主义幻想,不再和自己的DNA做抗争,认真睡觉,好好照顾自己,包括身体和心灵。通过定期运动,拥有了更强壮和相对健康的身体。通过去认识了解优秀和有趣的人、阅读、学习、体验和思考,让自己的灵魂也越来越有趣起来。 诚然有纠结,有疑虑,有悲伤,有恐惧。但也有勇敢,有认同,有真诚,有幸福,有过和自己和解,有过被别人成全。在新的一年里,愿将自己放逐于知识、智慧、艺术、生活和爱的丛林。在学习能力最强的年纪,体验和吸收一切美好的事物,同时也重新审视脑子里那些理所当然的观念和认知,比如说财富、地位、成功、幸福、时间、人与人之间的关系和距离等等一切那些被集体潜意识塑造的部分,深度地思考。全心全意学习,全心全意工作,全心全意恋爱,拒绝冗余的诱惑,在生活中沉沦。心存感激,专注于当下,不纠结于过去,不执妄于未来。如果可以,愿意这一生做一个善良的普通人,如山崖边的草,吸收日月天地精华,等到有朝一日,也能为自我为所爱为苍生而绽放。
JavaScript
UTF-8
5,507
3.703125
4
[]
no_license
class Board { constructor(len) { this.len = len; this.cells = '-'.repeat(len * len).split(''); } canMakeMove(row, col) { return !this.boardIsFull() && this.getCell(row, col) === '-'; } boardIsFull() { return !this.cells.includes('-'); } getWinner() { var results = []; // Check row results for (var i = 0; i < this.len; i++) { var rowResult = ''; for (var j = 0; j < this.len; j++) { rowResult += this.getCell(i, j); } results.push(rowResult); } // Check column results for (var i = 0; i < this.len; i++) { var colResult = ''; for (var j = 0; j < this.len; j++) { colResult += this.getCell(j, i); } results.push(colResult); } // Check left diagonal results var leftDiagResult = ''; for (var i = 0; i < this.len; i++) { leftDiagResult += this.getCell(i, i); } results.push(leftDiagResult); // Check right diagonal results var rightDiagResult = ''; for (var i = 0; i < this.len; i++) { rightDiagResult += this.getCell(i, this.len - 1 - i); } results.push(rightDiagResult); for (var i = 0; i < results.length; i++) { if (results[i] === 'xxx') { return 'x'; } else if (results[i] === 'ooo') { return 'o'; } } return null; } getCell(row, col) { var index = row * this.len + col return this.cells[index]; } setCell(row, col, char) { var index = row * this.len + col this.cells[index] = char; } } class GameState { constructor(startPlayer) { this.currentPlayer = startPlayer || 'x'; this.winner = null; this.winsX = 0; this.winsO = 0; } setWinner(winner) { this.winner = winner; if (winner === 'x') { this.winsX++; } else if (winner === 'o') { this.winsO++; } } togglePlayer() { this.currentPlayer = this.currentPlayer === 'x' ? 'o' : 'x'; } getWinner() { return this.winner; } getPlayer() { return this.currentPlayer; } getWinsX() { return this.winsX; } getWinsO() { return this.winsO; } } class App { constructor(len, ele) { // DOM related this.ele = ele; var table = this.ele.querySelector('table'); this.createBoardDOM(table); this.setupPlayerNames(); // Separation of concerns this.board = new Board(len); this.gameState = new GameState(); // Handlers var resetButton = this.ele.querySelector('button'); resetButton.addEventListener('click', this.reset.bind(this)); } setupPlayerNames() { var playerOneName = prompt('Please enter name for Player 1 (x):'); var playerTwoName = prompt('Please enter name for Player 2 (o):'); this.ele.querySelector('.player-one-name').textContent = playerOneName; this.ele.querySelector('.player-two-name').textContent = playerTwoName; this.ele.querySelector('.wins-player-one').textContent = playerOneName + ': '; this.ele.querySelector('.wins-player-two').textContent = playerTwoName + ': '; } createCellDOM(row, col) { var newCell = window.document.createElement('td'); newCell.textContent = '-'; newCell.addEventListener('click', this.handleClick.bind(this, row, col, newCell)); return newCell; } createBoardDOM(table) { for (var i = 0; i < 3; i++) { var newRow = window.document.createElement('tr'); table.appendChild(newRow); for (var j = 0; j < 3; j++) { var newCell = this.createCellDOM(i, j); newRow.appendChild(newCell); } } } handleClick(row, col, cellDOM) { if (this.gameState.getWinner() === null && this.board.canMakeMove(row, col)) { this.setPiece(row, col, cellDOM); var currWinner = this.board.getWinner(); if (currWinner) { this.setWinner(currWinner); this.setWinnerCount(currWinner); } else if (this.board.boardIsFull()) { this.setWinner('-'); this.gameState.togglePlayer(); this.setCurrentPlayer(this.gameState.getPlayer()); } else { this.gameState.togglePlayer(); this.setCurrentPlayer(this.gameState.getPlayer()); } } } setPiece(row, col, cellDOM) { var selectChar = this.gameState.getPlayer(); this.board.setCell(row, col, selectChar); cellDOM.textContent = selectChar; } setCurrentPlayer(player) { this.ele.querySelector('.current-player-name').textContent = player; } setWinner(winner) { this.gameState.setWinner(winner); if (winner === '-') { this.ele.querySelector('.current-winner').textContent = 'It\'s a tie!'; } else { this.ele.querySelector('.current-winner').textContent = 'Winner is ' + winner + '!'; } } setWinnerCount(winner) { if (winner === 'x') { this.ele.querySelector('.wins-x').textContent = this.gameState.getWinsX(); } else if (winner === 'o') { this.ele.querySelector('.wins-o').textContent = this.gameState.getWinsO(); } } reset() { this.setCurrentPlayer(this.gameState.getPlayer()); this.ele.querySelector('.current-winner').textContent = ''; this.gameState.setWinner(null); // Reset board this.board = new Board(this.board.len); var table = this.ele.querySelector('table'); while (table.hasChildNodes()) { table.removeChild(table.firstChild); } this.createBoardDOM(table); } } window.onload = function() { window.app = new App(3, window.document.querySelector('.app')); };
JavaScript
UTF-8
139
2.515625
3
[ "MIT" ]
permissive
function LoopItem(){ this.isRunning; this.update = function(elapsedTime){ } this.stop = function(){ this.isRunning=false; } }
JavaScript
UTF-8
524
3.265625
3
[]
no_license
/** * 管道 * * 类似组合函数,接收多个函数作为参数并返回一个新函数的方式, * * 新函数按照传入的参数顺序,从左往右依次执行,前一个函数的返回值是后一个函数的输入值 * * @summary pipe :: ((x -> y), ..., (a -> b)) -> ((x, ..., a) -> b) * @since 0.1.0 * @inner * @function * @param {...function} fns need pipe's function * @return {*} pipe's result */ const pipe = (...fns) => (a) => fns.reduce((r, fn) => fn(r), a) export default pipe
Python
UTF-8
324
3.375
3
[]
no_license
def is_prime(n): if n == 1: return False for i in range(2,int(n**0.5)+1): if n % i == 0: return False return True def main(): X = int(input()) for i in range(X, 10**12): if is_prime(i): print(i) exit() if __name__ == "__main__": main()
Java
UTF-8
2,726
2.09375
2
[]
no_license
package com.youlove.service.userimpl; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import com.youlove.service.domain.Friend; import com.youlove.service.domain.Pay; import com.youlove.service.domain.Police; import com.youlove.service.domain.User; import com.youlove.service.user.UserDao; @Repository("userDaoImpl") public class UserDaoImpl implements UserDao{ @Autowired @Qualifier("sqlSessionTemplate") private SqlSession sqlSession; public UserDaoImpl() { System.out.println(this.getClass()); } ///Method public void addUser(User user) throws Exception { sqlSession.insert("UserMapper.addUser", user); } public User getUser(Map<String,Object> map) throws Exception { return sqlSession.selectOne("UserMapper.getUser", map); } public String getCheckUser(String nickname) throws Exception { return sqlSession.selectOne("UserMapper.getCheckUser", nickname); } @Override public int updateUser(Map<String, Object> map) throws Exception { return sqlSession.update("UserMapper.updateUser",map); } @Override public List<User> getUserList(Map<String, Object> map) throws Exception { return sqlSession.selectList("UserMapper.getUserList", map); } @Override public List<Pay> getPayList(int userCode) throws Exception { return sqlSession.selectList("UserMapper.getPayList",userCode); } @Override public int addPay(Pay pay) throws Exception { return sqlSession.insert("UserMapper.addPay",pay); } @Override public List<Friend> getFriendList(Friend friend) throws Exception { return sqlSession.selectList("UserMapper.getFriendList",friend); } @Override public int addFriendMemo(Friend friend) throws Exception { return sqlSession.update("UserMapper.addFriendMemo",friend); } @Override public int inviteUser(Friend friend) throws Exception { return sqlSession.insert("UserMapper.inviteUser",friend); } @Override public int addPolice(Police police) throws Exception { return sqlSession.insert("UserMapper.addPolice",police); } @Override public List<Police> getPoliceList() throws Exception { return sqlSession.selectList("UserMapper.getPoliceList"); } @Override public int updatePolice(Police police) throws Exception { return sqlSession.update("UserMapper.updatePolice",police); } @Override public List<User> searchUser(User user) throws Exception { return sqlSession.selectList("UserMapper.searchUser",user); } }
Java
UTF-8
459
2.03125
2
[]
no_license
package com.exp.griddemo.bean; /** * 作者: gmh by Administrator on 2019/5/29. * 邮箱:gmh.com@qq.com */ public class TitleOneData extends DataModel { private String detailsTitle; public TitleOneData(String detailsTitle) { this.detailsTitle = detailsTitle; } public String getDetailsTitle() { return detailsTitle; } public void setDetailsTitle(String detailsTitle) { this.detailsTitle = detailsTitle; } }
Markdown
UTF-8
1,153
3.109375
3
[]
no_license
# Compiladores # Português Este repositório contém o projeto de um complador para a linguagem de programação K.night. O compilador foi inicialmente desenvolvido em Python, posteriormente será desenvolvido também em C/C++. Até o momento apenas o lexer (escrito em Python) está pronto. O projeto se encontra na pasta Compilador_k.night Compilador_k.night. A pasta Arquivos de teste, contém alguns arquivos que podem ser utilizados para teste do compilador. A pasta Scanner_v4 apresenta a última versão do Scanner do compilador. Os demais arquivos no inicio são versões anteriores do scanner. # English This repository contains the design of an advisor for the K.night programming language. The compiler was initially developed in Python, later it will also be developed in C / C ++. So far only lexer (written in Python) is ready. The project is in the folder Compilador_k.night Compilador_k.night. The Test Files folder contains some files that can be used for testing the compiler. The Scanner_v4 folder contains the latest version of the compiler Scanner. The rest of the files at the beginning are previous versions of the scanner.
Ruby
UTF-8
766
2.84375
3
[]
no_license
# The graphql-client is a really good library to consume Graphql APIs in Ruby. # https://github.com/github/graphql-client # You can execute a mutation the same way as if it was a regular query passing the variables you want to use: # cerner_2^5_2018 require 'graphql/client' require 'graphql/client/http' module Api HTTP = GraphQL::Client::HTTP.new(ENV['GRAPHQL_API_URL']) Schema = GraphQL::Client.load_schema(HTTP) Client = GraphQL::Client.new(schema: Schema, execute: HTTP) end CreateCityMutation = Api::Client.parse(<<~'GRAPHQL') mutation($name: String) { createCity(name: $name) { id } } GRAPHQL variables = {name: 'Jacksonville'} result = Api::Client.query(CreateCityMutation, variables: variables) puts result.data.create_city.id
C
UTF-8
5,950
3.484375
3
[]
no_license
// // List.h // List // // Created by Nicolas Nascimento on 5/16/16. // Copyright © 2016 LastLeaf. All rights reserved. // #ifndef List_h #define List_h #include <stdio.h> #include <stdlib.h> /// The function that tells wheter and object is equal to another typedef int(*comparatorFunction)(const void*,const void*); // if this is defined, that it will get called and should deallocate "info", else when simply calls free passing info as parameters typedef void(*deleteInfoFunction)(void*); // Use this to iterate in list typedef void(*visitorFunction)(void*); /// Standard Node typedef struct ListNode{ void* info; struct ListNode* next; struct ListNode* previous; } ListNode; /// Defines a regular List Data Structure typedef struct List { // References ListNode* firstNode; ListNode* lastNode; comparatorFunction comparator; deleteInfoFunction deleteInfo; // The amount of nodes in list int count; } List; /// Allocates a new node ListNode* newNode(void* info) { ListNode* node = malloc(sizeof(ListNode*)); node->info = info; node->previous = NULL; node->next = NULL; return node; } /// Deletes the node void deleteNode(struct ListNode* node, struct List* list) { if( list->deleteInfo != NULL ) { list->deleteInfo(node->info); }else{ free(node->info); } node->info = NULL; free(node); node = NULL; } /// Creates a new List, setting a comparator and deletion function struct List* newComposeObjectList(comparatorFunction function, deleteInfoFunction deletion) { List* list = malloc(sizeof(List)); list->firstNode = NULL; list->lastNode = NULL; list->comparator = function; list->deleteInfo = deletion; list->count = 0; return list; } /// Creates a new List, only with the comparasion function struct List* newSimpleObjectList(comparatorFunction function) { return newComposeObjectList(function, NULL); } /// Creates a new List for native types struct List* newSimpleTypeList() { return newComposeObjectList(NULL, NULL); } /// Appends an object to the message list void appendObject(struct List* list, void* info) { // Create the node ListNode* node = malloc(sizeof(ListNode*)); ListNode* previous = list->lastNode; node->info = info; node->previous = previous; node->next = NULL; // First item in list if( list->count == 0 ) { list->firstNode = node; list->lastNode = node; // Appends at the end }else{ list->lastNode->next = node; list->lastNode->previous = previous; list->lastNode = node; } // Doesn't handle lack of memory, so always increment counter list->count++; } /// removes an object from the message list void removeObject(struct List* list, void* info) { ListNode* currentNode = list->lastNode; while (currentNode != NULL) { // Compare messages if( list->comparator(info, currentNode->info) == 0 ) { list->count--; // Removes single node if( list->firstNode == currentNode && list->count == 0 ) { deleteNode(list->firstNode, list); list->firstNode = NULL; list->lastNode = NULL; break; // Removes first node }else if( list->firstNode == currentNode ) { ListNode* node = list->firstNode; list->firstNode = list->firstNode->next; list->firstNode->previous = NULL; node->next = NULL; deleteNode(node, list); break; // Removes last node }else if( list->lastNode == currentNode ) { ListNode* node = list->lastNode; list->lastNode = list->lastNode->previous; list->lastNode->next = NULL; node->previous = NULL; deleteNode(node, list); break; // Removes a node in the middle of the list }else{ ListNode* node = currentNode, *previous = node->previous, *next = node->next; previous->next = next; next->previous = previous; node->next = NULL; node->previous = NULL; deleteNode(node, list); break; } } // Continues iteration currentNode = currentNode->previous; } } /// Removes the last object from the list void removeLastObject(struct List* list) { removeObject(list, list->lastNode->info); } /// Frees a list pointer void deleteList(struct List* list) { /// Assures all elements in the list are freed while (list->count > 0) { removeLastObject(list); } /// Clears the message free(list); list = NULL; } /// Searches for the object in the list and returns it(if found) void* searchObject(struct List* list, void* info) { ListNode* currentNode = list->lastNode; while (currentNode != NULL) { // Compare messages if( list->comparator(info, currentNode->info) == 0 ) { return currentNode->info; } // Continues iteration currentNode = currentNode->previous; } return NULL; } /// Lists all messages void listMessages(struct List* list) { ListNode* currentNode = list->firstNode; while (currentNode != NULL) { printf("%p\n", currentNode->info); // Continues iteration currentNode = currentNode->next; } } void forEachObjectInList(struct List* list, visitorFunction function) { ListNode* currentNode = list->firstNode; while (currentNode != NULL) { function(currentNode->info); // Continues iteration currentNode = currentNode->next; } } #endif /* List_h */
Python
UTF-8
2,982
2.625
3
[]
no_license
import sqlite3, pygal, json from functools import wraps from flask import Flask, flash, redirect, render_template, request, session, url_for, g from forms import AddCompanyForm app = Flask(__name__) app.config.from_object('_config') def connect_db(): return sqlite3.connect(app.config['DATABASE_PATH']) def __init__(self, name, revenue): self.name = name self.revenue = revenue def login_required(test): @wraps(test) def wrap(*args, **kwargs): if 'logged_in' in session: return test(*args, **kwargs) else: flash('You need to log in.') return redirect(url_for('login')) return wrap @app.route('/logout/') def logout(): session.pop('logged_in', None) flash('Goodbye!') return redirect(url_for('login')) @app.route('/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['username'] != app.config['USERNAME'] or request.form['password'] != app.config['PASSWORD']: error = 'Invalid Credentials.' return render_template('login.html', error = error) else: session['logged_in'] = True flash('Welcome!') return redirect(url_for('companies')) return render_template('login.html') @app.route('/companies/') def companies(): g.db = connect_db() cur = g.db.execute( 'select name,revenue,company_id from companies' ) open_companies = [ dict(name=row[0], revenue=row[1], company_id=row[2]) for row in cur.fetchall() ] g.db.close() # title = 'Average Revenue' # bar_chart = pygal.Bar(width=1200, height=600, explicit_size=True, title=title, disable_xml_declaration=True) # html = """ # <h3>%s<//h3> # <div> # %s # </div> # </html> # """ % (title, bar_chart.render()) # return html return render_template( 'companies.html', form=AddCompanyForm(request.form), open_companies=open_companies ) @app.route('/add/', methods=['POST']) @login_required def new_company(): g.db = connect_db() name = request.form['name'] revenue = request.form['revenue'] if not name or not revenue: flash("All fields are required") return redirect(url_for('companies')) print('nay') else: g.db.execute('insert into companies(name,revenue) values (?,?)', [ request.form['name'], request.form['revenue'] ] ) g.db.commit() g.db.close() flash('New Entry Was Added') print('yay') return redirect(url_for('companies')) @app.route('/delete/<int:company_id>/') @login_required def delete_entry(company_id): g.db = connect_db() g.db.execute('delete from companies where company_id='+str(company_id)) g.db.commit() g.db.close() flash('Company Deleted') return redirect(url_for('companies'))
PHP
UTF-8
37,081
2.640625
3
[ "MIT" ]
permissive
<?php spl_autoload_register(function ($classname) {require ( $classname . ".php");}); /** * A class for core example reSlim project * * @package Core reSlim * @author M ABD AZIZ ALFIAN <github.com/aalfiann> * @copyright Copyright (c) 2016 M ABD AZIZ ALFIAN * @license https://github.com/aalfiann/reSlim/blob/master/license.md MIT License */ class Core { // Set title website var $title; // Set keyword website var $keyword; // Set description website var $description; // Set email address website var $email; // Set base path example project var $basepath; // Set home path example project var $homepath; // Set base api reslim var $api; // Set api keys var $apikey; // Set disqus var $disqus; // Set facebook var $facebook; // Set twitter var $twitter; // Set google plus var $gplus; // Set google publisher page var $gpub; // Set sharethis keys var $sharethis; // Set google analytics var $googleanalytics; // Set google webmaster tools var $googlewebmaster; // Set bing webmaster tools var $bingwebmaster; // Set yandex webmaster tools var $yandexwebmaster; // Set Google Drive API var $apidrive; // Set Keyword Dynamic Page var $seopage; // Set Keyword Competitor Site var $seosite; var $version = '1.0.0'; // Set language var $setlang = 'en'; var $datalang; private static $instance; function __construct() { require_once 'config.php'; $langs = glob(dirname(__FILE__) .'/language/*.'.$this->setlang.'.php'); foreach ($langs as $langname) { require $langname; } $lang += $backend; // append backend language $this->datalang = $lang; // set language $this->title = $config['title']; $this->keyword = $config['keyword']; $this->description = $config['description']; $this->email = $config['email']; $this->basepath = $config['basepath']; $this->homepath = $config['homepath']; $this->api = $config['api']; $this->apikey = $config['apikey']; $this->disqus = $config['disqus']; $this->sharethis = $config['sharethis']; $this->facebook = $config['facebook']; $this->twitter = $config['twitter']; $this->gplus = $config['gplus']; $this->gpub = $config['gpub']; $this->googleanalytics = $config['googleanalytics']; $this->googlewebmaster = $config['googlewebmaster']; $this->bingwebmaster = $config['bingwebmaster']; $this->yandexwebmaster = $config['yandexwebmaster']; $this->apidrive = $config['apidrive']; $this->seopage = $config['seopage']; $this->seosite = $config['seosite']; } public static function getInstance() { if ( is_null( self::$instance ) ) { self::$instance = new self(); } return self::$instance; } public static function lang($key){ return self::getInstance()->datalang[$key]; } // LIBRARY USER MANAGEMENT AND AUTHENTICATION====================================================================== /** * Get Message * * @param $type = the tpe of message in bootstrap. Example: success,warning,danger,info,primary,default * @param $primaryMessage = Message to show. * @param $secondaryMessage = Additional message to show. This is not required, so default is null. * @return string with message data */ public static function getMessage($type,$primaryMessage,$secondaryMessage=null){ return '<div class="alert alert-'.$type.'" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>'.$primaryMessage.'</strong> '.$secondaryMessage.' </div>'; } /** * CURL Post Request * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function execPostRequest($url,$post_array){ if(empty($url)){ return false;} //build query $fields_string =http_build_query($post_array); //open connection $ch = curl_init(); ////curl parameter set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); //execute post $result = curl_exec($ch); //close connection curl_close($ch); return $result; } /** * CURL Post Upload Request Multipart Data * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function execPostUploadRequest($url,$post_array){ if(empty($url)){ return false;} //open connection $ch = curl_init(); ////curl parameter set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15'); curl_setopt($ch, CURLOPT_HTTPHEADER,array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15','Referer: '.self::getInstance()->api,'Content-Type: multipart/form-data')); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS,$post_array); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //execute post $result = curl_exec($ch); if ($result === false){ $result = curl_error($ch); }; //close connection curl_close($ch); return $result; } /** * CURL Get Request * * @param $url = The url api to get the request * @return result json encoded data */ public static function execGetRequest($url){ //open connection $ch = curl_init($url); //curl parameter curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0); //execute post $data = curl_exec($ch); //close connection curl_close($ch); return $data; } /** * Verify API Token * * @param $token = Your token that generated from api server after login * @return boolean true / false */ public static function verifyToken($token){ $result = false; $data = json_decode(self::execGetRequest(self::getInstance()->api.'/user/verify/'.$token)); if (!empty($data)){ if ($data->{'status'} == "success"){ $result = true; } } return $result; } /** * Get Role by API Token * * @param $token = Your token that generated from api server after login * @return integer */ public static function getRole($token){ $result = 0; $data = json_decode(self::execGetRequest(self::getInstance()->api.'/user/scope/'.$token)); if (!empty($data)){ if ($data->{'status'} == "success"){ $result = $data->{'role'}; } } return $result; } /** * Revoke API Token * * @param $username = Your username * @param $token = Your token that generated from api server after login * @return boolean true / false */ public static function revokeToken($username,$token){ $result = false; $post_array = array( 'Username' => urlencode($username), 'Token' => urlencode($token) ); $url = self::getInstance()->api.'/user/logout'; $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ $result = true; } } return $result; } /** * Process Register * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function register($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo self::getMessage('success','Process Register Successfully!'); } else { echo self::getMessage('danger','Process Register Failed!',$data->{'message'}); } } else { echo self::getMessage('danger','Process Register Failed!','Can not connected to the server!'); } } /** * Process Update * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function update($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo self::getMessage('success','Process Update Successfuly!'); } else { echo self::getMessage('danger','Process Update Failed!',$data->{'message'}); } } else { echo self::getMessage('danger','Process Update Failed!','Can not connected to the server!'); } } /** * Process Login * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function login($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ if ($post_array['Rememberme'] == "on"){ session_start(); $_SESSION['username'] = $post_array['Username']; $_SESSION['token'] = $data->{'token'}; } else { setcookie('username', $post_array['Username'], time() + (3600 * 168), "/", NULL); // expired = 7 days setcookie('token', $data->{'token'}, time() + (3600 * 168), "/", NULL); // expired = 7 hari } header("Location: ".self::getInstance()->basepath."/index.php"); } else { echo self::getMessage('danger','Process Login Failed!',$data->{'message'}); } } else { echo self::getMessage('danger','Process Login Failed!','Can not connected to the server!'); } } /** * Process Logout * * @return redirect to login page */ public static function logout() { //Unset SESSION if (!isset($_SESSION['username'])) session_start(); if (self::revokeToken($_SESSION['username'],$_SESSION['token'])){ unset($_SESSION['username']); unset($_SESSION['token']); } // unset cookies if (isset($_SERVER['HTTP_COOKIE'])) { if (self::revokeToken($_COOKIE['username'],$_COOKIE['token'])){ setcookie('username', '', time()-1000, '/'); setcookie('token', '', time()-1000, '/'); } $cookies = explode(';', $_SERVER['HTTP_COOKIE']); foreach($cookies as $cookie) { $parts = explode('=', $cookie); $name = trim($parts[0]); setcookie($name, '', time()-1000); setcookie($name, '', time()-1000, '/'); } } header("Location: ".self::getInstance()->basepath."/modul-login.php?m=1"); } /** * Process Forgot Password * * @param $post_array = Data array to post * @return result json encoded data */ public static function forgotPassword($post_array){ $data = json_decode(self::execPostRequest(self::getInstance()->api.'/user/forgotpassword',$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ $linkverify = self::getInstance()->basepath.'/modul-verify.php?passkey='.$data->{'passkey'}; $email_array = array( 'To' => $post_array['Email'], 'Subject' => 'Request reset password', 'Message' => '<html><body><p>You have already requested to reset password.<br /><br /> Here is the link to reset: <a href="'.$linkverify.'" target="_blank"><b>'.$linkverify.'</b></a>.<br /><br /> Just ignore this email if You don\'t want to reset password. Link will be expired 3days from now.<br /><br /><br /> Thank You<br /> '.self::getInstance()->title.'</p></body></html>', 'Html' => 'true', 'From' => '', 'FromName' => '', 'CC' => '', 'BCC' => '', 'Attachment' => '' ); try { $sendemail = json_decode(self::execPostRequest(self::getInstance()->api.'/mail/send',$email_array)); echo self::getMessage('success','Request reset password hasbeen sent to your email!','If not, try to resend again later.'); } catch (Exception $e) { echo self::getMessage('danger','Process Forgot Password Failed!',$e->getMessage()); } } else { echo self::getMessage('danger','Process Forgot Password Failed!',$data->{'message'}); } } else { echo self::getMessage('danger','Process Forgot Password Failed!','Can not connected to the server!'); } } /** * Process Verify Pass Key * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function verifyPassKey($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo self::getMessage('success','Process Change Password Successfully!'); } else { echo self::getMessage('danger','Process Change Password Failed!',$data->{'message'}); } } else { echo self::getMessage('danger','Process Change Password Failed!','Can not connected to the server!'); } } /** * Process Upload File * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function uploadFile($url,$post_array){ $data = json_decode(self::execPostUploadRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo self::getMessage('success','Process Upload Successfuly!'); } else { echo self::getMessage('danger','Process Upload Failed!',$data->{'message'}); } } else { echo self::getMessage('danger','Process Upload Failed!','Can not connected to the server!'); } } /** * Process Update File * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function updateFile($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Update Successfuly!','This page will automatically refresh at 2 seconds...'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Update Failed!',$data->{'message'}.' This page will automatically refresh at 2 seconds...'); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Update Failed!','Can not connected to the server! This page will automatically refresh at 2 seconds...'); echo '</div>'; } } /** * Process Delete File * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function deleteFile($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Delete Successfuly!','This page will automatically refresh at 2 seconds...'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Delete Failed!',$data->{'message'}.'. This page will automatically refresh at 2 seconds...'); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Delete Failed!','Can not connected to the server! This page will automatically refresh at 2 seconds...'); echo '</div>'; } } /** * Process Send Email * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function sendMail($url,$post_array){ try{ $data = json_decode(self::execPostRequest($url,$post_array)); echo self::getMessage('success','The message is successfully sent!'); } catch (Exception $e) { echo self::getMessage('danger','The message is failed to sent!','Please try again later!'); } } /** * Process Send Email in Frontend * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function sendMailFrontend($url,$post_array){ try{ $data = json_decode(self::execPostRequest($url,$post_array)); echo '<div class="col-lg-12 forgottext"> <div class="alert alert-success alert-dismissible" role="alert"> <strong>'.self::lang('mail_success').'</strong> </div> </div>'; } catch (Exception $e) { echo '<div class="col-lg-12 forgottext"> <div class="alert alert-danger alert-dismissible" role="alert"> <strong>'.self::lang('mail_failed').'</strong> </div> </div>'; } } /** * Process Create New API * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function createNewAPI($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Add new API Keys Successfully!'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Add new API Keys Failed!',$data->{'message'}); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Add new API Keys Failed!','Can not connected to the server!'); echo '</div>'; } } /** * Process Update API * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function updateAPI($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Update Successfuly!'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Update Failed!',$data->{'message'}); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Update Failed!','Can not connected to the server!'); echo '</div>'; } } /** * Process Delete API * * @param $url = The url api to post the request * @param $post_array = Data array to post * @return result json encoded data */ public static function deleteAPI($url,$post_array){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Delete Successfuly!'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Delete Failed!',$data->{'message'}); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Delete Failed!','Can not connected to the server!'); echo '</div>'; } } /** * Process Create * * @param $url = The url api to post the request * @param $post_array = Data array to post * @param $title = Name of the process itself * @return result json encoded data */ public static function processCreate($url,$post_array,$title){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Add '.$title.' Successfully!'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Add '.$title.' Failed!',$data->{'message'}); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Add '.$title.' Failed!','Can not connected to the server!'); echo '</div>'; } } /** * Process Update * * @param $url = The url api to post the request * @param $post_array = Data array to post * @param $title = Name of the process itself * @return result json encoded data */ public static function processUpdate($url,$post_array,$title){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Update '.$title.' Successfuly!'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Update '.$title.' Failed!',$data->{'message'}); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Update '.$title.' Failed!','Can not connected to the server!'); echo '</div>'; } } /** * Process Delete * * @param $url = The url api to post the request * @param $post_array = Data array to post * @param $title = Name of the process itself * @return result json encoded data */ public static function processDelete($url,$post_array,$title){ $data = json_decode(self::execPostRequest($url,$post_array)); if (!empty($data)){ if ($data->{'status'} == "success"){ echo '<div class="col-lg-12">'; echo self::getMessage('success','Process Delete '.$title.' Successfuly!'); echo '</div>'; } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Delete '.$title.' Failed!',$data->{'message'}); echo '</div>'; } } else { echo '<div class="col-lg-12">'; echo self::getMessage('danger','Process Delete '.$title.' Failed!','Can not connected to the server!'); echo '</div>'; } } /** * Check SESSION, COOKIE and Verify Token * * @return data array, but if null will be redirect to login page */ public static function checkSessions() { // If cookie is not found then check session if (!isset($_COOKIE['username']) && !isset($_COOKIE['token'])) { session_start(); // if session is not found then redirect to login page if (!isset($_SESSION['username']) && !isset($_SESSION['token'])) { $out['username'] = null; $out['token'] = null; header("Location: ".self::getInstance()->basepath."/modul-login.php?m=1"); } else { if (self::verifyToken($_SESSION['token'])) { $out['username'] = $_SESSION['username']; $out['token'] = $_SESSION['token']; } else { $out['username'] = null; $out['token'] = null; header("Location: ".self::getInstance()->basepath."/modul-login.php?m=1"); } } } else // If there is a cookie then return array { if (self::verifyToken($_COOKIE['token'])) { $out['username'] = $_COOKIE['username']; $out['token'] = $_COOKIE['token']; } else { $out['username'] = null; $out['token'] = null; header("Location: ".self::getInstance()->basepath."/modul-login.php?m=1"); } } return $out; } /** * Redirect Page Location Header * * @param $page = The page to redirect * @param $timeout = The page will be redirected when time is out. Default is zero * @return redirect page */ public static function goToPage($page,$timeout=0) { return header("Refresh:".$timeout.";url= ".self::getInstance()->basepath."/".$page.""); } /** * Redirect Page Location Header for frontend * * @param $page = The page to redirect * @param $timeout = The page will be redirected when time is out. Default is zero * @return redirect page */ public static function goToPageFrontend($page,$timeout=0) { return header("Refresh:".$timeout.";url= ".self::getInstance()->homepath."/".$page.""); } /** * Redirect Page Location by meta header * * @param $url = The url to redirect * @param $timeout = The page will be redirected when time is out. Default is zero * @return redirect url */ public static function goToPageMeta($url,$timeout=0) { return '<meta http-equiv="refresh" content="'.$timeout.';url='.$url.'">'; } /** * Reload Page * * @param $timeout = The page will be redirected when time is out. Default is 2000 miliseconds. * @return reload self page */ public static function reloadPage($timeout=2000) { return '<script>setTimeout(function() {window.location.href=window.location.href}, '.$timeout.')</script>'; } /** * Save Settings * * @param $post_array = Data array to post * @return no return */ public static function saveSettings($post_array) { $newcontent = '<?php //Configurations $config[\'title\'] = \''.$post_array['Title'].'\'; //Your title website $config[\'keyword\'] = \''.$post_array['Keyword'].'\'; //Your keyword website $config[\'description\'] = \''.$post_array['Description'].'\'; //Your description website $config[\'email\'] = \''.$post_array['Email'].'\'; //Your default email $config[\'basepath\'] = \''.$post_array['Basepath'].'\'; //Your folder backend website $config[\'homepath\'] = \''.$post_array['Homepath'].'\'; //Your folder frontend website $config[\'api\'] = \''.$post_array['Api'].'\'; //Your folder rest api $config[\'apikey\'] = \''.$post_array['ApiKey'].'\'; //Your api key, you can leave this blank and fill this later $config[\'disqus\'] = \''.$post_array['Disqus'].'\'; //Your disqus username, you can leave this blank and fill this later $config[\'sharethis\'] = \''.$post_array['Sharethis'].'\'; //Your sharethis key, you can leave this blank and fill this later $config[\'facebook\'] = \''.$post_array['Facebook'].'\'; //Your facebook page, you can leave this blank and fill this later $config[\'twitter\'] = \''.$post_array['Twitter'].'\'; //Your twitter page, you can leave this blank and fill this later $config[\'gplus\'] = \''.$post_array['Gplus'].'\'; //Your google plus page, you can leave this blank and fill this later $config[\'gpub\'] = \''.$post_array['Gpub'].'\'; //Your google publisher page, you can leave this blank and fill this later $config[\'googleanalytics\'] = \''.$post_array['Googleanalytics'].'\'; //Your google analytics, you can leave this blank and fill this later $config[\'googlewebmaster\'] = \''.$post_array['Googlewebmaster'].'\'; //Your google webmaster, you can leave this blank and fill this later $config[\'bingwebmaster\'] = \''.$post_array['Bingwebmaster'].'\'; //Your bing webmaster, you can leave this blank and fill this later $config[\'yandexwebmaster\'] = \''.$post_array['Yandexwebmaster'].'\'; //Your yandex webmaster, you can leave this blank and fill this later $config[\'apidrive\'] = \''.$post_array['Apidrive'].'\'; //Google Drive API, you can leave this blank and fill this later $config[\'seopage\'] = \''.$post_array['Seopage'].'\'; //Keyword for dynamic page, you can leave this blank and fill this later $config[\'seosite\'] = \''.$post_array['Seosite'].'\'; //Keyword for competitor site, you can leave this blank and fill this later'; $handle = fopen('config.php','w+'); fwrite($handle,$newcontent); fclose($handle); echo self::getMessage('success','Settings hasbeen changed!', 'This page will refresh at 2 seconds...'); echo self::reloadPage(); } /** * Auto cut off long text * * @param $string = Data text * @param $limitLength = Limit value to be auto cut. Default value is 50 chars * @param $replaceValue = Value to replacing the cutted text. Default value is ... * @return string cutted text */ public static function cutLongText($string,$limitLength=50,$replaceValue='...'){ return (strlen($string) > $limitLength) ? substr($string, 0, $limitLength) . $replaceValue : $string; } /** * Time to seconds converter * * @param $str_time = String value must time only. Example: 00:23:45 * @return integer seconds */ public static function convertTimeToSeconds($str_time){ $str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time); sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds); $time_seconds = $hours * 3600 + $minutes * 60 + $seconds; return $time_seconds; } /** * Slug converter * * @param $text = Text value * @return string */ public static function convertToSlug($text){ // replace non letter or digits by - $text = preg_replace('~[^\pL\d]+~u', '-', $text); // transliterate $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); // remove unwanted characters $text = preg_replace('~[^-\w]+~', '', $text); // trim $text = trim($text, '-'); // remove duplicate - $text = preg_replace('~-+~', '-', $text); // lowercase $text = strtolower($text); if (empty($text)) { return 'n-a'; } return $text; } /** * Determine Server is use SSL or not. This support for full ssl and flexible ssl * * @return boolean */ public static function isHttpsButtflare() { $whitelist = array( '127.0.0.1', '::1' ); if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){ return isset($_SERVER['HTTPS']) || ($visitor = json_decode($_SERVER['HTTP_CF_VISITOR'])) && $visitor->scheme == 'https'; } else { return 0; } } }
Python
UTF-8
4,754
3.125
3
[]
no_license
import BT Confirmed_type = {"notConfirmed" : 1,"ConfirmedEmpty" : 2,"ConfirmedBlocked" : 3} class CSP(): #Initialize grid knowledge and Constraint solver def __init__(self, grid): self.grid = grid self.all_constraint_equations = [] self.empty_node_variables = [] self.blocked_node_variables = [] # Method called during Path Traversal for Agent 4 def Constraint_Solver(self): self.resolve_subsets() val = BT(self) return val #Creates Constraint Equations def create_constraint_equation_for_variable(self, node): row, col = node.get_pos() #Get row and col of Node for i in [-1, 0, 1]: # Iterate for 8 cells around you for j in [-1, 0, 1]: if (i == 0 and j == 0): continue if (row + i >= 0 and col + j >= 0 and row + i < self.grid.rows and col + j < self.grid.rows): # If a neighbour is Confirmed Empty, then do not add it to the constraint equation. if self.grid[row + i, col + j].confirmed == Confirmed_type["ConfirmedEmpty"]: continue # If a neighbour is already confirmed Blocked, then do not add it to the equation but subtract the constraint value of the current variable -- Cx. if self.grid[row + i, col + j].confirmed == Confirmed_type["ConfirmedBlocked"]: node.Cx -= 1 continue neighbour = self.grid[row + i, col + j] node.add_constraint_variable(variable = neighbour) # Append the equation in the global equation list self.all_constraint_equations.append([node.constraint_equation, node.Cx]) def remove_duplicates(self, array): # Create an empty list to store unique elements uniqueList = [] # Iterate over the original list and for each element # add it to uniqueList, if its not already there. for element in array: if element not in uniqueList: uniqueList.append(element) # Return the list of unique elements return uniqueList def resolve_subsets(self): # Sort all equations in increasing order of their length self.all_constraint_equations = sorted(self.all_constraint_equations, key = lambda x: len(x[0])) # Start resolving subsets for equation in self.all_constraint_equations: for equation2 in self.all_constraint_equations: if equation == equation2 or not equation[0] or not equation2[0] or not equation[1] or not equation2[1]: continue # Check if the equation is a subset of the other equations if set(equation[0]).issubset(set(equation2[0])): equation2[0] = list(set(equation2[0]) - set(equation[0])) equation2[1] -= equation[1] continue # Check if the equation is a superset of the other equations if set(equation2[0]).issuperset(set(equation[0])): equation[0] = list(set(equation[0]) - set(equation2[0])) equation[1] -= equation2[1] # After resolving subsets, check if now we can get blocked and unbloced nodes self.Check_Constraint_Equations_BlockedAndFree() def Check_Constraint_Equations_BlockedAndFree(self): for equation in self.all_constraint_equations.copy(): # If the equation is empty i.e. all its contraint nodes are removed if len(equation) == 0 or len(equation[0]) == 0: self.all_constraint_equations.remove(equation) continue # If value is 0, all nodes in that equation are free nodes. if equation[1] == 0: self.all_constraint_equations.remove(equation) for free_nodes in equation[0]: if not self.is_inferred(): self.make_inferred() self.confirmed = Confirmed_type["ConfirmedEmpty"] continue # If value is equal to the length of the equation, then all the nodes in the equation are blocked nodes. if len(equation[0]) == equation[1]: self.all_constraint_equations.remove(equation) for BlockedNode in equation[0]: if not self.env.flags[BlockedNode.row, BlockedNode.column] and BlockedNode not in self.mine_nodes: self.BlockedNodes.append(BlockedNode)
Java
UTF-8
385
3.125
3
[]
no_license
public class Palindrome { public static void main(String[] args) { int sum,n,d1,d2,d3; n=876; d1=n%100%10*100; d2=n%100/10*10; d3=n/100*1; sum=d1+d2+d3; if(sum==n) System.out.println("Given no. is Palindrome"); else System.out.println("Given no is not Palindrome"); } }
Markdown
UTF-8
1,851
2.5625
3
[ "MIT" ]
permissive
# docker-machine-zsh-completion A more functional and up-to-date zsh completion for docker-machine This has been merged in [docker-machine](https://github.com/docker/machine), but clone this repo to your completion path maybe a good way to easily keep it up-to-date. ## Installing Command Completion ### Manual installation Place the completion scripts in your `/path/to/zsh/completion`, using e.g. `~/.zsh/completion/` mkdir -p ~/.zsh/completion git clone https://github.com/leonhartX/docker-machine-zsh-completion.git ~/.zsh/completion/docker-machine Include the directory in your `$fpath`, e.g. by adding in `~/.zshrc` fpath=(~/.zsh/completion/docker-machine $fpath) Make sure `compinit` is loaded or do it by adding in `~/.zshrc` autoload -Uz compinit && compinit -i Then reload your shell exec $SHELL -l ### Using oh-my-zsh If you use [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh) then just clone the repository inside your oh-my-zsh repo: git clone https://github.com/leonhartX/docker-machine-zsh-completion.git ~/.oh-my-zsh/custom/plugins/docker-machine and enable it in your `.zshrc`: plugins+=(docker-machine) autoload -U compinit && compinit ### Available completions Depending on what you typed on the command line so far, it will complete - available docker-machine commands - options that are available for a particular command - machine names that make sense in a given context (e.g. `docker-machine ip` with only running machines vs. `docker-machine rm` with all machines). - swarm discovery that are available to join in. - driver options (e.g. `amazonec2-ami`) that are available for a particular driver after the `--driver,-d` options is specified. - arguments for selected options, e.g. `docker-machine ls --filter` will complete some filter options like `driver` and `name`.
Python
UTF-8
393
3.875
4
[]
no_license
text = "aabBcde" def duplicate_count(text): new_list = [] counter = 0 already_counted = [] for char in text: if char.lower() not in new_list: new_list.append(char) else: if char.lower() not in already_counted: counter += 1 already_counted.append(char) return counter print(duplicate_count(text))
Markdown
UTF-8
980
2.859375
3
[ "Apache-2.0" ]
permissive
# weex-vue-navigator weex-vue-navigator makes weex able to use SPA at web side, and use multi-page jumping at native side ## Install ``` npm i weex-vue-navigator --save-dev # or yarn add weex-vue-navigator --dev ``` ## Configuration ```js import Vue from 'vue' import Router from 'vue-router' import weexNavigator from 'weex-vue-navigator' import App from '{YouAppPath}.vue' Vue.use(Router) let router = new Router({ // you config }) Vue.use(weexNavigator, {router}) new Vue({ el: '#root', router, render: h => h(App), }) weexNavigator.bootstrap() ``` ## Usage ```js export default { methods: { jump(url) { this.$goTo(url) }, back() { this.$back() }, jumpOnSelf(url) { this.$goTo(url, true) } } } ``` ### `Vue.prototype.$goTo (url:string, isSelf:boolean = false)` - url: vue route url - isSelf: open on self view (use tab change) ### `Vue.prototype.$back ()`
JavaScript
UTF-8
528
3.46875
3
[]
no_license
// https://leetcode-cn.com/problems/linked-list-cycle/ /** * 环形列表 * 1. 暴力:遍历链表 hash/set * 2. 双指针:快慢指针 */ // 类似龟兔赛跑,一个快指针 一个慢指针 如果链表中有环的话 就会出现套圈的情况 function hasCycle(head) { if (head == null || head.next == null) return false let slow = head, fast = head.next while(slow != fast){ if(fast == null || fast.next == null) return false slow = slow.next fast = fast.next.next } return true }
Java
UTF-8
1,875
3.375
3
[]
no_license
package array; import java.util.*; /** * Created by home on 10/28/2020. */ public class TestSolution1 { public static void main(String args[]){ String input = "abcdzedcba"; //-> abcdzdcba aabbccdd "abbacacdaad" String result = amethod(input); System.out.println("TestSolution 1 " + result); } public static String amethod(String input) { Map<String, Integer> map = new HashMap(); char[] chars = input.toCharArray(); //check each alphabet getting count for (int i = 0; i < chars.length; i++) { Integer count = map.get(chars[i] + ""); if (count == null) map.put(chars[i] + "", 1); else map.put(chars[i] + "", ++count); } int k = 0; String result = ""; String left = "", right = "", mid = ""; String inValid ="Not a palindrom"; Set<String> keys = map.keySet(); Iterator iter = keys.iterator(); while (iter.hasNext()) { String st = (String) iter.next(); Integer count = map.get(st); if (count % 2 != 0) k++; if (k == 0 || k == 1) { if (count % 2 == 0) { for (int j = 1; j <= count / 2; j++) { left = left + st; right = st + right; } } else { for (int j = 1; j <= count; j++) { mid = mid + st; } } } else { result = inValid; } } //right = right + left; if(!result.equals(inValid)) result = left + mid + right; return result; } }
Java
UTF-8
900
2.328125
2
[]
no_license
/** * @nopublish * User: 贺扬 * Date: 2005-5-24 * Time: 16:08:25 * ${NAME}类的说明 */ package awin.dao.persistence.type; import java.io.InputStream; import java.io.Reader; abstract public class SQLTypeFactory { public static SQLParamType getNullType(int type) { return new NullParamType(type); } public static SQLParamType getBlobType(Object obj) { return new BlobParamType(obj); } public static SQLParamType getBlobType(byte[] bytes) { return new BlobParamType(bytes); } public static SQLParamType getBlobType(InputStream input, int length) { return new BlobParamType(input, length); } public static SQLParamType getClobType(String s) { return new ClobParamType(s); } public static SQLParamType getClobType(Reader reader,int length) { return new ClobParamType(reader,length); } }
Java
UTF-8
1,970
1.9375
2
[]
no_license
package com.br.collection.entity.vo; import java.util.Date; import com.br.collection.entity.CaseInfo; public class CaseInfoExtendCollectionVO extends CaseInfo { private static final long serialVersionUID = 1L; private Integer companyId; private String companyName; private Integer caseId; private String debtName; private String identityId; private String cardId; private Date electrotherapyBeginDate; private Integer dealUserId; private String dealUserName; @Override public Integer getCompanyId() { return companyId; } @Override public void setCompanyId(Integer companyId) { this.companyId = companyId; } @Override public String getCompanyName() { return companyName; } @Override public void setCompanyName(String companyName) { this.companyName = companyName; } public Integer getCaseId() { return caseId; } public void setCaseId(Integer caseId) { this.caseId = caseId; } @Override public String getDebtName() { return debtName; } @Override public void setDebtName(String debtName) { this.debtName = debtName; } @Override public String getIdentityId() { return identityId; } @Override public void setIdentityId(String identityId) { this.identityId = identityId; } @Override public String getCardId() { return cardId; } @Override public void setCardId(String cardId) { this.cardId = cardId; } @Override public Date getElectrotherapyBeginDate() { return electrotherapyBeginDate; } @Override public void setElectrotherapyBeginDate(Date electrotherapyBeginDate) { this.electrotherapyBeginDate = electrotherapyBeginDate; } @Override public Integer getDealUserId() { return dealUserId; } @Override public void setDealUserId(Integer dealUserId) { this.dealUserId = dealUserId; } @Override public String getDealUserName() { return dealUserName; } @Override public void setDealUserName(String dealUserName) { this.dealUserName = dealUserName; } }
Python
UTF-8
653
3.015625
3
[]
no_license
#!/usr/bin/python3 def result2steps(r, graph, good): if r in graph: good.add(graph[r][0]) for nr in graph[r][1]: result2steps(nr, graph, good) def filter_tasks(tasks, result): graph = {} for task in tasks: for o in task[2]: graph[o] = (task[0], task[1]) good = set() for r in result: result2steps(r, graph, good) return good def main(): fin = open('log.txt', 'r') tasks = [] for line in fin: task, inf, outf = line.strip().split(';') tasks.append((task, inf.split(' '), outf.split(' '))) good = filter_tasks(tasks, ['5',]) for task in tasks: if task[0] in good: print(task) if __name__ == '__main__': main()
JavaScript
UTF-8
2,430
2.625
3
[]
no_license
const botconfig = require('./botconfig.json'); const Discord = require('discord.js'); const bot = new Discord.Client({ disableEveryone: true }) bot.on('ready', async () => { console.log(`${bot.user.username} is online!`); while (true) { bot.user.setActivity('Chris buy a gun...', { type: 3 }) await wait(5000) bot.user.setActivity('Cyre buy bullets...', { type: 3 }) await wait(5000) bot.user.setActivity('Thomas load bullets...', { type: 3 }) await wait(5000) bot.user.setActivity('Hitman execute Peter!', { type: 3 }) await wait(5000) } }); function wait(ms) { return new Promise(resolve => { setTimeout(resolve, ms) }) } bot.on('message', async message => { if (message.author.bot) return; if (message.channel.type === 'dm') return; let prefix = botconfig.prefix; let messageArray = message.content.split(' '); let cmd = messageArray[0]; if (message.content === 'hello' || message.content === 'hey' || message.content === 'hi') { return message.channel.send(`Hello ${message.author}!`) } if (!cmd.startsWith('!', [0])) { return } if (cmd === prefix + 'training') { message.member.addRole('585878951428358155'); return message.channel.send('<@&587248463176007713>, <@' + message.author.id + '> needs training!') } else if (cmd === prefix + 'interview') { message.member.addRole('587377545205252116'); return message.channel.send(`<@&587248463176007713>, <@${message.author.id}> needs an interview!`) } else if (cmd === prefix + 'chp') { message.member.addRole('572745109523791908'); return message.channel.send(`Addded the 'CHP' role to <@${message.author.id}>.`) } else if (cmd === prefix + 'sheriff') { message.member.addRole('572749757752147988'); return message.channel.send(`Addded the 'Sheriff' role to <@${message.author.id}>.`) } else if (cmd === prefix + 'setactivity') { return bot.user.setActivity() } else if (cmd === prefix + 'joinchannel') { return message.member.voiceChannel.join().then(() => { message.delete() }) } else { return message.channel.send('Unknown command! Use !help to get a list of the commands.') } }) bot.login(botconfig.token);
C++
UTF-8
339
3.046875
3
[]
no_license
#ifndef SPIN_LOCK_H #define SPIN_LOCK_H #include<atomic> namespace PUF{ class SpinLock{ private: std::atomic_flag flag = ATOMIC_FLAG_INIT; public: void lock(){ while(flag.test_and_set(std::memory_order_acquire)){} } void unLock(){ flag.clear(std::memory_order_release); } }; }//namespace PUF #endif
JavaScript
UTF-8
1,229
2.5625
3
[]
no_license
import React from 'react'; import {Button} from 'react-bootstrap'; class AddReviews extends React.Component { constructor(props) { super(props); this.state = { title: '', reviews: '' } this.add=this.add.bind(this); this.updateTitle=this.updateTitle.bind(this); this.updateReviews=this.updateReviews.bind(this); } updateTitle(e){ this.setState({ title: e.target.value }) } updateReviews(e){ this.setState({ reviews: e.target.value }) } add(){ this.props.addReviews(this.state.title, this.state.reviews); this.setState({ title: '', reviews: '' }) } render () { return (<div> <center> <h2 className="TitulosYHeaders">El titulo de tu reseña</h2> <input id="txtReview" placeholder=" Una palabra que resume tu visita" onChange={this.updateTitle} value={this.state.title} ></input> <br /> <h2 className="TitulosYHeaders">Tu reseña</h2> <textarea id="txtReview2" placeholder=" Cuéntale a la gente sobre tu experiencia" onChange={this.updateReviews} value={this.state.reviews} ></textarea> <br /> <Button bsStyle="danger" onClick={this.add}>Agregar Reseña</Button> </center> </div>); } } export default AddReviews;
Python
UTF-8
959
4.84375
5
[]
no_license
# Experiment with scopes in Python. # Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables # When you use a variable in a function, it's local in scope to the function. x = 12 def change_x(): # In order to use a global variable inside a function, # you've got to "import" it with the global keyword global x x = 99 change_x() # This prints 12. What do we have to modify in change_x() to get it to print 99? print("--- Exercise 1: ") print(x) # This nested function has a similar problem. def outer(): y = 120 def inner(): # The nonlocal keyword works similar to the global keyword, # except it is used for inner/outer functions nonlocal y y = 999 inner() # This prints 120. What do we have to change in inner() to get it to print # 999? # Note: Google "python nested function scope". print("--- Exercise 2: ") print(y) outer()
Python
UTF-8
3,377
3.328125
3
[]
no_license
import requests import time import base64 import ecdsa def wallet(): response = None while response not in ["1","2","3","4"]: response = input(""" What do you want to do? 1) Generate Waller 2) Send Coins to another Wallet 3) Check transactions 4) Quit\n""") if response == "1": print("""===========IMPORTANT NOTICE: SAVE THIS CREADENTIALS OR YOU WONT BE ABLE TO RETRIEVE THIS INFORMATIUON EVER AGAIN\n""") generate_ECDSA_keys() elif response == "2": addr_from = input("Type / paste in your wallet address (public key)\n") private_key = input("Type / paste in your private key\n") addr_to = input("To: Destination wallet address?") amount = input("Amount: number of coins you want to transfer\n") print("=========================================\n\n") print("Is everything correct?\n") print("From: {0}\nPrivate Key: {1}\nTo: {2}\nAmount: {3}\n".format(addr_from, private_key, addr_to, amount)) response = input("y/n: ") if response.lower() == "y": send_transaction(addr_from, private_key, addr_to, amount) elif response == "3": check_transactions() else: quit() def send_transaction(addr_from, private_key, addr_to, amount): if len(private_key) == 64: signature, message = sign_ECDSA_msg(private_key) url = 'https://localhost:5000/txion' payload = {"from":addr_from, "to":addr_to, "amount":amount, "signature": signature.decode(), "message":message} headers = {"Content-Type": "application/json"} res = requests.post(url, json=payload, headers = headers) print(res.text) else: print("Wrong address or key length, Verify and try again") def check_transactions(): # this retrives the entire blockchain # the speed depends upon the length of the blockchain try: res = requests.get('http://localhost:5000/blocks') print(res.text) except requests.ConnectionError: print("Connection error, make sure you are connected to the node") def generate_ECDSA_keys(): # this function generates private and public keys # using the python library called //ecdsa/// sk = ecdsa.SigningKey.generate(curve = ecdsa.SECP256k1) private_key = sk.to_string().hex() vk = sk.get_verifying_key() public_key = vk.to_string().hex() # to encode the public key with a base64 bit crptography to make it more shorter public_key = base64.b64encode(bytes.fromhex(public_key)) filename = input("Choose a name for your address: ") + ".txt" with open(filename, "w") as f: f.write("Private address: {0}\nWallet address / Public Key: {1}\n".format(private_key, public_key.decode())) print("Your nre address and the private key are now in the file {0}".format(filename)) def sign_ECDSA_msg(private_key): # this functions returns two parameters called # 1)Signature: a base64 # 2) Message: str message = str(round(time.time())) bmessage = message.encode() sk = ecdsa.SigningKey.from_string(bytes.fromhex(private_key), curve=ecdsa.SECP256k1) signature = base64.b64encode(sk.sign(bmessage)) return signature, message if __name__ == '__main__': print("===================================================") print(""" A INSECURE CRYPTO NODLE v1.0.0 - BLOCKCHAIN SYSTEM\n\n """) print("===================================================") wallet() input("Press ENTER to exit.....")
Markdown
UTF-8
4,679
3.140625
3
[]
no_license
# **Scripting (weight: 30%)** ## **What version control systems have you used? Why use version control?** I have used CVS back in the day,and currently use both SVN and Git in my current job. We use version control so that we can conduct many different types and levels of devleopment activities, including: - Tracking file state over time - Tracking down when new feature sets were added - Tracking when bug fixes were introduced - Providing tags that we want to use for deployment to systems - Providing branches that one or more team members can use to isolate or implement new code ## **For a directory containing multiple files, implement a way to scan each file for the string "foobar" and replace it with "fubar"** There's a numerous different utilities which will allow you to do this, including sed, awk, etc. But, the performance of each is going to be vastly different. There's many articles on the Internet that go through benchmarking of the speed of sed vs. awk vs. other programming languages used for search/replace scripts. Here's an example result from one of the benchmarks: | Utility | Operation type | Execution time (10 iterations) | Characters processed per second | | --------------:|:-----------------:|:---------------------------------:| -------------------------------:| | grep | search only | 41 seconds | 489.3 million | | sed | search & replace | 4 minutes 4 seconds | 82.1 million | | awk | search & replace | 4 minutes 46 seconds | 69.8 million | | Python script | search & replace | 4 minutes 50 seconds | 69.0 million | | PHP script | search & replace | 15 minutes 44 seconds | 21.2 million | So, let's provide a solution for this using sed: `sed -i 's/foobar/fubar/g' /path/to/dir/*` ## **For this exercise, create a file containing 100 unique users. All fields must be unique. The data should be formatted in CSV format in this manner: id,name,email** There are a couple different elements that we want to focus on in the creation of this script: 1. id - I assume here that the id will start at 1, and for each line created in the file, we will iterate the id by 1. Just in case my assumption is incorrect, in the script I will provide a way to declare what number you want to use as your "start" id value. 2. name - Because there was no informational constraints given on the name, I will use the convention: AwesomeUnicornGlitter[id] 3. email - Even though there were no contraints on this field (other than it must be unique), we will follow loosely follow RFC convention on the email (though this might be controversial - http://girders.org/blog/2013/01/31/dont-rfc-validate-email-addresses/ discusses why you might not want to do this.) To be simple, let's go with [name]@puppet.com . 4. The file name - Since a desired name was not included in the question, we will use awesome-new-users.txt The creation of the script is detailed over in Github via https://github.com/brennx0r/puppet-questions/blob/master/scripting/create-100-unique-users.sh ## **How can you create 100 files named 000.pp ... 099.pp whose contents are:** ``` class myfile000 { if $kernel == "Linux" { file { '/tmp/myfile000': ensure => file, backup => false, content => "Hello myfile000", } } } ... class myfile099 { if $kernel == "Linux" { file { '/tmp/myfile099': ensure => file, backup => false, content => "Hello myfile099", } } } ``` First thing I would want to do is create a "baseline" seed file that is parameterized on the integer identities to use for creation of the files need myfile000.pp - myfile099.pp): https://github.com/brennx0r/puppet-questions/blob/master/scripting/seed.pp Next, I create the main script: https://github.com/brennx0r/puppet-questions/blob/master/scripting/create-100-unique-files.sh 1. Copies the seed file over to a new file called myfile$n.pp (where $n is defined for 2 relevent cases: 000-009 and 010-099) 2. Scans the created file and replaces $n with the parameter value for all relevant instances of $n in the file It should be noted that I'm calling the files "myfile$n.pp" and not "$n.pp" because if we called the file "$n.pp" it would result in a Puppet catalog error when we run the catalog (at least, this is what happens in 3.x versions of Puppet. If the file is not called init.pp, the class name and the file name MUST match or an error will be given.)
JavaScript
UTF-8
267
3.734375
4
[]
no_license
// string let name = " phoenix"; console.log("my name is "+ name); // object literals let stmarks = { phoenix : 99, Rohan : 79, harry: 80, } console.log(typeof stmarks); console.log(stmarks); // funcions function names(){ } console.log(typeof names);
Python
UTF-8
1,613
3.90625
4
[]
no_license
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, current, value): if self.root is None: self.root = Node(value) else: if current.value < value: if current.left is None: current.left = Node(value) else: self.insert(current.left, value) else: if current.right is None: current.right = value else: self.insert(current.right, value) def visit(self, node): print(node.value) def preorder(self, current): """ 1. visit 2. go left 3. go right """ self.visit(current) self.preorder(current.left) self.preorder(current.right) def inorder(self, current): """ 1. go left 2. visit 3. go right """ self.inorder(current.left) self.visit(current) self.inorder(current.right) def postorder(self, current): """ 1. go left 2. go right 3. visit """ self.postorder(current.left) self.postorder(current.right) self.visit(current) def search(self, current, key): if current is None or current.value == key: return current if current.value < key: self.search(current.right, key) self.search(current.left, key)
Python
UTF-8
775
3.453125
3
[]
no_license
# 763. Partition Labels # greedy sol - time complexity - O(n) # space complexity O(n)=O(1) because input only consist of a to z, only extra space for mapping 26 letters #e.g. "ababcbacadefegdehijhklij" ->"ababcbaca", "defegde", "hijhklij" ->Output: [9,7,8] # watch where a is. idx where a last occurs is m['a']=9. the last idx for b, c is before last of a. class Solution: def partitionLabels(self, S: str) -> List[int]: m = {c:i for i,c in enumerate(S)} ret = [] j,anchor=0,0 for i,c in enumerate(S): j=max(j, m[c]) #check max idx of the label if i==j: #at the end of the current partition ret.append(i-anchor+1) anchor=i+1 #move anchor to the start of the next partition return ret
C
UTF-8
514
3.078125
3
[]
no_license
#include <stdio.h> #include <string.h> #define NAME_LEN 64 struct student { char name[NAME_LEN]; int height; float weight; long schols; }; int main(void) { struct student sanaka; strcyp(sanaka.name, "Sanaka"); sanaka.height = 175; sanaka.weight = 62.5; sanaka.schols = 73000; printf("NAME : %s", sanaka.name); printf("HEIGHT : %d", sanaka.height); printf("NAME : %.1f", sanaka.weight); printf("NAME : %ld", sanaka.schols); return 0; }
Java
UTF-8
3,940
1.820313
2
[ "BSD-3-Clause" ]
permissive
/******************************************************************************* * Copyright (c) 2016 AT&T Intellectual Property. All rights reserved. *******************************************************************************/ package com.att.dao.aaf.cass; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.List; import com.att.authz.env.AuthzTrans; import com.att.authz.layer.Result; import com.att.dao.AbsCassDAO; import com.att.dao.Bytification; import com.att.dao.CassDAOImpl; import com.att.dao.Loader; import com.att.dao.Streamer; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Row; public class DelegateDAO extends CassDAOImpl<AuthzTrans, DelegateDAO.Data> { public static final String TABLE = "delegate"; private PSInfo psByDelegate; public DelegateDAO(AuthzTrans trans, Cluster cluster, String keyspace) { super(trans, DelegateDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); init(trans); } public DelegateDAO(AuthzTrans trans, AbsCassDAO<AuthzTrans,?> aDao) { super(trans, DelegateDAO.class.getSimpleName(),aDao,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); init(trans); } private static final int KEYLIMIT = 1; public static class Data implements Bytification { public String user; public String delegate; public Date expires; @Override public ByteBuffer bytify() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DelegateLoader.dflt.marshal(this,new DataOutputStream(baos)); return ByteBuffer.wrap(baos.toByteArray()); } @Override public void reconstitute(ByteBuffer bb) throws IOException { DelegateLoader.dflt.unmarshal(this, toDIS(bb)); } } private static class DelegateLoader extends Loader<Data> implements Streamer<Data>{ public static final int MAGIC=0xD823ACF2; public static final int VERSION=1; public static final int BUFF_SIZE=48; public static final DelegateLoader dflt = new DelegateLoader(KEYLIMIT); public DelegateLoader(int keylimit) { super(keylimit); } @Override public Data load(Data data, Row row) { data.user = row.getString(0); data.delegate = row.getString(1); data.expires = row.getDate(2); return data; } @Override protected void key(Data data, int idx, Object[] obj) { obj[idx]=data.user; } @Override protected void body(Data data, int _idx, Object[] obj) { int idx = _idx; obj[idx]=data.delegate; obj[++idx]=data.expires; } @Override public void marshal(Data data, DataOutputStream os) throws IOException { writeHeader(os,MAGIC,VERSION); writeString(os, data.user); writeString(os, data.delegate); os.writeLong(data.expires.getTime()); } @Override public void unmarshal(Data data, DataInputStream is) throws IOException { /*int version = */readHeader(is,MAGIC,VERSION); // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields byte[] buff = new byte[BUFF_SIZE]; data.user = readString(is, buff); data.delegate = readString(is,buff); data.expires = new Date(is.readLong()); } } private void init(AuthzTrans trans) { String[] helpers = setCRUD(trans, TABLE, Data.class, DelegateLoader.dflt); psByDelegate = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE + " WHERE delegate = ?", new DelegateLoader(1),readConsistency); } public Result<List<DelegateDAO.Data>> readByDelegate(AuthzTrans trans, String delegate) { return psByDelegate.read(trans, R_TEXT, new Object[]{delegate}); } }
JavaScript
UTF-8
168,020
2.515625
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
/* This file is part of Cytoscape Web. Copyright (c) 2009, The Cytoscape Consortium (www.cytoscape.org) The Cytoscape Consortium is: - Agilent Technologies - Institut Pasteur - Institute for Systems Biology - Memorial Sloan-Kettering Cancer Center - National Center for Integrative Biomedical Informatics - Unilever - University of California San Diego - University of California San Francisco - University of Toronto This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // ===[ namespaces ]================================================================================ // Create namespaces if not already defined: (function () { "use strict"; if (!this.org) { this.org = {}; } if (!this.org.cytoscapeweb) { /** @namespace */ this.org.cytoscapeweb = {}; } // Create a global map to store all instances of Cytoscape Web: this._cytoscapeWebInstances = { index: 0 }; // ===[ Visualization ]========================================================================= /** * <p>Initialise Cytoscape Web. It does not draw the network yet.</p> * <p>The {@link org.cytoscapeweb.Visualization#draw} method must be called when * you want the network to be displayed.</p> * @example * &lt;html&gt; * &lt;head&gt; &lt;/head&gt; * &lt;body&gt; * * &lt;h1&gt;Sample&lt;/h1&gt; * &lt;div id="cytoWebContent" style="width: 600px;height: 400px;"&gt;&lt;/div&gt; * * &lt;script type="text/javascript"&gt; * var options = { swfPath: "path/to/swf/CytoscapeWeb", * flashInstallerPath: "path/to/swf/playerProductInstall", * flashAlternateContent: "Le Flash Player est n&eacute;cessaire." }; * * var vis = new org.cytoscapeweb.Visualization("cytoWebContent", options); * * vis.draw({ network: '&lt;graphml&gt;...&lt;/graphml&gt;' }); * &lt;/script&gt; * * &lt;/body&gt; * &lt;html&gt; * @class * @param {String} containerId The id of the HTML element (containing your alternative content) * you would like to have replaced by the Flash object. * @param {Object} [options] Cytoscape Web parameters: * <ul class="options"> * <li><code>swfPath</code>: The path of the compiled Cytoscape Web SWF file, but without the * <code>.swf</code> extension. If you use the provided <code>CytoscapeWeb.swf</code> * file and put it in the root path of the web application, this option does not need * to be specified. But, for example, if you deploy the swf file at <code>/plugin/flash</code>, * the <code>swfPath</code> value must be "/plugin/flash/CytoscapeWeb".</li> * <li><code>flashInstallerPath</code>: The path to the compiled Flash video that should be displayed in case * the browser does not have the Flash Player version required by Cytoscape Web. * The default value is "playerProductInstall" and, if this option is not changed, * the <code>playerProductInstall.swf</code> file must be deployed in the * web site's root path. Otherwise, just specify the new path without the * <code>.swf</code> extension.</li> * <li><code>flashAlternateContent</code>: The text message that should be displayed if the browser does not have * the Flash Player plugin. If none is provided, Cytoscape Web will show * a default message and a link to the "Get Flash" page.</li> * <li><code>resourceBundleUrl</code>: An optional resource bundle path. Usually a <code>.properties</code> file * that redefines the default labels and messages used by Cytoscape Web. * Example of a valid file with all the available keys: * <pre> * global.wait = Please wait... * error.title = Error * pan.tooltip = Grab to pan * pan.up.tooltip = Pan up * pan.down.tooltip = Pan down * pan.left.tooltip = Pan left * pan.right.tooltip = Pan right * zoom.out.tooltip = Zoom out * zoom.in.tooltip = Zoom in * zoom.fit.tooltip = Fit to screen * zoom.slider.tooltip = {0}% * </pre></li> * <li><code>idToken</code>: A string used to create the embedded Flash video id * (usually an HTML <code>embed</code> or <code>object</code> tag). * The default token is "cytoscapeWeb" and the final id will be the token followed * by a number, so if the application has two instances of the Visualization in the same page, * their id's will be "cytoscapeWeb1" and "cytoscapeWeb2". * This token does not usually need to be changed.</li> * <li><code>mouseDownToDragDelay</code>: If the user clicks (mouse-down) the background and hold if for a while, * Cytoscape Web temporarily changes to grab-to-pan mode, so the user can drag the whole network. * If the user do the same over a node, the grab-to-pan mode can be activated as well, * but dragging the node will drag the node's disconnected component only, * not necessarily the whole network--if there are other disconnected parts, they will not be dragged. * This parameter lets you set the time (in milliseconds) Cytoscape Web should wait before changing modes. * The default value is <code>400</code>. * If this parameter is set to <code>-1</code>, Cytoscape Web will never activate the grab-to-pan mode * automatically, but users can still use the grab-to-pan option from the pan-zoom control.</li> * </ul> * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#draw * @see org.cytoscapeweb.Visualization#ready */ this.org.cytoscapeweb.Visualization = function (containerId, options) { this.containerId = containerId; if (!options) { options = {}; } this.options = options; // Part of the embed or object tag id: this.idToken = options.idToken ? options.idToken : "cytoscapeWeb"; // The .swf path, including its name, but without the file extension: this.swfPath = options.swfPath ? options.swfPath : "CytoscapeWeb"; // The path of the .swf file that updates the Flash player version: this.flashInstallerPath = options.flashInstallerPath ? options.flashInstallerPath : "playerProductInstall"; // Alternate content to be displayed in case user does not have Flash installed: this.flashAlternateContent = options.flashAlternateContent ? options.flashAlternateContent : 'This content requires the Adobe Flash Player. ' + '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>'; _cytoscapeWebInstances.index++; this.id = this.idToken + _cytoscapeWebInstances.index; _cytoscapeWebInstances[this.id] = this; }; org.cytoscapeweb.Visualization.prototype = { // PUBLIC METHODS: // ----------------------------------------------------------------------------------------- /** * <p>Start Cytoscape Web by drawing the network. * At least the <code>network</code> option must be specified.</p> * @example * var vis = new org.cytoscapeweb.Visualization("container-id"); * vis.draw({ network: '&lt;graphml&gt;...&lt;/graphml&gt;', * edgeLabelsVisible: false, * layout: 'Circle', * visualStyle: { * global: { * backgroundColor: "#000033", * nodeSelectionColor: "#ffce81" * }, * nodes: { * shape: "diamond" * }, * edges: { * width: 2 * } * } * }); * * @description * <p>Just remember that you probably want to register a callback function with {@link org.cytoscapeweb.Visualization#ready} * before calling <code>draw()</code>.</p> * * @example * var vis = new org.cytoscapeweb.Visualization("container-id"); * vis.ready(function () { * // Start interaction with the network here... * }); * vis.draw({ network: '&lt;graphml&gt;...&lt;/graphml&gt;' }); * * @param {Object} options * <ul class="options"> * <li><code>network</code>: The model that describes the network. Only this option is mandatory. It can be one of the following formats: * <ul><li>{@link org.cytoscapeweb.NetworkModel}: A simple JavaScript object that defines the raw data from which to build a network.</li> * <li><a href="http://graphml.graphdrawing.org/primer/graphml-primer.html" target="_blank">GraphML</a>: An XML format for graphs.</li> * <li><a href="http://www.cs.rpi.edu/~puninj/XGMML/" target="_blank">XGMML</a>: This XML format allows you to define * visual properties (e.g. colors and shapes) and nodes positioning, if you want to, * although using the <code>visualStyle</code> and <code>layout</code> options is usually better.</li> * <li><a href="http://cytoscape.wodaklab.org/wiki/Cytoscape_User_Manual/Network_Formats/" target="_blank">SIF</a>: A simpler text format * that can be very useful if you do not need to set custom nodes/edges attributes.</li> * </ul></li> * <li><code>visualStyle</code>: an optional {@link org.cytoscapeweb.VisualStyle} object to be applied on this network.</li> * <li><code>layout</code>: an optional {@link org.cytoscapeweb.Layout} object, or just the layout name. * The default is "ForceDirected", unless the network data is an * <a href="http://www.cs.rpi.edu/~puninj/XGMML/" target="_blank">XGMML</a>, whose * <code><a href="http://www.cs.rpi.edu/~puninj/XGMML/draft-xgmml-20010628.html#NodeE" target="_blank">node</a></code> * elements contain * <code><a href="http://www.cs.rpi.edu/~puninj/XGMML/draft-xgmml-20010628.html#GraphicsA" target="_blank">graphics</a></code> * tags with defined <code>x</code> and <code>y</code> attributes. In that case, the "Preset" layout is applied by default.</li> * <li><code>nodeLabelsVisible</code>: Boolean that defines whether or not the node labels will be visible. * The default value is <code>true</code>. * You can call {@link org.cytoscapeweb.Visualization#nodeLabelsVisible} * later (after the network is ready) to change it.</li> * <li><code>edgeLabelsVisible</code>: Boolean that defines whether or not the edge labels will be visible. * The default value is <code>false</code>. * You can use {@link org.cytoscapeweb.Visualization#edgeLabelsVisible} later to change it.</li> * <li><code>nodeTooltipsEnabled</code>: Boolean value that enables or disables the node tooltips. * The default value is <code>true</code>. * You can call {@link org.cytoscapeweb.Visualization#nodeTooltipsEnabled} later to change it.</li> * <li><code>edgeTooltipsEnabled</code>: Boolean that enables or disables the edge tooltips. * The default value is <code>true</code>. * You can use {@link org.cytoscapeweb.Visualization#edgeTooltipsEnabled} later to change it.</li> * <li><code>edgesMerged</code>: Boolean that defines whether or not the network will be initially * rendered with merged edges. The default value is <code>false</code>. * You can call {@link org.cytoscapeweb.Visualization#edgesMerged} after the network is ready to change it.</li> * <li><code>panZoomControlVisible</code>: Boolean value that sets whether or not the built-in control * will be visible. The default value is <code>true</code>. * The visibility of the control can be changed later with * {@link org.cytoscapeweb.Visualization#panZoomControlVisible}.</li> * <li><code>preloadImages</code>: Boolean that defines whether or not to load all images before rendering the network. * If <code>true</code>, all images from a * {@link org.cytoscapeweb.VisualStyle} or {@link org.cytoscapeweb.VisualStyleBypass} * will be loaded before the network is drawn or before a visual style (or bypass) is applied. * The default value is <code>true</code>.</li> * </ul> * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#ready * @see org.cytoscapeweb.VisualStyle * @see org.cytoscapeweb.Layout */ draw: function (options) { if (!options) { options = {}; } this.drawOptions = options; // Start the Flash video: this.embedSWF(); return this; }, /** * <p>Register a function to be called after a {@link org.cytoscapeweb.Visualization#draw} method is executed and the visualization * is ready to receive requests, such as getting or selecting nodes, zooming, etc.</p> * <p>If the application wants to interact with the rendered network, this function must be used * before calling the <code>draw</code> method.</p> * * @example * // 1. Create the visualization instance: * var vis = new org.cytoscapeweb.Visualization("container-id"); * * // 2. Register a callback function for the ready event: * vis.ready(function () { * // Write code to interact with Cytoscape Web, e.g: * var nodes = vis.nodes(); * // and so on... * }); * * // 3. And then call draw: * vis.draw({ network: '&lt;graphml&gt;...&lt;/graphml&gt;' }); * * @param {Function} fn The callback function that will be invoked after the network has been drawn * and the visualization is ready. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#draw */ ready: function (fn) { if (!fn) { this._onReady = function () {/*do nothing*/}; } else { this._onReady = fn; } return this; }, /** * <p>If the <code>layout</code> argument is passed, it applies the layout to the network. * Otherwise it just returns the the current layout object.</p> * <p>In order to set a layout, you can send a layout object or just the layout name, * if you want to use the default options.</p> * <p>See {@link org.cytoscapeweb.Layout} for the available options.</p> * * @example * // 1. Initialise Cytoscape Web with a Circle layout (default layout options): * var vis = new org.cytoscapeweb.Visualization("container-id"); * vis.draw({ network: '&lt;graphml&gt;...&lt;/graphml&gt;', layout: 'Circle' }); * * // 2. Get the current layout: * var layout = vis.layout(); // returns: { name: 'Circle', options: { angleWidth: 360 } }; * * // 3. Apply a new layout, using default options: * vis.layout('ForceDirected'); * * // 4. Apply a new layout with custom options: * var options = { * drag: 0.2, * gravitation: -200, * minDistance: 1, * maxDistance: 400, * mass: 2, * tension: 0.2, * weightAttr: "weight", * restLength: 100, * iterations: 200, * maxTime: 10000, * autoStabilize: false * }; * vis.layout({ name: 'ForceDirected', options: options }); * * @param {Object} [layout] The {@link org.cytoscapeweb.Layout} object or the layout name. * @return <ul><li>The current {@link org.cytoscapeweb.Layout} object for <code>layout()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>layout({Object})</code>.</li></ul> * @see org.cytoscapeweb.Layout */ layout: function (/*layout*/) { var swf = this.swf(); if (arguments.length > 0) { swf.applyLayout(arguments[0]); return this; } else { return swf.getLayout(); } }, /** * <p>If the <code>style</code> argument is passed, it applies that visual style to the network. * Otherwise it just returns the current visual style object.</p> * @param {org.cytoscapeweb.VisualStyle} [style] An object that contains the desired visual properties and attribute mappings. * @example * var style = { * global: { * backgroundColor: "#000000" * }, * nodes: { * color: "#ffffff", * size: 40 * } * }; * * vis.visualStyle(style); * * @return <ul><li>The {@link org.cytoscapeweb.VisualStyle} object for <code>visualStyle()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>visualStyle({Object})</code>.</li></ul> * @see org.cytoscapeweb.VisualStyle * @see org.cytoscapeweb.Visualization#visualStyleBypass */ visualStyle: function (/*style*/) { var swf = this.swf(); if (arguments.length > 0) { swf.setVisualStyle(arguments[0]); return this; } else { return swf.getVisualStyle(); } }, /** * <p>If the <code>bypass</code> argument is passed, it sets a visual style bypass on top of the regular styles. * Otherwise it just returns the current bypass object.</p> * <p>It allows you to override the visual styles (including the ones set by mappers) for individual nodes and edges, * which is very useful when the default visual style mechanism is not enough to create the desired effect.</p> * @example * // Change the labels of selected nodes and edges: * var selected = vis.selected(); * * var bypass = { nodes: { }, edges: { } }; * var props = { * labelFontSize: 16, * labelFontColor: "#ff0000", * labelFontWeight: "bold" * }; * * for (var i=0; i < selected.length; i++) { * var obj = selected[i]; * * // obj.group is either "nodes" or "edges"... * bypass[obj.group][obj.data.id] = props; * } * * vis.visualStyleBypass(bypass); * * @example * // To remove a bypass, just set <code>null</code> or an empty object: * vis.visualStyleBypass(null); * * @param {org.cytoscapeweb.VisualStyleBypass} bypass The visual properties for nodes and edges. Must be a map that has nodes/edges * ids as keys and the desired visual properties as values. * The visual properties are the same ones used by the VisualStyle objects, except that * <code>global</code> properties cannot be bypassed and are just ignored. Another difference is that you * cannot set visual mappers, but only static values. * @return <ul><li>The {@link org.cytoscapeweb.VisualStyleBypass} object for <code>visualStyleBypass()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} instance for <code>visualStyleBypass({Object})</code>.</li></ul> * @see org.cytoscapeweb.VisualStyleBypass * @see org.cytoscapeweb.Visualization#visualStyle */ visualStyleBypass: function (/*bypass*/) { var swf = this.swf(); var json; if (arguments.length > 0) { json = JSON.stringify(arguments[0]); // to avoid errors with special characters in node IDs swf.setVisualStyleBypass(json); return this; } else { json = swf.getVisualStyleBypass(); return JSON.parse(json); } }, /** * <p>If the boolean argument is passed, it shows or hides the built-in pan-zoom control.</p> * <p>If not, it just returns a boolean value indicating whether or not the control is visible.</p> * @param {Boolean} [visible] true to show it and false to hide it. * @return <ul><li>A boolean value for <code>panZoomControlVisible()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>panZoomControlVisible({Boolean})</code>.</li></ul> */ panZoomControlVisible: function (/*visible*/) { var swf = this.swf(); if (arguments.length > 0) { swf.showPanZoomControl(arguments[0]); return this; } else { return swf.isPanZoomControlVisible(); } }, /** * <p>If the boolean argument is passed, it merges or unmerge all the edges and returns the Visualization object.</p> * <p>If not, it returns a boolean value indicating whether or not the edges are merged.</p> * @param {Boolean} [merged] true to merge the edges or false to unmerge them. * @return <ul><li>A boolean value for <code>edgesMerged()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>edgesMerged({Boolean})</code>.</li></ul> */ edgesMerged: function (/*merged*/) { var swf = this.swf(); if (arguments.length > 0) { swf.mergeEdges(arguments[0]); return this; } else { return swf.isEdgesMerged(); } }, /** * <p>If the boolean argument is passed, it shows or hides all the node labels and returns the Visualization object.</p> * <p>If not, it returns a boolean value indicating whether or not the node labels are visible.</p> * @param {Boolean} [visible] true to show the labels or false to hide them. * @return <ul><li>A boolean value for <code>nodeLabelsVisible()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>nodeLabelsVisible({Boolean})</code>.</li></ul> */ nodeLabelsVisible: function (/*visible*/) { var swf = this.swf(); if (arguments.length > 0) { swf.showNodeLabels(arguments[0]); return this; } else { return swf.isNodeLabelsVisible(); } }, /** * <p>If the boolean argument is passed, it shows or hides all the edge labels and returns the Visualization object.</p> * <p>If not, it returns a boolean value indicating whether or not the edge labels are visible.</p> * @param {Boolean} [visible] true to show the labels or false to hide them. * @return <ul><li>A boolean value for <code>edgeLabelsVisible()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>edgeLabelsVisible({Boolean})</code>.</li></ul> */ edgeLabelsVisible: function (/*visible*/) { var swf = this.swf(); if (arguments.length > 0) { swf.showEdgeLabels(arguments[0]); return this; } else { return swf.isEdgeLabelsVisible(); } }, /** * <p>If the boolean argument is passed, it enables or disables the node tooltips.</p> * <p>If not, it returns a boolean value indicating whether or not the node tooltips are enabled.</p> * @param {Boolean} [enabled] true to enable the tooltips or false to disable them. * @return <ul><li>A boolean value for <code>nodeTooltipsEnabled()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>nodeTooltipsEnabled({Boolean})</code>.</li></ul> */ nodeTooltipsEnabled: function (/*enabled*/) { var swf = this.swf(); if (arguments.length > 0) { swf.enableNodeTooltips(arguments[0]); return this; } else { return swf.isNodeTooltipsEnabled(); } }, /** * <p>If the boolean argument is passed, it enables or disables the edge tooltips.</p> * <p>If not, it returns a boolean value indicating whether or not the edge tooltips are enabled.</p> * @param {Boolean} [enabled] true to enable the tooltips or false to disable them. * @return <ul><li>A boolean value for <code>edgeTooltipsEnabled()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>edgeTooltipsEnabled({Boolean})</code>.</li></ul> */ edgeTooltipsEnabled: function (/*enabled*/) { var swf = this.swf(); if (arguments.length > 0) { swf.enableEdgeTooltips(arguments[0]); return this; } else { return swf.isEdgeTooltipsEnabled(); } }, /** * <p>If the boolean argument is passed in, it enables or disables custom mouse cursors, such as the hand icon used when panning the network.</p> * <p>If no argument is passed in, it returns a boolean value indicating whether or not custom cursors are enabled.</p> * @param {Boolean} [enabled] If <code>true</code>, custom (Flash) cursors can be used in some actions. * If <code>false</code>, Cytoscape Web will never replace the operating system's cursors. * @return <ul><li>A boolean value for <code>customCursorsEnabled()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>panEnabled({Boolean})</code>.</li></ul> */ customCursorsEnabled: function (/*enabled*/) { if (arguments.length > 0) { this.swf().enableCustomCursors(arguments[0]); return this; } else { return this.swf().isCustomCursorsEnabled(); } }, /** * <p>If the boolean argument is passed, it enables or disables the "grab to pan" mode. * It's like clicking the "grab to pan" button in the pan-zoom control.</p> * <p>If no argument is passed, it returns a boolean value indicating whether or not the pan mode is enabled.</p> * @param {Boolean} [enabled] If <code>true</code>, clicking and dragging the background will pan the network. * If <code>false</code>, the pan mode is turned off - clicking and dragging the background * will start a drag-selection action. * @return <ul><li>A boolean value for <code>panEnabled()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>panEnabled({Boolean})</code>.</li></ul> * @see org.cytoscapeweb.Visualization#panBy * @see org.cytoscapeweb.Visualization#panToCenter */ panEnabled: function (/*enabled*/) { if (arguments.length > 0) { this.swf().enableGrabToPan(arguments[0]); return this; } else { return this.swf().isGrabToPanEnabled(); } }, /** * <p>Pan the "camera" by the specified amount, in pixels.</p> * @param {Number} amountX If negative, pan left (the network moves to the right side). * @param {Number} amountY If negative, pan up (the network moves down). * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#panEnabled * @see org.cytoscapeweb.Visualization#panToCenter */ panBy: function (amountX, amountY) { this.swf().panBy(amountX, amountY); return this; }, /** * <p>Center the network in the canvas area.</p> * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#panEnabled * @see org.cytoscapeweb.Visualization#panBy */ panToCenter: function () { this.swf().panToCenter(); return this; }, /** * <p>If the scale argument is passed, it changes the zoom level of the network. * Otherwise it gets the current zoom value.</p> * @param {Number} [scale] Value between 0 and 1. * @return <ul><li>A number for <code>zoom()</code>.</li> * <li>The {@link org.cytoscapeweb.Visualization} object for <code>zoom({Number})</code>.</li></ul> * @see org.cytoscapeweb.Visualization#zoomToFit */ zoom: function (/*scale*/) { var swf = this.swf(); if (arguments.length > 0) { swf.zoomTo(arguments[0]); return this; } else { return swf.getZoom(); } }, /** * <p>Change the scale of the network until it fits the screen.</p> * <p>If the network scale is or reaches 1 (100%) and it's not cropped, it is not zoomed in to more than that. * It also centers the network, even if the scale was not changed.</p> * <p>It does not return the result scale. * If you want to get the applied zoom level, add an event listener before calling <code>zoomToFit</code>.</p> * @example * var scale; * vis.addListener("zoom", function(evt) { * scale = evt.value; * }); * vis.zoomToFit(); * * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#zoom */ zoomToFit: function () { this.swf().zoomToFit(); return this; }, /** * <p>Get one node by its unique ID.</p> * @example * var node = vis.node("n4"); * * @param {String} id The node id. * @return {org.cytoscapeweb.Node} The node object or <code>null</code>, if there is no node with the specified id. * @see org.cytoscapeweb.Visualization#edge * @see org.cytoscapeweb.Visualization#nodes */ node: function (id) { var str = this.swf().getNodeById(id); return JSON.parse(str); }, /** * <p>Get all nodes from the network.</p> * @return {Array} List of nodes. * @see org.cytoscapeweb.Visualization#edges * @see org.cytoscapeweb.Visualization#node */ nodes: function () { var str = this.swf().getNodes(); return JSON.parse(str); }, /** * <p>Get one edge, including any merged edge, by its unique ID.</p> * @example * var edge = vis.edge("e10"); * * @param {String} id The edge id. * @return {org.cytoscapeweb.Edge} The edge object or <code>null</code>, if there is no edge with the specified id. * @see org.cytoscapeweb.Visualization#node * @see org.cytoscapeweb.Visualization#edges */ edge: function (id) { var str = this.swf().getEdgeById(id); return JSON.parse(str); }, /** * <p>Get all the regular edges from the network. Merged edges are not included.</p> * @return {Array} List of edges. * @see org.cytoscapeweb.Visualization#mergedEdges * @see org.cytoscapeweb.Visualization#nodes * @see org.cytoscapeweb.Visualization#edge * @see org.cytoscapeweb.Edge */ edges: function () { var str = this.swf().getEdges(); return JSON.parse(str); }, /** * <p>Get all merged edges from the network.</p> * @return {Array} List of merged edges. * @see org.cytoscapeweb.Visualization#edges * @see org.cytoscapeweb.Edge */ mergedEdges: function () { var str = this.swf().getMergedEdges(); return JSON.parse(str); }, /** * <p>Create a new node and add it to the network view.<p> * <p>If the node <code>id</code> is not specified, Cytoscape Web creates a new one automatically.</p> * <p>If you try to add data attributes that have not been previously defined, * Cytoscape Web will automatically add the necessary field definitions, although it might be safer to always add the * fields to the schema first, by calling {@link org.cytoscapeweb.Visualization#addDataField}.</p> * @example * var data = { id: "n4", * label: "MYO2 (Yeast)", * weight: 0.54 }; * * var node = vis.addNode(240, 360, data, true); * * @param {Object} x The horizontal coordinate of the node. * @param {Object} y The vertical coordinate of the node. * @param {Object} [data] The object that contains the node attributes. * @param {Boolean} [updateVisualMappers] It tells Cytoscape Web to update and reapply the visual mappers * to the network view after adding the node. * The default value is <code>false</code>. * @return {org.cytoscapeweb.Node} The new created node object. * @see org.cytoscapeweb.Visualization#addEdge * @see org.cytoscapeweb.Visualization#removeElements */ addNode: function (x, y/*, data, updateVisualMappers*/) { var data, updateVisualMappers = false, i = 2; if (arguments.length > i && typeof arguments[i] === "object") { data = arguments[i++]; } if (arguments.length > i && typeof arguments[i] === "boolean") { updateVisualMappers = arguments[i]; } return this.swf().addNode(x, y, data, updateVisualMappers); }, /** * <p>Create a new edge linking two nodes and add it to the network view.<p> * <p>If the edge <code>id</code> is not specified, Cytoscape Web creates a new one automatically.</p> * <p>Throws exception if missing <code>source</code> or <code>target</code>.</p> * <p>If you try to add data attributes that have not been previously defined, * Cytoscape Web will automatically add the necessary field definitions, although it might be safer to always add the * fields to the schema first, by calling {@link org.cytoscapeweb.Visualization#addDataField}.</p> * @example * var data = { id: "e10", * source: "n1", * target: "n4", * directed: false, * label: "Co-expression", * weight: 0.88 }; * * var edge = vis.addEdge(data, true); * * @param {Object} data The object that contains the edge attributes. * @param {Boolean} [updateVisualMappers] It tells Cytoscape Web to update and reapply the visual mappers * to the network view after adding the edge. * @return {org.cytoscapeweb.Edge} The new created edge object. * @see org.cytoscapeweb.Visualization#addNode * @see org.cytoscapeweb.Visualization#removeElements */ addEdge: function (data/*, updateVisualMappers*/) { var updateVisualMappers = false; if (data == null) { throw("The 'data' object is mandatory."); } if (data.source == null) { throw("The 'source' node ID mandatory."); } if (data.target == null) { throw("The 'target' node ID mandatory."); } if (arguments.length > 1) { updateVisualMappers = arguments[1]; } return this.swf().addEdge(data, updateVisualMappers); }, /** * <p>Permanently delete the specified node and its associated edges from the network.</p> * <p>If a node is deleted, all of its connected edges will be removed as well.</p> * @example * // 1. Pass the whole Node object: * var node = vis.nodes()[0]; * vis.removeNode(node); * * // 2. Or just specify the node id: * vis.removeNode("n3"); * * @param {Object} node The node to be removed from the network. It can be a {@link org.cytoscapeweb.Node} * object or just its <code>id</code> (String). * @param {Boolean} [updateVisualMappers] It tells Cytoscape Web to reapply the visual mappers * to the network view after removing the element. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#removeEdge * @see org.cytoscapeweb.Visualization#removeElements * @see org.cytoscapeweb.Visualization#addNode * @see org.cytoscapeweb.Visualization#addEdge */ removeNode: function(node, updateVisualMappers) { this.swf().removeElements("nodes", [node], updateVisualMappers); return this; }, /** * <p>Permanently delete the specified edge from the network.</p> * <p>If the specified edge is a merged one, all of its "regular" edges are deleted as well.</p> * @example * // 1. Pass the whole Edge object: * var edge = vis.edges()[0]; * vis.removeEdge(edge); * * // 2. Or just pass the edge id: * vis.removeEdge("e101"); * * @param {Object} edge The edge to be removed from the network. It can be an {@link org.cytoscapeweb.Edge} * object or just its <code>id</code> (String). * @param {Boolean} [updateVisualMappers] It tells Cytoscape Web to reapply the visual mappers * to the network view after removing the element. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#removeNode * @see org.cytoscapeweb.Visualization#removeElements * @see org.cytoscapeweb.Visualization#addNode * @see org.cytoscapeweb.Visualization#addEdge */ removeEdge: function(edge, updateVisualMappers) { this.swf().removeElements("edges", [edge], updateVisualMappers); return this; }, /** * <p>Permanently delete nodes and/or edges from the network.</p> * <p>If a node is deleted, all of its connected edges will be removed as well.</p> * @example * // 1. Remove edges by ID: * vis.removeElements("edges", ["1", "2", "5"]); * * // 2. Remove edges and nodes altogether, by passing the objects to be deleted: * var nodes = vis.nodes(); * var edges = vis.edges(); * vis.removeElements([nodes[0], nodes[1], edges[0]], true); * * // 3. Remove all edges: * vis.removeElements("edges"); * * // 4. Remove everything (nodes and edges): * vis.removeElements(); * * @param {org.cytoscapeweb.Group} [gr] The group of network elements. * @param {Array} [items] The items to be removed from the network. The array can contain node/edge objects or only * their <code>id</code> values. Remember that, if you pass only the id * and do not pass the group argument, if an edge and a node have the same id value, * both will be removed. * @param {Boolean} [updateVisualMappers] It tells Cytoscape Web to reapply the visual mappers * to the network view after removing the elements. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#removeNode * @see org.cytoscapeweb.Visualization#removeEdge * @see org.cytoscapeweb.Visualization#addNode * @see org.cytoscapeweb.Visualization#addEdge */ removeElements: function(/*gr, items, updateVisualMappers*/) { var gr, items, updateVisualMappers = false; if (arguments.length >= 1) { if (typeof arguments[0] === "string") { gr = arguments[0]; } else if (this._typeof(arguments[0]) === "array") { items = arguments[0]; } else if (typeof arguments[0] === "boolean") { updateVisualMappers = arguments[0]; } } if (arguments.length >= 2) { if (this._typeof(arguments[1]) === "array") { items = arguments[1]; } else if (typeof arguments[1] === "boolean") { updateVisualMappers = arguments[1]; } } if (arguments.length > 2) { updateVisualMappers = arguments[2]; } gr = this._normalizeGroup(gr); this.swf().removeElements(gr, items, updateVisualMappers); return this; }, /** * <p>Get the network data schema, which contains all the nodes and edges data fields.</p> * @example * var schema = vis.dataSchema(); * var nodeFields = schema.nodes; * var edgeFields = schema.edges; * * @return {org.cytoscapeweb.DataSchema} The data schema object. * @see org.cytoscapeweb.Visualization#addDataField * @see org.cytoscapeweb.Visualization#removeDataField * @see org.cytoscapeweb.Visualization#updateData */ dataSchema: function () { return this.swf().getDataSchema(); }, /** * <p>Add a custom attribute definition to the current node or edge data schema.</p> * <p>If an attribute with the same name is already defined for the same group, * the attribute will not be added again or replace the previous definitions.</p> * @example * // 1: Add the same new field to nodes and edges data: * var field = { name: "url", type: "string", defValue: "http://cytoscapeweb.cytoscape.org/" }; * vis.addDataField(field); * * // 2: Add new field to nodes only: * var field = { name: "score", type: "number", defValue: 0.15 }; * vis.addDataField("nodes", field); * * @param {org.cytoscapeweb.Group} [gr] The group of network elements. If no group is passed, * Cytoscape Web will try to add the new field to both nodes and edges data schema. * @param {org.cytoscapeweb.DataField} dataField An object that contains the attribute definitions. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#removeDataField * @see org.cytoscapeweb.Visualization#updateData * @see org.cytoscapeweb.Visualization#dataSchema */ addDataField: function (/*gr, dataField*/) { var gr, dataField, i = 0; if (arguments.length > 1) { gr = arguments[i++]; } dataField = arguments[i]; if (dataField == null) { throw("The 'dataField' object is mandatory."); } if (dataField.name == null) { throw("The 'name' of the data field is mandatory."); } if (dataField.type == null) { throw("The 'type' of the data field is mandatory."); } gr = this._normalizeGroup(gr); this.swf().addDataField(gr, dataField); return this; }, /** * <p>Remove a custom attribute definition from the data schema.</p> * <p>Remember that only custom metadata can be removed. Any attempt to remove the following data fields will be ignored:</p> * <ul> * <li><code>id</code> (nodes and edges)</li> * <li><code>source</code> (edges)</li> * <li><code>target</code> (edges)</li> * <li><code>directed</code> (edges)</li> * </ul> * @example * // 1: Remove a data field from nodes and edges: * vis.removeDataField("url"); * * // 2: Remove a data field from edges only: * vis.removeDataField("edges", "url"); * * @param {org.cytoscapeweb.Group} [gr] The group of network elements. If no group is passed, * Cytoscape Web will try to remove the field from both nodes and edges data schema. * @param {String} name The name of the custom data field that will be removed. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#addDataField * @see org.cytoscapeweb.Visualization#updateData * @see org.cytoscapeweb.Visualization#dataSchema */ removeDataField: function (/*gr, name*/) { var gr, name, i = 0; if (arguments.length > 1) { gr = arguments[i++]; } name = arguments[i]; if (name == null) { throw("The 'name' of the data field is mandatory."); } gr = this._normalizeGroup(gr); this.swf().removeDataField(gr, name); return this; }, /** * <p>This method updates nodes and edges <code>data</code> attributes. You can use it to * change the value of any existing data attribute, except:</p> * <ul> * <li><code>id</code> (nodes and edges)</li> * <li><code>source</code> (edges)</li> * <li><code>target</code> (edges)</li> * </ul> * <p>You can only update <code>data</code> attributes. Visual properties such as <code>color</code> * and <code>width</code> cannot be updated with this method. In order to change visual properties, * use {@link org.cytoscapeweb.Visualization#visualStyle} or {@link org.cytoscapeweb.Visualization#visualStyleBypass}.</p> * <p>If you try to change an attribute that has not been previously defined, Cytoscape Web will throw an {@link org.cytoscapeweb.Error}. * In this case, you have to add the attribute definition first, by calling {@link org.cytoscapeweb.Visualization#addDataField}.</p> * <p>Another important thing to remember is that you cannot directly change merged edges attributes.</p> * <p>Finally, all the continuous and custom mappers - defined by the current visual style - will be automatically recomputed after * updating the data.</p> * * @example * // 1: Update only one node or edge: * var n = vis.nodes()[0]; * n.data.label = "New Label..."; * n.data.weight *= 2; * vis.updateData([n]); * * // 2: Update more than one object at once: * var nodes = vis.nodes(); * var n1 = nodes[0]; * var n2 = nodes[1]; * n1.data.label = "New Label for N1"; * n2.data.label = "New Label for N2"; * * var e = vis.edges[0]; * e.data.weight = 0.8; * * vis.updateData([n1, n2, e]); * * // 3: Update more than one object from the same group at once, * // setting the same values to all of them: * var edge_ids = ["1","3","7"]; * var data = { weight: 0.5, interaction: "pp" }; * vis.updateData("edges", edge_ids, data); * * // 4: Update more than one node and edge at once, * // setting the same values to all of them: * var ids = ["n1","n2","e7","e10"]; * var data = { weight: 0 }; * vis.updateData(ids, data); * * // 5: Update all nodes and edges with the same attribute values: * var data = { weight: 0 }; * vis.updateData(data); * * @param {org.cytoscapeweb.Group} [gr] The group of network elements. * @param {Array} [items] The items to be updated. The array can contain node/edge objects or only * their <code>id</code> values. Notice however that, if you specify only the id * and do not pass the group argument, if an edge and a node have the same id value, * both will be updated. * @param {Object} [data] The data object that contains the attributes with the new values to be applied * to all the elements of the specified group or to the passed <code>items</code> only. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#addDataField * @see org.cytoscapeweb.Visualization#removeDataField * @see org.cytoscapeweb.Visualization#dataSchema */ updateData: function (/*gr, items, data*/) { var gr, items, data; if (arguments.length === 1) { if (typeof arguments[0] === "string") { gr = arguments[0]; } else if (this._typeof(arguments[0]) === "array") { items = arguments[0]; } else { data = arguments[0]; } } else if (arguments.length === 2) { if (typeof arguments[0] === "string") { gr = arguments[0]; if (this._typeof(arguments[1]) === "array") { items = arguments[1]; } else { data = arguments[1]; } } else { items = arguments[0]; data = arguments[1]; } } else if (arguments.length > 2) { gr = arguments[0]; items = arguments[1]; data = arguments[2]; } gr = this._normalizeGroup(gr); this.swf().updateData(gr, items, data); return this; }, /** * <p>Select the indicated nodes and edges.</p> * <p>The same method can also be used to select all nodes/edges. * To do that, just omit the <code>items</code> argument and specify the group of elements to be selected.</p> * <p>If you send repeated or invalid elements, they will be ignored.</p> * @example * // a) Select nodes by id: * var ids = [1,3,5,10]; * vis.select("nodes", ids); * * // b) Select one node: * // Notice that the group parameter ("nodes") is optional here, * // because it's sending a node object and not only its id. * var n = vis.nodes()[0]; * vis.select([n]); * * // c) Select nodes and edges at the same time: * var n = vis.nodes()[0]; * var e = vis.edges()[0]; * vis.select([n,e]); * * // d) Select all nodes: * vis.select("nodes"); * * // e) Select all edges: * vis.select("edges"); * * // f) Select all nodes and all edges: * vis.select(); * * @param {org.cytoscapeweb.Group} [gr] The group of network elements. * @param {Array} [items] The items to be selected. The array can contain node/edge objects or only * their <code>id</code> values. Notice however that, if you specify only the id * and do not pass the group argument, if an edge and a node have the same id value, * both will be selected. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#deselect * @see org.cytoscapeweb.Visualization#selected */ select: function (/*gr, items*/) { var gr, items; if (arguments.length === 1) { if (typeof arguments[0] === "string") { gr = arguments[0]; } else { items = arguments[0]; } } else if (arguments.length > 1) { gr = arguments[0]; items = arguments[1]; } gr = this._normalizeGroup(gr); this.swf().select(gr, items); return this; }, /** * <p>Get all selected nodes or edges from the network.</p> * @param {org.cytoscapeweb.Group} [gr] The group of network elements. * @return {Array} List of node or edge objects. If the group is not passed or is <code>null</code>, * the returned array may contain both nodes and edges. * @see org.cytoscapeweb.Visualization#select * @see org.cytoscapeweb.Visualization#deselect */ selected: function (gr) { return this._nodesAndEdges(gr, "getSelectedNodes", "getSelectedEdges"); }, /** * <p>Deselect the indicated nodes and edges, if they are selected.</p> * <p>The same method can also be used to deselect all nodes/edges. * To do that, just omit the <code>items</code> argument and specify the group of elements to be deselected.</p> * <p>If you send repeated or invalid elements, they will be ignored.</p> * @example * // a) Deselect edges by id: * var ids = [4,6,21]; * vis.deselect("edges", ids); * * // b) Deselect one edge only: * // Notice that the group parameter ("edges") is optional here, * // because it's sending an edge object and not only its id. * var e = vis.selected("edges")[0]; // assuming there is at least one selected edge! * vis.deselect([e]); * * // c) Deselect nodes and edges at the same time: * var n = vis.selected("nodes")[0]; * var e = vis.selected("edges")[0]; * vis.deselect([n,e]); * * // d) Deselect all nodes: * vis.deselect("nodes"); * * // e) Deselect all edges: * vis.deselect("edges"); * * // f) Deselect all nodes and all edges: * vis.deselect(); * * @param {org.cytoscapeweb.Group} [gr] The group of network elements. * If not specified, it will try to deselect elements from both <code>node</code> * and <code>edge</code> groups. * @param {Array} [items] The items to be deselected. The array can contain node/edge objects or only * their <code>id</code> values. Notice however that, if you specify only the id * and do not pass the group argument, and if an edge and a node have the same id value, * both will be deselected.<br> * If this argument is <code>null</code>, <code>undefined</code> * or omitted, it will deselect all selected items that belong to the indicated group.<br> * If you send an empty array, no action will be performed. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#select * @see org.cytoscapeweb.Visualization#selected */ deselect: function (/*gr, items*/) { var gr, items; if (arguments.length === 1) { if (typeof arguments[0] === "string") { gr = arguments[0]; } else { items = arguments[0]; } } else if (arguments.length > 1) { gr = arguments[0]; items = arguments[1]; } gr = this._normalizeGroup(gr); this.swf().deselect(gr, items); return this; }, /** * <p>Filter nodes or edges. The filtered out elements will be hidden.</p> * @example * // Hide all edges that have a weight that is lower than 0.4: * vis.filter("edges", function(edge) { * return edge.data.weight >= 0.4; * }); * * @param {org.cytoscapeweb.Group} [gr] The group of network elements to filter. * If <code>null</code>, filter both nodes and edges. * @param {Function} fn The filter function. It will receive a node or edge as argument and must * return a boolean value indicating the visibility of that element. * So, if it returns false, that node or edge will be hidden. * @param {Boolean} [updateVisualMappers] It tells Cytoscape Web to update and reapply the visual mappers * to the network view after the filtering action is done. * Remember that continuous mappers ignore filtered out elements * when interpolating the results. * The default value is <code>false</code>. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#removeFilter * @see org.cytoscapeweb.ContinuousMapper */ filter: function (/*gr, */fn/*, updateVisualMappers*/) { var gr, updateVisualMappers = false; if (arguments.length > 2) { gr = arguments[0]; fn = arguments[1]; updateVisualMappers = arguments[2]; } else if (arguments.length === 2) { if (typeof arguments[0] === 'string') { gr = arguments[0]; fn = arguments[1]; } else { fn = arguments[0]; updateVisualMappers = arguments[1]; } } gr = this._normalizeGroup(gr); var list = this._nodesAndEdges(gr, "getNodes", "getEdges"); if (list.length > 0 && fn) { var filtered = []; for (var i = 0; i < list.length; i++) { var obj = list[i]; if (fn(obj)) { filtered.push(obj); } } this.swf().filter(gr, filtered, updateVisualMappers); } return this; }, /** * <p>Remove a nodes or edges filter.</p> * @param {org.cytoscapeweb.Group} [gr] The group of network elements to remove the filter from. * If <code>null</code>, remove any existing filters from both nodes and edges. * @param {Boolean} [updateVisualMappers] It tells Cytoscape Web to update and reapply the visual mappers * to the network view after the filtering action is done. * Remember that continuous mappers ignore filtered out elements * when interpolating the results. * The default value is <code>false</code>. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#filter * @see org.cytoscapeweb.ContinuousMapper */ removeFilter: function (gr, updateVisualMappers) { gr = this._normalizeGroup(gr); this.swf().removeFilter(gr, updateVisualMappers); return this; }, /** * <p>Return the first neighbors of one or more nodes.</p> * @param {Array} nodes Array of node objects or node IDs. * @param {Boolean} [ignoreFilteredOut] If <code>true</code>, the algorithm will ignore any filtered out node and edge. * The default value is <code>false</code>. * @return An object that contains the following properties: * <ul class="options"><li><code>rootNodes</code> {Array}: the node objects that were passed as the function parameter.</li> * <li><code>neighbors</code> {Array}: the node objects that are neighbors of the root ones.</li> * <li><code>edges</code> {Array}: the edge objects that connects the root and the neighbor nodes.</li> * <li><code>mergedEdges</code> {Array}: the merged edge objects that connect the returned nodes.</li></ul>. */ firstNeighbors: function (nodes, ignoreFilteredOut) { var str = this.swf().firstNeighbors(nodes, ignoreFilteredOut); return JSON.parse(str); }, /** * <p>Return the network model as an object.</p> * @return {org.cytoscapeweb.NetworkModel} The network model as a JavaScript object. * @see org.cytoscapeweb.Visualization#graphml * @see org.cytoscapeweb.Visualization#xgmml * @see org.cytoscapeweb.Visualization#sif */ networkModel: function () { return this.swf().getNetworkModel(); }, /** * <p>Return the network data as <a href="http://graphml.graphdrawing.org/primer/graphml-primer.html" target="_blank">GraphML</a>.</p> * @return {String} The XML text. * @see org.cytoscapeweb.Visualization#xgmml * @see org.cytoscapeweb.Visualization#sif * @see org.cytoscapeweb.Visualization#networkModel */ graphml: function () { return this.swf().getNetworkAsText("graphml"); }, /** * <p>Return the network data as <a href="http://www.cs.rpi.edu/~puninj/XGMML/" target="_blank">XGMML</a>.</p> * @return {String} The XML text. * @see org.cytoscapeweb.Visualization#graphml * @see org.cytoscapeweb.Visualization#sif * @see org.cytoscapeweb.Visualization#networkModel */ xgmml: function () { return this.swf().getNetworkAsText("xgmml"); }, /** * <p>Return the network data as <a href="http://cytoscape.wodaklab.org/wiki/Cytoscape_User_Manual/Network_Formats/" target="_blank">Simple Interaction Format (SIF)</a>.</p> * <p>Cytoscape Web uses tab characters to delimit the fields, because the node and interaction names may contain spaces.</p> * <p>The node name in the SIF text is taken from the node's <code>data.id</code> attribute.</p> * <p>Cytoscape Web tries to get the interaction name from the edge's <code>data.interaction</code> attribute. * You can choose any other edge attribute to be the interaction name by passing an <code>interactionAttr</code> parameter. * If the edge data does not have the defined interaction field, Cytoscape Web just uses the edge <code>id</code>.</p> * @example * var xml = '&lt;graphml&gt;' + * // Create a custom "type" attribute: * '&lt;key id="type" for="edge" attr.name="type" attr.type="string"/&gt;' + * '&lt;graph&gt;' + * '&lt;node id="1"/&gt;' + * '&lt;node id="2"/&gt;' + * '&lt;edge source="1" target="2"&gt;' + * '&lt;data key="type"&gt;co-expression&lt;/data&gt;' + * '&lt;/edge&gt;' + * '&lt;edge source="2" target="1"&gt;' + * '&lt;data key="type"&gt;co-localization&lt;/data&gt;' + * '&lt;/edge&gt;' + * '&lt;/graph&gt;' + * '&lt;/graphml&gt;'; * * var vis = new org.cytoscapeweb.Visualization("container_id"); * * vis.ready(function() { * // Export to SIF, using the "type" attribute as edge interaction: * var text = vis.sif('type'); * * // text == '1\tco-expression\t2\n' + * // '2\tco-localization\t1\n' * }); * * vis.draw({ network: xml }); * * @param {String} [interactionAttr] Optional edge attribute name to be used as the SIF interaction name. * @return {String} The SIF text. * @see org.cytoscapeweb.Visualization#graphml * @see org.cytoscapeweb.Visualization#xgmml * @see org.cytoscapeweb.Visualization#networkModel */ sif: function (interactionAttr) { return this.swf().getNetworkAsText("sif", { interactionAttr: interactionAttr }); }, /** * <p>Return a PDF with the network vector image.</p> * @param {Object} [options] Additional options: * <ul class="options"> * <li><code>width</code>:</strong> The desired width of the image in pixels.</li> * <li><code>height</code>:</strong> The desired height of the image in pixels.</li> * </ul> * @return {String} The PDF binary data encoded to a Base64 string. */ pdf: function (options) { return this.swf().getNetworkAsImage("pdf", options); }, /** * <p>Return an SVG image.</p> * @param {Object} [options] Additional options: * <ul class="options"> * <li><code>width</code>:</strong> The desired width of the image in pixels.</li> * <li><code>height</code>:</strong> The desired height of the image in pixels.</li> * </ul> * @return {String} The SVG image. */ svg: function (options) { return this.swf().getNetworkAsImage("svg", options); }, /** * <p>Return the network as a PNG image.</p> * @return {String} The PNG binary data encoded to a Base64 string. */ png: function () { return this.swf().getNetworkAsImage("png"); }, /** * <p>Export the network to a URL. * It's useful when you want to download the network as an image or xml, for example.</p> * <p>This method requires a server-side part (e.g. Java, PHP, etc.) to receive the raw data from Cytoscape Web. * That server-side code should send the data back to the browser.</p> * @example * // The JavaScript code * vis.exportNetwork('xgmml', 'export.php?type=xml'); * * @example * &lt;?php * # ##### The server-side code in PHP #### * * # Type sent as part of the URL: * &#36;type = &#36;_GET['type']; * # Get the raw POST data: * &#36;data = file_get_contents('php://input'); * * # Set the content type accordingly: * if (&#36;type == 'png') { * header('Content-type: image/png'); * } elseif (&#36;type == 'pdf') { * header('Content-type: application/pdf'); * } elseif (&#36;type == 'svg') { * header('Content-type: image/svg+xml'); * } elseif (&#36;type == 'xml') { * header('Content-type: text/xml'); * } * * # To force the browser to download the file: * header('Content-disposition: attachment; filename="network.' . &#36;type . '"'); * # Send the data to the browser: * print &#36;data; * ?&gt; * * @param {String} format One of: <code>"png"</code>, <code>"svg"</code>, <code>"pdf"</code>, <code>"xgmml"</code>, <code>"graphml"</code>, <code>"sif"</code>. * @param {String} url The url that will receive the exported image (bytes) or xml (text). * @param {Object} [options] Additional options: * <ul class="options"><li><code>width</code>:</strong> The desired width of the image in pixels (only for 'pdf' format).</li> * <li><code>height</code>:</strong> The desired height of the image in pixels (only for 'pdf' format).</li> * <li><code>window</code>:</strong> The browser window or HTML frame in which to display the exported image or xml. * You can enter the name of a specific window or use one of the following values: * <ul><li><code>_self</code>: the current frame in the current window.</li> * <li><code>_blank</code>: a new window.</li> * <li><code>_parent</code>: the parent of the current frame.</li> * <li><code>_top</code>: the top-level frame in the current window.</li></ul> * The default is <code>_self</code>. * * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#png * @see org.cytoscapeweb.Visualization#pdf * @see org.cytoscapeweb.Visualization#sif * @see org.cytoscapeweb.Visualization#graphml * @see org.cytoscapeweb.Visualization#svg * @see org.cytoscapeweb.Visualization#xgmml */ exportNetwork: function (format, url, options) { format = format.toLowerCase().trim(); this.swf().exportNetwork(format, url, options); return this; }, /** * <p>Appends an event listener to the network.</p> * <p>Listeners can be added or removed at any time, even before the graph is rendered, which means that you do not * need to wait for the {@link org.cytoscapeweb.Visualization#ready} function to be called.</p> * * @example * // 1. Create the visualization instance: * var vis = new org.cytoscapeweb.Visualization("container-id"); * * // 2. Add listeners at any time: * vis.addListener("zoom", function(evt) { * var zoom = evt.value; * alert("New zoom value is " + (zoom * 100) + "%"); * }) * .addListener("click", "edges", function(evt) { * var edge = evt.target; * alert("Edge " + edge.data.id + " was clicked"); * }) * .addListener("select", "nodes", function(evt) { * var nodes = evt.target; * alert(nodes.length + " node(s) selected"); * }); * * // 3. Draw the network: * vis.draw({ network: '&lt;graphml&gt;...&lt;/graphml&gt;' }); * * @param {org.cytoscapeweb.EventType} evt The event type. * @param {org.cytoscapeweb.Group} [gr] The group of network elements to assign the listener to (optional for some events). * @param {Function} fn The callback function the event invokes. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Event * @see org.cytoscapeweb.Visualization#hasListener * @see org.cytoscapeweb.Visualization#removeListener */ addListener: function (evt, /*gr, */fn) { var gr; if (arguments.length > 2) { gr = arguments[1]; fn = arguments[2]; } evt = this._normalizeEvent(evt); gr = this._normalizeGroup(gr); if (!this._listeners) { this._listeners = {/* group: { event: listeners[] } */}; } if (!this._listeners[gr]) { this._listeners[gr] = {}; } var fnList = this._listeners[gr][evt]; if (!fnList) { fnList = []; this._listeners[gr][evt] = fnList; } var duplicated = false; for (var i = 0; i < fnList.length; i++) { if (fn === fnList[i]) { duplicated = true; break; } } if (!duplicated) { fnList.push(fn); } return this; }, /** * <p>Removes an event listener.</p> * @param {org.cytoscapeweb.EventType} evt The event type. * @param {org.cytoscapeweb.Group} [gr] The group of network elements to assign the listener to (optional for some events). * @param {Function} [fn] The function the event invokes. If undefined, all registered functions * for the specified event are removed. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Event * @see org.cytoscapeweb.Visualization#addListener * @see org.cytoscapeweb.Visualization#hasListener */ removeListener: function (evt/*, gr, fn*/) { var gr; var fn; if (arguments.length > 2) { gr = arguments[1]; fn = arguments[2]; } else if (arguments.length === 2) { if (typeof arguments[1] === 'function') { fn = arguments[1]; } else { gr = arguments[1]; } } evt = this._normalizeEvent(evt); gr = this._normalizeGroup(gr); var evtList; if (this._listeners) { evtList = this._listeners[gr] }; if (evtList) { if (!fn) { // Remove all of the event's functions: delete evtList[evt]; } else { // Remove only the specified function: var fnList = evtList[evt]; if (fnList) { for (var i = 0; i < fnList.length; i++) { if (fn === fnList[i]) { fnList.splice(i, 1); break; } } } } } return this; }, /** * <p>Tells whether or not there are listeners to an event type.</p> * @param {org.cytoscapeweb.EventType} evt The event type. * @param {org.cytoscapeweb.Group} [gr] The group of network elements the listener was assigned to (optional for some events). * @return {Boolean} True if there is at least one listener to the event, false otherwise. * @see org.cytoscapeweb.Event * @see org.cytoscapeweb.Visualization#addListener * @see org.cytoscapeweb.Visualization#removeListener */ hasListener: function (evt/*, gr*/) { var has = false; var gr; if (arguments.length > 1) { gr = arguments[1]; } evt = this._normalizeEvent(evt); gr = this._normalizeGroup(gr); if (this._listeners) { var evtList = this._listeners[gr]; if (evtList) { var fnList = evtList[evt]; has = fnList && fnList.length > 0; } } return has; }, /** * <p>Adds a custom menu item to the right-click context menu.</p> * <p>This method can only be used after a network has been drawn, so it is better to use it after the * <code>ready</code> callback function is called (see {@link org.cytoscapeweb.Visualization#ready}).</p> * <p>If an item with the same label has already been set to the same group, it will not add another * callback function to that menu item. In that case, the previous function will be replaced by * the new one and only one menu item will be displayed.</p> * <p>It is possible to add more than one menu item with the same label, but only if they are added to * different groups.</p> * * @example * // We will use the context menu to select the first neighbors of the * // right-clicked node. * * // 1. Assuming that you have created a visualization object: * var vis = new org.cytoscapeweb.Visualization("container-id"); * * // 2. Add a context menu item any time after the network is ready: * vis.ready(function () { * vis.addContextMenuItem("Select first neighbors", "nodes", * function (evt) { * // Get the right-clicked node: * var rootNode = evt.target; * * // Get the first neighbors of that node: * var fNeighbors = vis.firstNeighbors([rootNode]); * var neighborNodes = fNeighbors.neighbors; * * // Select the root node and its neighbors: * vis.select([rootNode]).select(neighborNodes); * } * ); * }); * @param {String} lbl The context menu item label to be displayed. * @param {org.cytoscapeweb.Group} [gr] The group of network elements the menu item will be assigned to. * If <code>"nodes"</code>, the menu item will be visible only on right-clicks * when the cursor is over a node. If <code>"edges"</code>, only when its over an edge. * If <code>"none"</code> or no group is provided, the menu item will be available after a right-click * over any network element, including the canvas background. * @param {Function} fn The callback function that is invoked after the user selects the injected menu item. * That function always receives an event object as argument. The event type is always <code>"contextmenu"</code>. * If the context menu was added to the <code>nodes</code> or <code>edges</code> group, you might want to * get the right-clicked node or edge object by using the event's <code>target</code> property. * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#removeContextMenuItem * @see org.cytoscapeweb.Visualization#removeAllContextMenuItems */ addContextMenuItem: function (lbl, /*gr, */fn) { if (lbl && fn) { var gr; if (arguments.length > 2) { gr = arguments[1]; fn = arguments[2]; } gr = this._normalizeGroup(gr); if (!this._contextMenuItems) { this._contextMenuItems = {/* group: {label: fn} */}; } var grItems = this._contextMenuItems[gr]; if (!grItems) { grItems = {}; this._contextMenuItems[gr] = grItems; } grItems[lbl] = fn; this.swf().addContextMenuItem(lbl, gr); } return this; }, /** * <p>Removes a menu item from the right-click context menu.</p> * @param {String} lbl The menu item label. * @param {org.cytoscapeweb.Group} [gr] <p>The related group. If <code>null</code>, and there is a menu item with the same label * associated with a <code>"nodes"</code> or <code>"edges"</code> group, that item will not be removed. * In that case, you need to call this function again with the other groups.</p> * </p>For example, <code>removeContextMenuItem("Select")</code> does not remove the menu item * added with <code>addContextMenuItem("Select", "edge")</code>, but only the the one added with * <code>addContextMenuItem("Select")</code>.<p> * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#addContextMenuItem * @see org.cytoscapeweb.Visualization#removeAllContextMenuItems */ removeContextMenuItem: function (lbl/*, gr*/) { if (lbl) { var gr; if (arguments.length > 1) { gr = arguments[1]; } gr = this._normalizeGroup(gr); if (this._contextMenuItems) { var grItems = this._contextMenuItems[gr]; if (grItems) { if (grItems[lbl]) { this.swf().removeContextMenuItem(lbl, gr); delete grItems[lbl]; } } } } return this; }, /** * <p>Removes all preset menu items from the right-click context menu.</p> * @return {org.cytoscapeweb.Visualization} The Visualization instance. * @see org.cytoscapeweb.Visualization#addContextMenuItem * @see org.cytoscapeweb.Visualization#removeContextMenuItem */ removeAllContextMenuItems: function () { if (this._contextMenuItems) { for (var gr in this._contextMenuItems) { if (this._contextMenuItems.hasOwnProperty(gr)) { var grItems = this._contextMenuItems[gr]; if (grItems) { for (var lbl in grItems) { if (grItems.hasOwnProperty(lbl)) { this.removeContextMenuItem(lbl, gr); } } } } } } return this; }, /** * <p>Get Cytoscape Web's Flash object.</p> * @return {Object} The appropriate reference to the Flash object. */ swf: function () { if (navigator.appName.indexOf("Microsoft") !== -1) { return window[this.id]; } else { return document[this.id]; } }, /** * <p>Redefine this function if you want to use another method to detect the Flash Player version * and embed the SWF file (e.g. SWFObject).</p> * <p>By default, Adobe's <a href="http://www.adobe.com/products/flashplayer/download/detection_kit/" target="_blank">Flash Player Detection Kit</a> * is used.</p> * @requires <code>AC_OETags.js</code> and <code>playerProductInstall.swf</code> */ embedSWF: function () { //Major version of Flash required var requiredMajorVersion = 9; //Minor version of Flash required var requiredMinorVersion = 0; //Minor version of Flash required var requiredRevision = 24; var containerId = this.containerId; // Let's redefine the default AC_OETags function, because we don't necessarily want // to replace the whole HTML page with the swf object: AC_Generateobj = function (objAttrs, params, embedAttrs) { var str = ''; var i; if (isIE && isWin && !isOpera) { str += '<object '; for (i in objAttrs) { if (Object.hasOwnProperty.call(objAttrs, i)) { str += i + '="' + objAttrs[i] + '" '; } } str += '>'; for (i in params) { if (Object.hasOwnProperty.call(params, i)) { str += '<param name="' + i + '" value="' + params[i] + '" /> '; } } str += '</object>'; } else { str += '<embed '; for (i in embedAttrs) { if (Object.hasOwnProperty.call(embedAttrs, i)) { str += i + '="' + embedAttrs[i] + '" '; } } str += '> </embed>'; } // Replace only the indicated DOM element: document.getElementById(containerId).innerHTML = str; }; // Version check for the Flash Player that has the ability to start Player Product Install (6.0r65) var hasProductInstall = DetectFlashVer(6, 0, 65); // Version check based upon the values defined in globals var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision); if (hasProductInstall && !hasRequestedVersion) { // DO NOT MODIFY THE FOLLOWING FOUR LINES // Location visited after installation is complete if installation is required var MMPlayerType = (isIE === true) ? "ActiveX" : "PlugIn"; var MMredirectURL = window.location; document.title = document.title.slice(0, 47) + " - Flash Player Installation"; var MMdoctitle = document.title; AC_FL_RunContent( "src", this.flashInstallerPath, "FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"", "width", "100%", "height", "100%", "align", "middle", "id", this.id, "quality", "high", "bgcolor", "#ffffff", "name", this.id, "allowScriptAccess","sameDomain", "type", "application/x-shockwave-flash", "pluginspage", "http://www.adobe.com/go/getflashplayer" ); } else if (hasRequestedVersion) { var optionKeys = ["resourceBundleUrl"]; var flashVars = ""; if (this.options) { for (var i in optionKeys) { if (Object.hasOwnProperty.call(optionKeys, i)) { var key = optionKeys[i]; if (this.options[key] !== undefined) { flashVars += key + "=" + this.options[key] + "&"; } } } flashVars += "id=" + this.id; } // if we've detected an acceptable version // embed the Flash Content SWF when all tests are passed AC_FL_RunContent( "src", this.swfPath, "width", "100%", "height", "100%", "align", "middle", "id", this.id, "quality", "high", "bgcolor", "#ffffff", "name", this.id, "allowScriptAccess", "always", "type", "application/x-shockwave-flash", "pluginspage", "http://www.adobe.com/go/getflashplayer", "wmode", "opaque", // DO NOT set it to "transparent", because it may crash FireFox and IE on Windows! "flashVars", flashVars ); } else { // flash is too old or we can't detect the plugin // Insert non-flash content: document.getElementById(containerId).innerHTML = this.flashAlternateContent; } return this; }, // PRIVATE METHODS: // ----------------------------------------------------------------------------------------- // -------------------------------------------- // Used by the ActionScript External Interface: // -------------------------------------------- /** * Workaround for a problem with Internet Explorer. * @ignore */ _onBeforeComplete: function() { var backup1 = window.__flash__addCallback; window.__flash__addCallback = function (instance, name) { try {backup1(instance, name);} catch (x){} }; var backup2 = window.__flash__removeCallback; window.__flash__removeCallback = function (instance, name) { try {backup2(instance, name);} catch (x){} }; }, /** * Callback for when the Flash object is completely loaded. * @ignore */ _onComplete: function() { this.swf().draw(this.drawOptions); }, _onReady: function () { // Do nothing. }, /** * Proxy function called by the Flash side when the object must be sent as JSON format, usually * to avoid compatibility problems when converting complex Flash objects to JavaScript. * The JSON argument is converted to an Object and the destination function is called. * Do NOT redefine this function!!! * @ignore */ _dispatch: function (functionName, jsonArg) { var arg = null; if (jsonArg != null) { arg = JSON.parse(jsonArg); } var ret = this[functionName](arg); return ret; }, /** * Just a proxy to hasListener. * @ignore */ _hasListener: function (evt) { return this.hasListener(evt.type, evt.group); }, /** * Invokes each listener that was registered to a given event type. * @ignore */ _invokeListeners: function (evt) { if (this._listeners) { var gr = this._normalizeGroup(evt.group); var evtList = this._listeners[gr]; if (evtList) { var type = this._normalizeEvent(evt.type); var fnList = evtList[type]; for (var i = 0; i < fnList.length; i++) { fnList[i](evt); } } } }, /** * Invokes a registered context menu callback function. * @ignore */ _invokeContextMenuCallback: function (evt) { if (this._contextMenuItems) { var gr = this._normalizeGroup(evt.group); var grItems = this._contextMenuItems[gr]; if (grItems) { evt = new org.cytoscapeweb.Event(evt); var fn = grItems[evt.value]; if (fn) { fn(evt); } } } }, // -------------------------------------------- // Utility functions: // -------------------------------------------- _normalizeEvent: function (evt) { if (evt) { evt = evt.toLowerCase().trim(); } return evt; }, _normalizeGroup: function (gr) { if (gr) { gr = gr.toLowerCase().trim(); } if (gr !== "nodes" && gr !== "edges") { gr = "none"; } return gr; }, _nodesAndEdges: function (gr, fnNodes, fnEdges) { var list = []; gr = this._normalizeGroup(gr); if (gr === "nodes" || gr === "none") { var nodes = JSON.parse(this.swf()[fnNodes]()); list = list.concat(nodes); } if (gr === "edges" || gr === "none") { var edges = JSON.parse(this.swf()[fnEdges]()); list = list.concat(edges); } return list; }, _typeof: function(v) { if (typeof(v) == "object") { if (v === null) return "null"; if (v.constructor == (new Array).constructor) return "array"; if (v.constructor == (new Date).constructor) return "date"; if (v.constructor == (new RegExp).constructor) return "regex"; return "object"; } return typeof(v); } }; if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,""); }; } // ===[ Events ]================================================================================ /** * <p>This object represents an Event.</p> * <p>Events are objects passed as arguments to listeners when an event occurs.</p> * <p>All event objects have at least the following fields:</p> * <ul><li><code>type</code></li><li><code>group</code></li></ul> * <p>The following tables lists the possible properties for each event type.</p> * <p><label><strong>click:</strong></label> Fired when the user clicks an element that belongs to the <code>group</code> you registered. * If you don't specify any group or if the group is <code>none</code>, the event will be fired when the background of the network visualization is clicked.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>{@link org.cytoscapeweb.Node}</td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>{@link org.cytoscapeweb.Edge}</td><td><code>undefined</code></td></tr> * <tr><td><code>none</code>: clicking the visualization background</td><td><code>undefined</code></td><td><code>undefined</code></td></tr> * </Table> * <p><label><strong>dblclick:</strong></label> Fired when the user double clicks an element that belongs to the <code>group</code> you registered. * If you don't specify any group or if the group is <code>none</code>, the event will be fired when the background of the network visualization is double-clicked.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>{@link org.cytoscapeweb.Node}</td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>{@link org.cytoscapeweb.Edge}</td><td><code>undefined</code></td></tr> * <tr><td><code>none</code>: double-clicking the visualization background</td><td><code>undefined</code></td><td><code>undefined</code></td></tr> * </Table> * <p><label><strong>mouseover:</strong></label> Fired when the user moves the mouse over an element that belongs to the <code>group</code> you registered. * If you don't specify any group or if the group is <code>none</code>, the event will be fired any time the cursor enters the visualization rectangle.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>{@link org.cytoscapeweb.Node}</td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>{@link org.cytoscapeweb.Edge}</td><td><code>undefined</code></td></tr> * <tr><td><code>none</code>: mouse enters the visualization area</td><td><code>undefined</code></td><td><code>undefined</code></td></tr> * </Table> * <p><label><strong>mouseout:</strong></label> Fired when the user moves the mouse out of an element that belongs to the <code>group</code> you registered. * If you don't specify any group or if the group is <code>none</code>, the event will be fired when the cursor leaves the visualization area.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>{@link org.cytoscapeweb.Node}</td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>{@link org.cytoscapeweb.Edge}</td><td><code>undefined</code></td></tr> * <tr><td><code>none</code>: mouse leaves the visualization area</td><td><code>undefined</code></td><td><code>undefined</code></td></tr> * </Table> * <p><label><strong>select:</strong></label> Fired when an element that belongs to the <code>group</code> you registered is selected. * Nodes and edges can be selected by three possible ways: * directly clicking it; using the drag-rectangle (the select event is dispatched only after the the mouse button is released); programmatically, with {@link org.cytoscapeweb.Visualization#select}. * If you don't specify any group or if the group is <code>none</code>, the event will be fired after selecting any nodes or edges.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>Array of selected {@link org.cytoscapeweb.Node} objects</td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>Array of selected {@link org.cytoscapeweb.Edge} objects</td><td><code>undefined</code></td></tr> * <tr><td><code>none</code></td><td>Array of selected {@link org.cytoscapeweb.Node} and {@link org.cytoscapeweb.Edge} objects</td><td><code>undefined</code></td></tr> * </Table> * <p><label><strong>deselect:</strong></label> Fired when an element that belongs to the <code>group</code> you registered is deselected. * Nodes and edges can be deselected by the user or programmatically, with {@link org.cytoscapeweb.Visualization#deselect}. * If you don't specify any group or if the group is <code>none</code>, the event will be fired after deselecting any nodes or edges.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>Array of deselected {@link org.cytoscapeweb.Node} objects</td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>Array of deselected {@link org.cytoscapeweb.Edge} objects</td><td><code>undefined</code></td></tr> * <tr><td><code>none</code></td><td>Array of deselected {@link org.cytoscapeweb.Node} and {@link org.cytoscapeweb.Edge} objects</td><td><code>undefined</code></td></tr> * </Table> * <p><label><strong>filter:</strong></label> Fired when the <code>group</code> you registered is filtered. * Nodes and edges can be filtered with {@link org.cytoscapeweb.Visualization#filter}. * If you don't specify any group or if the group is <code>none</code>, the event will be fired after filtering nodes or edges elements. * It is important to be aware that if no element of the specified <code>group</code> is filtered (no filter applied), * the event's <code>target</code> property will be <code>null</code>. * But if all the elements of that <code>group</code> is filtered out, <code>target</code> will be an empty array.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>Array of filtered {@link org.cytoscapeweb.Node} objects or <code>null</code></td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>Array of filtered {@link org.cytoscapeweb.Edge} objects or <code>null</code></td><td><code>undefined</code></td></tr> * <tr><td><code>none</code></td><td>Array of filtered {@link org.cytoscapeweb.Node} and {@link org.cytoscapeweb.Edge} objects or <code>null</code></td><td><code>undefined</code></td></tr> * </Table> * <p><label><strong>layout:</strong></label> Fired after a layout is applied (see {@link org.cytoscapeweb.Visualization#layout}.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>none</code></td><td><code>undefined</code></td><td><code>The applied {@link org.cytoscapeweb.Layout} object</code></td></tr> * </Table> * <p><label><strong>zoom:</strong></label> Fired after the network is rescaled, either by calling {@link org.cytoscapeweb.Visualization#zoom} or * when the user interacts with the visualization's pan-zoom control.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>none</code></td><td><code>undefined</code></td><td>The zoom value (float number from 0 to 1)</td></tr> * </Table> * <p><label><strong>error:</strong></label> Fired when an exception is thrown.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>none</code></td><td><code>undefined</code></td><td>The {@link org.cytoscapeweb.Error} object</td></tr> * </Table> * <p><label><strong>contextmenu:</strong></label> Events of this type are only passed to the callback functions that are registered with {@link org.cytoscapeweb.Visualization#addContextMenuItem}. * You cannot add listeners to this event.</p> * <table> * <tr><th>group</th><th>target</th><th>value</th></tr> * <tr><td><code>nodes</code></td><td>The related {@link org.cytoscapeweb.Node} object</td><td><code>undefined</code></td></tr> * <tr><td><code>edges</code></td><td>The related {@link org.cytoscapeweb.Edge} object</td><td><code>undefined</code></td></tr> * <tr><td><code>none</code></td><td>The {@link org.cytoscapeweb.Node} or {@link org.cytoscapeweb.Edge} object, if a node or edge was right-clicked. Or <code>undefined</code>, if the right click was done on an empty background area.</td><td><code>undefined</code></td></tr> * </Table> * * @class * @see org.cytoscapeweb.EventType * @see org.cytoscapeweb.Visualization#addListener * @see org.cytoscapeweb.Visualization#hasListener * @see org.cytoscapeweb.Visualization#removeListener */ this.org.cytoscapeweb.Event = function (options) { /** * The event type name. * @type org.cytoscapeweb.EventType */ this.type = options.type; /** * The group of network elements the event is related to. * @type org.cytoscapeweb.Group */ this.group = options.group; /** * The event target. For example, if one or more nodes are selected, the target of the * <code>"select"</code> event will be an array of node objects. * But if a node is clicked, the target of the <code>"click"</code> event will be just a node object. * This property is available only for event types that are related to actions performed on nodes or edges. * For the other events it is <code>undefined</code>. * @type Object */ this.target = options.target; /** * This property is a very generic one and is usually used to send back any important value that * is not defined as <code>target</code>. For example, for <code>"zoom"</code> events, value is * the new scale, but for <code>"error"</code> events it is an error object. */ this.value = options.value; /** * The local x coordinate of the mouse position, in pixels. * Available only when the event type is 'click', 'dblclick', 'mouseover', 'mouseout' or 'contextmenu'. */ this.mouseX = options.mouseX; /** * The local y coordinate of the mouse position, in pixels. * Available only when the event type is 'click', 'dblclick', 'mouseover', 'mouseout' or 'contextmenu'. */ this.mouseY = options.mouseY; }; // ===[ NetworkModel ]========================================================================== /** * <p>This object represents a NetworkModel type, but is actually just an untyped object.</p> * <p>It defines the raw data (nodes and edges data values) and the data schema for a network. * It is important to notice that the network model does <b>not</b> contain {@link org.cytoscapeweb.Node} and {@link org.cytoscapeweb.Edge} objects, * as it is not supposed to describe visual attributes such as colors, shapes and x/y coordinates. * Visual styles must be defined separately, through {@link org.cytoscapeweb.VisualStyle} or {@link org.cytoscapeweb.VisualStyleBypass}. * Nodes positioning are done by {@link org.cytoscapeweb.Layout} objects.</p> * <p>A NetworkModel object has only two fields:</p> * <ul class="options"> * <li><code>dataSchema</code> {{@link org.cytoscapeweb.DataSchema}}: It defines the nodes/edges data fields. * You do not need to specify these essential fields: * <code>id</code> (nodes or edges), <code>source</code> (edges), <code>target</code> (edges), <code>directed</code> (edges). * Actually, trying to modify these fields in the schema might throw an {@link org.cytoscapeweb.Error}.</li> * <li><code>data</code> {Object}: The actual nodes/edges data values used to create {@link org.cytoscapeweb.Node} and {@link org.cytoscapeweb.Edge} elements. * It contains two fields (<code>nodes</code> and <code>edges</code>), which are arrays of nodes/edges data objects. * Note: data attributes of type <code>int</code> or <code>boolean</code> (see {@link org.cytoscapeweb.DataField}) * do NOT accept <code>null</code> values.</li> *</ul> * @example * var network = { * * dataSchema: { * nodes: [ { name: "label", type: "string" }, * { name: "score", type: "number" } ], * * edges: [ { name: "label", type: "string" }, * { name: "weight", type: "number" }, * { name: "directed", type: "boolean", defValue: true} ] * }, * * data: { * nodes: [ { id: "n1", label: "Node 1", score: 1.0 }, * { id: "n2", label: "Node 2", score: 2.2 }, * { id: "n3", label: "Node 3", score: 3.5 } ], * * edges: [ { id: "e1", label: "Edge 1", weight: 1.1, source: "n1", target: "n3" }, * { id: "e2", label: "Edge 2", weight: 3.3, source:"n2", target:"n1"} ] * } * }; * @class * @name NetworkModel * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.Visualization#draw * @see org.cytoscapeweb.Visualization#networkModel * @see org.cytoscapeweb.Visualization#dataSchema * @see org.cytoscapeweb.DataSchema */ // ===[ Node ]================================================================================== /** * <p>This object represents a Node type, but is actually just an untyped object.</p> * <p>So never do:</p> * <p><code>var node = new org.cytoscapeweb.Node(); // Wrong!!!</code></p> * <p>In order to create a node, just create an object with the expected fields. * Notice that the attribute <code>group</code> must always be <code>"nodes"</code>, * because that is what really defines this type.</p> * @example * var node = { * group: "nodes", * shape: "TRIANGLE", * size: 20, * color: "0000ff", * // etc... * data: { * id: 1 * } * }; * @class * @name Node * @type Object * @memberOf org.cytoscapeweb */ /** * The group name that defines this Data type (always <code>"nodes"</code>). * @property * @name group * @type org.cytoscapeweb.Group * @memberOf org.cytoscapeweb.Node# */ /** * The object that stores the custom node attributes. * It should have at least the <code>id</code> property. * @property * @name data * @type Object * @memberOf org.cytoscapeweb.Node# */ /** * The shape name. * @property * @name shape * @type org.cytoscapeweb.NodeShape * @memberOf org.cytoscapeweb.Node# */ /** * The node fill color, in hexadecimal code (e.g. <code>"#ff3333"</code>). * @property * @name color * @type String * @memberOf org.cytoscapeweb.Node# */ /** * The node opacity, from <code>0</code> to <code>1.0</code> (100% opaque). * @property * @name opacity * @type Number * @memberOf org.cytoscapeweb.Node# */ /** * The border color, in hexadecimal code (e.g. <code>"#000000"</code>). * @property * @name borderColor * @type String * @memberOf org.cytoscapeweb.Node# */ /** * The border width, in pixels. * @property * @name borderWidth * @type Number * @memberOf org.cytoscapeweb.Node# */ /** * The absolute node height and width (in pixels), when the zoom level is 100%. * In Cytoscape Web, a node has the same value for both width and height. * Notice that this value is not scaled, so if you want its real visualized size, you need to multiply * this value by the current network scale, which is provided by {@link org.cytoscapeweb.Visualization#zoom}. * @property * @name size * @type Number * @memberOf org.cytoscapeweb.Node# */ /** * A boolean value that indicates whether or not the node is set to visible. * @property * @name visible * @type Boolean * @memberOf org.cytoscapeweb.Node# */ /** * The x coordinate value that indicates where the center of the node is positioned in * the horizontal axis of the Visualization rectangle. * If <code>x == 0</code>, the middle point of the node is located exactly at the left border of the network view. * @property * @name x * @type Number * @memberOf org.cytoscapeweb.Node# */ /** * The y coordinate value that indicates where the center of the node is positioned in * the vertical axis of the Visualization rectangle. * If <code>y == 0</code>, the middle point of the node is located exactly at the top border of the network view. * @property * @name y * @type Number * @memberOf org.cytoscapeweb.Node# */ // ===[ Edge ]================================================================================= /** * <p>This object represents an Edge type, but is just an untyped object.</p> * <p>So never do:</p> * <p><code>var edge = new org.cytoscapeweb.Edge(); // Wrong!!!</code></p> * <p>In order to create an edge, just create an object with the expected fields. * Notice that the attribute <code>group</code> must always be <code>"edges"</code>, * because that is what really defines this type.</p> * @example * var edge = { * group: "edges", * merged: false, * opacity: 0.8, * color: "333333", * width: 2, * // etc... * data: { * id: 1, * source: 1, * target: 3, * weight: 0.5 * } * }; * @class * @name Edge * @memberOf org.cytoscapeweb * @type Object */ /** * The group name that defines this Data type (always <code>"edges"</code>). * @property * @name group * @type org.cytoscapeweb.Group * @memberOf org.cytoscapeweb.Edge# */ /** * The object that stores the custom edge attributes. * It should have at least the following properties: * <ul class="options"> * <li><code>id</code> {String}: the edge id.</li> * <li><code>source</code> {String}: the source node id.</li> * <li><code>target</code> {String}: the target node id.</li> * <li><code>directed</code> {Boolean}: a directed edge has a default arrow pointed to the target node.</li></ul> * When the network was created from a SIF data format, the edge's data object will also have the <code>interaction</code> * attribute (String type). * @property * @name data * @type Object * @memberOf org.cytoscapeweb.Edge# */ /** * Indicate whether or not the edge is a merged one. Merged edges are used to simplify the * network visualization by just showing that two nodes are connected to each other, without * displaying all the real edges that link them together. * @property * @name merged * @type Boolean * @memberOf org.cytoscapeweb.Edge# * @see org.cytoscapeweb.Visualization#edgesMerged */ /** * If the edge is a merged one, this property provides the regular parallel edges that were merged together. * If the edge is already a regular non-merged type, this property is undefined. * @property * @name edges * @type Array * @memberOf org.cytoscapeweb.Edge# * @see org.cytoscapeweb.Edge#merged */ /** * The edge opacity, from <code>0</code> to <code>1.0</code> (100% opaque). * @property * @name opacity * @type Number * @memberOf org.cytoscapeweb.Edge# */ /** * The edge color, in hexadecimal code (e.g. <code>"#666666"</code>). * @property * @name color * @type String * @memberOf org.cytoscapeweb.Edge# */ /** * The edge line width, in pixels. * @property * @name width * @type Number * @memberOf org.cytoscapeweb.Edge# */ /** * The shape name of the edge's source arrow. * @default <code>"NONE"</code>, unless the current visual style sets a different value. * @property * @name sourceArrowShape * @type org.cytoscapeweb.ArrowShape * @memberOf org.cytoscapeweb.Edge# */ /** * The shape name of the edge's target arrow. * @default <ul><li><code>"NONE"</code>, if the edge is undirected</li> * <li><code>"DELTA"</code>, if the edge is directed</li> * @property * @name targetArrowShape * @type org.cytoscapeweb.ArrowShape * @memberOf org.cytoscapeweb.Edge# */ /** * The color code of the source arrow. * @property * @name sourceArrowColor * @type String * @memberOf org.cytoscapeweb.Edge# */ /** * The color code of the target arrow. * @property * @name targetArrowColor * @type String * @memberOf org.cytoscapeweb.Edge# */ /** * The value that defines the curvature rate of curved edges. Higher values create more curved edges. * @default 18 * @property * @name curvature * @type Number * @memberOf org.cytoscapeweb.Edge# */ /** * A boolean value that indicates whether or not the edge is set to visible. * @property * @name visible * @type Boolean * @memberOf org.cytoscapeweb.Edge# */ // ===[ Layout ]================================================================================ /** * <p>Layouts are just untyped objects.</p> * @example * var layout = { * name: "Radial", * options: { angleWidth: 180, radius: 80 } * }; * @class * @name Layout * @type String * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.Visualization#layout */ /** * <p>The layout name. This field is mandatory and must be one of:</p> * <ul class="options"><li><code>ForceDirected</code> * <li><code>Circle</code></li> * <li><code>Radial</code></li> * <li><code>Tree</code></li> * <li><code>Preset</code></li></ul> * @property * @name name * @type String * @memberOf org.cytoscapeweb.Layout# */ /** * <p>The available options for each layout type are:</p> * <ol class="options"> * <li><b>ForceDirected:</b></li> * <ul class="options"> * <li><code>mass</code> {Number}: The default mass value for nodes.</li> * <li><code>gravitation</code> {Number}: The gravitational attraction (or repulsion, for * negative values) between nodes.</li> * <li><code>tension</code> {Number}: The default spring tension for edges.</li> * <li><code>restLength</code> {Number}: The default spring rest length for edges.</li> * <li><code>drag</code> {Number}: The co-efficient for frictional drag forces.</li> * <li><code>iterations</code> {Number}: The number of iterations to run the simulation.</li> * <li><code>maxTime</code> {Number}: The maximum time to run the simulation, in milliseconds.</li> * <li><code>minDistance</code> {Number}: The minimum effective distance over which forces are exerted. * Any lesser distances will be treated as the minimum.</li> * <li><code>maxDistance</code> {Number}: The maximum distance over which forces are exerted. * Any greater distances will be ignored.</li> * <li><code>autoStabilize</code> {Boolean}: A common problem with force-directed layouts is that they can be highly unstable. * If this parameter is <code>true</code> and the edges are being stretched too much * between each iteration, Cytoscape Web automatically tries to stabilize * the network. The stabilization attempt is executed after the determined number * of <code>iterations</code>, until each edge length seems constant or until the * <code>maxTime</code> is reached. Set <code>false</code> if you think the results * look worse than expected, or if the layout is taking too long to execute.</li> * <li><code>weightAttr</code> {String}: The name of the edge attribute that contains the weights. * The default value is <code>null</code>, which means that the layout is unweighted with respect to edges. * If you want to generate an edge-weighted layout, you just need to provide the name of the data attribute that should be used as weight.</li> * <li><code>weightNorm</code> {String}: The normalization method that is applied to the weight values when using a weighted layout (i.e. <code>weightAttr != null</code>). * Possible values are: <code>"linear"</code>, <code>"invlinear"</code> and <code>"log"</code>. * The default value is <code>"linear"</code>.</li> * <li><code>minWeight</code> {Number}: The minimum edge weight to consider, if the layout is set to be weighted. * Do not specify any value if you want the layout to get the minimum weight from the rendered edges data (filtered-out edges are ignored). * Any edge with a weight bellow the minimum will be laid out the same as an edge with the minimum weight.</li> * <li><code>maxWeight</code> {Number}: The maximum edge weight to consider, if the layout is set to be weighted. * Do not specify any value if you want the layout to get the maximum weight from the rendered edges data (filtered-out edges are ignored). * Any edge with a weight above the maximum will be laid out the same as an edge with maximum weight.</li> * </ul> * <li><b>Circle:</b></li> * <ul class="options"> * <li><code>angleWidth</code> {Number}: The angular width of the layout, in degrees.</li> * <li><code>tree</code> {Boolean}: Flag indicating if any tree-structure in the data should be used to inform the layout. The default value is <code>false</code>.</li> * </ul> * <li><b>Radial:</b></li> * <ul class="options"> * <li><code>angleWidth</code> {Number}: The angular width of the layout, in degrees.</li> * <li><code>radius</code> {Number}: The radius increment between depth levels.</li> * </ul> * <li><b>Tree:</b></li> * <ul class="options"> * <li><code>orientation</code> {String}: The orientation of the tree. One of: * <code>"leftToRight"</code>, * <code>"rightToLeft"</code>, * <code>"topToBottom"</code>, * <code>"bottomToTop"</code>.</li> * <li><code>depthSpace</code> {Number}: The space between depth levels in the tree.</li> * <li><code>breadthSpace</code> {Number}: The space between siblings in the tree.</li> * <li><code>subtreeSpace</code> {Number}: The space between different sub-trees.</li> * </ul> * <li><b>Preset:</b></li> * <ul class="options"> * <li><code>fitToScreen</code> {Boolean}: If <code>true</code>, the network is centered, and can be zoomed out to fit the screen.</li> * <li><code>points</code> {Array}: A list of plain objects containing the node <code>id</code> and the <code>x</code>/<code>y</code> * coordinates. Example:<br> * <pre class="example ln-"><code class="js" * >var options = { * fitToScreen: false, * points: [ { id: "1", x: 10, y: 60 }, * { id: "2", x: -54, y: 32 }, * { id: "3", x: 120, y: -12 } ] * };</code></pre></li> * </ul> * </ol> * @property * @name options * @type Object * @memberOf org.cytoscapeweb.Layout# */ // ===[ VisualStyle ]=========================================================================== /** * <p>This object represents a Visual Style type, but it is actually just an untyped object.</p> * <p>A visual style may have three attributes:</p> * <ul class="options"> * <li><code>global</code></li> * <li><code>nodes</code></li> * <li><code>edges</code></li></ul> * <p>Each one is an object that defines a set of visual properties.</p> * * <p>For each visual property, you can specify a default value or define a dynamic visual mapping. * Cytoscape Web currently supports four different types of visual mappers:</p> * <ul class="options"> * <li><code>continuousMapper</code></li> * <li><code>discreteMapper</code></li> * <li><code>passthroughMapper</code></li> * <li><code>customMapper</code></li></ul> * * <p>In order to create a visual style, just create an object with the expected fields.</p> * <p>Never do:</p> * <p><code>var style = new org.cytoscapeweb.VisualStyle(); // Wrong!!!</code></p> * @example * var style = { * global: { * backgroundColor: "#ffffff", * tooltipDelay: 1000 * }, * nodes: { * shape: "ELLIPSE", * color: "#333333", * opacity: 1, * size: { defaultValue: 12, * continuousMapper: { attrName: "weight", * minValue: 12, * maxValue: 36 } }, * borderColor: "#000000", * tooltipText: "&lt;b&gt;&#36{label}&lt;/b&gt;: &#36{weight}" * }, * edges: { * color: "#999999", * width: 2, * mergeWidth: 2, * opacity: 1, * label: { passthroughMapper: { attrName: "id" } }, * labelFontSize: 10, * labelFontWeight: "bold" * } * }; * @class * @name VisualStyle * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.ContinuousMapper * @see org.cytoscapeweb.DiscreteMapper * @see org.cytoscapeweb.PassthroughMapper * @see org.cytoscapeweb.CustomMapper * @see org.cytoscapeweb.Visualization#visualStyle * @see org.cytoscapeweb.VisualStyleBypass */ /** * <p>An object that defines global visual properties.</p> * <p>Remember that global properties do not accept visual mappers, because they cannot be associated with nodes/edges data attributes. * If you try to set a mapper to a global property, the mapper is simply ignored.</p> * <p>The possible global properties are:</p> * <ul class="options"><li><code>backgroundColor</code> {String}: Background color of the network view (hexadecimal code). * The default value is "#ffffff".</li> * <li><code>tooltipDelay</code> {Number}: Number of milliseconds to delay before displaying the tooltip, when the cursor is over a node or edge. * The default value is 800 milliseconds.</li> * <li><code>selectionFillColor</code> {String}: Fill color of the drag-selection rectangle. The default value is "#8888ff".</li> * <li><code>selectionLineColor</code> {String}: Line color of the drag-selection border. The default value is "#8888ff".</li> * <li><code>selectionFillOpacity</code> {Number}: Fill opacity of the drag-selection rectangle (0 to 1). The default value is 0.1.</li> * <li><code>selectionLineOpacity</code> {Number}: Line opacity of the drag-selection border (0 to 1). The default value is 0.8.</li> * <li><code>selectionLineWidth</code> {Number}: Line width of the drag-selection border. The default value is 1.</li></ul> * @property * @name global * @type Object * @memberOf org.cytoscapeweb.VisualStyle# */ /** * <p>An object that defines visual styles for nodes.</p> * <p>The possible node properties are:</p> * <ul class="options"><li><code>shape</code> {{@link org.cytoscapeweb.NodeShape}}: Node shape name. The default value is "ELLIPSE".</li> * <li><code>size</code> {Number}: Node size, in pixels. The default value is 24.</li> * <li><code>color</code> {String}: Fill color code of nodes. The default value is "#f5f5f5".</li> * <li><code>image</code> {String}: The URL of the image to be used as the node background. No image is used by default. * If you specify a cross-domain address, then the image might not be loaded by Flash, unless * the host provides a cross-domain XML file that allows you to do so. We recommend you use * a server-side proxy on your web host machine if you have this issue. See an * <a href="http://www.abdulqabiz.com/blog/archives/2007/05/31/php-proxy-script-for-cross-domain-requests/" rel="external">example in PHP</a> * to understand the process of writing your own proxy.</li> * <li><code>borderColor</code> {String}: Border color of nodes. The default value is "#666666".</li> * <li><code>borderWidth</code> {Number}: Border width of nodes. The default value is 1.</li> * <li><code>opacity</code> {Number}: The node opacity (0 to 1). The default value is 0.8.</li> * <li><code>selectionColor</code> {String}: The fill color of selected nodes. * The default value is the same one set to <code>color</code>.</li> * <li><code>selectionBorderColor</code> {String}: The border color of selected nodes. * The default value is the same one set to <code>borderColor</code>.</li> * <li><code>selectionOpacity</code> {Number}: The opacity of selected nodes (0 to 1). * The default value is the same one set to <code>opacity</code>.</li> * <li><code>selectionBorderWidth</code> {Number}: The border width of selected nodes (0 to 1). * The default value is the same one set to <code>borderWidth</code>.</li> * <li><code>selectionGlowColor</code> {String}: The glow color of selected nodes.The default value is "#ffff33".</li> * <li><code>selectionGlowOpacity</code> {Number}: The glow transparency of selected nodes. Valid values are 0 to 1. * The default value is 0.6 (60% opaque).</li> * <li><code>selectionGlowBlur</code> {Number}: The amount of blur for the selection glow. Valid values are 0 to 255 (floating point). * The default value is 8. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) * are optimized to render more quickly.</li> * <li><code>selectionGlowStrength</code> {Number}: The strength of the glow color imprint or spread when the node is selected. * The higher the value, the more color is imprinted and the stronger the contrast * between the glow and the background. * Valid values are 0 to 255. The default is 6.</li> * <li><code>hoverOpacity</code> {Number}: The opacity of the node when the mouse is over it (0 to 1). * The default value is the same one set to <code>opacity</code>.</li> * <li><code>hoverBorderColor</code> {String}: The border color when the mouse is over a node. * The default value is the same one set to <code>borderColor</code>.</li> * <li><code>hoverBorderWidth</code> {Number}: The node border width on mouse over. * The default value is the same one set to <code>borderWidth</code>.</li> * <li><code>hoverGlowColor</code> {String}: The node glow color on mouse over. * The default value is "#aae6ff".</li> * <li><code>hoverGlowOpacity</code> {Number}: The node glow opacity on mouse over (0 to 1). * The default value is 0, which means that there is no visible glow on mouse over.</li> * <li><code>hoverGlowBlur</code> {Number}: The amount of blur for the mouse over glow. Valid values are 0 to 255 (floating point). * The default value is 8. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) * are optimized to render more quickly.</li> * <li><code>hoverGlowStrength</code> {Number}: The strength of the glow color imprint or spread on mouse over. * The higher the value, the more color is imprinted and the stronger the contrast * between the glow and the background. * Valid values are 0 to 255. The default is 6.</li> * <li><code>label</code> {String}: The text to be displayed as node label. A Passthrough Mapper is created by default, * and it displays the node <code>data.label</code> attribute value.</li> * <li><code>labelFontName</code> {String}: Font name of node labels. The default is "Arial".</li> * <li><code>labelFontSize</code> {Number}: The point size of node labels. The default size is 11.</li> * <li><code>labelFontColor</code> {String}: Font color of node labels. The default value "#000000".</li> * <li><code>labelFontWeight</code> {String}: <code>normal</code> or <code>bold</code>. The default is "normal".</li> * <li><code>labelFontStyle</code> {String}: <code>normal</code> or <code>italic</code>. The default is "normal".</li> * <li><code>labelHorizontalAnchor</code> {String}: The horizontal label anchor: * <code>left</code>, <code>center</code> or <code>right</code></li> * <li><code>labelVerticalAnchor</code> {String}: The vertical label anchor: * <code>top</code>, <code>middle</code> or <code>bottom</code></li> * <li><code>labelXOffset</code> {Number}: Horizontal distance of the label from the node border. * If <code>labelHorizontalAnchor</code> is "right", * the distance is measured from the left side of the node, and * a negative offset displaces the label towards left.</li> * <li><code>labelYOffset</code> {Number}: Vertical distance of the label from the node border. * If <code>labelVerticalAnchor</code> is "bottom", * the distance is measured from the top side of the node, and * a negative offset moves the label upper.</li> * <li><code>labelGlowColor</code> {String}: The color of the label glow. The default value is "#ffffff".</li> * <li><code>labelGlowOpacity</code> {Number}: The alpha transparency of the label glow. Valid values are 0 to 1. * The default value is 0 (totally transparent).</li> * <li><code>labelGlowBlur</code> {Number}: The amount of blur for the label glow. Valid values are 0 to 255 (floating point). * The default value is 8. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) * are optimized to render more quickly.</li> * <li><code>labelGlowStrength</code> {Number}: The strength of the imprint or spread. The higher the value, the more color * is imprinted and the stronger the contrast between the glow and the background. * Valid values are 0 to 255. The default is 20.</li> * <li><code>tooltipText</code> {String}: Static text or a text formatter for node tool tips. * A list with all the node <code>data</code> attributes is displayed by default.</li> * <li><code>tooltipFont</code> {String}: Font name of node tool tips. The default font is "Arial".</li> * <li><code>tooltipFontSize</code> {Number}: The point size of node tool tips. The default value is 11.</li> * <li><code>tooltipFontColor</code> {String}: Font color of node tool tips. The default value is "#000000".</li> * <li><code>tooltipBackgroundColor</code> {String}: Background color of node tool tips. The default value is "#f5f5cc".</li> * <li><code>tooltipBorderColor</code> {String}: Border color of node tool tips. The default value is "#000000".</li></ul> * @property * @name nodes * @type Object * @memberOf org.cytoscapeweb.VisualStyle# */ /** * <p>An object that defines visual styles for edges.</p> * <p>The possible edge properties are:</p> * <ul class="options"><li><code>color</code> {String}: Color of edges. The default value is "#999999".</li> * <li><code>width</code> {Number}: Line width of edges. The default value is 1 pixel.</li> * <li><code>opacity</code> {Number}: The edge opacity (0 to 1). The default value is 0.8.</li> * <li><code>style</code> {String}: The edge line style. * One of: <code>"SOLID"</code>, <code>"DOT"</code>, <code>"LONG_DASH"</code>, <code>"EQUAL_DASH"</code>. * The default value is <code>"SOLID"</code>.</li> * <li><code>mergeStyle</code> {String}: The line style for merged edges. * One of: <code>"SOLID"</code>, <code>"DOT"</code>, <code>"LONG_DASH"</code>, <code>"EQUAL_DASH"</code>. * The default value is <code>"SOLID"</code>.</li> * <li><code>mergeColor</code> {String}: Line color for merged edges. The default value is "#666666".</li> * <li><code>mergeWidth</code> {Number}: Line width for merged edges. The default value is 1 pixel.</li> * <li><code>mergeOpacity</code> {Number}: Opacity of merged edges (0 to 1). The default value is 0.8.</li> * <li><code>selectionColor</code> {String}: The fill color of selected edges. * The default value is the same one set to <code>color</code> * (or <code>mergeColor</code>, when edges are merged).</li> * <li><code>selectionOpacity</code> {Number}: The opacity of selected edges (0 to 1). * The default value is the same one set to <code>opacity</code>.</li> * <li><code>selectionGlowColor</code> {String}: The glow color of selected edges.The default value is "#ffff33".</li> * <li><code>selectionGlowOpacity</code> {Number}: The glow transparency of selected edges. Valid values are 0 to 1. * The default value is 0.6 (60% opaque).</li> * <li><code>selectionGlowBlur</code> {Number}: The amount of blur for the selection glow. Valid values are 0 to 255 (floating point). * The default value is 4. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) * are optimized to render more quickly.</li> * <li><code>selectionGlowStrength</code> {Number}: The strength of the glow color imprint or spread when the edge is selected. * The higher the value, the more color is imprinted and the stronger the contrast * between the glow and the background. * Valid values are 0 to 255. The default is 10.</li> * <li><code>hoverOpacity</code> {Number}: The opacity of the edge when the mouse is over it (0 to 1). * The default value is the same one set to <code>opacity</code>.</li> * <li><code>curvature</code> {Number}: The curvature amount of curved edges. The default value is 18.</li> * <li><code>sourceArrowShape</code> {{@link org.cytoscapeweb.ArrowShape}}: Shape name of source arrows. The default value is "NONE".</li> * <li><code>targetArrowShape</code> {{@link org.cytoscapeweb.ArrowShape}}: Shape name of target arrows. * For directed edges, the default value is "DELTA". * For undirected ones, the default value is "NONE".</li> * <li><code>sourceArrowColor</code> {String}: Color code of source arrows. * The default value is the same one set to the edge <code>color</code> property.</li> * <li><code>targetArrowColor</code> {String}: Color code of target arrows. * The default value is the same one set to the edge <code>color</code> property.</li> * <li><code>label</code> {String}: The text to be displayed as edge label. There is no default value or mapper for edge labels.</li> * <li><code>labelFontName</code> {String}: Font name of edge labels. The default is "Arial".</li> * <li><code>labelFontSize</code> {Number}: The point size of edge labels. The default size is 11.</li> * <li><code>labelFontColor</code> {String}: Font color of edge labels. The default value "#000000".</li> * <li><code>labelFontWeight</code> {String}: <code>normal</code> or <code>bold</code>. The default is "normal".</li> * <li><code>labelFontStyle</code> {String}: <code>normal</code> or <code>italic</code>. The default is "normal".</li> * <li><code>labelGlowColor</code> {String}: The color of the label glow. The default value is "#ffffff".</li> * <li><code>labelGlowOpacity</code> {Number}: The alpha transparency of the label glow. Valid values are 0 to 1. * The default value is 0 (totally transparent).</li> * <li><code>labelGlowBlur</code> {Number}: The amount of blur for the label glow. Valid values are 0 to 255 (floating point). * The default value is 2. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) * are optimized to render more quickly.</li> * <li><code>labelGlowStrength</code> {Number}: The strength of the imprint or spread. The higher the value, the more color * is imprinted and the stronger the contrast between the glow and the background. * Valid values are 0 to 255. The default is 20.</li> * <li><code>tooltipText</code> {String}: Static text or a text formatter for regular edge tool tips. * A list with all the edge <code>data</code> attributes is displayed by default.</li> * <li><code>mergeTooltipText</code> {String}: Static text or a text formatter for merged edge tool tips. * A list with all the merged edge <code>data</code> attributes is displayed by default.</li> * <li><code>tooltipFont</code> {String}: Font name of edge tool tips. The default font is "Arial".</li> * <li><code>tooltipFontSize</code> {Number}: The point size of edge tool tips. The default value is 11.</li> * <li><code>tooltipFontColor</code> {String}: Font color of edge tool tips. The default value is "#000000".</li> * <li><code>tooltipBackgroundColor</code> {String}: Background color of edge tool tips. The default value is "#f5f5cc".</li> * <li><code>tooltipBorderColor</code> {String}: Border color of edge tool tips. The default value is "#000000".</li></ul> * @property * @name edges * @type Object * @memberOf org.cytoscapeweb.VisualStyle# */ // ===[ VisualStyleBypass ]=========================================================================== /** * <p>This object represents a Visual Style Bypass type, but it is actually just an untyped object.</p> * <p>A visual style bypass may have two attributes:</p> * <ul class="options"> * <li><code>nodes</code></li> * <li><code>edges</code></li></ul> * <p>Each one is an object that redefines a set of visual properties. They are dictionaries * that have edges and nodes <code>id</code> values as keys, and objects that contain the visual styles as values.</p> * <p>Notice that you cannot bypass <code>global</code> properties, and it is not possible to set visual mappings either.</p> * <p>You can bypass any of the nodes or edges visual properties. Just use the same names listed at * {@link org.cytoscapeweb.VisualStyle}.</p> * @example * var bypass = { * nodes: { * "1": { color: "#ff0000", opacity: 0.5, size: 32 }, * "3": { color: "#ffff00", opacity: 0.9 }, * "7": { color: "#ffff00", opacity: 0.2 } * }, * edges: { * "22": { width: 4, opacity: 0.2 }, * "23": { width: 4, opacity: 0.2 } * } * }; * @class * @name VisualStyleBypass * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.VisualStyle * @see org.cytoscapeweb.Visualization#visualStyleBypass */ // ===[ Mappers ]=============================================================================== /** * <p>This object represents a Continuous Mapper type, although it is just an untyped object.</p> * <p>Depending on the visual attribute, there are two kinds of continuous mappers:</p> * <ol><li><strong>Continuous-to-Continuous Mapper:</strong> for example, you can map a continuous numerical value to a node size.</li> * <li><strong>Color Gradient Mapper:</strong> This is a special case of continuous-to-continuous mapping. * Continuous numerical values are mapped to a color gradient.</li></ol> * <p>Notice that: * <ul> * <li><strong>Continuous-to-Discrete</strong> mappers are not supported yet (e.g. all values below 0 are mapped to square nodes, * and all values above 0 are mapped to circular nodes).</li> * <li>Only numerical attributes and colors can be mapped with continuous mappers. For example, * there is no way to smoothly morph between circular nodes and square nodes.</il> * <li>The mapping algorithm uses a linear interpolation to calculate the values.</li> * <li>Continuous mappers ignore filtered out elements.</li> * </ul> * * @example * // A mapper that could be used to set the sizes of the nodes between 12 and 36 pixels: * var sizeMapper = { attrName: "weight", minValue: 12, maxValue: 36 }; * * // This one could be used to create a color range from yellow to green: * var colorMapper = { attrName: "score", minValue: "#ffff00", maxValue: "#00ff00" }; * * // This edge width mapper specifies the minimum and maximum data values for the scale. * // Weights lower than 0.1 are given a width of 1, and weights higher than 1.0 are given a width of 4. * var widthMapper = { attrName: "weight", minValue: 1, maxValue: 4, minAttrValue: 0.1, maxAttrValue: 1.0 }; * @class * @name ContinuousMapper * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.DiscreteMapper * @see org.cytoscapeweb.PassthroughMapper * @see org.cytoscapeweb.CustomMapper * @see org.cytoscapeweb.VisualStyle */ /** * The name of the data attribute that will be mapped to a visual style's property. * @property * @name attrName * @type String * @memberOf org.cytoscapeweb.ContinuousMapper# */ /** * The minimum value of the visual style's property. It is usually a number (e.g. edge width), * but accepts strings if the visual property is a color. * @property * @name minValue * @memberOf org.cytoscapeweb.ContinuousMapper# */ /** * The maximum value of the visual style's property. It is usually a number (e.g. edge width), * but accepts strings if the visual property is a color. * @property * @name maxValue * @memberOf org.cytoscapeweb.ContinuousMapper# */ /** * An optional minimum value for the linear scale. If you don't specify it, * Cytoscape Web gets the lowest attribute value from the rendered nodes or edges (filtered-out elements are ignored). * And if an element's data value is lower than the specified minimum, that element's visual property is simply scaled up to the minimum value. * @property * @name minAttrValue * @type Number * @memberOf org.cytoscapeweb.ContinuousMapper# */ /** * An optional maximum value for the linear scale. If you don't specify it, * Cytoscape Web gets the highest attribute value from the rendered nodes or edges (filtered-out elements are ignored). * And if an element's data value is higher than the specified maximum, that element's visual property is simply scaled down to the maximum value. * @property * @name maxAttrValue * @type Number * @memberOf org.cytoscapeweb.ContinuousMapper# */ /** * <p>This object represents a Discrete Mapper type, but is just an untyped object.</p> * <p>Discrete network attributes are mapped to discrete visual attributes.</p> * <p>For example, a discrete mapper can map node colors to gene annotations.</p> * @example * // Create the mapper: * var colorMapper = { * attrName: "molecular_function", * entries: [ { attrValue: "catalytic", value: "#ff0000" }, * { attrValue: "transporter", value: "#00ff00" }, * { attrValue: "binding", value: "#0000ff" } ] * }; * * // Set the mapper to a Visual Style; * var style = { * nodes: { * color: { discreteMapper: colorMapper } * } * }; * * // Set the new style to the Visualization: * vis.visualStyle(style); * * // Now, if ( node.data["molecular_function"] == "binding" ), * // then the node will be blue * * @class * @name DiscreteMapper * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.ContinuousMapper * @see org.cytoscapeweb.PassthroughMapper * @see org.cytoscapeweb.CustomMapper * @see org.cytoscapeweb.VisualStyle */ /** * The name of the data attribute that will be mapped to a visual style's property. * @property * @name attrName * @type String * @memberOf org.cytoscapeweb.DiscreteMapper# */ /** * An array of objects used to map data attributes to visual style values. * Each entry object must define: * <ul class="options"><li><code>attrValue</code>: The edge or node data attribute value.</li> * <li><code>value</code>: The visual style value (e.g. a color code).</li></ul> * @property * @name entries * @type Array * @memberOf org.cytoscapeweb.DiscreteMapper# */ /** * <p>This is an untyped object that represents a Passthrough Mapper type.</p> * <p>The values of network attributes are passed directly through to visual attributes.</p> * <p>The most common use case is using this mapper to specify node/edge labels. * For example, a passthrough mapper can label all nodes with their gene symbols.</p> * <p>When defining a passthrough mapper, you just need to specify the name of the node or edge * data attribute that contains the visual style values.</p> * @example * // Create the mapper and set it to a Visual Style's nodes.label property; * var style = { * nodes: { * label: { passthroughMapper: { attrName: "symbol" } } * } * }; * * // Set the new style to the Visualization: * vis.visualStyle(style); * * @class * @name PassthroughMapper * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.ContinuousMapper * @see org.cytoscapeweb.DiscreteMapper * @see org.cytoscapeweb.CustomMapper * @see org.cytoscapeweb.VisualStyle */ /** * <p>This is a special type of mapper that allows you to register a callback function * that will be called for each associated element (nodes or edges). * The function will then be responsible for returning the desired property value.</p> * <p>The callback function should expect a <code>data</code> object as argument.</p> * <p>You could, for example, use a custom mapper to create a better tooltip text.</p> * * @example * // 1. First, create a function and add it to the Visualization object. * vis["customTooltip"] = function (data) { * var value = Math.round(100 * data["weight"]) + "%"; * return 'The confidence level of this link is: ' + * '&lt;font color="#000099" face="Courier" size="14"&gt;' + value + '&lt;/font&gt;'; * }; * * // 2. Now create a new visual style (or get the current one) and register * // the custom mapper to one or more visual properties: * var style = vis.visualStyle(); * style.edges.tooltipText = { customMapper: { functionName: "customTooltip" } }, * * // 3. Finally set the visual style again: * vis.visualStyle(style); * * @class * @name CustomMapper * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.ContinuousMapper * @see org.cytoscapeweb.DiscreteMapper * @see org.cytoscapeweb.PassthroughMapper * @see org.cytoscapeweb.VisualStyle */ /** * The name of the JavaScript function that will return the visual style value for each node or edge. * The callback function always receives the node's or edge's <code>data</code> object as argument. * @property * @name functionName * @type String * @memberOf org.cytoscapeweb.CustomMapper# */ // ===[ Error ]================================================================================ /** * <p>This object represents an Error type, but is just an untyped object.</p> * <p>It is returned by <code>"error"</code> type events.</p> * @class * @name Error * @memberOf org.cytoscapeweb * @type Object * @see org.cytoscapeweb.EventType * @see org.cytoscapeweb.Event * @see org.cytoscapeweb.Visualization#addListener */ /** * The error message. * @property * @name msg * @type String * @memberOf org.cytoscapeweb.Error# */ /** * The error id. * @property * @name id * @type String * @memberOf org.cytoscapeweb.Error# */ /** * The error name. * @property * @name name * @type String * @memberOf org.cytoscapeweb.Error# */ /** * The stack trace of the error. * @property * @name stackTrace * @type String * @memberOf org.cytoscapeweb.Error# */ // ===[ Data Schema ]================================================================================== /** * <p>This is an untyped object that represents a Data Schema type.</p> * <p>A data schema is automatically created when a network is loaded into Cytoscape Web, * and cannot be created programatically through the API. * However you can use the {@link org.cytoscapeweb.Visualization#addDataField} and * {@link org.cytoscapeweb.Visualization#removeDataField} methods to change the current schema.</p> * <p>A data schema has two attributes:</p> * <ul class="options"> * <li><code>nodes</code> {Array}</li> * <li><code>edges</code> {Array}</li></ul> * <p>Those are arrays of {@link org.cytoscapeweb.DataField} objects:</p> * * @example * var schema = { * nodes: [ * { name: "id", type: "string" }, * { name: "label", type: "string" } * ], * edges: [ * { name: "id", type: "string" }, * { name: "weight", type: "number", defValue: 0.5 } * ] * }; * @class * @name DataSchema * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.Visualization#dataSchema * @see org.cytoscapeweb.DataField */ /** * <p>This untyped object represents a Data Field, which is a node or edge attribute definition.</p> * <p>A data field object contains the following properties:</p> * <ul class="options"> * <li><code>name</code>: The name of the data attribute.</li> * <li><code>type</code>: The data type of the attribute. One of: * <code>"string"</code>, <code>"boolean"</code>, <code>"number"</code>, <code>"int"</code>, <code>"object"</code>.</li> * <li><code>defValue</code>: An optional default value.</li> * </ul> * @class * @name DataField * @type Object * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.Visualization#addDataField * @see org.cytoscapeweb.Visualization#removeDataField * @see org.cytoscapeweb.Visualization#dataSchema * @see org.cytoscapeweb.DataSchema */ // ===[ Fake Enum Types ]======================================================================= /** * <p>This object represents a Group type. In actuality, it is a string.</p> * <p>However, its value must be one of:</p> * <ul class="options"><li><code>nodes</code></li><li><code>edges</code></li><li><code>none</code> (same as <code>null</code>)</li></ul> * @class * @name Group * @type String * @memberOf org.cytoscapeweb */ /** * <p>This object represents an event type. In actuality, it is a string.</p> * <p>All of them, but <code>"contextmenu"</code> can be used with the listener methods * ({@link org.cytoscapeweb.Visualization#addListener}, {@link org.cytoscapeweb.Visualization#hasListener} and * {@link org.cytoscapeweb.Visualization#removeListener}).</p> * <p>Its value must be one of:</p> * <ul class="options"><li><code>click</code>:</strong> For mouse click events on nodes, edges or the visualization background.</li> * <li><code>dblclick</code>:</strong> For double-click events on nodes, edges or the visualization background.</li> * <li><code>mouseover</code>:</strong> For mouse-over events on nodes, edges or the visualization background.</li> * <li><code>mouseout</code>:</strong> For mouse-out events on nodes, edges or the visualization background.</li> * <li><code>select</code>:</strong> For events dispatched after nodes or edges are selected (e.g. by direct mouse clicking or by drag-selecting).</li> * <li><code>deselect</code>:</strong> For events dispatched after nodes or edges are unselected.</li> * <li><code>filter</code>:</strong> For events dispatched after nodes or edges are filtered.</li> * <li><code>zoom</code>:</strong> For events dispatched after the network is rescaled.</li> * <li><code>layout</code>:</strong> For events dispatched after a new layout is applied or the current one is recomputed.</li> * <li><code>contextmenu</code>:</strong> For events dispatched after a right-click context menu item is selected. * You cannot use this type with the listener methods (e.g. {@link org.cytoscapeweb.Visualization#addListener}). * Events of this type are only dispatched to the callback functions that are registered with * {@link org.cytoscapeweb.Visualization#addContextMenuItem}.</li> * <li><code>error</code>:</strong> For events dispatched when an internal error or exception occurs.</li></ul> * @class * @name EventType * @type String * @memberOf org.cytoscapeweb * @see org.cytoscapeweb.Visualization#addListener * @see org.cytoscapeweb.Visualization#hasListener * @see org.cytoscapeweb.Visualization#removeListener * @see org.cytoscapeweb.Visualization#addContextMenuItem */ /** * <p>This object represents node shapes. In actuality, it is just a string.</p> * <p>Possible values:</p> * <ul class="options"> * <li><code>ELLIPSE</code></li> * <li><code>RECTANGLE</code></li> * <li><code>TRIANGLE</code></li> * <li><code>DIAMOND</code></li> * <li><code>HEXAGON</code></li> * <li><code>OCTAGON</code></li> * <li><code>PARALLELOGRAM</code></li> * <li><code>ROUNDRECT</code></li> * <li><code>VEE</code></li></ul> * @class * @name NodeShape * @type String * @memberOf org.cytoscapeweb */ /** * <p>This object represents edge arrow shapes. In actuality, it is just a string.</p> * <p>Its value must be one of:</p> * <ul class="options"> * <li><code>NONE</code></li> * <li><code>DELTA</code></li> * <li><code>ARROW</code></li> * <li><code>DIAMOND</code></li> * <li><code>CIRCLE</code></li> * <li><code>T</code></li></ul> * @class * @name ArrowShape * @type String * @memberOf org.cytoscapeweb */ })();
PHP
UTF-8
1,794
2.703125
3
[]
no_license
<?php session_start(); function envoyerValeur(){ try{ $serveur = $_SESSION['serveur']; $loginBDD = $_SESSION['loginBDD']; $password = $_SESSION['password']; $database = $_SESSION['database']; $connexion = new PDO("mysql:host=$serveur;dbname=$database",$loginBDD,$password); $connexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $statement = $connexion -> prepare("INSERT INTO suivi (id, date, heure, nomAnnexe, commentaire, projet, technologie) VALUES (null, ?,?, ?, ?, ?, ?)"); $statement->bindParam(1, $_POST['date']); $statement->bindParam(2, $_POST['heure']); $statement->bindParam(3, $_POST['nomAnnexe']); $statement->bindParam(4, $_POST['commentaire']); $statement->bindParam(5, $_POST['projet']); $statement->bindParam(6, $_POST['techno']); $statement->execute(); echo '<p align="center">Vos informations on bien ete transmis a la base de donnee</p>'; }catch (Exception $e){ echo "erreur lors de l'enregistrement dans la base de donnée, assurez vous d'avoir correctement rempli tous les informations "; echo "<br>voici le code erreur SQL : ".$e->getMessage(); } } envoyerValeur(); ?> <!DOCTYPE html> <html> <head> <title>Bonjour <?php echo $_SESSION['login']?></title> <meta charset="UTF-8"> <link rel="stylesheet" media="screen" type="text/css" title="page_web" href="css/style.css"/> <?php include 'header.php'; ?> </head> <body> <br> <br> <p align="center"><a href="tableauDeBord.php"><input type="button" value="Retour au tableau de bord" id="button"></a></p> <p align="center"><a href="index.php"><input type="button" value="Deconnexion" id="button"></a></p> </body> <footer> <h6><center><?php include 'piedDePage.php';?></center></h6> </footer> </html>
Markdown
UTF-8
2,405
2.875
3
[ "BSD-3-Clause", "CC-BY-SA-4.0", "LicenseRef-scancode-free-unknown", "CC-BY-4.0", "MIT" ]
permissive
--- id: 587d7fb3367417b2b2512bfb title: 'How to Use package.json, the Core of Any Node.js Project or npm Package' localeTitle: 'Cómo usar package.json, el núcleo de cualquier proyecto Node.js o paquete npm' challengeType: 2 --- ## Description <section id='description'> El archivo package.json es el centro de cualquier proyecto Node.js o paquete npm. Almacena información sobre su proyecto al igual que la sección &lt;head&gt; en un documento HTML describe el contenido de una página web. El package.json consiste en un solo objeto JSON donde la información se almacena en "clave": pares de valores. Solo hay dos campos obligatorios en un paquete mínimo.json (nombre y versión), pero es una buena práctica proporcionar información adicional sobre su proyecto que pueda ser útil para futuros usuarios o mantenedores. El campo de autor Si va al proyecto de Glitch que configuró anteriormente y mira en el lado izquierdo de su pantalla, encontrará el árbol de archivos donde puede ver un resumen de los diversos archivos en su proyecto. Bajo la sección de back-end del árbol de archivos, encontrará package.json, el archivo que mejoraremos en los próximos dos desafíos. Una de las piezas de información más comunes en este archivo es el campo de autor que especifica quién es el creador de un proyecto. Puede ser una cadena o un objeto con detalles de contacto. El objeto se recomienda para proyectos más grandes, pero en nuestro caso, una cadena simple como la del siguiente ejemplo servirá. <code>"author": "Jane Doe",</code> Instrucciones Agregue su nombre al campo de autor en el paquete.json de su proyecto de Glitch. Recuerda que estás escribiendo JSON. Todos los nombres de campo deben usar comillas dobles ("), por ejemplo," autor " Todos los campos deben estar separados por una coma (,) </section> ## Instructions <section id='instructions'> </section> ## Tests <section id='tests'> ```yml tests: - text: package.json debería tener una clave de "autor" válida testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.author, ''"author" is missing''); }, xhr => { throw new Error(xhr.responseText); })' ``` </section> ## Challenge Seed <section id='challengeSeed'> </section> ## Solution <section id='solution'> ```js // solution required ``` </section>
C
UTF-8
1,263
3.65625
4
[]
no_license
#include <studio.h> int main(void) { float num1, num2; char oper; do{ printf("\t\tCalculadora da Ale\n\n"); printf("Operacoes disponiveis\n"); printf("'+' : soma\n"); printf("'-' : subtracao\n"); printf("'*' : multiplicacao\n"); printf("'/' : divisao\n"); printf("'%%' : resto da divisao\n"); printf("\nDigite a expressao na forma: numero1 operador numero2\n"); printf("Exemplos: 1 + 1, 2.1*3.1\n"); printf("`Para sair digite: 0 0 0\n"); scanf("%f", &num1); scanf("%c", &oper); scanf("%f", &num2); system("cls || clear"); printf("Calculando: %.2f %c %.2f = ", num1,oper,num2); switch( oper ) { case '+': printf("%.2\n\n", num1 + num2); break; case '-': printf("%.2\n\n", num1 - num2); break; case '*': printf("%.2\n\n", num1 * num2); break; case '/': if(num2 !=0) printf("%.2\n\n", num1 / num2); else printf("Nao existe divisao po 0\n\n); break; case '%': printf("%d\n\n", (int)num1 % (int)num2); break; default: if(num1 !=0 && oper !='0' && num2 !=0) printf(" Operador invalido\n\n "); else printf(" Fechando calculadora!\n "); } }while(num1 !=0 && oper !='0' && num2 !=0); }
Python
UTF-8
347
3.578125
4
[]
no_license
# https://www.acmicpc.net/problem/2417 # 올림 함수인 ceil을 쓰기 위해 import 합니다. from math import ceil # 첫째 줄에 정수 n을 입력합니다. # 0 <= n < 2^63 n = int(input()) # q^2 >= n인 가장 작은 음이 아닌 정수 q를 저장하는 변수를 선언합니다. q = ceil(n ** 0.5) # q를 출력합니다. print(q)
Python
UTF-8
917
2.53125
3
[]
no_license
import numpy as np import sys import freenect import cv2 import os import signal import time def handler(signum, frame): print "Timed Out" exit(2) raise Exception("timeout") print "Initialisation" # time.sleep(5) signal.signal(signal.SIGALRM, handler) i = 0 while True: signal.alarm(2) try : depth = freenect.sync_get_depth()[0] except Exception, exc: if exc == "timeout": print "Timed out : ", else : print "Can't connect to the Kinect :", print "Error loading the depth image ! \tTrying again ({})...".format(i) i+=1 signal.alarm(2) else : print"Loaded correctly !" break signal.alarm(0) time.sleep(1) os.system('clear') while True: depth = freenect.sync_get_depth() print np.shape(depth) # cv2.imshow("image",depth) if cv2.waitKey(1) == 27: break cv2.destroyAllWindows()
Markdown
UTF-8
1,284
3
3
[]
no_license
# EoDP Assignment 2 Data Server A basic server to fetch and store data ## Usage ```python import requests import json import pandas as pd id = 'exampleid' server = '0.0.0.0' # get original data with dataset id, replace server to our server ip res = requests.get(f"http://{server}:5000/datasets/original/{id}) data = res.json()['data'] # get all datasets' id and fields res = requests.get(f"http://{server}:5000/datasets/original/) data = res.json()['data'] # get entries of existing custom data res = requests.get(f"http://{server}:5000/datasets/modified/) data = res.json()['data'] # get an custom object using title title = 'some-title' res = requests.get(f"http://{server}:5000/datasets/modified/{title}) data = res.json()['data'] # load an custom dataset using title title = 'some-title' res = requests.get(f"http://{server}:5000/datasets/modified/{title}) data = res.json()['data'] df = pd.DataFrame.from_records(data) # upload custom object obj = {'some': 'object'} requests.post('https://{server}:5000/datasets/modified', data={'title':'some-title', 'data': obj}) # upload custom pandas DataFrame result = df.to_json(orient="records") parsed = json.loads(result) requests.post('https://{server}:5000/datasets/modified', data={'title':'some-title', 'data': parsed}) ```
PHP
UTF-8
1,735
2.578125
3
[ "MIT" ]
permissive
<?php namespace spec\Fitbug\SymfonySerializer\YamlEncoderDecoder; use PhpSpec\ObjectBehavior; class YamlEncodeSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Fitbug\SymfonySerializer\YamlEncoderDecoder\YamlEncode'); } function it_is_a_encoder() { $this->shouldImplement('Symfony\Component\Serializer\Encoder\EncoderInterface'); } function it_supports_type_yaml() { $this->supportsEncoding('yaml')->shouldReturn(true); } function it_does_not_support_other_formats() { $this->supportsEncoding('json')->shouldReturn(false); } function it_encodes_yaml() { $basicYaml = <<<YAML example: yaml YAML; $this->encode(['example' => 'yaml'], 'yaml')->shouldReturn($basicYaml); } function it_encodes_using_passes_options_in_constructor_to_parser() { $basicYaml = <<<YAML example: yaml: example YAML; $this->beConstructedWith( false, false, false, false, 2, 4 ); $this->encode(['example' => ['yaml' => 'example']], 'yaml')->shouldReturn($basicYaml); } function it_passes_options_in_the_contect_to_the_parser_and_overrides_defaults() { $basicYaml = <<<YAML example: yaml: example YAML; $this->beConstructedWith( false, false, false, false, 2, 4 ); $this->encode( ['example' => ['yaml' => 'example']], 'yaml', ['yaml_encode_indent' => 2] )->shouldReturn( $basicYaml ); } }
TypeScript
UTF-8
3,291
2.75
3
[]
no_license
import { isEmpty } from "../utils/objectUtils"; import { Status } from "../utils/declarations"; const Joi = require("joi"); const { Author } = require("../models/Author"); const authorSchema = Joi.object({ author_id: Joi.number().integer(), first_name: Joi.string().min(1).max(50).required(), last_name: Joi.string().min(1).max(50).required(), }); const verifyParameter = (ctx) => { const { params } = ctx; if (!params.id) { ctx.response.status = 400; ctx.throw("Author ID is required"); } }; const getAuthors = async (ctx) => { const author = new Author(); try { const result = await author.all(); ctx.body = { status: Status.SUCCESS, message: "", data: { authors: result, }, }; } catch (error) { ctx.response.status = 400; ctx.throw(error.message); } }; const getAuthor = async (ctx) => { verifyParameter(ctx); const author = new Author(); await author.find(ctx.params.id); if (isEmpty(author)) { ctx.response.status = 400; throw new Error(`Author with ID ${ctx.params.id} not found`); } ctx.body = { status: Status.SUCCESS, message: "", data: { author, }, }; }; const createAuthor = async (ctx) => { const request = ctx.request.body; const author = new Author(request); const validator = authorSchema.validate(author); if (validator.error) { ctx.response.status = 400; ctx.throw(validator.error.details[0].message); } try { const result = await author.store(); author.author_id = result.rows[0]["author_id"]; ctx.body = { status: Status.SUCCESS, message: "Author created", data: { author, }, }; } catch (error) { ctx.response.status = 400; ctx.throw(error.message); } }; const updateAuthor = async (ctx) => { verifyParameter(ctx); const request = ctx.request.body; const author = new Author(); await author.find(ctx.params.id); if (isEmpty(author)) { ctx.response.status = 400; throw new Error(`Author with ID ${ctx.params.id} not found`); } // Replace the author data with the new updated author data author.author_id = parseInt(ctx.params.id); author.first_name = request.first_name; author.last_name = request.last_name; const validator = authorSchema.validate(author); if (validator.error) { ctx.response.status = 400; ctx.throw(validator.error.details[0].message); } try { await author.update(); ctx.body = { status: Status.SUCCESS, message: "Author updated", data: author, }; } catch (error) { ctx.response.status = 400; ctx.throw(error.message); } }; const removeAuthor = async (ctx) => { verifyParameter(ctx); const author = new Author(); await author.find(ctx.params.id); if (isEmpty(author)) { ctx.response.status = 400; throw new Error(`Author with ID ${ctx.params.id} not found`); } try { await author.remove(); ctx.body = { status: Status.SUCCESS, message: "Author removed", data: {}, }; } catch (error) { ctx.response.status = 400; ctx.throw(error.message); } }; const authorController = { removeAuthor, updateAuthor, createAuthor, getAuthor, getAuthors, }; export default authorController;
Python
UTF-8
3,091
2.671875
3
[]
no_license
from bs4 import BeautifulSoup from tqdm import tqdm import pandas as pd from html import unescape from exploration import get_citances_for_file if __name__ == "__main__": valid = ["C00-2123", "C04-1089", "I05-5011", "J96-3004", "N06-2049", "P05-1004", "P05-1053", "P98-1046"] folder = "./data/Training-Set-2019/Task1/From-Training-Set-2018/" result_dict = {} data = pd.read_csv("doc_ids_dev_ground_truth_3_new.csv", delimiter="\t") tp = 0 overall_truth = 0 overall_predicted = 0 count_errors = 0 count_citances = 0 for i, row in data.iterrows(): # unescape html characters clean_text = BeautifulSoup(row["query"]).text if clean_text.startswith("Levin"): clean_text = clean_text.replace("Levin&aposs", "Levin's") elif clean_text.startswith("In explormg these quest1ons"): clean_text = "In explormg these quest1ons" doc_ids = [str(el) for el in eval(row["doc_id"])] labels = eval(row["label"]) similarities = eval(row["similiarity"]) # Use for thresholding # relevant_doc_ids = set() # for i in range(len(doc_ids)): # if similarities[i] <= 0.3: # relevant_doc_ids.add(doc_ids[i]) # Fixed return of the highest 4 similarity scores "Always 4" sorted_doc_ids = [x for _, x in sorted(zip(similarities, doc_ids), reverse=True)] relevant_doc_ids = set(sorted_doc_ids[:4]) result_dict[clean_text] = relevant_doc_ids for filename in tqdm(valid): # Used for the validation runs with the UoM data citances = get_citances_for_file(filename, list(), folder) for i, citance in enumerate(citances, start=1): count_citances += 1 all_query_sentences = citance["Citation Text"] soup = BeautifulSoup(all_query_sentences, "html.parser") truth = set(citance["Reference Offset"]) texts = soup.findAll() satya_input_query = "" # Add text together from different citation sentences. # Results show that a big single query performs better. for el in texts: satya_input_query += el.text key = satya_input_query.strip(" \t\n") if key.startswith("In explormg these quest1ons"): key = "In explormg these quest1ons" try: predicted = result_dict[key] tp += len(truth.intersection(predicted)) print(predicted) print(truth) print("-------------------------------------") overall_predicted += len(predicted) overall_truth += len(truth) except KeyError: count_errors += 1 print(f"Found {count_errors} KeyErrors, with a total of {len(result_dict)} queries.") print(tp) prec = tp / overall_predicted print(f"Precision: {prec:.4f}") rec = tp / overall_truth print(f"Recall: {rec:.4f}") f1 = 2* (prec * rec) / (prec + rec) print(f"F1: {f1:.4f}")
Java
UTF-8
4,449
2.15625
2
[ "Apache-2.0" ]
permissive
/** * Copyright (C) 2017 Red Hat, Inc. * * 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 io.atlasmap.core; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.hamcrest.Matchers.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class AtlasUtilTest { @Test public void testIsEmpty() { assertTrue(AtlasUtil.isEmpty(null)); assertTrue(AtlasUtil.isEmpty("")); assertTrue(AtlasUtil.isEmpty(" ")); assertTrue(AtlasUtil.isEmpty("\n\n")); assertTrue(AtlasUtil.isEmpty("\t\t")); assertTrue(AtlasUtil.isEmpty("\r\n")); assertTrue(AtlasUtil.isEmpty("\f\t\n\r")); // Note: We can live with 'backspace' not being 'empty' assertFalse(AtlasUtil.isEmpty("\b")); } @Test public void testAtlasUri() { String uriJavaNover = "atlas:java"; String uriJavaNoverWParm = "atlas:java?foo=bar"; String uriJavaNoverWParms = "atlas:java?foo=bar&bar=blah"; String uriJavaVer1 = "atlas:java::1"; String uriJavaVer2 = "atlas:java::2"; String uriJavaVer2WParm = "atlas:java::2?foo=bar"; String uriJavaVer2WParams = "atlas:java::2?foo=bar&bar=blah"; List<String> javaUris = Arrays.asList(uriJavaNover, uriJavaNoverWParm, uriJavaNoverWParms, uriJavaVer1, uriJavaVer2, uriJavaVer2WParm, uriJavaVer2WParams); List<String> noverUris = Arrays.asList(uriJavaNover, uriJavaNoverWParm, uriJavaNoverWParms); List<String> javaVer1Uris = Arrays.asList(uriJavaVer1); List<String> javaVer2Uris = Arrays.asList(uriJavaVer2, uriJavaVer2WParm, uriJavaVer2WParams); List<String> parmUris = Arrays.asList(uriJavaNoverWParm, uriJavaVer2WParm); List<String> parmsUris = Arrays.asList(uriJavaNoverWParms, uriJavaVer2WParams); for (String uri : javaUris) { assertEquals("atlas", AtlasUtil.getUriScheme(uri)); } for (String uri : javaUris) { assertEquals("java", AtlasUtil.getUriModule(uri)); } for (String uri : javaUris) { assertNull(AtlasUtil.getUriDataType(uri)); } for (String uri : noverUris) { assertNull(AtlasUtil.getUriModuleVersion(uri)); } for (String uri : javaVer1Uris) { assertEquals("1", AtlasUtil.getUriModuleVersion(uri)); } for (String uri : javaVer2Uris) { assertEquals("2", AtlasUtil.getUriModuleVersion(uri)); } for (String uri : parmUris) { Map<String, String> params = AtlasUtil.getUriParameters(uri); assertNotNull(params); assertEquals(Integer.valueOf(1), Integer.valueOf(params.size())); assertEquals("bar", params.get("foo")); assertNull(params.get("bar")); } for (String uri : parmsUris) { Map<String, String> params = AtlasUtil.getUriParameters(uri); assertNotNull(params); assertEquals(Integer.valueOf(2), Integer.valueOf(params.size())); assertEquals("bar", params.get("foo")); assertEquals("blah", params.get("bar")); assertNull(params.get("blah")); } } @Test public void testFindClassesForPackage() { List<Class<?>> classes = AtlasUtil.findClassesForPackage("io.atlasmap.v2"); assertNotNull(classes); assertThat(classes.stream().map(Class::getName).collect(Collectors.toList()), hasItems("io.atlasmap.v2.Field", "io.atlasmap.v2.AtlasMapping", "io.atlasmap.v2.Action", "io.atlasmap.v2.Capitalize")); } }
Python
UTF-8
728
3.234375
3
[]
no_license
# GAP algorithm import math def merge(a,n,b,m): total = m + n gap = math.ceil(total / 2) while gap>0: i = 0 j = i+gap while j<(m+n): if i<n and j<n: if a[j]<a[i]: a[i], a[j] = a[j], a[i] elif i>=n and j>=n: if b[j-n]<b[i-n]: b[j-n], b[i-n] = b[i-n], b[j-n] else: if b[j-n]<a[i]: a[i],b[j-n] = b[j-n],a[i] i+=1 j+=1 if gap == 1: break gap = math.ceil(gap / 2) n, m = map(int, input().split()) a = list(map(int ,input().split())) b = list(map(int, input().split())) merge(a,n,b,m) print(a,b)
Markdown
UTF-8
2,262
3.265625
3
[]
no_license
--- layout: post title: Weighing the Pros and Cons of Working Remotely date: 2023-06-16 10:00:00 tags: - Transaction Management hidden: false excerpt: What you need to know before transitioning to a work-from-home setup. enclosure: pullquote: >- Whether or not you're a good fit for working from home depends on your work style and preferences. enclosure_type: video/mp4 enclosure_time: use_youtube_image: false youtube_alternate_image: /uploads/high-angle-desk-arrangement-with-laptop.jpg youtube_code: --- Many professionals have chosen to work from home in recent years. For real estate agents, it’s an option that can provide a range of benefits. Some of the tasks that we have to do daily, such as following up on leads and scheduling showings, can easily be done without leaving the house. However, it is important to carefully consider the pros and cons of a work-from-home setup before making the transition. In terms of advantages, **the flexibility that working from home offers is a huge plus.** You can create your own schedule and work at your own pace, which means you have more control over your work-life balance. This is especially important in the real estate industry where you may have to work irregular hours to accommodate your clients. Additionally, working from home can help you save money on transportation, utilities, and meals. **{% include pullquote.html %}** Despite the benefits, there are also potential drawbacks to working from home. One of the biggest challenges is isolation. You may miss the social interactions and sense of community that come with working in an office environment. It can also be difficult to separate your work life from your personal life, which may lead to burnout. Additionally, **working from home may require more self-discipline** since there are often more distractions at home than in an office setting. Plus, it could be challenging to set boundaries with family members or roommates who don’t understand the importance of your work. Ultimately, whether or not working from home is a good fit for you depends on your work style and preferences. If you need help deciding if you should work from home or have any questions about real estate, call or email me. I’d love to help you.
JavaScript
UTF-8
515
2.546875
3
[]
no_license
const jwt = require('jsonwebtoken'); const config = require('config'); module.exports = function(req, res, next) { //Conseguir el OTken dle Header const token = req.header('x-auth-token'); //Checar si no es el token if (!token) { return res.status(401).json({ msg: 'No estas autorizado perro' }); } try { const decoded = jwt.verify(token, config.get('jwtSecret')); req.user = decoded.user; next(); } catch (error) { res.status(401).json({ msg: 'El token no es valido' }); } };