repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Polygalaceae/Polygala/Polygala violacea/Polygala brizoides brizoides/README.md
175
# Polygala brizoides var. brizoides VARIETY #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Lonchocarpus/Lonchocarpus bicolor/README.md
186
# Lonchocarpus bicolor M.Sousa SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Lecanoromycetes/Ostropales/Thelotremataceae/Thelotrema/Thelotrema cameroonensis/README.md
227
# Thelotrema cameroonensis C.W. Dodge SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Ann. Mo. bot. Gdn 40: 342 (1953) #### Original name Thelotrema cameroonensis C.W. Dodge ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Sphaerella/Sphaerella acerina/README.md
200
# Sphaerella acerina (Wallr.) Sacc. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Sphaeria acerina (Rehm) Cooke & Plowr. ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Bacillariophyta/Bacillariophyceae/Thalassiophysales/Catenulaceae/Amphora/Amphora macilenta/README.md
183
# Amphora macilenta Gregory SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Prosthechea/Prosthechea chacaoensis/ Syn. Epidendrum chacaoense/README.md
186
# Epidendrum chacaoense Rchb.f. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
xiyangyuge/boxing
boxing-impl/src/main/java/com/bilibili/boxing_impl/ui/BoxingViewActivity.java
11625
/* * Copyright (C) 2017 Bilibili * * 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 com.bilibili.boxing_impl.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import com.bilibili.boxing.AbsBoxingViewActivity; import com.bilibili.boxing.Boxing; import com.bilibili.boxing.model.BoxingManager; import com.bilibili.boxing.model.entity.BaseMedia; import com.bilibili.boxing.model.entity.impl.ImageMedia; import com.bilibili.boxing.model.task.IMediaTask; import com.bilibili.boxing_impl.BoxingResHelper; import com.bilibili.boxing_impl.R; import com.bilibili.boxing_impl.view.HackyViewPager; import java.util.ArrayList; import java.util.List; /** * An Activity to show raw image by holding {@link BoxingViewFragment}. * * @author ChenSL */ public class BoxingViewActivity extends AbsBoxingViewActivity { public static final String EXTRA_TYPE_BACK = "com.bilibili.boxing_impl.ui.BoxingViewActivity.type_back"; HackyViewPager mGallery; ProgressBar mProgressBar; private boolean mNeedEdit; private boolean mNeedLoading; private boolean mFinishLoading; private boolean mNeedAllCount = true; private int mCurrentPage; private int mTotalCount; private int mStartPos; private int mPos; private int mMaxCount; private String mAlbumId; private Toolbar mToolbar; private ImagesAdapter mAdapter; private ImageMedia mCurrentImageItem; private Button mOkBtn; private ArrayList<BaseMedia> mImages; private ArrayList<BaseMedia> mSelectedImages; private MenuItem mSelectedMenuItem; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_boxing_view); createToolbar(); initData(); initView(); startLoading(); } private void createToolbar() { mToolbar = (Toolbar) findViewById(R.id.nav_top_bar); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); getSupportActionBar().setDisplayShowTitleEnabled(false); } private void initData() { mSelectedImages = getSelectedImages(); mAlbumId = getAlbumId(); mStartPos = getStartPos(); mNeedLoading = BoxingManager.getInstance().getBoxingConfig().isNeedLoading(); mNeedEdit = BoxingManager.getInstance().getBoxingConfig().isNeedEdit(); mMaxCount = getMaxCount(); mImages = new ArrayList<>(); if (!mNeedLoading && mSelectedImages != null) { mImages.addAll(mSelectedImages); } } private void initView() { mAdapter = new ImagesAdapter(getSupportFragmentManager()); mOkBtn = (Button) findViewById(R.id.image_items_ok); mGallery = (HackyViewPager) findViewById(R.id.pager); mProgressBar = (ProgressBar) findViewById(R.id.loading); mGallery.setAdapter(mAdapter); mGallery.addOnPageChangeListener(new OnPagerChangeListener()); if (!mNeedEdit) { View chooseLayout = findViewById(R.id.item_choose_layout); chooseLayout.setVisibility(View.GONE); } else { setOkTextNumber(); mOkBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finishByBackPressed(false); } }); } } private void setOkTextNumber() { if (mNeedEdit) { int selectedSize = mSelectedImages.size(); int size = Math.max(mSelectedImages.size(), mMaxCount); mOkBtn.setText(getString(R.string.boxing_image_preview_ok_fmt, String.valueOf(selectedSize) , String.valueOf(size))); mOkBtn.setEnabled(selectedSize > 0); } } private void finishByBackPressed(boolean value) { Intent intent = new Intent(); intent.putParcelableArrayListExtra(Boxing.EXTRA_SELECTED_MEDIA, mSelectedImages); intent.putExtra(EXTRA_TYPE_BACK, value); setResult(RESULT_OK, intent); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mNeedEdit) { getMenuInflater().inflate(R.menu.activity_boxing_image_viewer, menu); mSelectedMenuItem = menu.findItem(R.id.menu_image_item_selected); if (mCurrentImageItem != null) { setMenuIcon(mCurrentImageItem.isSelected()); } else { setMenuIcon(false); } return true; } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.menu_image_item_selected) { if (mCurrentImageItem == null) { return false; } if (mSelectedImages.size() >= mMaxCount && !mCurrentImageItem.isSelected()) { String warning = getString(R.string.boxing_max_image_over_fmt, mMaxCount); Toast.makeText(this, warning, Toast.LENGTH_SHORT).show(); return true; } if (mCurrentImageItem.isSelected()) { cancelImage(); } else { if (!mSelectedImages.contains(mCurrentImageItem)) { if (mCurrentImageItem.isGifOverSize()) { Toast.makeText(getApplicationContext(), R.string.boxing_gif_too_big, Toast.LENGTH_SHORT).show(); return true; } mCurrentImageItem.setSelected(true); mSelectedImages.add(mCurrentImageItem); } } setOkTextNumber(); setMenuIcon(mCurrentImageItem.isSelected()); return true; } return super.onOptionsItemSelected(item); } private void cancelImage() { if (mSelectedImages.contains(mCurrentImageItem)) { mSelectedImages.remove(mCurrentImageItem); } mCurrentImageItem.setSelected(false); } private void setMenuIcon(boolean isSelected) { if (mNeedEdit) { mSelectedMenuItem.setIcon(isSelected ? BoxingResHelper.getMediaCheckedRes(): BoxingResHelper.getMediaUncheckedRes()); } } @Override public void startLoading() { if (!mNeedLoading) { mCurrentImageItem = (ImageMedia) mSelectedImages.get(mStartPos); if (mStartPos > 0 && mStartPos < mSelectedImages.size()) { mGallery.setCurrentItem(mStartPos, false); } mToolbar.setTitle(getString(R.string.boxing_image_preview_title_fmt, String.valueOf(mStartPos + 1) , String.valueOf(mSelectedImages.size()))); mProgressBar.setVisibility(View.GONE); mGallery.setVisibility(View.VISIBLE); mAdapter.setMedias(mImages); } else { loadMedia(mAlbumId, mStartPos, mCurrentPage); mAdapter.setMedias(mImages); } } private void loadMedia(String albumId, int startPos, int page) { this.mPos = startPos; loadMedias(page, albumId); } @Override public void showMedia(@Nullable List<BaseMedia> medias, int totalCount) { if (medias == null || totalCount <= 0) { return; } mImages.addAll(medias); mAdapter.notifyDataSetChanged(); checkSelectedMedia(mImages, mSelectedImages); setupGallery(); if (mToolbar != null && mNeedAllCount) { mToolbar.setTitle(getString(R.string.boxing_image_preview_title_fmt, String.valueOf(++mPos), String.valueOf(totalCount))); mNeedAllCount = false; } loadOtherPagesInAlbum(totalCount); } private void setupGallery() { int startPos = mStartPos; if (mGallery == null || startPos < 0) { return; } if (startPos < mImages.size() && !mFinishLoading) { mGallery.setCurrentItem(mStartPos, false); mCurrentImageItem = (ImageMedia) mImages.get(startPos); mProgressBar.setVisibility(View.GONE); mGallery.setVisibility(View.VISIBLE); mFinishLoading = true; invalidateOptionsMenu(); } else if (startPos >= mImages.size()) { mProgressBar.setVisibility(View.VISIBLE); mGallery.setVisibility(View.GONE); } } private void loadOtherPagesInAlbum(int totalCount) { mTotalCount = totalCount; if (mCurrentPage <= (mTotalCount / IMediaTask.PAGE_LIMIT)) { mCurrentPage++; loadMedia(mAlbumId, mStartPos, mCurrentPage); } } @Override protected void onSaveInstanceState(Bundle outState) { if (mSelectedImages != null) { outState.putParcelableArrayList(Boxing.EXTRA_SELECTED_MEDIA, mSelectedImages); } outState.putString(Boxing.EXTRA_ALBUM_ID, mAlbumId); super.onSaveInstanceState(outState); } @Override public void onBackPressed() { finishByBackPressed(true); } private class ImagesAdapter extends FragmentStatePagerAdapter { private ArrayList<BaseMedia> mMedias; ImagesAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { return BoxingRawImageFragment.newInstance((ImageMedia) mMedias.get(i)); } @Override public int getCount() { return mMedias == null ? 0 : mMedias.size(); } public void setMedias(ArrayList<BaseMedia> medias) { this.mMedias = medias; notifyDataSetChanged(); } } private class OnPagerChangeListener extends ViewPager.SimpleOnPageChangeListener { @Override public void onPageSelected(int position) { if (mToolbar != null && position < mImages.size()) { mToolbar.setTitle(getString(R.string.boxing_image_preview_title_fmt, String.valueOf(position + 1) , mNeedLoading ? String.valueOf(mTotalCount) : String.valueOf(mImages.size()))); mCurrentImageItem = (ImageMedia) mImages.get(position); invalidateOptionsMenu(); } } } }
apache-2.0
sailzeng/zcelib
src/commsvr/wormholesvrd/wormhole_proxyprocess.cpp
23023
#include "wormhole_predefine.h" #include "wormhole_proxyprocess.h" #include "wormhole_application.h" #include "wormhole_stat_define.h" //=================================================================================================== Interface_WH_Proxy::Interface_WH_Proxy() { } Interface_WH_Proxy::~Interface_WH_Proxy() { } Interface_WH_Proxy::PROXY_TYPE Interface_WH_Proxy::str_to_proxytype(const char *str_proxy) { if (0 == strcasecmp(str_proxy, "ECHO")) { return PROXY_TYPE_ECHO; } else if (0 == strcasecmp(str_proxy, "TRANSMIT")) { return PROXY_TYPE_TRANSMIT; } else if (0 == strcasecmp(str_proxy, "BROADCAST")) { return PROXY_TYPE_BROADCAST; } else if (0 == strcasecmp(str_proxy, "MODULO_UID")) { return PROXY_TYPE_MODULO_UID; } else if (0 == strcasecmp(str_proxy, "MODULO_SENDSVCID")) { return PROXY_TYPE_MODULO_SENDSVCID; } else { return INVALID_PROXY_TYPE; } } //代理接口制造的工厂 Interface_WH_Proxy *Interface_WH_Proxy::create_proxy_factory(PROXY_TYPE proxytype) { Interface_WH_Proxy *tmpintface = NULL; ZCE_LOG(RS_INFO, "Interface_Proxy_Process::CreatePorxyFactory PROXY_TYPE: %d.", proxytype); switch (proxytype) { // 回显服务器 case PROXY_TYPE_ECHO: { tmpintface = new Echo_Proxy_Process(); break; } // 透转转发的方式 case PROXY_TYPE_TRANSMIT: { tmpintface = new Transmit_Proxy(); break; } // 对数据进行拷贝分发广播 case PROXY_TYPE_BROADCAST: { tmpintface = new Broadcast_ProxyProcess(); break; } // DBPROXY的模式,采用UIN取模的方式的到服务器的ID case PROXY_TYPE_MODULO_UID: { tmpintface = new Modulo_ProxyProcess(Modulo_ProxyProcess::MODULO_UID); break; } // DBPROXY的模式,采用APPID和UIN的方式的到服务器的ID case PROXY_TYPE_MODULO_SENDSVCID: { tmpintface = new Modulo_ProxyProcess(Modulo_ProxyProcess::MODULO_SENDSVC_ID); break; } default: { // 错误 ZCE_LOG(RS_ERROR, "Error Proxy Type define. Please check you code. "); return NULL; } } return tmpintface; } int Interface_WH_Proxy::init_proxy_instance() { // int ret =0; // 初始化MMAP内存的PIPE zerg_mmap_pipe_ = Soar_MMAP_BusPipe::instance(); return 0; } //读取配置 int Interface_WH_Proxy::get_proxy_config(const ZCE_Conf_PropertyTree *conf_tree) { ZCE_UNUSED_ARG(conf_tree); return 0; } //=================================================================================================== Echo_Proxy_Process::Echo_Proxy_Process() { } Echo_Proxy_Process::~Echo_Proxy_Process() { } int Echo_Proxy_Process::get_proxy_config(const ZCE_Conf_PropertyTree *conf_tree) { // int ret = Interface_WH_Proxy::get_proxy_config(conf_tree); if (ret != 0) { return ret; } return 0; } int Echo_Proxy_Process::process_proxy(Zerg_App_Frame *proc_frame) { ZCE_LOGMSG_DEBUG(RS_DEBUG, "Receive a echo frame to process," "send svr:[%u|%u], " "recv svr:[%u|%u], " "frame_uin:%u, " "frame_cmd:%u, " "frame_len:%u. ", proc_frame->send_service_.services_type_, proc_frame->send_service_.services_id_, proc_frame->recv_service_.services_type_, proc_frame->recv_service_.services_id_, proc_frame->frame_uid_, proc_frame->frame_command_, proc_frame->frame_length_); int ret = 0; // 内部处理的命令 bool bsnderr; if (proc_frame->is_internal_process(bsnderr) == true) { ZCE_LOG(RS_DEBUG, "Receive a internal command, frame_uin:%u, frame_command:%u. ", proc_frame->frame_uid_, proc_frame->frame_command_); return 0; } // 返回这个帧 proc_frame->exchange_rcvsnd_svcid(); ret = zerg_mmap_pipe_->push_back_sendpipe(proc_frame); // if (ret != 0) { return SOAR_RET::ERR_PROXY_SEND_PIPE_IS_FULL; } ZCE_LOGMSG_DEBUG(RS_DEBUG, "Echo to [%u|%u], frame_uin:%u, frame_command:%u, frame_len:%u. ", proc_frame->recv_service_.services_type_, proc_frame->recv_service_.services_id_, proc_frame->frame_uid_, proc_frame->frame_command_, proc_frame->frame_length_); return 0; } //=================================================================================================== //直接进行转发处理,不对数据帧进行任何处理 Transmit_Proxy::Transmit_Proxy() { } Transmit_Proxy::~Transmit_Proxy() { } int Transmit_Proxy::get_proxy_config(const ZCE_Conf_PropertyTree *conf_tree) { // int ret = Interface_WH_Proxy::get_proxy_config(conf_tree); if (ret != 0) { return ret; } return 0; } int Transmit_Proxy::process_proxy(Zerg_App_Frame *proc_frame) { ZCE_LOGMSG_DEBUG(RS_DEBUG, "Receive a transmit frame to process," "send svr:[%u|%u], " "recv svr:[%u|%u], " "frame_uin:%u, " "frame_cmd:%u, " "frame_len:%u. ", proc_frame->send_service_.services_type_, proc_frame->send_service_.services_id_, proc_frame->recv_service_.services_type_, proc_frame->recv_service_.services_id_, proc_frame->frame_uid_, proc_frame->frame_command_, proc_frame->frame_length_); int ret = 0; // 内部处理的命令,跳过 bool bsnderr; if (proc_frame->is_internal_process(bsnderr) == true) { ZCE_LOG(RS_DEBUG, "Receive a internal command, frame_uin:%u, frame_command:%u. ", proc_frame->frame_uid_, proc_frame->frame_command_); return 0; } ret = zerg_mmap_pipe_->push_back_sendpipe(proc_frame); // if (ret != 0) { return SOAR_RET::ERR_PROXY_SEND_PIPE_IS_FULL; } ZCE_LOGMSG_DEBUG(RS_DEBUG, "Transmit to [%u|%u], frame_uin:%u, frame_command:%u, frame_len:%u, trans_id[%u]. ", proc_frame->recv_service_.services_type_, proc_frame->recv_service_.services_id_, proc_frame->frame_uid_, proc_frame->frame_command_, proc_frame->frame_length_, proc_frame->transaction_id_); return 0; } //=================================================================================================== //将数据复制转发给所有配置的服务器 Broadcast_ProxyProcess::Broadcast_ProxyProcess() : Interface_WH_Proxy(), broadcast_svctype_(0), broadcast_svcnum_(0) { memset(broadcast_svcid_, 0, sizeof(broadcast_svcid_)); } Broadcast_ProxyProcess::~Broadcast_ProxyProcess() { } int Broadcast_ProxyProcess::get_proxy_config(const ZCE_Conf_PropertyTree *conf_tree) { // int ret = Interface_WH_Proxy::get_proxy_config(conf_tree); if (ret != 0) { return ret; } ret = conf_tree->path_get_leaf("BROADCAST_CFG", "BROADCAST_SVCTYPE", broadcast_svctype_); if (0 != ret || broadcast_svctype_ == SERVICES_ID::INVALID_SERVICES_TYPE) { SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } ret = conf_tree->path_get_leaf("BROADCAST_CFG", "BROADCAST_NUM", broadcast_svcnum_); ZCE_LOG(RS_DEBUG, "Broadcast service num: %u.", broadcast_svcnum_); if (0 != ret || broadcast_svcnum_ == 0 || broadcast_svcnum_ > MAX_NUM_COPY_SVC) { SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } //注意是从1开始 for (size_t i = 0; i < broadcast_svcnum_; ++i) { ret = conf_tree->pathseq_get_leaf("BROADCAST_CFG", "BROADCAST_SVCID_", i + 1, broadcast_svcid_[i]); ZCE_LOG(RS_DEBUG, "Broadcast service id: %hu.%u.", broadcast_svctype_, broadcast_svcid_[i]); if (0 != ret) { SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } } // 检查是否有重复的ID std::list <uint32_t> check_list; for (size_t i = 0; i < broadcast_svcnum_; ++i) { check_list.push_back(broadcast_svcid_[i]); } // 不讲求效率的地方 check_list.sort(); check_list.unique(); if (check_list.size() != broadcast_svcnum_) { ZCE_LOG(RS_ERROR, "Cfg file have repeat svc id,Please check."); SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } return 0; } // int Broadcast_ProxyProcess::process_proxy(Zerg_App_Frame *proc_frame) { int ret = 0; // 输出包头,看看 proc_frame->dumpoutput_framehead("[FROM RECV FRAME]", RS_DEBUG); // 内部处理的命令,跳过 bool bsnderr; if (proc_frame->is_internal_process(bsnderr) == true) { ZCE_LOG(RS_DEBUG, "Receive a internal command, frame_uin:%u, frame_command:%u. ", proc_frame->frame_uid_, proc_frame->frame_command_); return 0; } // 这样处理是否好,我不知道, if (proc_frame->recv_service_.services_type_ != broadcast_svctype_) { ZCE_LOG(RS_ERROR, "Can't Porcess services_type_%u. ", proc_frame->recv_service_.services_type_); return SOAR_RET::ERR_PROXY_RCVSVC_TYPE_ERROR; } // 复制生成N个帧,转发到不同的服务器 for (size_t i = 0; i < broadcast_svcnum_; ++i) { // 修改为新的ID proc_frame->recv_service_.services_id_ = broadcast_svcid_[i]; ret = zerg_mmap_pipe_->push_back_sendpipe(proc_frame); // if (ret != 0) { return ret; } ZCE_LOGMSG_DEBUG(RS_DEBUG, "Copy to [%u|%u], frame_uin:%u, frame_command:%u, frame_len:%u, trans_id[%u]. ", proc_frame->recv_service_.services_type_, proc_frame->recv_service_.services_id_, proc_frame->frame_uid_, proc_frame->frame_command_, proc_frame->frame_length_, proc_frame->transaction_id_); } return 0; } //=================================================================================================== Modulo_ProxyProcess::Modulo_ProxyProcess(MODULO_TYPE modulo_type) : Interface_WH_Proxy(), modulo_type_(modulo_type) { memset(modulo_svcid_, 0, sizeof(modulo_svcid_)); } Modulo_ProxyProcess::~Modulo_ProxyProcess() { } int Modulo_ProxyProcess::get_proxy_config(const ZCE_Conf_PropertyTree *conf_tree) { // int ret = Interface_WH_Proxy::get_proxy_config(conf_tree); if (ret != 0) { return ret; } ret = conf_tree->path_get_leaf("MODULO_CFG", "MODULO_SVCTYPE", modulo_svctype_); if (0 != ret || modulo_svctype_ == SERVICES_ID::INVALID_SERVICES_TYPE) { SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } ret = conf_tree->path_get_leaf("MODULO_CFG", "MODULO_NUM", modulo_svcnum_); ZCE_LOG(RS_DEBUG, "Modulo service num: %u.", modulo_svcnum_); if (0 != ret || modulo_svcnum_ == 0 || modulo_svcnum_ > MAX_NUM_MODULO_SVC) { SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } //注意是从1开始 for (size_t i = 0; i < modulo_svcnum_; ++i) { ret = conf_tree->pathseq_get_leaf("MODULO_CFG", "MODULO_SVCID_", i + 1, modulo_svcid_[i]); ZCE_LOG(RS_DEBUG, "Broadcast service id: %hu.%u.", modulo_svctype_, modulo_svcid_[i]); if (0 != ret) { SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } } // 检查是否有重复的ID std::list <uint32_t> check_list; for (size_t i = 0; i < modulo_svcnum_; ++i) { check_list.push_back(modulo_svcid_[i]); } // 不讲求效率的地方 check_list.sort(); check_list.unique(); if (check_list.size() != modulo_svcnum_) { ZCE_LOG(RS_ERROR, "Cfg file have repeat svc id,Please check."); SOAR_CFG_READ_FAIL(RS_ERROR); return SOAR_RET::ERROR_GET_CFGFILE_CONFIG_FAIL; } return 0; } // int Modulo_ProxyProcess::process_proxy(Zerg_App_Frame *proc_frame) { int ret = 0; // 输出包头,看看 proc_frame->dumpoutput_framehead("[FROM RECV FRAME]", RS_DEBUG); // 内部处理的命令,跳过 bool bsnderr; if (proc_frame->is_internal_process(bsnderr) == true) { ZCE_LOG(RS_DEBUG, "Receive a internal command, frame_uin:%u, frame_command:%u. ", proc_frame->frame_uid_, proc_frame->frame_command_); return 0; } // 这样处理是否好,我不知道, if (proc_frame->recv_service_.services_type_ != modulo_svctype_) { ZCE_LOG(RS_ERROR, "Can't Porcess services_type_%u. ", proc_frame->recv_service_.services_type_); return SOAR_RET::ERR_PROXY_RCVSVC_TYPE_ERROR; } uint32_t mod_number = 0; if ( MODULO_UID == modulo_type_) { mod_number = proc_frame->frame_uid_; } else if (MODULO_SENDSVC_ID == modulo_type_) { mod_number = proc_frame->send_service_.services_id_; } else { ZCE_ASSERT(true); } proc_frame->recv_service_.services_id_ = modulo_svcid_[mod_number % modulo_svcnum_]; ret = zerg_mmap_pipe_->push_back_sendpipe(proc_frame); // if (ret != 0) { return ret; } ZCE_LOGMSG_DEBUG(RS_DEBUG, "Copy to [%u|%u], frame_uin:%u, frame_command:%u, frame_len:%u, trans_id[%u]. ", proc_frame->recv_service_.services_type_, proc_frame->recv_service_.services_id_, proc_frame->frame_uid_, proc_frame->frame_command_, proc_frame->frame_length_, proc_frame->transaction_id_); return 0; } //const DBModalMGRouteItem *DBModalMGProxyInfo::find_route(unsigned int uid) //{ // if (route_cfg_.size() == 0) // { // // 没有配置路由,这一定是个错误 // ZCE_LOG(RS_ERROR,"[%s] no route configed", __ZCE_FUNC__); // return NULL; // } // // DBModalMGRouteItem tmp; // // 取uid的低16位作为hash值,应该够随机的 // tmp.hash_ = (uid & 0xFFFF); // // std::vector<DBModalMGRouteItem>::iterator iter // = std::upper_bound(route_cfg_.begin(), route_cfg_.end(), tmp); // // // 如果指向路由表的末尾,那么实际上应该是是路由表的第一项 // if (iter == route_cfg_.end()) // { // iter = route_cfg_.begin(); // } // // return &(*iter); //} ////=================================================================================================== // ////按照DB取模进行Proxy转发,用于DBServer和金融服务器 //DBModalProxyProcess::DBModalProxyProcess(): // Interface_WH_Proxy() //{ //} // //DBModalProxyProcess::~DBModalProxyProcess() //{ // std::map<unsigned short, DBModalProxyInfo*>::iterator iter = dbmodal_proxy_map_.begin(); // // for (; iter != dbmodal_proxy_map_.end(); iter++) // { // // 释放分配的内存 // delete iter->second; // iter->second = NULL; // } //} // // //int DBModalProxyProcess::get_proxy_config(const ZCE_Conf_PropertyTree *conf_tree) //{ // // int ret = 0; // // //得到过滤得命令 // ret = Interface_WH_Proxy::get_proxy_config(conf_tree); // if (ret != 0) // { // return ret; // } // // // // for (unsigned int i = 0; i < cfg->dbmodal_info_.route_num_; i++) // { // DBModalProxyInfo *dbmodal_proxy_info = new DBModalProxyInfo(); // conf_proxysvr::RouteInfo *route_info = &(cfg->dbmodal_info_.route_info_[i]); // // dbmodal_proxy_info->distribute_module_ = route_info->distribute_module_; // dbmodal_proxy_info->distribute_offset_ = route_info->distribute_offset_; // dbmodal_proxy_info->router_svr_type_ = route_info->svr_type_; // // ZCE_LOG(RS_INFO,"[DBModalProxy] route_svr_type:%u, distribute_offset:%u, distribute_module:%u", // dbmodal_proxy_info->router_svr_type_, // dbmodal_proxy_info->distribute_offset_, // dbmodal_proxy_info->distribute_module_); // // dbmodal_proxy_info->normal_router_cfg_.resize(dbmodal_proxy_info->distribute_module_); // dbmodal_proxy_info->clone_router_cfg_.resize(dbmodal_proxy_info->distribute_module_); // // for (unsigned int k = 0; k < dbmodal_proxy_info->distribute_module_; k++) // { // dbmodal_proxy_info->normal_router_cfg_[k] = route_info->svr_id_[k].nomal_service_id_; // // if (route_info->svr_id_[k].clone_service_id_) // { // dbmodal_proxy_info->clone_router_cfg_[k] = route_info->svr_id_[k].clone_service_id_; // } // else // { // dbmodal_proxy_info->clone_router_cfg_[k] = SERVICES_ID::INVALID_SERVICES_ID; // } // // ZCE_LOG(RS_INFO,"[DBModalProxy] normal service:%u|%u, clone service:%u|%u, passby service:%u|%u", // dbmodal_proxy_info->router_svr_type_, dbmodal_proxy_info->normal_router_cfg_[k], // dbmodal_proxy_info->router_svr_type_, dbmodal_proxy_info->clone_router_cfg_[k]); // } // // dbmodal_proxy_map_.insert(std::make_pair<unsigned short, DBModalProxyInfo*> // (dbmodal_proxy_info->router_svr_type_, dbmodal_proxy_info)); // } // // return 0; //} // ////要处理的帧 //int DBModalProxyProcess::process_proxy(Zerg_App_Frame *proc_frame) //{ // ZCE_LOG(RS_DEBUG,"Receive a dbmode frame to process," // "send svr:[%u|%u], " // "recv svr:[%u|%u], " // "frame_uid:%u, " // "frame_cmd:%u, " // "frame_len:%u. ", // proc_frame->send_service_.services_type_, // proc_frame->send_service_.services_id_, // proc_frame->recv_service_.services_type_, // proc_frame->recv_service_.services_id_, // proc_frame->frame_uid_, // proc_frame->frame_command_, // proc_frame->frame_length_); // // int ret = 0; // // 内部处理的命令,跳过 // bool bsnderr; // // if (proc_frame->is_internal_process(bsnderr) == true) // { // ZCE_LOG(RS_INFO,"Receive a internal command, frame_uin:%u, frame_command:%u. ", // proc_frame->frame_uid_, proc_frame->frame_command_); // return 0; // } // // std::map<unsigned short, DBModalProxyInfo*>::iterator iter = // dbmodal_proxy_map_.find(proc_frame->recv_service_.services_type_); // // if (iter != dbmodal_proxy_map_.end()) // { // // 要转发的类型已配置, 获取对应路由信息 // DBModalProxyInfo *dbmodal_proxy_info = iter->second; // // //------------------------------------------------------------------ // unsigned int uid = proc_frame->frame_uid_; // // // 过滤掉uid为0的数据 // if (uid == 0 ) // { // // proc_frame->dumpoutput_framehead("[FROM RECV FRAME]", RS_ERROR); // // Soar_Stat_Monitor::instance()->increase_once(WORMHOLE_TRANS_PKG_ERROR); // // return SOAR_RET::ERROR_APPFRAME_ERROR; // } // // // 关键代码处 // unsigned int mod = // (uid >> dbmodal_proxy_info->distribute_offset_) % dbmodal_proxy_info->distribute_module_; // // // ------------------------------------------------------------------ // proc_frame->recv_service_.services_type_ = dbmodal_proxy_info->router_svr_type_; // proc_frame->recv_service_.services_id_ = dbmodal_proxy_info->normal_router_cfg_[mod]; // // // 日志调整为DEBUG级别的 // ZCE_LOG(RS_DEBUG,"Send to main services [%u|%u], frame_uin:%u, " // "frame_command:%u, frame_len:%u, trans_id[%u]. ", // proc_frame->recv_service_.services_type_, // proc_frame->recv_service_.services_id_, // proc_frame->frame_uid_, // proc_frame->frame_command_, // proc_frame->frame_length_, // proc_frame->transaction_id_); // // // 只生成了一个帧 // int ret = zerg_mmap_pipe_->push_back_sendpipe(proc_frame); // // // // if (ret != 0) // { // return SOAR_RET::ERR_PROXY_SEND_PIPE_IS_FULL; // } // // // 如果有备份路由,则将数据转发给一个备份的代理 // if (dbmodal_proxy_info->clone_router_cfg_[mod] != SERVICES_ID::INVALID_SERVICES_ID ) // { // // proc_frame->recv_service_.services_id_ = dbmodal_proxy_info->clone_router_cfg_[mod]; // ZCE_LOG(RS_INFO,"Send to backup services [%u|%u], frame_uin:%u," // " frame_command:%u, frame_len:%u, back trans_id[%u]. ", // proc_frame->recv_service_.services_type_, // proc_frame->recv_service_.services_id_, // proc_frame->frame_uid_, // proc_frame->frame_command_, // proc_frame->frame_length_, // proc_frame->backfill_trans_id_); // // ret = zerg_mmap_pipe_->push_back_sendpipe(proc_frame); // // if (ret != 0) // { // return SOAR_RET::ERR_PROXY_SEND_PIPE_IS_FULL; // } // } // // } // // 另外一个路由方向的事情,直接透传 // else // { // // // // 加一条日志,方便跟踪 // ZCE_LOG(RS_INFO,"Send back [%u|%u], frame_uin:%u, frame_command:%u, frame_len:%u. ", // proc_frame->recv_service_.services_type_, // proc_frame->recv_service_.services_id_, // proc_frame->frame_uid_, // proc_frame->frame_command_, // proc_frame->frame_length_); // // ret = zerg_mmap_pipe_->push_back_sendpipe(proc_frame); // // // // if (ret != 0) // { // return SOAR_RET::ERR_PROXY_SEND_PIPE_IS_FULL; // } // } // // return 0; //}
apache-2.0
fairchild/one-mirror
include/Template.h
6486
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ #ifndef TEMPLATE_H_ #define TEMPLATE_H_ #include <iostream> #include <map> #include <vector> #include "Attribute.h" using namespace std; /** * Base class for file templates. A template is a file (or a tring for the * matter of fact) containing a set of attribute definitions of the form: * NAME = VALUE * where NAME is a string representing the name of the attribute, and VALUE can * be a single string or a vector value (array of string pairs). The file can * contain several attributes with the same name. */ class Template { public: Template(bool _replace_mode = false, const char _separator = '=', const char * _xml_root = "TEMPLATE"): replace_mode(_replace_mode), separator(_separator), xml_root(_xml_root){}; /** * The class destructor frees all the attributes conforming the template */ virtual ~Template(); /** * Parse a string representing the template, each attribute is inserted * in the template class. * @param parse_str string with template attributes * @param error_msg error string, must be freed by the calling funtion. * This string is null if no error occurred. * @return 0 on success. */ int parse(const string &parse_str, char **error_msg); /** * Parse a template file. * @param filename of the template file * @param error_msg error string, must be freed by the calling funtion. * This string is null if no error occurred. * @return 0 on success. */ int parse(const char * filename, char **error_msg); /** * Marshall a template. This function generates a single string with the * template attributes ("VAR=VAL<delim>..."). * @param str_tempalte string that hold the template * @param delim to separate attributes */ void marshall(string &str, const char delim='\n'); /** * Writes the template in a simple xml string: * <template> * <single>value</single> * <vector> * <attr>value</attr> * ... * </vector> * ... * </template> * The name of the root element is set when the Template object is created * @param xml string that hold the xml template representation * @return a reference to the generated string */ string& to_xml(string& xml) const; /** * Writes the template in a plain text string * @param str string that hold the template representation * @return a reference to the generated string */ string& to_str(string& str) const; /** * Sets a new attribute, the attribute MUST BE ALLOCATED IN THE HEAP, and * will be freed when the template destructor is called. * @param attr pointer to the attribute */ virtual void set(Attribute * attr); /** * Removes an attribute from the template. The attributes are returned. The * attributes MUST be freed by the calling funtion * @param name of the attribute * @param values a vector containing a pointer to the attributes * @returns the number of attributes removed */ virtual int remove( const string& name, vector<Attribute *>& values); /** * Gets all the attributes with the given name. * @param name the attribute name. * @returns the number of elements in the vector */ virtual int get( const string& name, vector<const Attribute*>& values) const; /** * Gets all the attributes with the given name, non-const version * @param name the attribute name. * @returns the number of elements in the vector */ virtual int get( const string& name, vector<Attribute*>& values); /** * Gets the value of a Single attributes (string) with the given name. * @param name the attribute name. * @param value the attribute value, a string, "" if the attribute is not * defined or not Single */ virtual void get( string& name, string& value) const; /** * Gets the value of a Single attributes (int) with the given name. * @param name the attribute name. * @param value the attribute value, an int, 0 if the attribute is not * defined or not Single */ virtual void get( string& name, int& value) const; friend ostream& operator<<(ostream& os, const Template& t); protected: /** * The template attributes */ multimap<string,Attribute *> attributes; private: bool replace_mode; /** * Mutex to perform just one flex-bison parsing at a time */ static pthread_mutex_t mutex; /** * Character to separate key from value when dump onto a string **/ char separator; /** * Name of the Root element for the XML document */ string xml_root; }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ #endif /*TEMPLATE_H_*/
apache-2.0
resin-io/resin-cli
lib/utils/device/deploy.ts
16586
/** * @license * Copyright 2018-2021 Balena Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as semver from 'balena-semver'; import * as Docker from 'dockerode'; import * as _ from 'lodash'; import { Composition } from 'resin-compose-parse'; import { BuildTask, getAuthConfigObj, LocalImage, RegistrySecrets, } from 'resin-multibuild'; import type { Readable } from 'stream'; import { BALENA_ENGINE_TMP_PATH } from '../../config'; import { ExpectedError } from '../../errors'; import { checkBuildSecretsRequirements, loadProject, makeBuildTasks, tarDirectory, } from '../compose_ts'; import Logger = require('../logger'); import { DeviceAPI, DeviceInfo } from './api'; import * as LocalPushErrors from './errors'; import LivepushManager from './live'; import { displayBuildLog } from './logs'; import { stripIndent } from '../lazy'; const LOCAL_APPNAME = 'localapp'; const LOCAL_RELEASEHASH = 'localrelease'; // Define the logger here so the debug output // can be used everywhere const globalLogger = Logger.getLogger(); export interface DeviceDeployOptions { source: string; deviceHost: string; devicePort?: number; dockerfilePath?: string; registrySecrets: RegistrySecrets; multiDockerignore: boolean; nocache: boolean; nogitignore: boolean; // v13: delete this line noParentCheck: boolean; nolive: boolean; pull: boolean; detached: boolean; services?: string[]; system: boolean; env: string[]; convertEol: boolean; } interface ParsedEnvironment { [serviceName: string]: { [key: string]: string }; } async function environmentFromInput( envs: string[], serviceNames: string[], logger: Logger, ): Promise<ParsedEnvironment> { // A normal environment variable regex, with an added part // to find a colon followed servicename at the start const varRegex = /^(?:([^\s:]+):)?([^\s]+?)=(.*)$/; const ret: ParsedEnvironment = {}; // Populate the object with the servicenames, as it // also means that we can do a fast lookup of whether a // service exists for (const service of serviceNames) { ret[service] = {}; } for (const env of envs) { const maybeMatch = env.match(varRegex); if (maybeMatch == null) { throw new ExpectedError(`Unable to parse environment variable: ${env}`); } const match = maybeMatch!; let service: string | undefined; if (match[1]) { // This is for a service, we check that it actually // exists if (!(match[1] in ret)) { logger.logDebug( `Warning: Cannot find a service with name ${match[1]}. Treating the string as part of the environment variable name.`, ); match[2] = `${match[1]}:${match[2]}`; } else { service = match[1]; } } if (service != null) { ret[service][match[2]] = match[3]; } else { for (const serviceName of serviceNames) { ret[serviceName][match[2]] = match[3]; } } } return ret; } export async function deployToDevice(opts: DeviceDeployOptions): Promise<void> { // Resolve .local addresses to IP to avoid // issue with Windows and rapid repeat lookups. // see: https://github.com/balena-io/balena-cli/issues/1518 if (opts.deviceHost.includes('.local')) { const util = await import('util'); const dns = await import('dns'); const { address } = await util.promisify(dns.lookup)(opts.deviceHost, { family: 4, }); opts.deviceHost = address; } const port = 48484; const api = new DeviceAPI(globalLogger, opts.deviceHost, port); // First check that we can access the device with a ping try { globalLogger.logDebug('Checking we can access device'); await api.ping(); } catch (e) { throw new ExpectedError(stripIndent` Could not communicate with device supervisor at address ${opts.deviceHost}:${port}. Device may not have local mode enabled. Check with: balena device local-mode <device-uuid> `); } const versionError = new Error( 'The supervisor version on this remote device does not support multicontainer local mode. ' + 'Please update your device to balenaOS v2.20.0 or greater from the dashboard.', ); try { const version = await api.getVersion(); globalLogger.logDebug(`Checking device supervisor version: ${version}`); if (!semver.satisfies(version, '>=7.21.4')) { throw new ExpectedError(versionError); } if (!opts.nolive && !semver.satisfies(version, '>=9.7.0')) { globalLogger.logWarn( `Using livepush requires a balena supervisor version >= 9.7.0. A live session will not be started.`, ); opts.nolive = true; } } catch (e) { // Very old supervisor versions do not support /version endpoint // a DeviceAPIError is expected in this case if (e instanceof LocalPushErrors.DeviceAPIError) { throw new ExpectedError(versionError); } else { throw e; } } globalLogger.logInfo(`Starting build on device ${opts.deviceHost}`); const project = await loadProject(globalLogger, { convertEol: opts.convertEol, dockerfilePath: opts.dockerfilePath, multiDockerignore: opts.multiDockerignore, nogitignore: opts.nogitignore, // v13: delete this line noParentCheck: opts.noParentCheck, projectName: 'local', projectPath: opts.source, isLocal: true, }); // Attempt to attach to the device's docker daemon const docker = connectToDocker( opts.deviceHost, opts.devicePort != null ? opts.devicePort : 2375, ); await checkBuildSecretsRequirements(docker, opts.source); globalLogger.logDebug('Tarring all non-ignored files...'); const tarStream = await tarDirectory(opts.source, { composition: project.composition, convertEol: opts.convertEol, multiDockerignore: opts.multiDockerignore, nogitignore: opts.nogitignore, // v13: delete this line }); // Try to detect the device information const deviceInfo = await api.getDeviceInformation(); let buildLogs: Dictionary<string> | undefined; if (!opts.nolive) { buildLogs = {}; } const { awaitInterruptibleTask } = await import('../helpers'); const buildTasks = await awaitInterruptibleTask<typeof performBuilds>( performBuilds, project.composition, tarStream, docker, deviceInfo, globalLogger, opts, buildLogs, ); globalLogger.outputDeferredMessages(); // Print a newline to clearly separate build time and runtime console.log(); const envs = await environmentFromInput( opts.env, Object.getOwnPropertyNames(project.composition.services), globalLogger, ); globalLogger.logDebug('Setting device state...'); // Now set the target state on the device const currentTargetState = await api.getTargetState(); const targetState = generateTargetState( currentTargetState, project.composition, buildTasks, envs, ); globalLogger.logDebug(`Sending target state: ${JSON.stringify(targetState)}`); await api.setTargetState(targetState); // Now that we've set the target state, the device will do it's thing // so we can either just display the logs, or start a livepush session // (whilst also display logs) const promises: Array<Promise<void>> = [streamDeviceLogs(api, opts)]; let livepush: LivepushManager | null = null; if (!opts.nolive) { livepush = new LivepushManager({ api, buildContext: opts.source, buildTasks, docker, logger: globalLogger, composition: project.composition, buildLogs: buildLogs!, deployOpts: opts, }); promises.push(livepush.init()); if (opts.detached) { globalLogger.logLivepush( 'Running in detached mode, no service logs will be shown', ); } globalLogger.logLivepush('Watching for file changes...'); } try { await awaitInterruptibleTask(() => Promise.all(promises)); } finally { // Stop watching files after log streaming ends (e.g. on SIGINT) livepush?.close(); await livepush?.cleanup(); } } async function streamDeviceLogs( deviceApi: DeviceAPI, opts: DeviceDeployOptions, ) { // Only show logs if we're not detaching if (opts.detached) { return; } globalLogger.logInfo('Streaming device logs...'); const { connectAndDisplayDeviceLogs } = await import('./logs'); return connectAndDisplayDeviceLogs({ deviceApi, logger: globalLogger, system: opts.system || false, filterServices: opts.services, maxAttempts: 1001, }); } function connectToDocker(host: string, port: number): Docker { return new Docker({ host, port, Promise: require('bluebird'), }); } async function performBuilds( composition: Composition, tarStream: Readable, docker: Docker, deviceInfo: DeviceInfo, logger: Logger, opts: DeviceDeployOptions, buildLogs?: Dictionary<string>, ): Promise<BuildTask[]> { const multibuild = await import('resin-multibuild'); const buildTasks = await makeBuildTasks( composition, tarStream, deviceInfo, logger, LOCAL_APPNAME, LOCAL_RELEASEHASH, (content) => { if (!opts.nolive) { return LivepushManager.preprocessDockerfile(content); } else { return content; } }, ); logger.logDebug('Probing remote daemon for cache images'); await assignDockerBuildOpts(docker, buildTasks, opts); // If we're passed a build logs object make sure to set it // up properly let logHandlers: ((serviceName: string, line: string) => void) | undefined; if (buildLogs != null) { for (const task of buildTasks) { if (!task.external) { buildLogs[task.serviceName] = ''; } } logHandlers = (serviceName: string, line: string) => { buildLogs[serviceName] += `${line}\n`; }; } logger.logDebug('Starting builds...'); assignOutputHandlers(buildTasks, logger, logHandlers); const localImages = await multibuild.performBuilds( buildTasks, docker, BALENA_ENGINE_TMP_PATH, ); // Check for failures await inspectBuildResults(localImages); const imagesToRemove: string[] = []; // Now tag any external images with the correct name that they should be, // as this won't be done by resin-multibuild await Promise.all( localImages.map(async (localImage) => { if (localImage.external) { // We can be sure that localImage.name is set here, because of the failure code above const image = docker.getImage(localImage.name!); await image.tag({ repo: generateImageName(localImage.serviceName), force: true, }); imagesToRemove.push(localImage.name!); } }), ); await Promise.all( _.uniq(imagesToRemove).map((image) => docker.getImage(image).remove({ force: true }), ), ); return buildTasks; } // Rebuild a single container, execute it on device, and // return the build logs export async function rebuildSingleTask( serviceName: string, docker: Docker, logger: Logger, deviceInfo: DeviceInfo, composition: Composition, source: string, opts: DeviceDeployOptions, // To cancel a running build, you must first find the // container id that it's running in. This is printed in // the logs, so any calller who wants to keep track of // this should provide the following callback containerIdCb?: (id: string) => void, ): Promise<string> { const multibuild = await import('resin-multibuild'); // First we run the build task, to get the new image id let buildLogs = ''; const logHandler = (_s: string, line: string) => { buildLogs += `${line}\n`; if (containerIdCb != null) { const match = line.match(/^\s*--->\s*Running\s*in\s*([a-f0-9]*)\s*$/i); if (match != null) { containerIdCb(match[1]); } } }; const tarStream = await tarDirectory(source, { composition, convertEol: opts.convertEol, multiDockerignore: opts.multiDockerignore, nogitignore: opts.nogitignore, // v13: delete this line }); const task = _.find( await makeBuildTasks( composition, tarStream, deviceInfo, logger, LOCAL_APPNAME, LOCAL_RELEASEHASH, (content) => { if (!opts.nolive) { return LivepushManager.preprocessDockerfile(content); } else { return content; } }, ), { serviceName }, ); if (task == null) { throw new ExpectedError( `Could not find build task for service ${serviceName}`, ); } await assignDockerBuildOpts(docker, [task], opts); await assignOutputHandlers([task], logger, logHandler); const [localImage] = await multibuild.performBuilds( [task], docker, BALENA_ENGINE_TMP_PATH, ); if (!localImage.successful) { throw new LocalPushErrors.BuildError([ { error: localImage.error!, serviceName, }, ]); } return buildLogs; } function assignOutputHandlers( buildTasks: BuildTask[], logger: Logger, logCb?: (serviceName: string, line: string) => void, ) { _.each(buildTasks, (task) => { if (task.external) { task.progressHook = (progressObj) => { displayBuildLog( { serviceName: task.serviceName, message: progressObj.progress }, logger, ); }; } else { task.streamHook = (stream) => { stream.on('data', (buf: Buffer) => { const str = _.trimEnd(buf.toString()); if (str !== '') { displayBuildLog( { serviceName: task.serviceName, message: str }, logger, ); if (logCb) { logCb(task.serviceName, str); } } }); }; } }); } async function getDeviceDockerImages(docker: Docker): Promise<string[]> { const images = await docker.listImages({ all: true }); return _.map(images, 'Id'); } // Mutates buildTasks async function assignDockerBuildOpts( docker: Docker, buildTasks: BuildTask[], opts: DeviceDeployOptions, ): Promise<void> { // Get all of the images on the remote docker daemon, so // that we can use all of them for cache const images = await getDeviceDockerImages(docker); globalLogger.logDebug(`Using ${images.length} on-device images for cache...`); await Promise.all( buildTasks.map(async (task: BuildTask) => { task.dockerOpts = { cachefrom: images, labels: { 'io.resin.local.image': '1', 'io.resin.local.service': task.serviceName, }, t: generateImageName(task.serviceName), nocache: opts.nocache, forcerm: true, pull: opts.pull, }; if (task.external) { task.dockerOpts.authconfig = await getAuthConfigObj( task.imageName!, opts.registrySecrets, ); } else { task.dockerOpts.registryconfig = opts.registrySecrets; } }), ); } function generateImageName(serviceName: string): string { return `local_image_${serviceName}:latest`; } export function generateTargetState( currentTargetState: any, composition: Composition, buildTasks: BuildTask[], env: ParsedEnvironment, ): any { const keyedBuildTasks = _.keyBy(buildTasks, 'serviceName'); const services: { [serviceId: string]: any } = {}; let idx = 1; _.each(composition.services, (opts, name) => { // Get rid of any build specific stuff opts = _.cloneDeep(opts); delete opts.build; delete opts.image; const defaults = { environment: {}, labels: {}, }; opts.environment = _.merge(opts.environment, env[name]); // This function can be called with a subset of the // build tasks, when a single dockerfile has changed // when livepushing, so check the build task exists for // this composition entry (everything else in this // function comes from the composition which doesn't // change) let contract; if (name in keyedBuildTasks) { contract = keyedBuildTasks[name].contract; } services[idx] = { ...defaults, ...opts, ...(contract != null ? { contract } : {}), ...{ imageId: idx, serviceName: name, serviceId: idx, image: generateImageName(name), running: true, }, }; idx += 1; }); const targetState = _.cloneDeep(currentTargetState); delete targetState.local.apps; targetState.local.apps = { 1: { name: LOCAL_APPNAME, commit: LOCAL_RELEASEHASH, releaseId: '1', services, volumes: composition.volumes || {}, networks: composition.networks || {}, }, }; return targetState; } async function inspectBuildResults(images: LocalImage[]): Promise<void> { const failures: LocalPushErrors.BuildFailure[] = []; _.each(images, (image) => { if (!image.successful) { failures.push({ error: image.error!, serviceName: image.serviceName, }); } }); if (failures.length > 0) { throw new LocalPushErrors.BuildError(failures).toString(); } }
apache-2.0
ifu-lobuntu/jbpm
jbpm-installer/db/ddl-scripts/sybase/sybase-jbpm-schema.sql
27014
create table Attachment ( id numeric(19,0) identity not null, accessType int null, attachedAt datetime null, attachmentContentId numeric(19,0) not null, contentType varchar(255) null, name varchar(255) null, attachment_size int null, attachedBy_id varchar(255) null, TaskData_Attachments_Id numeric(19,0) null, primary key (id) ) lock datarows go create table AuditTaskImpl ( id numeric(19,0) identity not null, activationTime datetime null, actualOwner varchar(255) null, createdBy varchar(255) null, createdOn datetime null, deploymentId varchar(255) null, description varchar(255) null, dueDate datetime null, name varchar(255) null, parentId numeric(19,0) not null, priority int not null, processId varchar(255) null, processInstanceId numeric(19,0) not null, processSessionId numeric(19,0) not null, status varchar(255) null, taskId numeric(19,0) null, workItemId numeric(19,0) null, primary key (id) ) lock datarows go create table BAMTaskSummary ( pk numeric(19,0) identity not null, createdDate datetime null, duration numeric(19,0) null, endDate datetime null, processInstanceId numeric(19,0) not null, startDate datetime null, status varchar(255) null, taskId numeric(19,0) not null, taskName varchar(255) null, userId varchar(255) null, OPTLOCK int null, primary key (pk) ) lock datarows go create table BooleanExpression ( id numeric(19,0) identity not null, expression text null, type varchar(255) null, Escalation_Constraints_Id numeric(19,0) null, primary key (id) ) lock datarows go create table Content ( id numeric(19,0) identity not null, content image null, primary key (id) ) lock datarows go create table ContextMappingInfo ( mappingId numeric(19,0) identity not null, CONTEXT_ID varchar(255) not null, KSESSION_ID numeric(19,0) not null, OWNER_ID varchar(255) null, OPTLOCK int null, primary key (mappingId) ) lock datarows go create table CorrelationKeyInfo ( keyId numeric(19,0) identity not null, name varchar(255) null, processInstanceId numeric(19,0) not null, OPTLOCK int null, primary key (keyId) ) lock datarows go create table CorrelationPropertyInfo ( propertyId numeric(19,0) identity not null, name varchar(255) null, value varchar(255) null, OPTLOCK int null, correlationKey_keyId numeric(19,0) null, primary key (propertyId) ) lock datarows go create table Deadline ( id numeric(19,0) identity not null, deadline_date datetime null, escalated smallint null, Deadlines_StartDeadLine_Id numeric(19,0) null, Deadlines_EndDeadLine_Id numeric(19,0) null, primary key (id) ) lock datarows go create table Delegation_delegates ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table DeploymentStore ( id numeric(19,0) identity not null, attributes varchar(255) null, DEPLOYMENT_ID varchar(255) null, deploymentUnit text null, state int null, updateDate datetime null, primary key (id) ) lock datarows go create table ErrorInfo ( id numeric(19,0) identity not null, message varchar(255) null, stacktrace varchar(5000) null, timestamp datetime null, REQUEST_ID numeric(19,0) not null, primary key (id) ) lock datarows go create table Escalation ( id numeric(19,0) identity not null, name varchar(255) null, Deadline_Escalation_Id numeric(19,0) null, primary key (id) ) lock datarows go create table EventTypes ( InstanceId numeric(19,0) not null, element varchar(255) null ) lock datarows go create table I18NText ( id numeric(19,0) identity not null, language varchar(255) null, shortText varchar(255) null, text text null, Task_Subjects_Id numeric(19,0) null, Task_Names_Id numeric(19,0) null, Task_Descriptions_Id numeric(19,0) null, Reassignment_Documentation_Id numeric(19,0) null, Notification_Subjects_Id numeric(19,0) null, Notification_Names_Id numeric(19,0) null, Notification_Documentation_Id numeric(19,0) null, Notification_Descriptions_Id numeric(19,0) null, Deadline_Documentation_Id numeric(19,0) null, primary key (id) ) lock datarows go create table NodeInstanceLog ( id numeric(19,0) identity not null, connection varchar(255) null, log_date datetime null, externalId varchar(255) null, nodeId varchar(255) null, nodeInstanceId varchar(255) null, nodeName varchar(255) null, nodeType varchar(255) null, processId varchar(255) null, processInstanceId numeric(19,0) not null, type int not null, workItemId numeric(19,0) null, primary key (id) ) lock datarows go create table Notification ( DTYPE varchar(31) not null, id numeric(19,0) identity not null, priority int not null, Escalation_Notifications_Id numeric(19,0) null, primary key (id) ) lock datarows go create table Notification_BAs ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table Notification_Recipients ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table Notification_email_header ( Notification_id numeric(19,0) not null, emailHeaders_id numeric(19,0) not null, mapkey varchar(255) not null, primary key (Notification_id, mapkey) ) lock datarows go create table OrganizationalEntity ( DTYPE varchar(31) not null, id varchar(255) not null, primary key (id) ) lock datarows go create table PeopleAssignments_BAs ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table PeopleAssignments_ExclOwners ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table PeopleAssignments_PotOwners ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table PeopleAssignments_Recipients ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table PeopleAssignments_Stakeholders ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table ProcessInstanceInfo ( InstanceId numeric(19,0) identity not null, lastModificationDate datetime null, lastReadDate datetime null, processId varchar(255) null, processInstanceByteArray image null, startDate datetime null, state int not null, OPTLOCK int null, primary key (InstanceId) ) lock datarows go create table ProcessInstanceLog ( id numeric(19,0) identity not null, correlationKey varchar(255) null, duration numeric(19,0) null, end_date datetime null, externalId varchar(255) null, user_identity varchar(255) null, outcome varchar(255) null, parentProcessInstanceId numeric(19,0) null, processId varchar(255) null, processInstanceDescription varchar(255) null, processInstanceId numeric(19,0) not null, processName varchar(255) null, processVersion varchar(255) null, start_date datetime null, status int null, primary key (id) ) lock datarows go create table QueryDefinitionStore ( id numeric(19,0) identity not null, qExpression text null, qName varchar(255) null, qSource varchar(255) null, qTarget varchar(255) null, primary key (id) ) lock datarows go create table Reassignment ( id numeric(19,0) identity not null, Escalation_Reassignments_Id numeric(19,0) null, primary key (id) ) lock datarows go create table Reassignment_potentialOwners ( task_id numeric(19,0) not null, entity_id varchar(255) not null ) lock datarows go create table RequestInfo ( id numeric(19,0) identity not null, commandName varchar(255) null, deploymentId varchar(255) null, executions int not null, businessKey varchar(255) null, message varchar(255) null, owner varchar(255) null, priority int not null, requestData image null, responseData image null, retries int not null, status varchar(255) null, timestamp datetime null, primary key (id) ) lock datarows go create table SessionInfo ( id numeric(19,0) identity not null, lastModificationDate datetime null, rulesByteArray image null, startDate datetime null, OPTLOCK int null, primary key (id) ) lock datarows go create table Task ( id numeric(19,0) identity not null, archived smallint null, allowedToDelegate varchar(255) null, description varchar(255) null, formName varchar(255) null, name varchar(255) null, priority int not null, subTaskStrategy varchar(255) null, subject varchar(255) null, activationTime datetime null, createdOn datetime null, deploymentId varchar(255) null, documentAccessType int null, documentContentId numeric(19,0) not null, documentType varchar(255) null, expirationTime datetime null, faultAccessType int null, faultContentId numeric(19,0) not null, faultName varchar(255) null, faultType varchar(255) null, outputAccessType int null, outputContentId numeric(19,0) not null, outputType varchar(255) null, parentId numeric(19,0) not null, previousStatus int null, processId varchar(255) null, processInstanceId numeric(19,0) not null, processSessionId numeric(19,0) not null, skipable tinyint not null, status varchar(255) null, workItemId numeric(19,0) not null, taskType varchar(255) null, OPTLOCK int null, taskInitiator_id varchar(255) null, actualOwner_id varchar(255) null, createdBy_id varchar(255) null, primary key (id) ) lock datarows go create table TaskDef ( id numeric(19,0) identity not null, name varchar(255) null, priority int not null, primary key (id) ) lock datarows go create table TaskEvent ( id numeric(19,0) identity not null, logTime datetime null, message varchar(255) null, processInstanceId numeric(19,0) null, taskId numeric(19,0) null, type varchar(255) null, userId varchar(255) null, OPTLOCK int null, workItemId numeric(19,0) null, primary key (id) ) lock datarows go create table TaskVariableImpl ( id numeric(19,0) identity not null, modificationDate datetime null, name varchar(255) null, processId varchar(255) null, processInstanceId numeric(19,0) null, taskId numeric(19,0) null, type int null, value varchar(4000) null, primary key (id) ) lock datarows go create table VariableInstanceLog ( id numeric(19,0) identity not null, log_date datetime null, externalId varchar(255) null, oldValue varchar(255) null, processId varchar(255) null, processInstanceId numeric(19,0) not null, value varchar(255) null, variableId varchar(255) null, variableInstanceId varchar(255) null, primary key (id) ) lock datarows go create table WorkItemInfo ( workItemId numeric(19,0) identity not null, creationDate datetime null, name varchar(255) null, processInstanceId numeric(19,0) not null, state numeric(19,0) not null, OPTLOCK int null, workItemByteArray image null, primary key (workItemId) ) lock datarows go create table email_header ( id numeric(19,0) identity not null, body text null, fromAddress varchar(255) null, language varchar(255) null, replyToAddress varchar(255) null, subject varchar(255) null, primary key (id) ) lock datarows go create table task_comment ( id numeric(19,0) identity not null, addedAt datetime null, text text null, addedBy_id varchar(255) null, TaskData_Comments_Id numeric(19,0) null, primary key (id) ) lock datarows go alter table Attachment add constraint FK1C93543D937BFB5 foreign key (attachedBy_id) references OrganizationalEntity go alter table Attachment add constraint FK1C9354333CA892A foreign key (TaskData_Attachments_Id) references Task go alter table BooleanExpression add constraint FKE3D208C06C97C90E foreign key (Escalation_Constraints_Id) references Escalation go alter table CorrelationPropertyInfo add constraint FK761452A5D87156ED foreign key (correlationKey_keyId) references CorrelationKeyInfo go alter table Deadline add constraint FK21DF3E78A9FE0EF4 foreign key (Deadlines_StartDeadLine_Id) references Task go alter table Deadline add constraint FK21DF3E78695E4DDB foreign key (Deadlines_EndDeadLine_Id) references Task go alter table Delegation_delegates add constraint FK47485D5772B3A123 foreign key (entity_id) references OrganizationalEntity go alter table Delegation_delegates add constraint FK47485D57786553A5 foreign key (task_id) references Task go alter table DeploymentStore add constraint UK_DeploymentStore_1 unique (DEPLOYMENT_ID) go alter table ErrorInfo add constraint FK8B1186B6724A467 foreign key (REQUEST_ID) references RequestInfo go alter table Escalation add constraint FK67B2C6B5D1E5CC1 foreign key (Deadline_Escalation_Id) references Deadline go alter table EventTypes add constraint FKB0E5621F7665489A foreign key (InstanceId) references ProcessInstanceInfo go alter table I18NText add constraint FK2349686BF4ACCD69 foreign key (Task_Subjects_Id) references Task go alter table I18NText add constraint FK2349686B424B187C foreign key (Task_Names_Id) references Task go alter table I18NText add constraint FK2349686BAB648139 foreign key (Task_Descriptions_Id) references Task go alter table I18NText add constraint FK2349686BB340A2AA foreign key (Reassignment_Documentation_Id) references Reassignment go alter table I18NText add constraint FK2349686BF0CDED35 foreign key (Notification_Subjects_Id) references Notification go alter table I18NText add constraint FK2349686BCC03ED3C foreign key (Notification_Names_Id) references Notification go alter table I18NText add constraint FK2349686B77C1C08A foreign key (Notification_Documentation_Id) references Notification go alter table I18NText add constraint FK2349686B18DDFE05 foreign key (Notification_Descriptions_Id) references Notification go alter table I18NText add constraint FK2349686B78AF072A foreign key (Deadline_Documentation_Id) references Deadline go alter table Notification add constraint FK2D45DD0BC0C0F29C foreign key (Escalation_Notifications_Id) references Escalation go alter table Notification_BAs add constraint FK2DD68EE072B3A123 foreign key (entity_id) references OrganizationalEntity go alter table Notification_BAs add constraint FK2DD68EE093F2090B foreign key (task_id) references Notification go alter table Notification_Recipients add constraint FK98FD214E72B3A123 foreign key (entity_id) references OrganizationalEntity go alter table Notification_Recipients add constraint FK98FD214E93F2090B foreign key (task_id) references Notification go alter table Notification_email_header add constraint UK_F30FE3446CEA0510 unique (emailHeaders_id) go alter table Notification_email_header add constraint FKF30FE3448BED1339 foreign key (emailHeaders_id) references email_header go alter table Notification_email_header add constraint FKF30FE3443E3E97EB foreign key (Notification_id) references Notification go alter table PeopleAssignments_BAs add constraint FK9D8CF4EC72B3A123 foreign key (entity_id) references OrganizationalEntity go alter table PeopleAssignments_BAs add constraint FK9D8CF4EC786553A5 foreign key (task_id) references Task go alter table PeopleAssignments_ExclOwners add constraint FKC77B97E472B3A123 foreign key (entity_id) references OrganizationalEntity go alter table PeopleAssignments_ExclOwners add constraint FKC77B97E4786553A5 foreign key (task_id) references Task go alter table PeopleAssignments_PotOwners add constraint FK1EE418D72B3A123 foreign key (entity_id) references OrganizationalEntity go alter table PeopleAssignments_PotOwners add constraint FK1EE418D786553A5 foreign key (task_id) references Task go alter table PeopleAssignments_Recipients add constraint FKC6F615C272B3A123 foreign key (entity_id) references OrganizationalEntity go alter table PeopleAssignments_Recipients add constraint FKC6F615C2786553A5 foreign key (task_id) references Task go alter table PeopleAssignments_Stakeholders add constraint FK482F79D572B3A123 foreign key (entity_id) references OrganizationalEntity go alter table PeopleAssignments_Stakeholders add constraint FK482F79D5786553A5 foreign key (task_id) references Task go alter table QueryDefinitionStore add constraint UK_4ry5gt77jvq0orfttsoghta2j unique (qName) go alter table Reassignment add constraint FK724D056062A1E871 foreign key (Escalation_Reassignments_Id) references Escalation go alter table Reassignment_potentialOwners add constraint FK90B59CFF72B3A123 foreign key (entity_id) references OrganizationalEntity go alter table Reassignment_potentialOwners add constraint FK90B59CFF35D2FEE0 foreign key (task_id) references Reassignment go alter table Task add constraint FK27A9A53C55C806 foreign key (taskInitiator_id) references OrganizationalEntity go alter table Task add constraint FK27A9A5B723BE8B foreign key (actualOwner_id) references OrganizationalEntity go alter table Task add constraint FK27A9A55427E8F1 foreign key (createdBy_id) references OrganizationalEntity go alter table task_comment add constraint FK61F475A57A3215D9 foreign key (addedBy_id) references OrganizationalEntity go alter table task_comment add constraint FK61F475A5F510CB46 foreign key (TaskData_Comments_Id) references Task go create index IDX_Attachment_Id ON Attachment(attachedBy_id) create index IDX_Attachment_DataId ON Attachment(TaskData_Attachments_Id) create index IDX_BoolExpr_Id ON BooleanExpression(Escalation_Constraints_Id) create index IDX_CorrPropInfo_Id ON CorrelationPropertyInfo(correlationKey_keyId) create index IDX_Deadline_StartId ON Deadline(Deadlines_StartDeadLine_Id) create index IDX_Deadline_EndId ON Deadline(Deadlines_EndDeadLine_Id) create index IDX_Delegation_EntityId ON Delegation_delegates(entity_id) create index IDX_Delegation_TaskId ON Delegation_delegates(task_id) create index IDX_ErrorInfo_Id ON ErrorInfo(REQUEST_ID) create index IDX_Escalation_Id ON Escalation(Deadline_Escalation_Id) create index IDX_EventTypes_Id ON EventTypes(InstanceId) create index IDX_I18NText_SubjId ON I18NText(Task_Subjects_Id) create index IDX_I18NText_NameId ON I18NText(Task_Names_Id) create index IDX_I18NText_DescrId ON I18NText(Task_Descriptions_Id) create index IDX_I18NText_ReassignId ON I18NText(Reassignment_Documentation_Id) create index IDX_I18NText_NotSubjId ON I18NText(Notification_Subjects_Id) create index IDX_I18NText_NotNamId ON I18NText(Notification_Names_Id) create index IDX_I18NText_NotDocId ON I18NText(Notification_Documentation_Id) create index IDX_I18NText_NotDescrId ON I18NText(Notification_Descriptions_Id) create index IDX_I18NText_DeadDocId ON I18NText(Deadline_Documentation_Id) create index IDX_Not_EscId ON Notification(Escalation_Notifications_Id) create index IDX_NotBAs_Entity ON Notification_BAs(entity_id) create index IDX_NotBAs_Task ON Notification_BAs(task_id) create index IDX_NotRec_Entity ON Notification_Recipients(entity_id) create index IDX_NotRec_Task ON Notification_Recipients(task_id) create index IDX_NotEmail_Header ON Notification_email_header(emailHeaders_id) create index IDX_NotEmail_Not ON Notification_email_header(Notification_id) create index IDX_PAsBAs_Entity ON PeopleAssignments_BAs(entity_id) create index IDX_PAsBAs_Task ON PeopleAssignments_BAs(task_id) create index IDX_PAsExcl_Entity ON PeopleAssignments_ExclOwners(entity_id) create index IDX_PAsExcl_Task ON PeopleAssignments_ExclOwners(task_id) create index IDX_PAsPot_Entity ON PeopleAssignments_PotOwners(entity_id) create index IDX_PAsPot_Task ON PeopleAssignments_PotOwners(task_id) create index IDX_PAsRecip_Entity ON PeopleAssignments_Recipients(entity_id) create index IDX_PAsRecip_Task ON PeopleAssignments_Recipients(task_id) create index IDX_PAsStake_Entity ON PeopleAssignments_Stakeholders(entity_id) create index IDX_PAsStake_Task ON PeopleAssignments_Stakeholders(task_id) create index IDX_Reassign_Esc ON Reassignment(Escalation_Reassignments_Id) create index IDX_ReassignPO_Entity ON Reassignment_potentialOwners(entity_id) create index IDX_ReassignPO_Task ON Reassignment_potentialOwners(task_id) create index IDX_Task_Initiator ON Task(taskInitiator_id) create index IDX_Task_ActualOwner ON Task(actualOwner_id) create index IDX_Task_CreatedBy ON Task(createdBy_id) create index IDX_TaskComments_CreatedBy ON task_comment(addedBy_id) create index IDX_TaskComments_Id ON task_comment(TaskData_Comments_Id) create index IDX_Task_processInstanceId on Task(processInstanceId) create index IDX_Task_processId on Task(processId) create index IDX_Task_status on Task(status) create index IDX_Task_archived on Task(archived) create index IDX_Task_workItemId on Task(workItemId) create index IDX_EventTypes_element ON EventTypes(element) create index IDX_CMI_Context ON ContextMappingInfo(CONTEXT_ID) create index IDX_CMI_KSession ON ContextMappingInfo(KSESSION_ID) create index IDX_CMI_Owner ON ContextMappingInfo(OWNER_ID) create index IDX_RequestInfo_status ON RequestInfo(status) create index IDX_RequestInfo_timestamp ON RequestInfo(timestamp) create index IDX_RequestInfo_owner ON RequestInfo(owner) create index IDX_BAMTaskSumm_createdDate on BAMTaskSummary(createdDate) create index IDX_BAMTaskSumm_duration on BAMTaskSummary(duration) create index IDX_BAMTaskSumm_endDate on BAMTaskSummary(endDate) create index IDX_BAMTaskSumm_pInstId on BAMTaskSummary(processInstanceId) create index IDX_BAMTaskSumm_startDate on BAMTaskSummary(startDate) create index IDX_BAMTaskSumm_status on BAMTaskSummary(status) create index IDX_BAMTaskSumm_taskId on BAMTaskSummary(taskId) create index IDX_BAMTaskSumm_taskName on BAMTaskSummary(taskName) create index IDX_BAMTaskSumm_userId on BAMTaskSummary(userId) create index IDX_PInstLog_duration on ProcessInstanceLog(duration) create index IDX_PInstLog_end_date on ProcessInstanceLog(end_date) create index IDX_PInstLog_extId on ProcessInstanceLog(externalId) create index IDX_PInstLog_user_identity on ProcessInstanceLog(user_identity) create index IDX_PInstLog_outcome on ProcessInstanceLog(outcome) create index IDX_PInstLog_parentPInstId on ProcessInstanceLog(parentProcessInstanceId) create index IDX_PInstLog_pId on ProcessInstanceLog(processId) create index IDX_PInstLog_pInsteDescr on ProcessInstanceLog(processInstanceDescription) create index IDX_PInstLog_pInstId on ProcessInstanceLog(processInstanceId) create index IDX_PInstLog_pName on ProcessInstanceLog(processName) create index IDX_PInstLog_pVersion on ProcessInstanceLog(processVersion) create index IDX_PInstLog_start_date on ProcessInstanceLog(start_date) create index IDX_PInstLog_status on ProcessInstanceLog(status) create index IDX_PInstLog_correlation on ProcessInstanceLog(correlationKey) create index IDX_VInstLog_pInstId on VariableInstanceLog(processInstanceId); create index IDX_VInstLog_varId on VariableInstanceLog(variableId); create index IDX_VInstLog_pId on VariableInstanceLog(processId); create index IDX_NInstLog_pInstId on NodeInstanceLog(processInstanceId); create index IDX_NInstLog_nodeType on NodeInstanceLog(nodeType); create index IDX_NInstLog_pId on NodeInstanceLog(processId);
apache-2.0
rigetticomputing/grove
grove/tests/tomography/test_process_tomography.py
6859
############################################################################## # Copyright 2017-2018 Rigetti Computing # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## import pytest import os import numpy as np from unittest.mock import patch, MagicMock, Mock import json from pyquil.api import Job, QVMConnection from grove.tomography.tomography import (MAX_QUBITS_PROCESS_TOMO, default_channel_ops) from grove.tomography.process_tomography import (DEFAULT_PROCESS_TOMO_SETTINGS, process_tomography_programs, do_process_tomography, ProcessTomography, COMPLETELY_POSITIVE) from grove.tomography.process_tomography import (TRACE_PRESERVING) from grove.tomography.utils import (make_histogram, sample_bad_readout, basis_state_preps, estimate_assignment_probs, BAD_2Q_READOUT, SEED, EPS, CNOT_PROGRAM, import_qutip, import_cvxpy) from grove.tomography.operator_utils import make_diagonal_povm, POVM_PI_BASIS qt = import_qutip() cvxpy = import_cvxpy() if not qt: pytest.skip("Qutip not installed, skipping tests", allow_module_level=True) if not cvxpy: pytest.skip("CVXPY not installed, skipping tests", allow_module_level=True) SHOTS_PATH = os.path.join(os.path.dirname(__file__), 'process_shots.json') RESULTS_PATH = os.path.join(os.path.dirname(__file__), 'process_results.json') sample_bad_readout = MagicMock(sample_bad_readout) sample_bad_readout.side_effect = [np.array(shots) for shots in json.load(open(SHOTS_PATH, 'r'))] # these mocks are set up such that a single mock Job is returned by the QVMConnection's wait_for_job # but calling job.result() returns a different value every time via the side_effect defined below cxn = MagicMock(QVMConnection) job = MagicMock(Job) job.result.side_effect = json.load(open(RESULTS_PATH, 'r')) cxn.wait_for_job.return_value = job def test_process_tomography(): num_qubits = len(CNOT_PROGRAM.get_qubits()) dimension = 2 ** num_qubits tomo_seq = list(process_tomography_programs(CNOT_PROGRAM)) nsamples = 3000 np.random.seed(SEED) # We need more samples on the readout to ensure convergence. state_prep_hists = [make_histogram(sample_bad_readout(p, 2 * nsamples, BAD_2Q_READOUT, cxn), dimension) for p in basis_state_preps(*range(num_qubits))] assignment_probs = estimate_assignment_probs(state_prep_hists) histograms = np.zeros((len(tomo_seq), dimension)) for jj, p in enumerate(tomo_seq): histograms[jj] = make_histogram(sample_bad_readout(p, nsamples, BAD_2Q_READOUT, cxn), dimension) channel_ops = list(default_channel_ops(num_qubits)) histograms = histograms.reshape((len(channel_ops), len(channel_ops), dimension)) povm = make_diagonal_povm(POVM_PI_BASIS ** num_qubits, assignment_probs) cnot_ideal = qt.cnot() for settings in [ DEFAULT_PROCESS_TOMO_SETTINGS, DEFAULT_PROCESS_TOMO_SETTINGS._replace(constraints={TRACE_PRESERVING}), DEFAULT_PROCESS_TOMO_SETTINGS._replace(constraints={TRACE_PRESERVING, COMPLETELY_POSITIVE}), ]: process_tomo = ProcessTomography.estimate_from_ssr(histograms, povm, channel_ops, channel_ops, settings) assert abs(1 - process_tomo.avg_gate_fidelity(cnot_ideal)) < EPS transfer_matrix = process_tomo.pauli_basis.transfer_matrix(qt.to_super(cnot_ideal)) assert abs(1 - process_tomo.avg_gate_fidelity(transfer_matrix)) < EPS chi_rep = process_tomo.to_chi().data.toarray() # When comparing to the identity, the chi representation is quadratically larger than the # Hilbert space representation, so we take a square root. probabilty_scale = np.sqrt(chi_rep.shape[0]) super_op_from_chi = np.zeros(process_tomo.pauli_basis.ops[0].shape, dtype=np.complex128) for i, si in enumerate(process_tomo.pauli_basis.ops): for j, sj in enumerate(process_tomo.pauli_basis.ops): contribution = chi_rep[i][j] * si.data.toarray().conj().T.dot(sj.data.toarray()) super_op_from_chi += contribution / probabilty_scale assert np.isclose(np.eye(process_tomo.pauli_basis.ops[0].shape[0]), super_op_from_chi, atol=EPS).all() choi_rep = process_tomo.to_choi() # Choi matrix should be a valid density matrix, scaled by the dimension of the system. assert np.isclose(np.trace(choi_rep.data.toarray()) / probabilty_scale, 1, atol=EPS) super_op = process_tomo.to_super() # The map should be trace preserving. assert np.isclose(np.sum(super_op[0]), 1, atol=EPS) kraus_ops = process_tomo.to_kraus() assert np.isclose(sum(np.trace(k.conjugate().T.dot(k)) for k in kraus_ops), kraus_ops[0].shape[0], atol=.1) assert abs(1 - process_tomo.avg_gate_fidelity(qt.to_super(cnot_ideal))) < EPS with patch("grove.tomography.utils.plot_pauli_transfer_matrix"), \ patch("grove.tomography.process_tomography.plt") as mplt: mplt.subplots.return_value = Mock(), Mock() process_tomo.plot() def test_do_process_tomography(): nsamples = 3000 qubits = list(range(MAX_QUBITS_PROCESS_TOMO + 1)) # Test with too many qubits. with pytest.raises(ValueError): _ = do_process_tomography(CNOT_PROGRAM, nsamples, cxn, qubits) process_tomo, assignment_probs, histograms = do_process_tomography(CNOT_PROGRAM, nsamples, cxn) cnot_ideal = qt.cnot() assert abs(1 - process_tomo.avg_gate_fidelity(cnot_ideal)) < EPS for histogram_collection in histograms: for histogram in histogram_collection: assert np.sum(histogram) == nsamples num_qubits = len(CNOT_PROGRAM.get_qubits()) assert np.isclose(assignment_probs, np.eye(2 ** num_qubits), atol=EPS).all()
apache-2.0
MonALISA-CIT/fdt
src/lia/util/net/copy/FileBlock.java
1871
/* * $Id$ */ package lia.util.net.copy; import java.nio.ByteBuffer; import java.util.UUID; /** * Wrapper class for a simple block ( can be an offset in whatever stream ... not only a file ) * * @author ramiro */ public class FileBlock { //used for signaling between Producers/Consumers //public static final FileBlock EOF_FB = new FileBlock(UUID.randomUUID(), UUID.randomUUID(), -1, ByteBuffer.allocate(0)); public final UUID fdtSessionID; public final UUID fileSessionID; public final long fileOffset; public final ByteBuffer buff; private FileBlock(final UUID fdtSessionID, final UUID fileSessionID, final long fileOffset, final ByteBuffer buff) { if (fdtSessionID == null) { throw new NullPointerException(" [ FDT Bug ? ] fdtSessionID cannot be null; fileSessionID: " + fileSessionID); } if (fileSessionID == null) { throw new NullPointerException(" [ FDT Bug ? ] fileSessionID cannot be null; fdtSessionID: " + fdtSessionID); } if (buff == null) { throw new NullPointerException(" [ FDT Bug ? ] buff cannot be null; fdtSessionID: " + fdtSessionID + " fileSessionID: " + fileSessionID); } this.fdtSessionID = fdtSessionID; this.fileSessionID = fileSessionID; this.fileOffset = fileOffset; this.buff = buff; } //TODO - Make a simple cache of FileBlock-s objects ... I don't think FDT will gain anything from this "feature" // so I will not implement it, yet public static FileBlock getInstance(UUID fdtSessionID, UUID fileSessionID, long fileOffset, ByteBuffer buff) { return new FileBlock(fdtSessionID, fileSessionID, fileOffset, buff); } public String toString() { return "FileBlock for [ " + fileSessionID + " ] offset: " + fileOffset + " payload: " + buff; } }
apache-2.0
mrinsss/Full-Repo
jobshoppa/system/application/models/user_type_model.php
30165
<?php /********* * Author: Iman Biswas * Date : 14 sep 2011 * Modified By: * Modified Date: * * Purpose: * Model For User Type Master * * @package User * @subpackage Access Control * * @includes infModel.php * @includes MY_Model.php * * @link MY_Model.php */ class User_type_model extends MY_Model implements InfModel { private $conf; private $tbl;///used for this class public function __construct() { try { parent::__construct(); $this->tbl=$this->db->USER_TYPE; $this->conf=&get_config(); } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /****** * This method will fetch all records from the db. * * @param string $s_where, ex- " status=1 " * @param int $i_start, starting value for pagination * @param int $i_limit, number of records to fetch used for pagination * @returns array */ public function fetch_multi($s_where=null,$i_start=null,$i_limit=null) { try { $ret_=array(); $s_qry="SELECT * FROM ".$this->tbl." ut " .($s_where!=""?$s_where:"" ).(is_numeric($i_start) && is_numeric($i_limit)?" Limit ".intval($i_start).",".intval($i_limit):"" ); $rs=$this->db->query($s_qry); $i_cnt=0; if($rs->num_rows()>0) { //while($row=) foreach($rs->result() as $row) { $ret_[$i_cnt]["id"]=$row->id;////always integer $ret_[$i_cnt]["s_user_type"]=stripslashes($row->s_user_type); $ret_[$i_cnt]["i_created_by"]=intval($row->i_created_by); $ret_[$i_cnt]["dt_created_on"]=date($this->conf["site_date_format"],intval($row->dt_created_on)); $ret_[$i_cnt]["i_status"]=intval($row->i_status); $ret_[$i_cnt]["s_status"]=(intval($row->i_status)==1?"Active":"Inactive"); $i_cnt++; } $rs->free_result(); } unset($s_qry,$rs,$row,$i_cnt,$s_where,$i_start,$i_limit); return $ret_; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /**** * Fetch Total records * @param string $s_where, ex- " status=1 AND deleted=0 " * @returns int on success and FALSE if failed */ public function gettotal_info($s_where=null) { try { $ret_=0; $s_qry="Select count(*) as i_total " ."From ".$this->tbl." ut " .($s_where!=""?$s_where:"" ); //echo $s_qry; $rs=$this->db->query($s_qry); $i_cnt=0; if($rs->num_rows()>0) { //while($row=) foreach($rs->result() as $row) { $ret_=intval($row->i_total); } $rs->free_result(); } unset($s_qry,$rs,$row,$i_cnt,$s_where,$i_start,$i_limit); return $ret_; //return $this->db->count_all($this->tbl); } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /******* * Fetches One record from db for the id value. * * @param int $i_id * @returns array */ public function fetch_this($i_id) { try { $ret_=array(); ////Using Prepared Statement/// $s_qry="Select * " ."From ".$this->tbl." ut " ." Where ut.id=?"; $rs=$this->db->query($s_qry,array(intval($i_id))); if($rs->num_rows()>0) { foreach($rs->result() as $row) { $ret_["id"]=$row->id;////always integer $ret_["s_user_type"]=stripslashes($row->s_user_type); $ret_["dt_created_on"]=date($this->conf["site_date_format"],intval($row->dt_created_on)); $ret_["i_status "]=intval($row->i_status ); $ret_["s_status"]=(intval($row->i_status )==1?"Active":"Inactive"); $ret_["access_controll_array"] = $this->fetch_controller_access($ret_["id"]); } $rs->free_result(); } unset($s_qry,$rs,$row,$i_id); return $ret_; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /*** * Inserts new records into db. As we know the table name * we will not pass it into params. * * @param array $info, array of fields(as key) with values,ex-$arr["field_name"]=value * @returns $i_new_id on success and FALSE if failed */ public function add_info($info) { try { $i_ret_=0;////Returns false if(!empty($info)) { $s_qry="Insert Into ".$this->tbl." Set "; $s_qry.=" s_user_type=? "; $s_qry.=", dt_created_on=? "; //$s_qry.=", i_is_deleted=?"; ///have default value $this->db->query($s_qry,array(addslashes(htmlspecialchars(trim($info["s_user_type"]))), intval($info["dt_created_on"]) )); $i_ret_=$this->db->insert_id(); if($i_ret_) { $logi["msg"]="Inserting into ".$this->tbl." "; $logi["sql"]= serialize(array($s_qry,array(addslashes(htmlspecialchars(trim($info["s_user_type"]))), intval($info["dt_created_on"]) )) ) ; $this->log_info($logi); unset($logi,$logindata); } } unset($s_qry); return $i_ret_; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /*** * Update records in db. As we know the table name * we will not pass it into params. * * @param array $info, array of fields(as key) with values,ex-$arr["field_name"]=value * @param int $i_id, id value to be updated used in where clause * @returns $i_rows_affected on success and FALSE if failed */ public function edit_info($info,$i_id) { try { $i_ret_=0;////Returns false if(!empty($info)) { $s_qry="Update ".$this->tbl." Set "; $s_qry.=" s_user_type=? "; //$s_qry.=", i_created_by=? "; //$s_qry.=", dt_created_on=? "; //$s_qry.=", i_is_deleted=? "; ///have default value $s_qry.=" Where id=? "; $this->db->query($s_qry,array( addslashes(htmlspecialchars(trim($info["s_user_type"]))) , /*intval($info["i_created_by"]), intval($info["dt_created_on"]),*/ intval($i_id) )); $i_ret_=$this->db->affected_rows(); if($i_ret_) { $logi["msg"]="Updating ".$this->tbl." "; $logi["sql"]= serialize(array($s_qry,array(addslashes(htmlspecialchars(trim($info["s_user_type"]))), intval($info["i_created_by"]), intval($info["dt_created_on"]), intval($i_id) )) ) ; $this->log_info($logi); unset($logi,$logindata); } } unset($s_qry); return $i_ret_; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /****** * Deletes all or single record from db. * For Master entries deletion only change the flag i_is_deleted. * * @param int $i_id, id value to be deleted used in where clause * @returns $i_rows_affected on success and FALSE if failed * */ public function delete_info($i_id) { try { $i_ret_=0;////Returns false if(intval($i_id)>0) { $s_qry="Update ".$this->tbl." Set i_is_deleted=1 "; $s_qry.=" Where id=? "; $this->db->query($s_qry, array(intval($i_id)) ); $i_ret_=$this->db->affected_rows(); if($i_ret_) { $logi["msg"]="Deleting ".$this->tbl." "; $logi["sql"]= serialize(array($s_qry, array(intval($i_id))) ) ; $this->log_info($logi); unset($logi,$logindata); } } elseif(intval($i_id)==-1)////Deleting All { $s_qry="Update ".$this->tbl." Set i_is_deleted=1 "; $this->db->query($s_qry); $i_ret_=$this->db->affected_rows(); if($i_ret_) { $logi["msg"]="Deleting all information from ".$this->tbl." "; $logi["sql"]= serialize(array($s_qry) ) ; $this->log_info($logi); unset($logi,$logindata); } } unset($s_qry); return $i_ret_; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /**** * Register a log for add,edit and delete operation * * @param mixed $attr * @returns TRUE on success and FALSE if failed */ public function log_info($attr) { try { $logindata=$this->session->userdata("admin_loggedin"); return $this->write_log($attr["msg"],decrypt($logindata["user_id"]),($attr["sql"]?$attr["sql"]:"")); } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /****** * This method will fetch all records regarding controller access from the db. * * @param int $s_controller, i_user_type_id * @returns array */ public function fetch_controller_access($i_user_type_id=null,$s_controller=null) { try { $ret_=array(); /////////////////Define your query here///////////// $s_qry="Select uta.id,uta.i_user_type_id,uta.s_controller,uta.i_action_add,uta.i_action_edit,uta.i_action_delete,ut.s_user_type ,uta.dt_created_on,uta.i_is_deleted " ."From ".$this->db->USER_TYPE_ACCESS." uta " ."Left Join ".$this->db->USER_TYPE." ut On uta.i_user_type_id=ut.id " ." Where uta.i_user_type_id=?"; /////////////////end Define your query here///////////// $this->db->trans_begin();///new $rs=$this->db->query($s_qry,array(intval($i_user_type_id))); if(is_array($rs->result())) { foreach($rs->result() as $row) { $ret_[$row->s_controller]["id"]=$row->id;////always integer $ret_[$row->s_controller]['controller']=get_unformatted_string($row->s_controller); $ret_[$row->s_controller]['i_action_add']=intval($row->i_action_add); $ret_[$row->s_controller]["i_action_edit"]=intval($row->i_action_edit); $ret_[$row->s_controller]["i_action_delete"]=intval($row->i_action_delete); $ret_[$row->s_controller]["i_user_type_id"]=intval($row->i_user_type_id); $ret_[$row->s_controller]["s_user_type"]=get_unformatted_string($row->s_user_type); $ret_[$row->s_controller]["dt_created_on"]=date($this->conf["site_date_format"],strtotime($row->dt_created_on)); $ret_[$row->s_controller]["i_is_deleted"]=intval($row->i_is_deleted); $ret_[$row->s_controller]["s_is_deleted"]=(intval($row->i_is_deleted)==1?"Removed":""); $i_cnt++; } $rs->free_result(); } $this->db->trans_commit();///new unset($s_qry,$rs,$row,$i_id); return $ret_; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /*** * Update user type access records or insert anew row in db. * @param array $info, $i_id with values,ex-$arr["field_name"]=value * @param $s_controller,$i_id to be updated used in where clause * @returns $i_rows_affected on success and FALSE if failed */ public function update_access($info,$i_id) { try { $i_ret_=0;////Returns false if(!empty($info)) { //check if row exist in access table // $where = "uta.i_user_type_id='".$i_user_type_id."' AND uta.s_controller='".$s_controller."' "; if(intval($i_id)>0)//update { $s_qry="UPDATE ".$this->db->USER_TYPE_ACCESS." SET "; $s_qry.=" i_action_add=? "; $s_qry.=", i_action_edit=? "; $s_qry.=", i_action_delete=? "; $s_qry.=" WHERE id=?"; $this->db->trans_begin();///new $this->db->query($s_qry,array( intval($info["i_action_add"]), intval($info["i_action_edit"]), intval($info["i_action_delete"]), intval($i_id) )); $i_ret_=$this->db->affected_rows(); if($i_ret_) { $logi["msg"]="Updating ".$this->tbl." "; $logi["sql"]= serialize(array($s_qry,array( intval($info["i_action_add"]), intval($info["i_action_edit"]), intval($info["i_action_delete"]), intval($i_id) )) ) ; $this->log_info($logi); unset($logi); $this->db->trans_commit();///new } else { $this->db->trans_rollback();///new } } else //add new row { $s_qry="INSERT INTO ".$this->db->USER_TYPE_ACCESS ." ( i_user_type_id, s_controller, i_action_add, i_action_edit, i_action_delete, dt_created_on) VALUES (?,?,?,?,?,?)"; $this->db->trans_begin();///new $this->db->query($s_qry,array(intval($info["i_user_type_id"]), ($info["s_controller"]), intval($info["i_action_add"]), intval($info["i_action_edit"]), intval($info["i_action_delete"]), date($this->conf["db_date_format"],strtotime($info["dt_created_on"])) )); $i_ret_=$this->db->insert_id(); if($i_ret_) { $logi["msg"]="Inserting into ".$this->tbl." "; $logi["sql"]= serialize(array($s_qry,array(intval($info["i_user_type_id"]), ($info["s_controller"]), intval($info["i_action_add"]), intval($info["i_action_edit"]), intval($info["i_action_delete"]), date($this->conf["db_date_format"],strtotime($info["dt_created_on"])) )) ) ; $this->log_info($logi); unset($logi); $this->db->trans_commit();///new } else { $this->db->trans_rollback();///new } } // ////////////////////// } unset($s_qry); return $i_ret_; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } /**** * Fetch Menus having access rights to control them. * Company controller cannot be edited or deleted because in some of php scripts * the company id used are hardcodded. * * @param int $i_user_type_id, user type; 0=> super admin * @returns array of menu controllers */ public function fetch_menus($i_user_type_id=null,$product_section=null) { try { if($product_section=="Finance") $all_controllers=$this->db->FIN_CONTROLLER_NAME; else $all_controllers=$this->db->CONTROLLER_NAME; /*For superadmin and others dont allow these controllers to be * inserted,edited or deleted * ex- Any user including super admin cannot edit or delete the company master */ $force_controller_toreact=array(); $force_controller_toreact=array( 'Auto_mail'=>array( 'action_add'=>0, 'action_edit'=>0, 'action_delete'=>0 ), 'Manage_feedback'=>array( 'action_add'=>0, 'action_edit'=>1, 'action_delete'=>0 ), 'Manage_jobs'=>array( 'action_add'=>0, 'action_edit'=>0, 'action_delete'=>1 ), 'Manage_private_message'=>array( 'action_add'=>0, 'action_edit'=>0, 'action_delete'=>1 ), 'Manage_tradesman'=>array( 'action_add'=>0, 'action_edit'=>1, 'action_delete'=>0 ), 'Manage_buyers'=>array( 'action_add'=>0, 'action_edit'=>1, 'action_delete'=>0 ), 'Manage_verification'=>array( 'action_add'=>1, 'action_edit'=>0, 'action_delete'=>0 ), 'Newsletter_subscribers'=>array( 'action_add'=>1, 'action_edit'=>1, 'action_delete'=>0 ), 'How_it_works_tradesman'=>array( 'action_add'=>0, 'action_edit'=>1, 'action_delete'=>1 ), 'Manage_invoice'=>array( 'action_add'=>0, 'action_edit'=>0, 'action_delete'=>1 ), 'Payment_subscription'=>array( 'action_add'=>1, 'action_edit'=>0, 'action_delete'=>0 ), 'How_it_works_buyer'=>array( 'action_add'=>0, 'action_edit'=>1, 'action_delete'=>1 ) ); ///////////end force to act/////// /** * Alias Controllers:- when some controller depends on other controller * then allow access to those controllers as well. */ $alias_controllers=array(); $controllers_access=array(); //pr($_SESSION); //echo $i_user_type_id;exit; if($i_user_type_id>0) { $s_qry="Select * From ".$this->db->USER_TYPE_ACCESS; $s_qry.=" Where i_user_type_id=? AND (i_action_add=1 OR i_action_edit=1 OR i_action_delete=1 OR s_controller='Dashboard')";///Dashboard is allowed to all users $this->db->trans_begin();///new $rs=$this->db->query($s_qry, intval($i_user_type_id)); $i_cnt=0; if(is_array($rs->result()) ) ///new { foreach($rs->result() as $row) { $tmp_=stripslashes($row->s_controller); $controllers_access[$tmp_]=$all_controllers[$tmp_]; /*For superadmin and others dont allow these controllers to be * inserted,edited or deleted * ex- Any user including super admin cannot edit or delete the company master */ if(!$force_controller_toreact[$tmp_]) { if($controllers_access[$tmp_]["top_menu"]!="Report") { $controllers_access[$tmp_]["action_add"]=intval($row->i_action_add); $controllers_access[$tmp_]["action_edit"]=intval($row->i_action_edit); $controllers_access[$tmp_]["action_delete"]=intval($row->i_action_delete); } else { $controllers_access[$tmp_]["action_add"]=0; $controllers_access[$tmp_]["action_edit"]=0; $controllers_access[$tmp_]["action_delete"]=0; } }///////end if else { $controllers_access[$tmp_]["action_add"]=$force_controller_toreact[$tmp_]["action_add"]; $controllers_access[$tmp_]["action_edit"]=$force_controller_toreact[$tmp_]["action_edit"]; $controllers_access[$tmp_]["action_delete"]=$force_controller_toreact[$tmp_]["action_delete"]; }///end else /** * Alias Controllers:- when some controller depends on other controller * then allow access to those controllers as well. * Alias Controllers can be comma seperated Controllers names */ if(trim($controllers_access[$tmp_]["alias_controller"])!="") { $tmpAlis=explode(",",$controllers_access[$tmp_]["alias_controller"]); if(is_array($tmpAlis)) { foreach($tmpAlis as $ali) { $alias_name=$ali; $alias_controllers[$alias_name]["action_add"]=0; $alias_controllers[$alias_name]["action_edit"]=0; $alias_controllers[$alias_name]["action_delete"]=0; } unset($ali); } else { $alias_name=$controllers_access[$tmp_]["alias_controller"]; $alias_controllers[$alias_name]["action_add"]=0; $alias_controllers[$alias_name]["action_edit"]=0; $alias_controllers[$alias_name]["action_delete"]=0; } unset($alias_name,$tmpAlis); }///end if Alias controller } $rs->free_result(); } $this->db->trans_commit();///new unset($s_qry,$rs,$row,$i_cnt); ///////Keeping the access rights into the sessions///// } else////for super admin { foreach($all_controllers as $k=>$menus) { $tmp_=$k; $controllers_access[$tmp_]=$all_controllers[$tmp_]; /*For superadmin and others dont allow these controllers to be * inserted,edited or deleted * ex- Any user including super admin cannot edit or delete the company master */ if(!$force_controller_toreact[$tmp_]) { if($controllers_access[$tmp_]["top_menu"]!="Report") { $controllers_access[$tmp_]["action_add"]=1; $controllers_access[$tmp_]["action_edit"]=1; $controllers_access[$tmp_]["action_delete"]=1; } else { $controllers_access[$tmp_]["action_add"]=0; $controllers_access[$tmp_]["action_edit"]=0; $controllers_access[$tmp_]["action_delete"]=0; } }///////end if else { $controllers_access[$tmp_]["action_add"]=$force_controller_toreact[$tmp_]["action_add"]; $controllers_access[$tmp_]["action_edit"]=$force_controller_toreact[$tmp_]["action_edit"]; $controllers_access[$tmp_]["action_delete"]=$force_controller_toreact[$tmp_]["action_delete"]; }///end else /** * Alias Controllers:- when some controller depends on other controller * then allow access to those controllers as well. */ if(trim($controllers_access[$tmp_]["alias_controller"])!="") { $tmpAlis=explode(",",$controllers_access[$tmp_]["alias_controller"]); if(is_array($tmpAlis)) { foreach($tmpAlis as $ali) { $alias_name=$ali; $alias_controllers[$alias_name]["action_add"]=0; $alias_controllers[$alias_name]["action_edit"]=0; $alias_controllers[$alias_name]["action_delete"]=0; } unset($ali); } else { $alias_name=$controllers_access[$tmp_]["alias_controller"]; $alias_controllers[$alias_name]["action_add"]=0; $alias_controllers[$alias_name]["action_edit"]=0; $alias_controllers[$alias_name]["action_delete"]=0; } unset($alias_name,$tmpAlis); }///end if Alias controller } } //$this->session->set_userdata(array("controllers_access"=>$controllers_access)); //pr($this->session->userdata("controllers_access"),1); /** * DEFAULT ACCESS TO DASHBOARD * For a special case:- * user had created but no access control assigned for that user type. * then dashboard will have default access to any user who logged in */ $controllers_access["Dashboard"]=$all_controllers["Dashboard"]; $controllers_access["Dashboard"]["action_add"]=0; $controllers_access["Dashboard"]["action_edit"]=1; $controllers_access["Dashboard"]["action_delete"]=0; /////end DEFAULT ACCESS TO DASHBOARD/// /** * Alias Controllers:- when some controller depends on other controller * then allow access to those controllers as well. * Finally assigning all alias controllers to main controllers. */ if(!empty($alias_controllers)) { foreach($alias_controllers as $al=>$arr) { if(!array_key_exists($al,$controllers_access)) { $controllers_access[$al]=$arr; } } unset($al,$arr); }///end if Alias controller //pr($controllers_access); unset($all_controllers,$tmp_,$k,$alias_controllers); return $controllers_access; } catch(Exception $err_obj) { show_error($err_obj->getMessage()); } } public function __destruct() {} } ///end of class ?>
apache-2.0
opetrovski/development
oscm-portal/javasrc/org/oscm/ui/dialog/classic/manageudas/ManageUdaDefinitionPage.java
3781
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Creation Date: 2012-6-11 * *******************************************************************************/ package org.oscm.ui.dialog.classic.manageudas; import java.util.List; import org.oscm.ui.beans.UdaBean; /** * @author yuyin * */ public class ManageUdaDefinitionPage { private List<UdaDefinitionRowModel> subscriptionUdas; private List<UdaDefinitionRowModel> customerUdas; private UdaDefinitionDetails currentUdaDefinition; private UdaDefinitionDetails newUdaDefinition; private String udaType; /** * @return the subscriptionUdas */ public List<UdaDefinitionRowModel> getSubscriptionUdas() { return subscriptionUdas; } /** * @param subscriptionUdas * the subscriptionUdas to set */ public void setSubscriptionUdas(List<UdaDefinitionRowModel> subscriptionUdas) { this.subscriptionUdas = subscriptionUdas; } /** * @return the customerUdas */ public List<UdaDefinitionRowModel> getCustomerUdas() { return customerUdas; } /** * @param customerUdas * the customerUdas to set */ public void setCustomerUdas(List<UdaDefinitionRowModel> customerUdas) { this.customerUdas = customerUdas; } /** * @return the currentUdaDefinition */ public UdaDefinitionDetails getCurrentUdaDefinition() { if (null == currentUdaDefinition) { currentUdaDefinition = new UdaDefinitionDetails(); } return currentUdaDefinition; } /** * @param currentUdaDefinition * the currentUdaDefinition to set */ public void setCurrentUda(UdaDefinitionDetails currentUdaDefinition) { this.currentUdaDefinition = currentUdaDefinition; } /** * @return the newUdaDefinition */ public UdaDefinitionDetails getNewUdaDefinition() { if (null == newUdaDefinition) { newUdaDefinition = new UdaDefinitionDetails(); } return newUdaDefinition; } /** * @param newUdaDefinition * the newUdaDefinition to set */ public void setNewUdaDefinition(UdaDefinitionDetails newUdaDefinition) { this.newUdaDefinition = newUdaDefinition; } /** * @param udaType * the udaType to set */ public void setUdaType(String udaType) { // refresh newUdaDefinition while open create customer attributes dialog this.newUdaDefinition = null; this.udaType = udaType; } /** * @return the udaType */ public String getUdaType() { return udaType; } /** * set current selected Uda to currentUdaDefinition for * <code>customerUdas</code> or <code>subscriptionUdas</code> * * @param index */ public void setCurrentUdaIndex(int index) { if (udaType.equals(UdaBean.CUSTOMER)) { currentUdaDefinition = UdaModelConverter .convertUdaDefinitionRowModelToUdaDefDetails(customerUdas .get(index)); } else { currentUdaDefinition = UdaModelConverter .convertUdaDefinitionRowModelToUdaDefDetails(subscriptionUdas .get(index)); } } }
apache-2.0
samogami/grommet
src/js/components/Legend.js
3868
// (C) Copyright 2014 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import FormattedMessage from './FormattedMessage'; const CLASS_ROOT = "legend"; export default class Legend extends Component { constructor(props) { super(props); this._onActive = this._onActive.bind(this); this.state = {activeIndex: this.props.activeIndex}; } componentWillReceiveProps (newProps) { this.setState({activeIndex: newProps.activeIndex}); } _onActive (index) { this.setState({activeIndex: index}); if (this.props.onActive) { this.props.onActive(index); } } _itemColorIndex (item, index) { return item.colorIndex || ('graph-' + (index + 1)); } render () { var classes = [CLASS_ROOT]; if (this.props.series.length === 1) { classes.push(CLASS_ROOT + "--single"); } if (this.props.className) { classes.push(this.props.className); } var totalValue = 0; var items = this.props.series.map(function (item, index) { var legendClasses = [CLASS_ROOT + "__item"]; if (index === this.state.activeIndex) { legendClasses.push(CLASS_ROOT + "__item--active"); } if (item.onClick) { legendClasses.push(CLASS_ROOT + "__item--clickable"); } var colorIndex = this._itemColorIndex(item, index); totalValue += item.value; var valueClasses = [CLASS_ROOT + "__item-value"]; if (1 === this.props.series.length) { valueClasses.push("large-number-font"); } var swatch; if (item.hasOwnProperty('colorIndex')) { swatch = ( <svg className={CLASS_ROOT + "__item-swatch color-index-" + colorIndex} viewBox="0 0 12 12"> <path className={item.className} d="M 5 0 l 0 12" /> </svg> ); } var label; if (item.hasOwnProperty('label')) { label = ( <span className={CLASS_ROOT + "__item-label"}>{item.label}</span> ); } var value; if (item.hasOwnProperty('value')) { value = ( <span className={valueClasses.join(' ')}> {item.value} <span className={CLASS_ROOT + "__item-units"}> {item.units || this.props.units} </span> </span> ); } return ( <li key={item.label || index} className={legendClasses.join(' ')} onClick={item.onClick} onMouseOver={this._onActive.bind(this, index)} onMouseOut={this._onActive.bind(this, null)} > {swatch} {label} {value} </li> ); }, this); // build legend from bottom to top, to align with Meter bar stacking items.reverse(); var total = null; if (this.props.total && this.props.series.length > 1) { total = ( <li className={CLASS_ROOT + "__total"}> <span className={CLASS_ROOT + "__total-label"}> <FormattedMessage id="Total" defaultMessage="Total" /> </span> <span className={CLASS_ROOT + "__total-value"}> {totalValue} <span className={CLASS_ROOT + "__total-units"}>{this.props.units}</span> </span> </li> ); } return ( <ol className={classes.join(' ')} role="presentation"> {items.reverse()} {total} </ol> ); } } Legend.propTypes = { activeIndex: PropTypes.number, onActive: PropTypes.func, series: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.string, value: PropTypes.number, units: PropTypes.string, colorIndex: PropTypes.oneOfType([ PropTypes.number, // 1-6 PropTypes.string // status ]), onClick: PropTypes.func })).isRequired, total: PropTypes.bool, units: PropTypes.string, value: PropTypes.number };
apache-2.0
magnetsystems/message-common
src/main/java/com/magnet/mmx/protocol/Constants.java
12172
/* Copyright (c) 2015 Magnet Systems, 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 com.magnet.mmx.protocol; /** * @hide * Common MMX element, namespace and attributes. */ public class Constants { /** * The default domain or service name for MMX server. */ public final static String MMX_DOMAIN = "mmx"; /** * The max length for topic name. */ public final static int MMX_MAX_TOPIC_LEN = 50; public final static int MMX_MAX_CHANNEL_LEN = 50; /** * The max length for tag name. */ public final static int MMX_MAX_TAG_LEN = 25; /** * The minimum user ID length for regular user account. */ public final static int MMX_MIN_USERID_LEN = 5; /** * The maximum user ID length for regular user account. */ public final static int MMX_MAX_USERID_LEN = 42; /** * The max payload size in bytes that MMX server supports. It is not * necessary same as what the client allows. */ public final static int MAX_PAYLOAD_SIZE = 2 * 1024 * 1024; /** * The payload threshold in bytes to switch from RAM to memory-mapped I/O. */ public final static int PAYLOAD_THRESHOLD = 102400; /** * A delimiter used in multi-tenant environment. */ public final static char APP_ID_DELIMITER = '%'; /** * A flag to control if '@' is allowed in the user ID. */ public final static boolean AT_SIGN_DISALLOWED = false; /** * The current protocol major version number. */ public final static int MMX_VERSION_MAJOR = 2; /** * The current protocol minor version number. */ public final static int MMX_VERSION_MINOR = 1; /** * The elements for MMX. */ public final static String MMX_ELEMENT = "mmx"; public final static String MMX = MMX_ELEMENT; public final static String MMX_APP_REG = MMX_ELEMENT; public final static String MMX_DEV_REG = MMX_ELEMENT; public final static String MMX_MMXMETA = "mmxmeta"; public final static String MMX_META = "meta"; public final static String MMX_PAYLOAD = "payload"; /** * The default encoding type to be used for binary payload. */ public final static String BASE64 = "base64"; /** * The default message type if it is not specified or it is empty. */ public final static String MMX_MTYPE_UNKNOWN = "unknown"; /** * The message type for GeoLocaion. */ public final static String MMX_MTYPE_GEOLOC = "geoloc"; /** * The message type for MMXError. */ public final static String MMX_MTYPE_ERROR = "mmxerror"; // XEP-0184 message delivery receipts public final static String XMPP_REQUEST = "request"; public final static String XMPP_RECEIVED = "received"; public final static String XMPP_ATTR_ID = "id"; public final static String XMPP_NS_RECEIPTS = "urn:xmpp:receipts"; /** * The namespaces used in the MMX extension. */ public final static String MMX_NS_APP = "com.magnet:appreg"; public final static String MMX_NS_DEV = "com.magnet:dev"; public final static String MMX_NS_USER = "com.magnet:user"; public final static String MMX_NS_AUTH = "com.magnet:auth"; public final static String MMX_NS_MSG_ACTION = "com.magnet:msg:action"; public final static String MMX_NS_MSG_PAYLOAD = "com.magnet:msg:payload"; public final static String MMX_NS_MSG_STATE = "com.magnet:msg:state"; public final static String MMX_NS_MSG_ACK = "com.magnet:msg:ack"; public final static String MMX_NS_MSG_PUSH = "com.magnet:msg:push"; public final static String MMX_NS_MSG_WAKEUP = "com.magnet:msg:wakeup"; public final static String MMX_NS_PUBSUB = "com.magnet:pubsub"; public final static String MMX_NS_CONTEXT = "com.magnet:ctx"; public static final String MMX_NS_MSG_SIGNAL = "com.magnet:msg:signal"; public final static String MMX_ACTION_CODE_WAKEUP = "w"; public final static String MMX_ACTION_CODE_PUSH = "p"; /** * The attributes used in the MMX extension. */ public final static String MMX_ATTR_COMMAND = "command"; public final static String MMX_ATTR_CTYPE = "ctype"; public final static String MMX_ATTR_MTYPE = "mtype"; public final static String MMX_ATTR_STAMP = "stamp"; public final static String MMX_ATTR_CHUNK = "chunk"; public final static String MMX_ATTR_CID = "cid"; public final static String MMX_ATTR_DST = "dst"; /** * User extended properties as metadata of UserCreate; this goes into the User tables */ public final static String MMX_PROP_NAME_USER_GUEST_MODE = "guest"; public final static String MMX_PROP_VALUE_USER_GUEST_TRUE = "true"; public final static String MMX_PROP_VALUE_USER_GUEST_FALSE = "false"; public final static String MMX_PROP_VALUE_USER_GUEST_REMOVE = "remove"; public static enum UserCreateMode { /** * Anonymous user as guest. */ GUEST, // create the user as a guest user /** * Regular authenticated user. */ UPGRADE_USER // upgrade to real user; mark current logged in user as deactive if in guest mode } public final static String UTF8_CHARSET = "utf-8"; public final static int STATUS_CODE_200 = 200; public final static int STATUS_CODE_400 = 400; public final static int STATUS_CODE_500 = 500; /** * Commands for device management. */ public static enum DeviceCommand { REGISTER, UNREGISTER, QUERY, GETTAGS, SETTAGS, ADDTAGS, REMOVETAGS, } /** * Commands for application management. */ public static enum AppMgmtCommand { create, read, readMine, update, delete, } /** * Commands for account (user) management. */ public static enum UserCommand { create, delete, query, get, list, search, update, reset, getTags, setTags, addTags, removeTags, searchByTags, } /** * Commands for wake-up messages. */ public static enum PingPongCommand { /** * One way request without any response. */ ping, /** * One way response from the two-way request. */ pong, /** * Two-way request: one-way request and one-way response. */ pingpong, /** * Send a notification using the Notification payload. */ notify, /** * Wakeup the device and ask it to phone home */ retrieve, /** * Pubsub wakeup with the PubSubNotification payload. */ pubsub, } /** * Possible message states returned by the MessageManager. */ public static enum MessageState { /** * The message is in an unknown state. */ UNKNOWN, /** * client-only: the message has not been communicated MMX and can be cancelled. */ CLIENT_PENDING, /** * Every message starts in this state */ PENDING, /** * Multicast message has been submitted to the server. */ SUBMITTED, /** * Message has been accepted and validated by the server. */ ACCEPTED, /** * Recipient is offline and hence we need to send a wake-up notification */ WAKEUP_REQUIRED, /** * Message wake up has been timed out */ WAKEUP_TIMEDOUT, /** * We are waiting for recipient to wake up */ WAKEUP_SENT, /** * Recipient is online and hence we transitioned to this * state */ DELIVERY_ATTEMPTED, /** * XMPP packet has been delivered to the endpoint */ DELIVERED, /** * Message has been processed by the endpoint */ RECEIVED, /** * Timeout experienced by server when attempting delivery */ TIMEDOUT, } /** * Commands for message management. The setEvents/getEvents/addEvents/removeEvents * are applicable to push messages in PushManager. */ public static enum MessageCommand { query, ack, setTags, getTags, addTags, removeTags, setEvents, getEvents, addEvents, removeEvents, } /** * Commands for PubSub. */ public static enum PubSubCommand { /** * Get the latest published items. */ getlatest, /** * List all nodes under an app ID. */ listtopics, /** * Create a topic. */ createtopic, /** * Delete a topic. */ deletetopic, /** * Get topic information by a topic ID. * @deprecated #getTopics */ getTopic, /** * Get topic information by topic ID's. */ getTopics, /** * Retract a published item or all items. */ retract, /** * Retract all published items from a topic owned by a user. */ retractall, /** * Subscribe to a topic. */ subscribe, /** * Unsubscribe a subscription. */ unsubscribe, /** * Unsubscribe all topics for a device. */ unsubscribeForDev, /** * Get the summary of topics. */ getSummary, /** * Get the tags */ getTags, /** * Set the tags */ setTags, /** * Add the tags */ addTags, /** * Remove the tags */ removeTags, /** * Query for topics * @deprecated Use {@link #searchTopic} */ queryTopic, /** * Search for topics. */ searchTopic, /* * Fetch published items */ fetch, /** * Search topics by tags */ searchByTags, /** * Get published items by item ID's */ getItems, /** * Get all subscribers to a topic. */ getSubscribers, } // constants used in top level push payloads // define it here for Android sharing and gson serialized names /** * Name of the push title */ public static final String PAYLOAD_PUSH_TITLE = "title"; /** * Name of the push body text */ public static final String PAYLOAD_PUSH_BODY = "body"; /** * Name of the icon */ public static final String PAYLOAD_PUSH_ICON = "icon"; /** * Name of the sound */ public static final String PAYLOAD_PUSH_SOUND = "sound"; /** * Name of the badge */ public static final String PAYLOAD_PUSH_BADGE = "badge"; //constants related to mmx dictionary in push/ping payloads /** * Name of the mmx dictionary element */ public static final String PAYLOAD_MMX_KEY = "_mmx"; /** * Key for the callback url value */ public static final String PAYLOAD_CALLBACK_URL_KEY = "cu"; /** * Key for the type value */ public static final String PAYLOAD_TYPE_KEY = "ty"; /** * Key for the id value */ public static final String PAYLOAD_ID_KEY = "id"; /** * Key for the custom dictionary */ public static final String PAYLOAD_CUSTOM_KEY = "custom"; /** * The display name for all-versions of Android topic. */ public static final String MMX_TOPIC_ANDROID_ALL = "Android-All"; /** * The display name for all versions of iOS topic. */ public static final String MMX_TOPIC_IOS_ALL = "iOS-All"; /** * A partial display name for user's geo-location topic. */ public static final String MMX_TOPIC_GEOLOCATION = "GeoLocation"; /** * A special address for MMX multicast. When a message has multiple * recipients, the message should be sent to this address. */ public static final String MMX_MULTICAST = "mmx$multicast"; /** * Keys for the unicast message server ack, multicast message acks. */ public static final String SERVER_ACK_KEY = "serverack"; public static final String BEGIN_ACK_KEY = "beginack"; public static final String END_ACK_KEY = "endack"; /** * Flag indicated if MMX is integrated with MMS. */ public static final boolean MMS_INTEGRATION_ENABLED = true; }
apache-2.0
kubevirt/kubevirt
cluster-up/cluster/K8S_DEV_GUIDE.md
9313
# kubevirtci K8s provider dev guide. Note: in the following scenarios we are using `${KUBEVIRT_PROVIDER_VERSION}` as pointer to the `major.minor` k8s version we are using This then can map to any of these folders: * `cluster-provision/k8s/${KUBEVIRT_PROVIDER_VERSION}` * `cluster-up/cluster/k8s-${KUBEVIRT_PROVIDER_VERSION}` ## Creating or updating a provider The purpose of kubevirtci is to create pre-provisioned K8s clusters as container images, allowing people to easily run a K8s cluster. The target audience is developers of kubevirtci, who want to create a new provider, or to update an existing one. Please refer first to the following documents on how to run k8s-1.x:\ [k8s-1.x cluster-up](./K8S.md) In this doc, we will go on what kubevirtci provider image consists of, what its inner architecture is, flow of starting a pre-provisioned cluster, flow of creating a new provider, and how to create a new provider. A provider includes all the images (K8s base image, nodes OS image) and the scripts that allows it to start a cluster offline, without downloading / installing / compiling new resources. Deploying a cluster will create containers, which communicate with each other, in order to act as a K8s cluster. It's a bit different from running bare-metal cluster where the nodes are physical machines or when the nodes are virtual machines on the host itself, It gives us isolation advantage and state freezing of the needed components, allowing offline deploy, agnostic of the host OS, and installed packages. # Project structure * cluster-provision folder - creating preprovisioned clusters. * cluster-up folder - spinning up preprovisioned clusters. * gocli - gocli is a binary that assist in provisioning and spinning up a cluster. sources of gocli are at cluster-provision/gocli. # K8s Deployment Running `make cluster-up` will deploy a pre-provisioned cluster. Upon finishing deployment of a K8s deploy, we will have 3 containers: * k8s-${KUBEVIRT_PROVIDER_VERSION} vm container - a container that runs a qemu VM, which is the K8s node, in which the pods will run. * Registry container - a shared image registry. * k8s-${KUBEVIRT_PROVIDER_VERSION} dnsmasq container - a container that run dnsmasq, which gives dns and dhcp services. The containers are running and look like this: ``` [root@modi01 1.21.0]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3589e85efc7d kubevirtci/k8s-1.21.0 "/bin/bash -c '/vm.s…" About an hour ago Up About an hour k8s-1.21.0-node01 4742dc02add2 registry:2.7.1 "/entrypoint.sh /etc…" About an hour ago Up About an hour k8s-1.21.0-registry 13787e7d4ac9 kubevirtci/k8s-1.21.0 "/bin/bash -c /dnsma…" About an hour ago Up About an hour 127.0.0.1:8443->8443/tcp, 0.0.0.0:32794->2201/tcp, 0.0.0.0:32793->5000/tcp, 0.0.0.0:32792->5901/tcp, 0.0.0.0:32791->6443/tcp k8s-1.21.0-dnsmasq ``` Nodes: ``` [root@modi01 kubevirtci]# oc get nodes NAME STATUS ROLES AGE VERSION node01 Ready control-plane 83m v1.21.0 ``` # Inner look of a deployed cluster We can connect to the node of the cluster by: ``` ./cluster-up/ssh.sh node01 ``` List the pods ``` [vagrant@node01 ~]$ sudo crictl pods POD ID CREATED STATE NAME NAMESPACE ATTEMPT 403513878c8b7 10 minutes ago Ready coredns-6955765f44-m6ckl kube-system 4 0c3e25e58b9d0 10 minutes ago Ready local-volume-provisioner-fkzgk default 4 e6d96770770f4 10 minutes ago Ready coredns-6955765f44-mhfgg kube-system 4 19ad529c78acc 10 minutes ago Ready kube-flannel-ds-amd64-mq5cx kube-system 0 47acef4276900 10 minutes ago Ready kube-proxy-vtj59 kube-system 0 df5863c55a52f 11 minutes ago Ready kube-scheduler-node01 kube-system 0 ca0637d5ac82f 11 minutes ago Ready kube-apiserver-node01 kube-system 0 f0d90506ce3b8 11 minutes ago Ready kube-controller-manager-node01 kube-system 0 f873785341215 11 minutes ago Ready etcd-node01 kube-system 0 ``` Check kubelet service status ``` [vagrant@node01 ~]$ systemctl status kubelet ● kubelet.service - kubelet: The Kubernetes Node Agent Loaded: loaded (/usr/lib/systemd/system/kubelet.service; enabled; vendor preset: disabled) Drop-In: /usr/lib/systemd/system/kubelet.service.d └─10-kubeadm.conf Active: active (running) since Wed 2020-01-15 13:39:54 UTC; 11min ago Docs: https://kubernetes.io/docs/ Main PID: 4294 (kubelet) CGroup: /system.slice/kubelet.service ‣ 4294 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/boo... ``` Connect to the container that runs the vm: ``` CONTAINER=$(docker ps | grep vm | awk '{print $1}') docker exec -it $CONTAINER bash ``` From within the container we can see there is a process of qemu which runs the node as a virtual machine. ``` [root@855de8c8310f /]# ps -ef | grep qemu root 1 0 36 13:39 ? 00:05:22 qemu-system-x86_64 -enable-kvm -drive format=qcow2,file=/var/run/disk/disk.qcow2,if=virtio,cache=unsafe -device virtio-net-pci,netdev=network0,mac=52:55:00:d1:55:01 -netdev tap,id=network0,ifname=tap01,script=no,downscript=no -device virtio-rng-pci -vnc :01 -cpu host -m 5120M -smp 5 -serial pty ``` # Flow of K8s provisioning ${KUBEVIRT_PROVIDER_VERSION} `cluster-provision/k8s/${KUBEVIRT_PROVIDER_VERSION}/provision.sh` * Runs the common cluster-provision/k8s/provision.sh. * Runs cluster-provision/cli/cli (bash script). * Creates a container for dnsmasq and runs dnsmasq.sh in it. * Create a container, and runs vm.sh in it. * Creates a vm using qemu, and checks its ready (according ssh). * Runs cluster-provision/k8s/scripts/provision.sh in the container. * Update docker trusted registries. * Start kubelet service and K8s cluster. * Enable ip routing. * Apply additional manifests, such as flannel. * Wait for pods to become ready. * Pull needed images such as Ceph CSI. * Create local volume directories. * Shutdown the vm and commit its container. # Flow of K8s cluster-up ${KUBEVIRT_PROVIDER_VERSION} Run ``` export KUBEVIRT_PROVIDER=k8s-${KUBEVIRT_PROVIDER_VERSION} make cluster-up ``` * Runs cluster-up/up.sh which sources the following: * cluster-up/cluster/k8s-${KUBEVIRT_PROVIDER_VERSION}/provider.sh (selected according $KUBEVIRT_PROVIDER), which sources: * cluster-up/cluster/k8s-provider-common.sh * Runs `up` (which appears at cluster-up/cluster/k8s-provider-common.sh). It Triggers `gocli run` - (cluster-provision/gocli/cmd/run.go) which create the following containers: * Cluster container (that one with the vm from the provisioning, vm.sh is used with parameters here that starts an already created vm). * Registry. * Container for dnsmasq (provides dns, dhcp services). # Creating new K8s provider Clone folders of k8s, folder name should be x/y as in the provider name x-y (ie. k8s-${KUBEVIRT_PROVIDER_VERSION}.0) and includes: * cluster-provision/k8s/${KUBEVIRT_PROVIDER_VERSION}/provision.sh # used to create a new provider * cluster-provision/k8s/${KUBEVIRT_PROVIDER_VERSION}/publish.sh # used to publish new provider * cluster-up/cluster/k8s-${KUBEVIRT_PROVIDER_VERSION}/provider.sh # used by cluster-up * cluster-up/cluster/k8s-${KUBEVIRT_PROVIDER_VERSION}/README.md # Example - Adding a new manifest to K8s * First add the file at cluster-provision/manifests, this folder would be copied to /tmp in the container, by cluster-provision/cli/cli as part of provision. * Add this snippet at cluster-provision/k8s/scripts/provision.sh, before "Wait at least for 7 pods" line. ``` custom_manifest="/tmp/custom_manifest.yaml" kubectl --kubeconfig=/etc/kubernetes/admin.conf create -f "$custom_manifest" ``` * Run ./cluster-provision/k8s/${KUBEVIRT_PROVIDER_VERSION}/provision.sh, it will create a new provision and test it. # Manual steps for publishing a new provider The steps to create, test and integrate a new KubeVirtCI provider are [mostly automated](./K8S_AUTOMATION.md), but just in case you need to do it manually: * Run `./cluster-provision/k8s/${KUBEVIRT_PROVIDER_DIR}/publish.sh`, it will publish the new created image to quay.io * Create a PR with the following files: * The new manifest. * Updated `cluster-provision/k8s/scripts/provision.sh` * Updated `cluster-up/cluster/images.sh`.
apache-2.0
acton393/incubator-weex
weex_core/Source/include/wtf/icu/unicode/std_string.h
1592
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* ******************************************************************************* * * Copyright (C) 2009-2011, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * file name: std_string.h * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * created on: 2009feb19 * created by: Markus W. Scherer */ #ifndef __STD_STRING_H__ #define __STD_STRING_H__ /** * \file * \brief C++ API: Central ICU header for including the C++ standard &lt;string&gt; * header and for related definitions. */ #include "unicode/utypes.h" #if U_HAVE_STD_STRING #include <string> #endif // U_HAVE_STD_STRING #endif // __STD_STRING_H__
apache-2.0
rsudev/c-geo-opensource
main/src/cgeo/geocaching/filters/gui/GeocacheFilterActivity.java
24922
package cgeo.geocaching.filters.gui; import cgeo.geocaching.R; import cgeo.geocaching.activity.AbstractActionBarActivity; import cgeo.geocaching.databinding.CacheFilterActivityBinding; import cgeo.geocaching.databinding.CacheFilterListItemBinding; import cgeo.geocaching.filters.core.AndGeocacheFilter; import cgeo.geocaching.filters.core.BaseGeocacheFilter; import cgeo.geocaching.filters.core.GeocacheFilter; import cgeo.geocaching.filters.core.GeocacheFilterContext; import cgeo.geocaching.filters.core.GeocacheFilterType; import cgeo.geocaching.filters.core.IGeocacheFilter; import cgeo.geocaching.filters.core.LogicalGeocacheFilter; import cgeo.geocaching.filters.core.NotGeocacheFilter; import cgeo.geocaching.filters.core.OrGeocacheFilter; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.ui.TextParam; import cgeo.geocaching.ui.TextSpinner; import cgeo.geocaching.ui.ViewUtils; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.ui.dialog.SimpleDialog; import cgeo.geocaching.ui.recyclerview.ManagedListAdapter; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.TextUtils; import static cgeo.geocaching.filters.core.GeocacheFilterContext.FilterType.TRANSIENT; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; /** * Show a filter selection using an {@code ExpandableListView}. */ public class GeocacheFilterActivity extends AbstractActionBarActivity { public static final int REQUEST_SELECT_FILTER = 456; public static final String EXTRA_FILTER_CONTEXT = "efc"; private static final String STATE_CURRENT_FILTER = "state_current_filter"; private static final String STATE_ADVANCED_VIEW = "state_advanced_view"; private static final String STATE_FILTER_CONTEXT = "state_filter_context"; private static final String STATE_ORIGINAL_FILTER_CONFIG = "state_original_filter_config"; private static final GeocacheFilterType[] BASIC_FILTER_TYPES = new GeocacheFilterType[]{GeocacheFilterType.TYPE, GeocacheFilterType.DIFFICULTY_TERRAIN, GeocacheFilterType.STATUS }; private static final Set<GeocacheFilterType> BASIC_FILTER_TYPES_SET = new HashSet<>(Arrays.asList(BASIC_FILTER_TYPES)); private static final GeocacheFilterType[] INTERNAL_FILTER_TYPES = new GeocacheFilterType[]{GeocacheFilterType.DIFFICULTY, GeocacheFilterType.TERRAIN }; private static final Set<GeocacheFilterType> INTERNAL_FILTER_TYPES_SET = new HashSet<>(Arrays.asList(INTERNAL_FILTER_TYPES)); private GeocacheFilterContext filterContext = new GeocacheFilterContext(TRANSIENT); private String originalFilterConfig; private CacheFilterActivityBinding binding; private FilterListAdapter filterListAdapter; private CheckBox andOrFilterCheckbox; private CheckBox inverseFilterCheckbox; private CheckBox includeInconclusiveFilterCheckbox; private final TextSpinner<GeocacheFilterType> addFilter = new TextSpinner<>(); @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setThemeAndContentView(R.layout.cache_filter_activity); binding = CacheFilterActivityBinding.bind(findViewById(R.id.activity_viewroot)); binding.filterPropsCheckboxes.removeAllViews(); this.andOrFilterCheckbox = ViewUtils.addCheckboxItem(this, binding.filterPropsCheckboxes, TextParam.id(R.string.cache_filter_option_and_or), R.drawable.ic_menu_logic); this.inverseFilterCheckbox = ViewUtils.addCheckboxItem(this, binding.filterPropsCheckboxes, TextParam.id(R.string.cache_filter_option_inverse), R.drawable.ic_menu_invert); this.includeInconclusiveFilterCheckbox = ViewUtils.addCheckboxItem(this, binding.filterPropsCheckboxes, TextParam.id(R.string.cache_filter_option_include_inconclusive), R.drawable.ic_menu_vague, TextParam.id(R.string.cache_filter_option_include_inconclusive_info)); filterListAdapter = new FilterListAdapter(binding.filterList); initializeFilterAdd(); initializeStorageOptions(); // Get parameters from intent and basic cache information from database final Bundle extras = getIntent().getExtras(); if (extras != null) { filterContext = extras.getParcelable(EXTRA_FILTER_CONTEXT); } if (filterContext == null) { filterContext = new GeocacheFilterContext(TRANSIENT); } setTitle(getString(filterContext.getType().titleId)); fillViewFromFilter(filterContext.get().toConfig(), false); originalFilterConfig = getFilterFromView().toConfig(); this.binding.filterBasicAdvanced.setOnCheckedChangeListener((v, c) -> { if (c) { switchToAdvanced(); } else if (isBasicPossibleWithoutLoss()) { switchToBasic(); } else { SimpleDialog.of(this).setTitle(R.string.cache_filter_mode_basic_change_confirm_loss_title).setMessage(R.string.cache_filter_mode_basic_change_confirm_loss_message).confirm( (vv, ii) -> switchToBasic(), (vv, ii) -> this.binding.filterBasicAdvanced.setChecked(true)); } }); } @Override public void onConfigurationChanged(@NonNull final Configuration newConfig) { super.onConfigurationChanged(newConfig); } private void initializeStorageOptions() { //handling of "save" button binding.filterStorageSave.setOnClickListener(v -> { String filterName = binding.filterStorageName.getText().toString(); if (filterName.endsWith("*")) { filterName = filterName.substring(0, filterName.length() - 1); } SimpleDialog.of(this).setTitle(R.string.cache_filter_storage_save_title) .input(-1, filterName, null, null, newName -> { final GeocacheFilter filter = getFilterFromView(); if (GeocacheFilter.Storage.existsAndDiffers(newName, filter)) { SimpleDialog.of(this).setTitle(R.string.cache_filter_storage_save_confirm_title).setMessage(R.string.cache_filter_storage_save_confirm_message, newName).confirm( (dialog, which) -> saveAs(newName)); } else { saveAs(newName); } }); }); ViewUtils.setTooltip(binding.filterStorageSave, TextParam.id(R.string.cache_filter_storage_save_title)); //handling of "load/delete" button binding.filterStorageManage.setOnClickListener(v -> { final List<GeocacheFilter> filters = new ArrayList<>(GeocacheFilter.Storage.getStoredFilters()); if (filters.isEmpty()) { SimpleDialog.of(this).setTitle(R.string.cache_filter_storage_load_delete_title).setMessage(R.string.cache_filter_storage_load_delete_nofilter_message).show(); } else { Dialogs.selectItemDialogWithAdditionalDeleteButton(this, R.string.cache_filter_storage_load_delete_title, filters, (f) -> TextParam.text(f.getName()), // select listener (f) -> fillViewFromFilter(f.toConfig(), isAdvancedView()), // delete listener (f) -> SimpleDialog.of(this).setTitle(R.string.cache_filter_storage_delete_title) .setMessage(R.string.cache_filter_storage_delete_message) .confirm((dialog, which) -> { GeocacheFilter.Storage.delete(f); //if currently shown view was just deleted -> then delete it in view as well if (f.getName().contentEquals(binding.filterStorageName.getText())) { binding.filterStorageName.setText(""); } }) ); } }); ViewUtils.setTooltip(binding.filterStorageManage, TextParam.id(R.string.cache_filter_storage_load_delete_title)); } private void saveAs(final String newName) { binding.filterStorageName.setText(newName); final GeocacheFilter filter = getFilterFromView(); GeocacheFilter.Storage.save(filter); } @Override public void onSaveInstanceState(@NonNull final Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_CURRENT_FILTER, getFilterFromView().toConfig()); outState.putBoolean(STATE_ADVANCED_VIEW, isAdvancedView()); outState.putParcelable(STATE_FILTER_CONTEXT, filterContext); outState.putString(STATE_ORIGINAL_FILTER_CONFIG, originalFilterConfig); } @Override protected void onRestoreInstanceState(@NonNull final Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.getString(STATE_CURRENT_FILTER) != null) { fillViewFromFilter(savedInstanceState.getString(STATE_CURRENT_FILTER), savedInstanceState.getBoolean(STATE_ADVANCED_VIEW)); } filterContext = (GeocacheFilterContext) savedInstanceState.getSerializable(STATE_FILTER_CONTEXT); if (filterContext == null) { filterContext = new GeocacheFilterContext(TRANSIENT); } originalFilterConfig = savedInstanceState.getString(STATE_ORIGINAL_FILTER_CONFIG); } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.menu_ok_cancel, menu); menu.findItem(R.id.menu_item_delete).setVisible(true); return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { // Handle presses on the action bar items final int itemId = item.getItemId(); if (itemId == R.id.menu_item_delete) { clearView(); return true; } else if (itemId == R.id.menu_item_save) { finishWithResult(); return true; } else if (itemId == R.id.menu_item_cancel) { finish(); return true; } else if (itemId == android.R.id.home) { onBackPressed(); return true; } return false; } private void fillViewFromFilter(final String inputFilter, final boolean forceAdvanced) { includeInconclusiveFilterCheckbox.setChecked(false); inverseFilterCheckbox.setChecked(false); andOrFilterCheckbox.setChecked(false); boolean setAdvanced = false; if (inputFilter != null) { try { final List<IFilterViewHolder<?>> filterList = new ArrayList<>(); final GeocacheFilter filter = GeocacheFilter.checkConfig(inputFilter); binding.filterStorageName.setText(filter.getNameForUserDisplay()); includeInconclusiveFilterCheckbox.setChecked(filter.isIncludeInconclusive()); setAdvanced = filter.isOpenInAdvancedMode(); IGeocacheFilter filterTree = filter.getTree(); if (filterTree instanceof NotGeocacheFilter) { inverseFilterCheckbox.setChecked(true); filterTree = filterTree.getChildren().get(0); } if (filterTree instanceof LogicalGeocacheFilter) { andOrFilterCheckbox.setChecked(filterTree instanceof OrGeocacheFilter); for (IGeocacheFilter c : filterTree.getChildren()) { filterList.add(FilterViewHolderCreator.createFor(c, this)); } } if (filterTree instanceof BaseGeocacheFilter) { filterList.add(FilterViewHolderCreator.createFor(filterTree, this)); } filterListAdapter.setItems(filterList); adjustFilterEmptyView(); //filterListAdapter.submitList(filterList, this::adjustFilterEmptyView); } catch (ParseException pe) { Log.w("Exception parsing input filter", pe); } } //set basic/advanced switch if (!forceAdvanced && !setAdvanced && isBasicPossibleWithoutLoss()) { this.binding.filterBasicAdvanced.setChecked(false); switchToBasic(); } else { this.binding.filterBasicAdvanced.setChecked(true); switchToAdvanced(); } } private void initializeFilterAdd() { final List<GeocacheFilterType> filterTypes = new ArrayList<>(Arrays.asList(GeocacheFilterType.values())); filterTypes.removeAll(INTERNAL_FILTER_TYPES_SET); Collections.sort(filterTypes, (left, right) -> TextUtils.COLLATOR.compare(left.getUserDisplayableName(), right.getUserDisplayableName())); addFilter.setValues(filterTypes) .setDisplayMapper(GeocacheFilterType::getUserDisplayableName) .setTextHideSelectionMarker(true) .setView(binding.filterAdditem, (v, t) -> { }) .setTextGroupMapper(GeocacheFilterType::getUserDisplayableGroup) .setChangeListener(gcf -> { filterListAdapter.addItem(0, FilterViewHolderCreator.createFor(gcf, this)); binding.filterList.smoothScrollToPosition(0); adjustFilterEmptyView(); }, false); } private void adjustFilterEmptyView() { final boolean listIsEmpty = filterListAdapter.getItemCount() == 0; binding.filterList.setVisibility(listIsEmpty ? View.GONE : View.VISIBLE); binding.filterListEmpty.setVisibility(!listIsEmpty ? View.GONE : View.VISIBLE); } private void clearView() { filterListAdapter.clearList(); andOrFilterCheckbox.setChecked(false); inverseFilterCheckbox.setChecked(false); includeInconclusiveFilterCheckbox.setChecked(false); binding.filterStorageName.setText(""); if (!isAdvancedView()) { switchToBasic(); } adjustFilterEmptyView(); } private void finishWithResult() { final Intent resultIntent = new Intent(); final GeocacheFilter newFilter = getFilterFromView(); filterContext.set(newFilter); resultIntent.putExtra(EXTRA_FILTER_CONTEXT, filterContext); FilterViewHolderCreator.clearListInfo(); setResult(Activity.RESULT_OK, resultIntent); finish(); } @Override public void onBackPressed() { final GeocacheFilter newFilter = getFilterFromView(); final boolean filterWasChanged = !originalFilterConfig.equals(newFilter.toConfig()); if (filterWasChanged) { SimpleDialog.of(this).setTitle(R.string.confirm_unsaved_changes_title).setMessage(R.string.confirm_discard_changes).confirm((dialog, which) -> finish()); } else { finish(); } } @NotNull private GeocacheFilter getFilterFromView() { IGeocacheFilter filter = null; if (filterListAdapter.getItemCount() > 0) { filter = andOrFilterCheckbox.isChecked() ? new OrGeocacheFilter() : new AndGeocacheFilter(); for (IFilterViewHolder<?> f : filterListAdapter.getItems()) { filter.addChild(FilterViewHolderCreator.createFrom(f)); } if (inverseFilterCheckbox.isChecked()) { final IGeocacheFilter notFilter = new NotGeocacheFilter(); notFilter.addChild(filter); filter = notFilter; } } return GeocacheFilter.create( binding.filterStorageName.getText().toString(), binding.filterBasicAdvanced.isChecked(), this.includeInconclusiveFilterCheckbox.isChecked(), filter); } public static void selectFilter(@NonNull final Activity context, final GeocacheFilterContext filterContext, final Collection<Geocache> filteredList, final boolean isComplete) { final Intent intent = new Intent(context, GeocacheFilterActivity.class); intent.putExtra(EXTRA_FILTER_CONTEXT, filterContext); FilterViewHolderCreator.setListInfo(filteredList, isComplete); context.startActivityForResult(intent, REQUEST_SELECT_FILTER); } private boolean isBasicPossibleWithoutLoss() { if (!StringUtils.isBlank(binding.filterStorageName.getText()) || this.inverseFilterCheckbox.isChecked() || this.andOrFilterCheckbox.isChecked() || this.includeInconclusiveFilterCheckbox.isChecked()) { return false; } final Set<GeocacheFilterType> found = new HashSet<>(); for (IFilterViewHolder<?> fvh : filterListAdapter.getItems()) { if (!BASIC_FILTER_TYPES_SET.contains(fvh.getType()) || found.contains(fvh.getType())) { return false; } if (fvh.isOf(StatusFilterViewHolder.class) && !fvh.castTo(StatusFilterViewHolder.class).canBeSimplifiedLossless()) { return false; } found.add(fvh.getType()); } return true; } private void switchToAdvanced() { this.binding.filterBasicAdvanced.setChecked(true); this.binding.filterStorageOptions.setVisibility(View.VISIBLE); this.binding.filterStorageOptionsLine.setVisibility(View.VISIBLE); this.binding.filterPropsCheckboxes.setVisibility(View.VISIBLE); this.binding.filterPropsCheckboxesLine.setVisibility(View.VISIBLE); this.binding.filterAdditem.setVisibility(View.VISIBLE); // start with the highest index, as we will remove all filters which are not actively filtering for (int pos = filterListAdapter.getItemCount() - 1; pos >= 0; pos--) { final ItemHolder itemHolder = (ItemHolder) this.binding.filterList.findViewHolderForLayoutPosition(pos); if (itemHolder != null) { if (!itemHolder.getFilterViewHolder().createFilterFromView().isFiltering()) { this.filterListAdapter.removeItem(pos); continue; } itemHolder.setControlsEnabled(true); if (itemHolder.getFilterViewHolder().isOf(StatusFilterViewHolder.class)) { itemHolder.getFilterViewHolder().castTo(StatusFilterViewHolder.class).setSimpleView(false); } } } adjustFilterEmptyView(); } private void switchToBasic() { this.binding.filterBasicAdvanced.setChecked(false); this.binding.filterStorageName.setText(""); this.inverseFilterCheckbox.setChecked(false); this.andOrFilterCheckbox.setChecked(false); this.includeInconclusiveFilterCheckbox.setChecked(false); this.binding.filterStorageOptions.setVisibility(View.GONE); this.binding.filterStorageOptionsLine.setVisibility(View.GONE); this.binding.filterPropsCheckboxes.setVisibility(View.GONE); this.binding.filterPropsCheckboxesLine.setVisibility(View.GONE); this.binding.filterAdditem.setVisibility(View.GONE); for (int pos = 0; pos < filterListAdapter.getItemCount(); pos++) { final ItemHolder itemHolder = (ItemHolder) this.binding.filterList.findViewHolderForLayoutPosition(pos); if (itemHolder != null) { itemHolder.setControlsEnabled(false); } } int startPos = 0; for (GeocacheFilterType type : BASIC_FILTER_TYPES) { boolean found = false; for (int pos = startPos; pos < this.filterListAdapter.getItemCount(); pos++) { final IFilterViewHolder<?> fvh = this.filterListAdapter.getItem(pos); if (fvh.getType() == type) { if (pos > startPos) { final IFilterViewHolder<?> item = this.filterListAdapter.removeItem(pos); this.filterListAdapter.addItem(startPos, item); } final IFilterViewHolder<?> item = this.filterListAdapter.getItem(startPos); if (item.isOf(StatusFilterViewHolder.class)) { item.castTo(StatusFilterViewHolder.class).setSimpleView(true); } found = true; break; } } if (!found) { final IFilterViewHolder<?> item = FilterViewHolderCreator.createFor(type, this); if (item.isOf(StatusFilterViewHolder.class)) { item.castTo(StatusFilterViewHolder.class).setSimpleView(true); } this.filterListAdapter.addItem(startPos, item); } startPos++; } while (this.filterListAdapter.getItemCount() > BASIC_FILTER_TYPES.length) { this.filterListAdapter.removeItem(this.filterListAdapter.getItemCount() - 1); } adjustFilterEmptyView(); } private boolean isAdvancedView() { return this.binding.filterBasicAdvanced.isChecked(); } private static class ItemHolder extends RecyclerView.ViewHolder { private final CacheFilterListItemBinding binding; private IFilterViewHolder<?> filterViewHolder; ItemHolder(final View rowView) { super(rowView); binding = CacheFilterListItemBinding.bind(rowView); } public void setFilterViewHolder(final IFilterViewHolder<?> filterViewHolder) { this.filterViewHolder = filterViewHolder; this.binding.filterTitle.setText(this.filterViewHolder.getType().getUserDisplayableName()); //create view final View view = filterViewHolder.getView(); // insert into main view final ViewGroup insertPoint = this.binding.insertPoint; insertPoint.removeAllViews(); //views are reused, so make sure to cleanup if (view.getParent() != null) { ((ViewGroup) view.getParent()).removeAllViews(); } insertPoint.addView(view); } public IFilterViewHolder<?> getFilterViewHolder() { return this.filterViewHolder; } public void setControlsEnabled(final boolean enabled) { binding.filterDelete.setVisibility(enabled ? View.VISIBLE : View.GONE); binding.filterDrag.setVisibility(enabled ? View.VISIBLE : View.GONE); } } private final class FilterListAdapter extends ManagedListAdapter<IFilterViewHolder<?>, ItemHolder> { private FilterListAdapter(final RecyclerView recyclerView) { super(new ManagedListAdapter.Config(recyclerView) .setNotifyOnPositionChange(true) .setSupportDragDrop(true)); } private void fillViewHolder(final ItemHolder holder, final IFilterViewHolder<?> filterViewHolder) { if (filterViewHolder == null) { return; } holder.setFilterViewHolder(filterViewHolder); setTheme(); } @NonNull @Override public ItemHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) { final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cache_filter_list_item, parent, false); final ItemHolder viewHolder = new ItemHolder(view); viewHolder.setControlsEnabled(isAdvancedView()); viewHolder.binding.filterDelete.setOnClickListener(v -> { removeItem(viewHolder.getBindingAdapterPosition()); adjustFilterEmptyView(); }); registerStartDrag(viewHolder, viewHolder.binding.filterDrag); return viewHolder; } @Override public void onBindViewHolder(@NonNull final ItemHolder holder, final int position) { holder.setControlsEnabled(isAdvancedView()); fillViewHolder(holder, getItem(position)); } } @Override public void onDestroy() { super.onDestroy(); } }
apache-2.0
jaxio/celerio
celerio-spi-example/src/main/java/com/jaxio/celerio/spi/example/ExampleEntity.java
1208
/* * Copyright 2015 JAXIO http://www.jaxio.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 com.jaxio.celerio.spi.example; import com.jaxio.celerio.model.Entity; import com.jaxio.celerio.spi.EntitySpi; public class ExampleEntity implements EntitySpi { private Entity entity; @Override public void init(Entity entity) { this.entity = entity; } @Override public String velocityVar() { return "example"; } @Override public Object getTarget() { return this; } public String getHello() { return "Hello from ExampleEntity: this entity has " + entity.getCurrentAttributes().size() + " attributes"; } }
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Magnoliales/Annonaceae/Guatteria/Guatteria alutacea/Guatteria alutacea steinbachii/README.md
203
# Guatteria alutacea var. steinbachii R. E. Fr. VARIETY #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
nicolaierbs/free-your-stuff-server
src/main/java/freeyourstuff/data/model/ItemMapper.java
684
package freeyourstuff.data.model; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class ItemMapper { private static ObjectMapper mapper = new ObjectMapper(); public static String mapToJson(Item item) throws JsonGenerationException, JsonMappingException, IOException{ return mapper.writeValueAsString(item); } public static Item mapToItem(String jsonString) throws JsonParseException, JsonMappingException, IOException{ return mapper.readValue(jsonString, Item.class); } }
apache-2.0
pebble2015/cpoi
src/org/apache/poi/hpsf/MarkUnsupportedException.cpp
1808
// Generated from /POI/java/org/apache/poi/hpsf/MarkUnsupportedException.java #include <org/apache/poi/hpsf/MarkUnsupportedException.hpp> poi::hpsf::MarkUnsupportedException::MarkUnsupportedException(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::hpsf::MarkUnsupportedException::MarkUnsupportedException() : MarkUnsupportedException(*static_cast< ::default_init_tag* >(0)) { ctor(); } poi::hpsf::MarkUnsupportedException::MarkUnsupportedException(::java::lang::String* msg) : MarkUnsupportedException(*static_cast< ::default_init_tag* >(0)) { ctor(msg); } poi::hpsf::MarkUnsupportedException::MarkUnsupportedException(::java::lang::Throwable* reason) : MarkUnsupportedException(*static_cast< ::default_init_tag* >(0)) { ctor(reason); } poi::hpsf::MarkUnsupportedException::MarkUnsupportedException(::java::lang::String* msg, ::java::lang::Throwable* reason) : MarkUnsupportedException(*static_cast< ::default_init_tag* >(0)) { ctor(msg,reason); } void poi::hpsf::MarkUnsupportedException::ctor() { super::ctor(); } void poi::hpsf::MarkUnsupportedException::ctor(::java::lang::String* msg) { super::ctor(msg); } void poi::hpsf::MarkUnsupportedException::ctor(::java::lang::Throwable* reason) { super::ctor(reason); } void poi::hpsf::MarkUnsupportedException::ctor(::java::lang::String* msg, ::java::lang::Throwable* reason) { super::ctor(msg, reason); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::hpsf::MarkUnsupportedException::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.hpsf.MarkUnsupportedException", 44); return c; } java::lang::Class* poi::hpsf::MarkUnsupportedException::getClass0() { return class_(); }
apache-2.0
arthurmilliken/gateway
models/resource.js
374
const db = require('./db') ; let schema = new db.Schema({ owner: { type: String, indexed: true, required: true }, // user.id name: { type: String, required: true }, path: { type: String, unique: true, required: true }, info: db.Schema.Types.Mixed, content: db.Schema.Types.Mixed }, { timestamps: db.timestamps }); module.exports = db.model('Resource', schema);
apache-2.0
wyukawa/presto
presto-main/src/test/java/io/prestosql/memory/TestMemoryPools.java
16621
/* * 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.prestosql.memory; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.airlift.stats.TestingGcMonitor; import io.airlift.units.DataSize; import io.prestosql.Session; import io.prestosql.execution.buffer.TestingPagesSerdeFactory; import io.prestosql.memory.context.LocalMemoryContext; import io.prestosql.operator.Driver; import io.prestosql.operator.DriverContext; import io.prestosql.operator.Operator; import io.prestosql.operator.OperatorContext; import io.prestosql.operator.OutputFactory; import io.prestosql.operator.TableScanOperator; import io.prestosql.operator.TaskContext; import io.prestosql.plugin.tpch.TpchConnectorFactory; import io.prestosql.spi.Page; import io.prestosql.spi.QueryId; import io.prestosql.spi.memory.MemoryPoolId; import io.prestosql.spiller.SpillSpaceTracker; import io.prestosql.sql.planner.plan.PlanNodeId; import io.prestosql.testing.LocalQueryRunner; import io.prestosql.testing.PageConsumerOperator.PageConsumerOutputFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import static com.google.common.base.Preconditions.checkState; import static io.airlift.units.DataSize.Unit.BYTE; import static io.airlift.units.DataSize.Unit.GIGABYTE; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static io.prestosql.testing.LocalQueryRunner.queryRunnerWithInitialTransaction; import static io.prestosql.testing.TestingSession.testSessionBuilder; import static io.prestosql.testing.TestingTaskContext.createTaskContext; import static java.lang.String.format; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @Test(singleThreaded = true) public class TestMemoryPools { private static final DataSize TEN_MEGABYTES = new DataSize(10, MEGABYTE); private static final DataSize TEN_MEGABYTES_WITHOUT_TWO_BYTES = new DataSize(TEN_MEGABYTES.toBytes() - 2, BYTE); private static final DataSize ONE_BYTE = new DataSize(1, BYTE); private QueryId fakeQueryId; private LocalQueryRunner localQueryRunner; private MemoryPool userPool; private List<Driver> drivers; private TaskContext taskContext; private void setUp(Supplier<List<Driver>> driversSupplier) { checkState(localQueryRunner == null, "Already set up"); Session session = testSessionBuilder() .setCatalog("tpch") .setSchema("tiny") .setSystemProperty("task_default_concurrency", "1") .build(); localQueryRunner = queryRunnerWithInitialTransaction(session); // add tpch localQueryRunner.createCatalog("tpch", new TpchConnectorFactory(1), ImmutableMap.of()); userPool = new MemoryPool(new MemoryPoolId("test"), TEN_MEGABYTES); fakeQueryId = new QueryId("fake"); SpillSpaceTracker spillSpaceTracker = new SpillSpaceTracker(new DataSize(1, GIGABYTE)); QueryContext queryContext = new QueryContext(new QueryId("query"), TEN_MEGABYTES, new DataSize(20, MEGABYTE), userPool, new TestingGcMonitor(), localQueryRunner.getExecutor(), localQueryRunner.getScheduler(), TEN_MEGABYTES, spillSpaceTracker); taskContext = createTaskContext(queryContext, localQueryRunner.getExecutor(), session); drivers = driversSupplier.get(); } private void setUpCountStarFromOrdersWithJoin() { // query will reserve all memory in the user pool and discard the output setUp(() -> { OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> {})); return localQueryRunner.createDrivers("SELECT COUNT(*) FROM orders JOIN lineitem ON CAST(orders.orderkey AS VARCHAR) = CAST(lineitem.orderkey AS VARCHAR)", outputFactory, taskContext); }); } private RevocableMemoryOperator setupConsumeRevocableMemory(DataSize reservedPerPage, long numberOfPages) { AtomicReference<RevocableMemoryOperator> createOperator = new AtomicReference<>(); setUp(() -> { DriverContext driverContext = taskContext.addPipelineContext(0, false, false, false).addDriverContext(); OperatorContext revokableOperatorContext = driverContext.addOperatorContext( Integer.MAX_VALUE, new PlanNodeId("revokable_operator"), TableScanOperator.class.getSimpleName()); OutputFactory outputFactory = new PageConsumerOutputFactory(types -> (page -> {})); Operator outputOperator = outputFactory.createOutputOperator(2, new PlanNodeId("output"), ImmutableList.of(), Function.identity(), new TestingPagesSerdeFactory()).createOperator(driverContext); RevocableMemoryOperator revocableMemoryOperator = new RevocableMemoryOperator(revokableOperatorContext, reservedPerPage, numberOfPages); createOperator.set(revocableMemoryOperator); Driver driver = Driver.createDriver(driverContext, revocableMemoryOperator, outputOperator); return ImmutableList.of(driver); }); return createOperator.get(); } @AfterMethod(alwaysRun = true) public void tearDown() { if (localQueryRunner != null) { localQueryRunner.close(); localQueryRunner = null; } } @Test public void testBlockingOnUserMemory() { setUpCountStarFromOrdersWithJoin(); assertTrue(userPool.tryReserve(fakeQueryId, "test", TEN_MEGABYTES.toBytes())); runDriversUntilBlocked(waitingForUserMemory()); assertTrue(userPool.getFreeBytes() <= 0, format("Expected empty pool but got [%d]", userPool.getFreeBytes())); userPool.free(fakeQueryId, "test", TEN_MEGABYTES.toBytes()); assertDriversProgress(waitingForUserMemory()); } @Test public void testNotifyListenerOnMemoryReserved() { setupConsumeRevocableMemory(ONE_BYTE, 10); AtomicReference<MemoryPool> notifiedPool = new AtomicReference<>(); AtomicLong notifiedBytes = new AtomicLong(); userPool.addListener(MemoryPoolListener.onMemoryReserved(pool -> { notifiedPool.set(pool); notifiedBytes.set(pool.getReservedBytes()); })); userPool.reserve(fakeQueryId, "test", 3); assertEquals(notifiedPool.get(), userPool); assertEquals(notifiedBytes.get(), 3L); } @Test public void testMemoryFutureCancellation() { setUpCountStarFromOrdersWithJoin(); ListenableFuture<?> future = userPool.reserve(fakeQueryId, "test", TEN_MEGABYTES.toBytes()); assertTrue(!future.isDone()); try { future.cancel(true); fail("cancel should fail"); } catch (UnsupportedOperationException e) { assertEquals(e.getMessage(), "cancellation is not supported"); } userPool.free(fakeQueryId, "test", TEN_MEGABYTES.toBytes()); assertTrue(future.isDone()); } @Test public void testBlockingOnRevocableMemoryFreeUser() { setupConsumeRevocableMemory(ONE_BYTE, 10); assertTrue(userPool.tryReserve(fakeQueryId, "test", TEN_MEGABYTES_WITHOUT_TWO_BYTES.toBytes())); // we expect 2 iterations as we have 2 bytes remaining in memory pool and we allocate 1 byte per page assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2); assertTrue(userPool.getFreeBytes() <= 0, format("Expected empty pool but got [%d]", userPool.getFreeBytes())); // lets free 5 bytes userPool.free(fakeQueryId, "test", 5); assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 5); assertTrue(userPool.getFreeBytes() <= 0, format("Expected empty pool but got [%d]", userPool.getFreeBytes())); // 3 more bytes is enough for driver to finish userPool.free(fakeQueryId, "test", 3); assertDriversProgress(waitingForRevocableSystemMemory()); assertEquals(userPool.getFreeBytes(), 10); } @Test public void testBlockingOnRevocableMemoryFreeViaRevoke() { RevocableMemoryOperator revocableMemoryOperator = setupConsumeRevocableMemory(ONE_BYTE, 5); assertTrue(userPool.tryReserve(fakeQueryId, "test", TEN_MEGABYTES_WITHOUT_TWO_BYTES.toBytes())); // we expect 2 iterations as we have 2 bytes remaining in memory pool and we allocate 1 byte per page assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2); revocableMemoryOperator.getOperatorContext().requestMemoryRevoking(); // 2 more iterations assertEquals(runDriversUntilBlocked(waitingForRevocableSystemMemory()), 2); revocableMemoryOperator.getOperatorContext().requestMemoryRevoking(); // 3 more bytes is enough for driver to finish assertDriversProgress(waitingForRevocableSystemMemory()); assertEquals(userPool.getFreeBytes(), 2); } @Test public void testTaggedAllocations() { QueryId testQuery = new QueryId("test_query"); MemoryPool testPool = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE)); testPool.reserve(testQuery, "test_tag", 10); Map<String, Long> allocations = testPool.getTaggedMemoryAllocations().get(testQuery); assertEquals(allocations, ImmutableMap.of("test_tag", 10L)); // free 5 bytes for test_tag testPool.free(testQuery, "test_tag", 5); assertEquals(allocations, ImmutableMap.of("test_tag", 5L)); testPool.reserve(testQuery, "test_tag2", 20); assertEquals(allocations, ImmutableMap.of("test_tag", 5L, "test_tag2", 20L)); // free the remaining 5 bytes for test_tag testPool.free(testQuery, "test_tag", 5); assertEquals(allocations, ImmutableMap.of("test_tag2", 20L)); // free all for test_tag2 testPool.free(testQuery, "test_tag2", 20); assertEquals(testPool.getTaggedMemoryAllocations().size(), 0); } @Test public void testMoveQuery() { QueryId testQuery = new QueryId("test_query"); MemoryPool pool1 = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE)); MemoryPool pool2 = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE)); pool1.reserve(testQuery, "test_tag", 10); Map<String, Long> allocations = pool1.getTaggedMemoryAllocations().get(testQuery); assertEquals(allocations, ImmutableMap.of("test_tag", 10L)); pool1.moveQuery(testQuery, pool2); assertNull(pool1.getTaggedMemoryAllocations().get(testQuery)); allocations = pool2.getTaggedMemoryAllocations().get(testQuery); assertEquals(allocations, ImmutableMap.of("test_tag", 10L)); assertEquals(pool1.getFreeBytes(), 1000); assertEquals(pool2.getFreeBytes(), 990); pool2.free(testQuery, "test", 10); assertEquals(pool2.getFreeBytes(), 1000); } @Test public void testMoveUnknownQuery() { QueryId testQuery = new QueryId("test_query"); MemoryPool pool1 = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE)); MemoryPool pool2 = new MemoryPool(new MemoryPoolId("test"), new DataSize(1000, BYTE)); assertNull(pool1.getTaggedMemoryAllocations().get(testQuery)); pool1.moveQuery(testQuery, pool2); assertNull(pool1.getTaggedMemoryAllocations().get(testQuery)); assertNull(pool2.getTaggedMemoryAllocations().get(testQuery)); } private long runDriversUntilBlocked(Predicate<OperatorContext> reason) { long iterationsCount = 0; // run driver, until it blocks while (!isOperatorBlocked(drivers, reason)) { for (Driver driver : drivers) { driver.process(); } iterationsCount++; } // driver should be blocked waiting for memory for (Driver driver : drivers) { assertFalse(driver.isFinished()); } return iterationsCount; } private void assertDriversProgress(Predicate<OperatorContext> reason) { do { assertFalse(isOperatorBlocked(drivers, reason)); boolean progress = false; for (Driver driver : drivers) { ListenableFuture<?> blocked = driver.process(); progress = progress | blocked.isDone(); } // query should not block assertTrue(progress); } while (!drivers.stream().allMatch(Driver::isFinished)); } private Predicate<OperatorContext> waitingForUserMemory() { return (OperatorContext operatorContext) -> !operatorContext.isWaitingForMemory().isDone(); } private Predicate<OperatorContext> waitingForRevocableSystemMemory() { return (OperatorContext operatorContext) -> !operatorContext.isWaitingForRevocableMemory().isDone() && !operatorContext.isMemoryRevokingRequested(); } private static boolean isOperatorBlocked(List<Driver> drivers, Predicate<OperatorContext> reason) { for (Driver driver : drivers) { for (OperatorContext operatorContext : driver.getDriverContext().getOperatorContexts()) { if (reason.apply(operatorContext)) { return true; } } } return false; } private static class RevocableMemoryOperator implements Operator { private final DataSize reservedPerPage; private final long numberOfPages; private final OperatorContext operatorContext; private long producedPagesCount; private final LocalMemoryContext revocableMemoryContext; public RevocableMemoryOperator(OperatorContext operatorContext, DataSize reservedPerPage, long numberOfPages) { this.operatorContext = operatorContext; this.reservedPerPage = reservedPerPage; this.numberOfPages = numberOfPages; this.revocableMemoryContext = operatorContext.localRevocableMemoryContext(); } @Override public ListenableFuture<?> startMemoryRevoke() { return Futures.immediateFuture(null); } @Override public void finishMemoryRevoke() { revocableMemoryContext.setBytes(0); } @Override public OperatorContext getOperatorContext() { return operatorContext; } @Override public void finish() { revocableMemoryContext.setBytes(0); } @Override public boolean isFinished() { return producedPagesCount >= numberOfPages; } @Override public boolean needsInput() { return false; } @Override public void addInput(Page page) { throw new UnsupportedOperationException(); } @Override public Page getOutput() { revocableMemoryContext.setBytes(revocableMemoryContext.getBytes() + reservedPerPage.toBytes()); producedPagesCount++; if (producedPagesCount == numberOfPages) { finish(); } return new Page(10); } } }
apache-2.0
agentframework/agentframework
doc/architecture/decisions/0008-minify-build.md
295
# 8. minify build Date: 2019-01-04 ## Status Accepted ## Context AgentFramework is also use for Browser ## Decision We need minify build because package.json don't have a property called `minMain` ## Consequences Hard to read the generated build. But you can read source code directly.
apache-2.0
SVilgelm/CloudFerry
cloudferry/model/storage.py
1801
# Copyright 2016 Mirantis 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. from cloudferry import model from cloudferry.model import identity @model.type_alias('volume_attachments') class Attachment(model.Model): object_id = model.PrimaryKey() server = model.Reference('cloudferry.model.compute.Server', ensure_existence=False) volume = model.Dependency('cloudferry.model.storage.Volume') device = model.String(required=True) def equals(self, other): # pylint: disable=no-member if super(Attachment, self).equals(other): return True if self.server is None: return False return self.server.equals(other.server) and self.device == other.device @model.type_alias('volumes') class Volume(model.Model): object_id = model.PrimaryKey() name = model.String(required=True, allow_none=True) description = model.String(required=True, allow_none=True) availability_zone = model.String(required=True) encrypted = model.Boolean(missing=False) host = model.String(required=True) size = model.Integer(required=True) tenant = model.Dependency(identity.Tenant, required=True) metadata = model.Dict(missing=dict) volume_type = model.String(required=True, allow_none=True)
apache-2.0
vespa-engine/vespa
searchcore/src/vespa/searchcore/proton/matching/session_manager_explorer.h
771
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/vespalib/net/state_explorer.h> namespace proton::matching { class SessionManager; /** * Class used to explore the state of a session manager */ class SessionManagerExplorer : public vespalib::StateExplorer { private: const SessionManager &_manager; public: SessionManagerExplorer(const SessionManager &manager) : _manager(manager) {} virtual void get_state(const vespalib::slime::Inserter &inserter, bool full) const override; virtual std::vector<vespalib::string> get_children_names() const override; virtual std::unique_ptr<vespalib::StateExplorer> get_child(vespalib::stringref name) const override; }; }
apache-2.0
Richard-Ballard/pack-planner
src/test/java/com/github/richardballard/packplanner/item/order/ComparatorFromSortOrderFunctionTest.java
2881
/* * (C) Copyright 2016 Richard Ballard. * * 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 com.github.richardballard.packplanner.item.order; import com.github.richardballard.packplanner.item.Item; import com.google.common.collect.Ordering; import org.jetbrains.annotations.NotNull; import org.testng.annotations.Test; import java.util.Comparator; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Test public class ComparatorFromSortOrderFunctionTest { @NotNull private Item getItem(final int lengthMm) { final Item item = mock(Item.class); when(item.getLengthMm()) .thenReturn(lengthMm); return item; } public void naturalGivesSecondGreaterComparator() { final Comparator<? super Item> comparator = new ComparatorFromSortOrderFunction().apply(SortOrder.NATURAL); final Item itemA = getItem(2); final Item itemB = getItem(4); assertThat(comparator.compare(itemA, itemB)) .isEqualTo(1); assertThat(comparator.compare(itemB, itemA)) .isEqualTo(1); assertThat(comparator.compare(itemA, itemA)) .isEqualTo(0); } public void shortToLongGivesAppropriateComparator() { final Ordering<? super Item> ordering = Ordering.from(new ComparatorFromSortOrderFunction().apply(SortOrder.SHORT_TO_LONG)); final Item itemA = getItem(2); final Item itemB = getItem(4); assertThat(ordering.min(itemA, itemB)) .isEqualTo(itemA); assertThat(ordering.max(itemA, itemB)) .isEqualTo(itemB); assertThat(ordering.compare(itemA, itemA)) .isEqualTo(0); } public void longToShortGivesAppropriateComparator() { final Ordering<? super Item> ordering = Ordering.from(new ComparatorFromSortOrderFunction().apply(SortOrder.LONG_TO_SHORT)); final Item itemA = getItem(4); final Item itemB = getItem(2); assertThat(ordering.min(itemA, itemB)) .isEqualTo(itemA); assertThat(ordering.max(itemA, itemB)) .isEqualTo(itemB); assertThat(ordering.compare(itemA, itemA)) .isEqualTo(0); } }
apache-2.0
OpenSextant/Xponents
doc/core-apidocs/org/opensextant/extractors/flexpat/package-frame.html
1500
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_232) on Thu Dec 26 23:25:36 EST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.opensextant.extractors.flexpat (Xponents Core API)</title> <meta name="date" content="2019-12-26"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../org/opensextant/extractors/flexpat/package-summary.html" target="classFrame">org.opensextant.extractors.flexpat</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="AbstractFlexPat.html" title="class in org.opensextant.extractors.flexpat" target="classFrame">AbstractFlexPat</a></li> <li><a href="PatternTestCase.html" title="class in org.opensextant.extractors.flexpat" target="classFrame">PatternTestCase</a></li> <li><a href="RegexPattern.html" title="class in org.opensextant.extractors.flexpat" target="classFrame">RegexPattern</a></li> <li><a href="RegexPatternManager.html" title="class in org.opensextant.extractors.flexpat" target="classFrame">RegexPatternManager</a></li> <li><a href="TextMatchResult.html" title="class in org.opensextant.extractors.flexpat" target="classFrame">TextMatchResult</a></li> </ul> </div> </body> </html>
apache-2.0
falost/falost.github.io
static/libs/vue-router/types/router.d.ts
3536
import Vue, { ComponentOptions, PluginFunction, AsyncComponent } from "vue"; type Component = ComponentOptions<Vue> | typeof Vue | AsyncComponent; type Dictionary<T> = { [key: string]: T }; type ErrorHandler = (err: Error) => void; export type RouterMode = "hash" | "history" | "abstract"; export type RawLocation = string | Location; export type RedirectOption = RawLocation | ((to: Route) => RawLocation); export type NavigationGuard<V extends Vue = Vue> = ( to: Route, from: Route, next: (to?: RawLocation | false | ((vm: V) => any) | void) => void ) => any export declare class VueRouter { constructor (options?: RouterOptions); app: Vue; mode: RouterMode; currentRoute: Route; beforeEach (guard: NavigationGuard): Function; beforeResolve (guard: NavigationGuard): Function; afterEach (hook: (to: Route, from: Route) => any): Function; push (location: RawLocation, onComplete?: Function, onAbort?: ErrorHandler): void; replace (location: RawLocation, onComplete?: Function, onAbort?: ErrorHandler): void; go (n: number): void; back (): void; forward (): void; getMatchedComponents (to?: RawLocation | Route): Component[]; onReady (cb: Function, errorCb?: ErrorHandler): void; onError (cb: ErrorHandler): void; addRoutes (routes: RouteConfig[]): void; resolve (to: RawLocation, current?: Route, append?: boolean): { location: Location; route: Route; href: string; // backwards compat normalizedTo: Location; resolved: Route; }; static install: PluginFunction<never>; } type Position = { x: number, y: number }; type PositionResult = Position | { selector: string, offset?: Position } | void; export interface RouterOptions { routes?: RouteConfig[]; mode?: RouterMode; fallback?: boolean; base?: string; linkActiveClass?: string; linkExactActiveClass?: string; parseQuery?: (query: string) => Object; stringifyQuery?: (query: Object) => string; scrollBehavior?: ( to: Route, from: Route, savedPosition: Position | void ) => PositionResult | Promise<PositionResult>; } type RoutePropsFunction = (route: Route) => Object; export interface PathToRegexpOptions { sensitive?: boolean; strict?: boolean; end?: boolean; } export interface RouteConfig { path: string; name?: string; component?: Component; components?: Dictionary<Component>; redirect?: RedirectOption; alias?: string | string[]; children?: RouteConfig[]; meta?: any; beforeEnter?: NavigationGuard; props?: boolean | Object | RoutePropsFunction; caseSensitive?: boolean; pathToRegexpOptions?: PathToRegexpOptions; } export interface RouteRecord { path: string; regex: RegExp; components: Dictionary<Component>; instances: Dictionary<Vue>; name?: string; parent?: RouteRecord; redirect?: RedirectOption; matchAs?: string; meta: any; beforeEnter?: ( route: Route, redirect: (location: RawLocation) => void, next: () => void ) => any; props: boolean | Object | RoutePropsFunction | Dictionary<boolean | Object | RoutePropsFunction>; } export interface Location { name?: string; path?: string; hash?: string; query?: Dictionary<string | (string | null)[] | null | undefined>; params?: Dictionary<string>; append?: boolean; replace?: boolean; } export interface Route { path: string; name?: string; hash: string; query: Dictionary<string | (string | null)[]>; params: Dictionary<string>; fullPath: string; matched: RouteRecord[]; redirectedFrom?: string; meta?: any; }
apache-2.0
24-timmarsseglingarna/app
src/icomoon/style.css
1872
@font-face { font-family: 'icomoon'; src: url('fonts/icomoon.eot?d1ikzg'); src: url('fonts/icomoon.eot?d1ikzg#iefix') format('embedded-opentype'), url('fonts/icomoon.ttf?d1ikzg') format('truetype'), url('fonts/icomoon.woff?d1ikzg') format('woff'), url('fonts/icomoon.svg?d1ikzg#icomoon') format('svg'); font-weight: normal; font-style: normal; } [class^="icon-"], [class*=" icon-"] { /* use !important to prevent issues with browser extensions that change fonts */ font-family: 'icomoon' !important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .icon-clock:before { content: "\e907"; } .icon-no-sailing:before { content: "\e906"; } .icon-light:before { content: "\e905"; } .icon-engine-charging:before { content: "\e904"; } .icon-plan:before { content: "\e901"; } .icon-plus:before { content: "\f067"; } .icon-close:before { content: "\f00d"; } .icon-gear:before { content: "\f013"; } .icon-trash:before { content: "\f014"; } .icon-clock-0:before { content: "\f017"; } .icon-book:before { content: "\f02d"; } .icon-exclamation-circle:before { content: "\f06a"; } .icon-calendar:before { content: "\f073"; } .icon-list-ul:before { content: "\f0ca"; } .icon-angle-left:before { content: "\f104"; } .icon-angle-right:before { content: "\f105"; } .icon-angle-up:before { content: "\f106"; } .icon-angle-down:before { content: "\f107"; } .icon-ellipsis-v:before { content: "\f142"; } .icon-edit:before { content: "\e902"; } .icon-sailing-boat:before { content: "\e903"; } .icon-stack:before { content: "\e92e"; } .icon-plan2:before { content: "\ea82"; } .icon-pencil:before { content: "\e900"; }
apache-2.0
hcoles/pitest
pitest-entry/src/test/java/org/pitest/mutationtest/build/CompoundMutationInterceptorTest.java
4212
package org.pitest.mutationtest.build; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.pitest.bytecode.analysis.ClassTree; import org.pitest.mutationtest.engine.Mutater; import org.pitest.mutationtest.engine.MutationDetails; import java.util.Arrays; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.pitest.mutationtest.engine.MutationDetailsMother.aMutationDetail; @RunWith(MockitoJUnitRunner.class) public class CompoundMutationInterceptorTest { @Mock MutationInterceptor modifyChild; @Mock MutationInterceptor filterChild; @Mock MutationInterceptor otherChild; @Mock MutationInterceptor reportChild; @Mock MutationInterceptor cosmeticChild; @Mock Mutater mutater; CompoundMutationInterceptor testee; @Before public void setUp() { when(this.modifyChild.type()).thenReturn(InterceptorType.MODIFY); when(this.filterChild.type()).thenReturn(InterceptorType.FILTER); when(this.otherChild.type()).thenReturn(InterceptorType.OTHER); when(this.cosmeticChild.type()).thenReturn(InterceptorType.MODIFY_COSMETIC); when(this.reportChild.type()).thenReturn(InterceptorType.REPORT); } @Test public void shouldNotifyAllChildrenOfNewClass() { this.testee = new CompoundMutationInterceptor(Arrays.asList(this.modifyChild,this.filterChild)); final ClassTree aClass = new ClassTree(null); this.testee.begin(aClass); verify(this.modifyChild).begin(aClass); verify(this.filterChild).begin(aClass); } @Test public void shouldFilterChildren() { this.testee = new CompoundMutationInterceptor(Arrays.asList(this.modifyChild,this.filterChild)); final ClassTree aClass = new ClassTree(null); this.testee.filter(i -> i == modifyChild).begin(aClass); verify(this.modifyChild).begin(aClass); verify(this.filterChild, never()).begin(aClass); } @Test public void shouldChainModifiedMutantListsThroughChildrenInCorrectOrder() { // add out of order this.testee = new CompoundMutationInterceptor(Arrays.asList(this.cosmeticChild, this.otherChild, this.modifyChild, this.reportChild, this.filterChild)); final Collection<MutationDetails> original = aMutationDetail().build(1); final Collection<MutationDetails> modifyResult = aMutationDetail().build(2); final Collection<MutationDetails> filterResult = aMutationDetail().build(3); final Collection<MutationDetails> reportResult = aMutationDetail().build(3); final Collection<MutationDetails> cosmeticResult = aMutationDetail().build(3); final Collection<MutationDetails> otherResult = aMutationDetail().build(3); when(this.modifyChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(modifyResult); when(this.filterChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(filterResult); when(this.reportChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(reportResult); when(this.cosmeticChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(cosmeticResult); when(this.otherChild.intercept(any(Collection.class), any(Mutater.class))).thenReturn(otherResult); final Collection<MutationDetails> actual = this.testee.intercept(original, this.mutater); assertThat(actual).isEqualTo(reportResult); verify(this.otherChild).intercept(original,this.mutater); verify(this.modifyChild).intercept(otherResult,this.mutater); verify(this.filterChild).intercept(modifyResult,this.mutater); verify(this.cosmeticChild).intercept(cosmeticResult,this.mutater); verify(this.reportChild).intercept(cosmeticResult,this.mutater); } @Test public void shouldNotifyAllChildrenOfEnd() { this.testee = new CompoundMutationInterceptor(Arrays.asList(this.modifyChild,this.filterChild)); this.testee.end(); verify(this.modifyChild).end(); verify(this.filterChild).end(); } }
apache-2.0
quarkusio/quarkus
test-framework/maven/src/main/java/io/quarkus/maven/it/verifier/MavenProcessInvocationResult.java
1770
package io.quarkus.maven.it.verifier; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.InvocationResult; import org.apache.maven.shared.utils.cli.CommandLineException; /** * Result of {@link MavenProcessInvoker#execute(InvocationRequest)}. It keeps a reference on the created process. * * @author <a href="http://escoffier.me">Clement Escoffier</a> */ public class MavenProcessInvocationResult implements InvocationResult { private Process process; private CommandLineException exception; void destroy() { if (process != null) { process.destroy(); try { process.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } } MavenProcessInvocationResult setProcess(Process process) { this.process = process; return this; } public MavenProcessInvocationResult setException(CommandLineException exception) { // Print the stack trace immediately to give some feedback early // In intellij, the used `mvn` executable is not "executable" by default on Mac and probably linux. // You need to chmod +x the file. exception.printStackTrace(); this.exception = exception; return this; } @Override public CommandLineException getExecutionException() { return exception; } @Override public int getExitCode() { if (process == null) { throw new IllegalStateException("No process"); } else { return process.exitValue(); } } public Process getProcess() { return process; } }
apache-2.0
quarkusio/quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/request/AcceptHeaders.java
10428
package org.jboss.resteasy.reactive.server.core.request; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.BadRequestException; import javax.ws.rs.core.MediaType; /** * @author Pascal S. de Kloe */ public class AcceptHeaders { /** * Gets the strings from a comma-separated list. * All "*" entries are replaced with {@code null} keys. * * @param header the header value. * @return the listed items in order of appearance or {@code null} if the header didn't contain any entries. */ public static Map<String, QualityValue> getStringQualityValues(String header) { if (header == null) { return null; } header = header.trim(); if (header.length() == 0) { return null; } Map<String, QualityValue> result = new LinkedHashMap<String, QualityValue>(); int offset = 0; while (true) { int endIndex = header.indexOf(',', offset); String content; if (endIndex < 0) { content = header.substring(offset); } else { content = header.substring(offset, endIndex); } QualityValue qualityValue = QualityValue.DEFAULT; int qualityIndex = content.indexOf(';'); if (qualityIndex >= 0) { String parameter = content.substring(qualityIndex + 1); content = content.substring(0, qualityIndex); int equalsIndex = parameter.indexOf('='); if (equalsIndex < 0) { throw new BadRequestException("Malformed parameter: " + parameter); } String name = parameter.substring(0, equalsIndex).trim(); if (!"q".equals(name)) { throw new BadRequestException("Unsupported parameter: " + parameter); } String value = parameter.substring(equalsIndex + 1).trim(); qualityValue = QualityValue.valueOf(value); } content = content.trim(); if (content.length() == 0) { throw new BadRequestException("Empty Field in header: " + header); } if (content.equals("*")) { result.put(null, qualityValue); } else { result.put(content, qualityValue); } if (endIndex < 0) { break; } offset = endIndex + 1; } return result; } /** * Gets the locales from a comma-separated list. * Any "*" entries are replaced with {@code null} keys. * * @param header the header value. * @return the listed items in order of appearance or {@code null} if the header didn't contain any entries. */ public static Map<Locale, QualityValue> getLocaleQualityValues(String header) { Map<String, QualityValue> stringResult = getStringQualityValues(header); if (stringResult == null) return null; Map<Locale, QualityValue> result = new LinkedHashMap<Locale, QualityValue>(stringResult.size() * 2); for (Entry<String, QualityValue> entry : stringResult.entrySet()) { QualityValue quality = entry.getValue(); Locale locale = null; String value = entry.getKey(); if (value != null) { int length = value.length(); if (length == 2) { locale = new Locale(value); } else if (length == 5 && value.charAt(2) == '-') { String language = value.substring(0, 2); String country = value.substring(3, 5); locale = new Locale(language, country); } else { //LogMessages.LOGGER.ignoringUnsupportedLocale(value); continue; } } result.put(locale, quality); } //LogMessages.LOGGER.debug(result.toString()); return result; } /** * Gets the media types from a comma-separated list. * * @param header the header value. * @return the listed items in order of appearance or {@code null} if the header didn't contain any entries. */ public static Map<MediaType, QualityValue> getMediaTypeQualityValues(String header) { if (header == null) return null; header = header.trim(); if (header.length() == 0) return null; Map<MediaType, QualityValue> result = new LinkedHashMap<MediaType, QualityValue>(); int offset = 0; while (offset >= 0) { int slashIndex = header.indexOf('/', offset); if (slashIndex < 0) throw new BadRequestException("Malformed media type: " + header); String type = header.substring(offset, slashIndex); String subtype; Map<String, String> parameters = null; QualityValue qualityValue = QualityValue.DEFAULT; offset = slashIndex + 1; int parameterStartIndex = header.indexOf(';', offset); int itemEndIndex = header.indexOf(',', offset); if (parameterStartIndex == itemEndIndex) { assert itemEndIndex == -1; subtype = header.substring(offset); offset = -1; } else if (itemEndIndex < 0 || (parameterStartIndex >= 0 && parameterStartIndex < itemEndIndex)) { subtype = header.substring(offset, parameterStartIndex); offset = parameterStartIndex + 1; parameters = new LinkedHashMap<String, String>(); offset = parseParameters(parameters, header, offset); qualityValue = evaluateAcceptParameters(parameters); } else { subtype = header.substring(offset, itemEndIndex); offset = itemEndIndex + 1; } result.put(new MediaType(type.trim(), subtype.trim(), parameters), qualityValue); } //LogMessages.LOGGER.debug(result.toString()); return result; } private static int parseParameters(Map<String, String> parameters, String header, int offset) { while (true) { int equalsIndex = header.indexOf('=', offset); if (equalsIndex < 0) throw new BadRequestException("Malformed parameters: " + header); String name = header.substring(offset, equalsIndex).trim(); offset = equalsIndex + 1; if (header.charAt(offset) == '"') { int end = offset; ++offset; do { end = header.indexOf('"', ++end); if (end < 0) throw new BadRequestException("Unclosed quotes:" + header); } while (header.charAt(end - 1) == '\\'); String value = header.substring(offset, end); parameters.put(name, value); offset = end + 1; int parameterEndIndex = header.indexOf(';', offset); int itemEndIndex = header.indexOf(',', offset); if (parameterEndIndex == itemEndIndex) { assert itemEndIndex == -1; if (header.substring(offset).trim().length() != 0) throw new BadRequestException("Extra characters after quoted string:" + header); return -1; } else if (parameterEndIndex < 0 || (itemEndIndex >= 0 && itemEndIndex < parameterEndIndex)) { if (header.substring(offset, itemEndIndex).trim().length() != 0) throw new BadRequestException("Extra characters after quoted string:" + header); return itemEndIndex + 1; } else { if (header.substring(offset, parameterEndIndex).trim().length() != 0) throw new BadRequestException("Extra characters after quoted string:" + header); offset = parameterEndIndex + 1; } } else { int parameterEndIndex = header.indexOf(';', offset); int itemEndIndex = header.indexOf(',', offset); if (parameterEndIndex == itemEndIndex) { assert itemEndIndex == -1; String value = header.substring(offset).trim(); parameters.put(name, value); return -1; } else if (parameterEndIndex < 0 || (itemEndIndex >= 0 && itemEndIndex < parameterEndIndex)) { String value = header.substring(offset, itemEndIndex).trim(); parameters.put(name, value); return itemEndIndex + 1; } else { String value = header.substring(offset, parameterEndIndex).trim(); parameters.put(name, value); offset = parameterEndIndex + 1; } } } } /** * Evaluates and removes the accept parameters. * * <pre> * accept-params = ";" "q" "=" qvalue *( accept-extension ) * accept-extension = ";" token [ "=" ( token | quoted-string ) ] * </pre> * * @param parameters all parameters in order of appearance. * @return the qvalue. * @see "accept-params */ private static QualityValue evaluateAcceptParameters(Map<String, String> parameters) { Iterator<String> i = parameters.keySet().iterator(); while (i.hasNext()) { String name = i.next(); if ("q".equals(name)) { if (i.hasNext()) { //LogMessages.LOGGER.acceptExtensionsNotSupported(); i.remove(); do { i.next(); i.remove(); } while (i.hasNext()); return QualityValue.NOT_ACCEPTABLE; } else { String value = parameters.get(name); i.remove(); return QualityValue.valueOf(value); } } } return QualityValue.DEFAULT; } }
apache-2.0
akalankapagoda/andes
modules/andes-core/broker/src/main/java/org/wso2/andes/server/exchange/AbstractExchange.java
10726
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.wso2.andes.server.exchange; import org.apache.log4j.Logger; import org.wso2.andes.AMQException; import org.wso2.andes.framing.AMQShortString; import org.wso2.andes.server.binding.Binding; import org.wso2.andes.server.configuration.ConfigStore; import org.wso2.andes.server.configuration.ConfiguredObject; import org.wso2.andes.server.configuration.ExchangeConfigType; import org.wso2.andes.server.logging.LogSubject; import org.wso2.andes.server.logging.actors.CurrentActor; import org.wso2.andes.server.logging.messages.ExchangeMessages; import org.wso2.andes.server.logging.subjects.ExchangeLogSubject; import org.wso2.andes.server.management.Managable; import org.wso2.andes.server.management.ManagedObject; import org.wso2.andes.server.message.InboundMessage; import org.wso2.andes.server.queue.AMQQueue; import org.wso2.andes.server.queue.BaseQueue; import org.wso2.andes.server.queue.QueueRegistry; import org.wso2.andes.server.virtualhost.VirtualHost; import javax.management.JMException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public abstract class AbstractExchange implements Exchange, Managable { private AMQShortString _name; private final AtomicBoolean _closed = new AtomicBoolean(); private Exchange _alternateExchange; protected boolean _durable; protected int _ticket; private VirtualHost _virtualHost; private final List<Exchange.Task> _closeTaskList = new CopyOnWriteArrayList<Exchange.Task>(); protected AbstractExchangeMBean _exchangeMbean; /** * Whether the exchange is automatically deleted once all queues have detached from it */ protected boolean _autoDelete; //The logSubject for ths exchange private LogSubject _logSubject; private Map<ExchangeReferrer,Object> _referrers = new ConcurrentHashMap<ExchangeReferrer,Object>(); private final CopyOnWriteArrayList<Binding> _bindings = new CopyOnWriteArrayList<Binding>(); private final ExchangeType<? extends Exchange> _type; private UUID _id; private final AtomicInteger _bindingCountHigh = new AtomicInteger(); private final AtomicLong _receivedMessageCount = new AtomicLong(); private final AtomicLong _receivedMessageSize = new AtomicLong(); private final AtomicLong _routedMessageCount = new AtomicLong(); private final AtomicLong _routedMessageSize = new AtomicLong(); private final CopyOnWriteArrayList<Exchange.BindingListener> _listeners = new CopyOnWriteArrayList<Exchange.BindingListener>(); //TODO : persist creation time private long _createTime = System.currentTimeMillis(); public AbstractExchange(final ExchangeType<? extends Exchange> type) { _type = type; } public AMQShortString getNameShortString() { return _name; } public final AMQShortString getTypeShortString() { return _type.getName(); } /** * Concrete exchanges must implement this method in order to create the managed representation. This is * called during initialisation (template method pattern). * @return the MBean */ protected abstract AbstractExchangeMBean createMBean() throws JMException; public void initialise(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete) throws AMQException { _virtualHost = host; _name = name; _durable = durable; _autoDelete = autoDelete; _ticket = ticket; // TODO - fix _id = getConfigStore().createId(); getConfigStore().addConfiguredObject(this); try { _exchangeMbean = createMBean(); _exchangeMbean.register(); } catch (JMException e) { getLogger().error(e); } _logSubject = new ExchangeLogSubject(this, this.getVirtualHost()); // Log Exchange creation CurrentActor.get().message(ExchangeMessages.CREATED(String.valueOf(getTypeShortString()), String.valueOf(name), durable)); } public ConfigStore getConfigStore() { return getVirtualHost().getConfigStore(); } public abstract Logger getLogger(); public boolean isDurable() { return _durable; } public boolean isAutoDelete() { return _autoDelete; } public int getTicket() { return _ticket; } public void close() throws AMQException { if(_closed.compareAndSet(false,true)) { if (_exchangeMbean != null) { _exchangeMbean.unregister(); } getConfigStore().removeConfiguredObject(this); if(_alternateExchange != null) { _alternateExchange.removeReference(this); } CurrentActor.get().message(_logSubject, ExchangeMessages.DELETED()); for(Task task : _closeTaskList) { task.onClose(this); } _closeTaskList.clear(); } } public String toString() { return getClass().getSimpleName() + "[" + getNameShortString() +"]"; } public ManagedObject getManagedObject() { return _exchangeMbean; } public VirtualHost getVirtualHost() { return _virtualHost; } public QueueRegistry getQueueRegistry() { return getVirtualHost().getQueueRegistry(); } public boolean isBound(String bindingKey, Map<String,Object> arguments, AMQQueue queue) { return isBound(new AMQShortString(bindingKey), queue); } public boolean isBound(String bindingKey, AMQQueue queue) { return isBound(new AMQShortString(bindingKey), queue); } public boolean isBound(String bindingKey) { return isBound(new AMQShortString(bindingKey)); } public Exchange getAlternateExchange() { return _alternateExchange; } public void setAlternateExchange(Exchange exchange) { if(_alternateExchange != null) { _alternateExchange.removeReference(this); } if(exchange != null) { exchange.addReference(this); } _alternateExchange = exchange; } public void removeReference(ExchangeReferrer exchange) { _referrers.remove(exchange); } public void addReference(ExchangeReferrer exchange) { _referrers.put(exchange, Boolean.TRUE); } public boolean hasReferrers() { return !_referrers.isEmpty(); } public void addCloseTask(final Task task) { _closeTaskList.add(task); } public void removeCloseTask(final Task task) { _closeTaskList.remove(task); } public final void addBinding(final Binding binding) { _bindings.add(binding); int bindingCountSize = _bindings.size(); int maxBindingsSize; while((maxBindingsSize = _bindingCountHigh.get()) < bindingCountSize) { _bindingCountHigh.compareAndSet(maxBindingsSize, bindingCountSize); } for(BindingListener listener : _listeners) { listener.bindingAdded(this, binding); } onBind(binding); } public long getBindingCountHigh() { return _bindingCountHigh.get(); } public final void removeBinding(final Binding binding) { onUnbind(binding); for(BindingListener listener : _listeners) { listener.bindingRemoved(this, binding); } _bindings.remove(binding); } public final Collection<Binding> getBindings() { return Collections.unmodifiableList(_bindings); } protected abstract void onBind(final Binding binding); protected abstract void onUnbind(final Binding binding); public String getName() { return _name.toString(); } public ExchangeType getType() { return _type; } public Map<String, Object> getArguments() { // TODO - Fix return Collections.EMPTY_MAP; } public UUID getId() { return _id; } public ExchangeConfigType getConfigType() { return ExchangeConfigType.getInstance(); } public ConfiguredObject getParent() { return _virtualHost; } public long getBindingCount() { return getBindings().size(); } public final ArrayList<? extends BaseQueue> route(final InboundMessage message) { _receivedMessageCount.incrementAndGet(); _receivedMessageSize.addAndGet(message.getSize()); final ArrayList<? extends BaseQueue> queues = doRoute(message); if(queues != null && !queues.isEmpty()) { _routedMessageCount.incrementAndGet(); _routedMessageSize.addAndGet(message.getSize()); } return queues; } protected abstract ArrayList<? extends BaseQueue> doRoute(final InboundMessage message); public long getMsgReceives() { return _receivedMessageCount.get(); } public long getMsgRoutes() { return _routedMessageCount.get(); } public long getByteReceives() { return _receivedMessageSize.get(); } public long getByteRoutes() { return _routedMessageSize.get(); } public long getCreateTime() { return _createTime; } public void addBindingListener(final BindingListener listener) { _listeners.add(listener); } public void removeBindingListener(final BindingListener listener) { _listeners.remove(listener); } }
apache-2.0
mdoering/backbone
life/Plantae/Bryophyta/Bryopsida/Hypnales/Hypnaceae/Isopterygium/Isopterygium tenerum/ Syn. Isopterygium drummondii/README.md
192
# Isopterygium drummondii Crum et al. SPECIES #### Status SYNONYM #### According to Integrated Taxonomic Information System #### Published in null #### Original name null ### Remarks null
apache-2.0
baowp/platform
biz/src/main/java/com/abbcc/module/usersite/AttachAction.java
1740
/** * Copyright (c) 2010 Abbcc Corp. * No 225,Wen Yi RD, Hang Zhou, Zhe Jiang, China. * All rights reserved. * * "AttachAction.java is the copyrighted, * proprietary property of Abbcc Company and its * subsidiaries and affiliates which retain all right, title and interest * therein." * * Revision History * * Date Programmer Notes * --------- --------------------- -------------------------------------------- * 2010-3-22 baowp initial */ package com.abbcc.module.usersite; import java.util.Date; import com.abbcc.action.FileUploadAction; import com.abbcc.models.AbcAttachment; import com.abbcc.util.ObjectUtil; import com.abbcc.util.constant.ModelType; @SuppressWarnings("serial") public class AttachAction extends FileUploadAction<AbcAttachment> { public String callback; private String uploaded() { uploadImage(); return "back"; } protected void prepareAttach(AbcAttachment attach){ entity.setBelongType(ModelType.AE); ObjectUtil.extend(attach, entity); } public String topic() { return uploaded(); } public String sign(){ return uploaded(); } public String nav(){ return uploaded(); } public String title(){ return uploaded(); } public String inBg(){ return uploaded(); } public String outBg(){ return uploaded(); } public String log(){ return uploaded(); } public String flash(){ doUpload(); if(uploadFilePath!=null){ entity.setBelongType(ModelType.AE); entity.setServerPath(uploadFilePath); entity.setFilename(newFilename); entity.setUserId(getCurrentUser().getUserId()); entity.setUploadTime(new Date()); attachmentService.save(entity); } return "back"; } }
apache-2.0
quarkusio/quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/providers/serialisers/jsonp/ServerJsonStructureHandler.java
1483
package org.jboss.resteasy.reactive.server.providers.serialisers.jsonp; import java.io.ByteArrayOutputStream; import java.lang.reflect.Type; import javax.json.JsonObject; import javax.json.JsonStructure; import javax.json.JsonWriter; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.common.providers.serialisers.jsonp.JsonStructureHandler; import org.jboss.resteasy.reactive.common.providers.serialisers.jsonp.JsonpUtil; import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo; import org.jboss.resteasy.reactive.server.spi.ServerMessageBodyWriter; import org.jboss.resteasy.reactive.server.spi.ServerRequestContext; public class ServerJsonStructureHandler extends JsonStructureHandler implements ServerMessageBodyWriter<JsonStructure> { @Override public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) { return JsonStructure.class.isAssignableFrom(type) && !JsonObject.class.isAssignableFrom(type); } @Override public void writeResponse(JsonStructure o, Type genericType, ServerRequestContext context) throws WebApplicationException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (JsonWriter writer = JsonpUtil.writer(out, context.getResponseMediaType())) { writer.write(o); } context.serverResponse().end(out.toByteArray()); } }
apache-2.0
abaditsegay/arangodb
js/apps/system/_admin/aardvark/APP/frontend/js/views/documentsView.js
35454
/*jshint browser: true */ /*jshint unused: false */ /*global arangoHelper, _, $, window, arangoHelper, templateEngine, Joi, btoa */ (function() { "use strict"; window.DocumentsView = window.PaginationView.extend({ filters : { "0" : true }, filterId : 0, paginationDiv : "#documentsToolbarF", idPrefix : "documents", addDocumentSwitch: true, activeFilter: false, lastCollectionName: undefined, restoredFilters: [], editMode: false, allowUpload: false, el: '#content', table: '#documentsTableID', template: templateEngine.createTemplate("documentsView.ejs"), collectionContext : { prev: null, next: null }, editButtons: ["#deleteSelected", "#moveSelected"], initialize : function () { this.documentStore = this.options.documentStore; this.collectionsStore = this.options.collectionsStore; this.tableView = new window.TableView({ el: this.table, collection: this.collection }); this.tableView.setRowClick(this.clicked.bind(this)); this.tableView.setRemoveClick(this.remove.bind(this)); }, setCollectionId : function (colid, pageid) { this.collection.setCollection(colid); var type = arangoHelper.collectionApiType(colid); this.pageid = pageid; this.type = type; this.checkCollectionState(); this.collection.getDocuments(this.getDocsCallback.bind(this)); this.collectionModel = this.collectionsStore.get(colid); }, getDocsCallback: function() { //Hide first/last pagination $('#documents_last').css("visibility", "hidden"); $('#documents_first').css("visibility", "hidden"); this.drawTable(); this.renderPaginationElements(); }, events: { "click #collectionPrev" : "prevCollection", "click #collectionNext" : "nextCollection", "click #filterCollection" : "filterCollection", "click #markDocuments" : "editDocuments", "click #indexCollection" : "indexCollection", "click #importCollection" : "importCollection", "click #exportCollection" : "exportCollection", "click #filterSend" : "sendFilter", "click #addFilterItem" : "addFilterItem", "click .removeFilterItem" : "removeFilterItem", "click #deleteSelected" : "deleteSelectedDocs", "click #moveSelected" : "moveSelectedDocs", "click #addDocumentButton" : "addDocumentModal", "click #documents_first" : "firstDocuments", "click #documents_last" : "lastDocuments", "click #documents_prev" : "prevDocuments", "click #documents_next" : "nextDocuments", "click #confirmDeleteBtn" : "confirmDelete", "click .key" : "nop", "keyup" : "returnPressedHandler", "keydown .queryline input" : "filterValueKeydown", "click #importModal" : "showImportModal", "click #resetView" : "resetView", "click #confirmDocImport" : "startUpload", "click #exportDocuments" : "startDownload", "change #newIndexType" : "selectIndexType", "click #createIndex" : "createIndex", "click .deleteIndex" : "prepDeleteIndex", "click #confirmDeleteIndexBtn" : "deleteIndex", "click #documentsToolbar ul" : "resetIndexForms", "click #indexHeader #addIndex" : "toggleNewIndexView", "click #indexHeader #cancelIndex" : "toggleNewIndexView", "change #documentSize" : "setPagesize", "change #docsSort" : "setSorting" }, showSpinner: function() { $('#uploadIndicator').show(); }, hideSpinner: function() { $('#uploadIndicator').hide(); }, showImportModal: function() { $("#docImportModal").modal('show'); }, hideImportModal: function() { $("#docImportModal").modal('hide'); }, setPagesize: function() { var size = $('#documentSize').find(":selected").val(); this.collection.setPagesize(size); this.collection.getDocuments(this.getDocsCallback.bind(this)); }, setSorting: function() { var sortAttribute = $('#docsSort').val(); if (sortAttribute === '' || sortAttribute === undefined || sortAttribute === null) { sortAttribute = '_key'; } this.collection.setSort(sortAttribute); }, returnPressedHandler: function(event) { if (event.keyCode === 13 && $(event.target).is($('#docsSort'))) { this.collection.getDocuments(this.getDocsCallback.bind(this)); } if (event.keyCode === 13) { if ($("#confirmDeleteBtn").attr("disabled") === false) { this.confirmDelete(); } } }, toggleNewIndexView: function () { $('#indexEditView').toggle("fast"); $('#newIndexView').toggle("fast"); this.resetIndexForms(); }, nop: function(event) { event.stopPropagation(); }, resetView: function () { //clear all input/select - fields $('input').val(''); $('select').val('=='); this.removeAllFilterItems(); $('#documentSize').val(this.collection.getPageSize()); $('#documents_last').css("visibility", "visible"); $('#documents_first').css("visibility", "visible"); this.addDocumentSwitch = true; this.collection.resetFilter(); this.collection.loadTotal(); this.restoredFilters = []; //for resetting json upload this.allowUpload = false; this.files = undefined; this.file = undefined; $('#confirmDocImport').attr("disabled", true); this.markFilterToggle(); this.collection.getDocuments(this.getDocsCallback.bind(this)); }, startDownload: function() { var query = this.collection.buildDownloadDocumentQuery(); if (query !== '' || query !== undefined || query !== null) { window.open(encodeURI("query/result/download/" + btoa(JSON.stringify(query)))); } else { arangoHelper.arangoError("Document error", "could not download documents"); } }, startUpload: function () { var result; if (this.allowUpload === true) { this.showSpinner(); result = this.collection.uploadDocuments(this.file); if (result !== true) { this.hideSpinner(); this.hideImportModal(); this.resetView(); arangoHelper.arangoError(result); return; } this.hideSpinner(); this.hideImportModal(); this.resetView(); return; } }, uploadSetup: function () { var self = this; $('#importDocuments').change(function(e) { self.files = e.target.files || e.dataTransfer.files; self.file = self.files[0]; $('#confirmDocImport').attr("disabled", false); self.allowUpload = true; }); }, buildCollectionLink : function (collection) { return "collection/" + encodeURIComponent(collection.get('name')) + '/documents/1'; }, /* prevCollection : function () { if (this.collectionContext.prev !== null) { $('#collectionPrev').parent().removeClass('disabledPag'); window.App.navigate( this.buildCollectionLink( this.collectionContext.prev ), { trigger: true } ); } else { $('#collectionPrev').parent().addClass('disabledPag'); } }, nextCollection : function () { if (this.collectionContext.next !== null) { $('#collectionNext').parent().removeClass('disabledPag'); window.App.navigate( this.buildCollectionLink( this.collectionContext.next ), { trigger: true } ); } else { $('#collectionNext').parent().addClass('disabledPag'); } },*/ markFilterToggle: function () { if (this.restoredFilters.length > 0) { $('#filterCollection').addClass('activated'); } else { $('#filterCollection').removeClass('activated'); } }, //need to make following functions automatically! editDocuments: function () { $('#indexCollection').removeClass('activated'); $('#importCollection').removeClass('activated'); $('#exportCollection').removeClass('activated'); this.markFilterToggle(); $('#markDocuments').toggleClass('activated'); this.changeEditMode(); $('#filterHeader').hide(); $('#importHeader').hide(); $('#indexHeader').hide(); $('#editHeader').slideToggle(200); $('#exportHeader').hide(); }, filterCollection : function () { $('#indexCollection').removeClass('activated'); $('#importCollection').removeClass('activated'); $('#exportCollection').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); this.markFilterToggle(); this.activeFilter = true; $('#importHeader').hide(); $('#indexHeader').hide(); $('#editHeader').hide(); $('#exportHeader').hide(); $('#filterHeader').slideToggle(200); var i; for (i in this.filters) { if (this.filters.hasOwnProperty(i)) { $('#attribute_name' + i).focus(); return; } } }, exportCollection: function () { $('#indexCollection').removeClass('activated'); $('#importCollection').removeClass('activated'); $('#filterHeader').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); $('#exportCollection').toggleClass('activated'); this.markFilterToggle(); $('#exportHeader').slideToggle(200); $('#importHeader').hide(); $('#indexHeader').hide(); $('#filterHeader').hide(); $('#editHeader').hide(); }, importCollection: function () { this.markFilterToggle(); $('#indexCollection').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); $('#importCollection').toggleClass('activated'); $('#exportCollection').removeClass('activated'); $('#importHeader').slideToggle(200); $('#filterHeader').hide(); $('#indexHeader').hide(); $('#editHeader').hide(); $('#exportHeader').hide(); }, indexCollection: function () { this.markFilterToggle(); $('#importCollection').removeClass('activated'); $('#exportCollection').removeClass('activated'); $('#markDocuments').removeClass('activated'); this.changeEditMode(false); $('#indexCollection').toggleClass('activated'); $('#newIndexView').hide(); $('#indexEditView').show(); $('#indexHeader').slideToggle(200); $('#importHeader').hide(); $('#editHeader').hide(); $('#filterHeader').hide(); $('#exportHeader').hide(); }, changeEditMode: function (enable) { if (enable === false || this.editMode === true) { $('#documentsTableID tbody tr').css('cursor', 'default'); $('.deleteButton').fadeIn(); $('.addButton').fadeIn(); $('.selected-row').removeClass('selected-row'); this.editMode = false; this.tableView.setRowClick(this.clicked.bind(this)); } else { $('#documentsTableID tbody tr').css('cursor', 'copy'); $('.deleteButton').fadeOut(); $('.addButton').fadeOut(); $('.selectedCount').text(0); this.editMode = true; this.tableView.setRowClick(this.editModeClick.bind(this)); } }, getFilterContent: function () { var filters = [ ]; var i; for (i in this.filters) { if (this.filters.hasOwnProperty(i)) { var value = $('#attribute_value' + i).val(); try { value = JSON.parse(value); } catch (err) { value = String(value); } if ($('#attribute_name' + i).val() !== ''){ filters.push({ attribute : $('#attribute_name'+i).val(), operator : $('#operator'+i).val(), value : value }); } } } return filters; }, sendFilter : function () { this.restoredFilters = this.getFilterContent(); var self = this; this.collection.resetFilter(); this.addDocumentSwitch = false; _.each(this.restoredFilters, function (f) { if (f.operator !== undefined) { self.collection.addFilter(f.attribute, f.operator, f.value); } }); this.collection.setToFirst(); this.collection.getDocuments(this.getDocsCallback.bind(this)); this.markFilterToggle(); }, restoreFilter: function () { var self = this, counter = 0; this.filterId = 0; $('#docsSort').val(this.collection.getSort()); _.each(this.restoredFilters, function (f) { //change html here and restore filters if (counter !== 0) { self.addFilterItem(); } if (f.operator !== undefined) { $('#attribute_name' + counter).val(f.attribute); $('#operator' + counter).val(f.operator); $('#attribute_value' + counter).val(f.value); } counter++; //add those filters also to the collection self.collection.addFilter(f.attribute, f.operator, f.value); }); }, addFilterItem : function () { // adds a line to the filter widget var num = ++this.filterId; $('#filterHeader').append(' <div class="queryline querylineAdd">'+ '<input id="attribute_name' + num + '" type="text" placeholder="Attribute name">'+ '<select name="operator" id="operator' + num + '" class="filterSelect">'+ ' <option value="==">==</option>'+ ' <option value="!=">!=</option>'+ ' <option value="&lt;">&lt;</option>'+ ' <option value="&lt;=">&lt;=</option>'+ ' <option value="&gt;=">&gt;=</option>'+ ' <option value="&gt;">&gt;</option>'+ '</select>'+ '<input id="attribute_value' + num + '" type="text" placeholder="Attribute value" ' + 'class="filterValue">'+ ' <a class="removeFilterItem" id="removeFilter' + num + '">' + '<i class="icon icon-minus arangoicon"></i></a></div>'); this.filters[num] = true; }, filterValueKeydown : function (e) { if (e.keyCode === 13) { this.sendFilter(); } }, removeFilterItem : function (e) { // removes line from the filter widget var button = e.currentTarget; var filterId = button.id.replace(/^removeFilter/, ''); // remove the filter from the list delete this.filters[filterId]; delete this.restoredFilters[filterId]; // remove the line from the DOM $(button.parentElement).remove(); }, removeAllFilterItems : function () { var childrenLength = $('#filterHeader').children().length; var i; for (i = 1; i <= childrenLength; i++) { $('#removeFilter'+i).parent().remove(); } this.filters = { "0" : true }; this.filterId = 0; }, addDocumentModal: function () { var collid = window.location.hash.split("/")[1], buttons = [], tableContent = [], // second parameter is "true" to disable caching of collection type doctype = arangoHelper.collectionApiType(collid, true); if (doctype === 'edge') { tableContent.push( window.modalView.createTextEntry( 'new-edge-from-attr', '_from', '', "document _id: document handle of the linked vertex (incoming relation)", undefined, false, [ { rule: Joi.string().required(), msg: "No _from attribute given." } ] ) ); tableContent.push( window.modalView.createTextEntry( 'new-edge-to', '_to', '', "document _id: document handle of the linked vertex (outgoing relation)", undefined, false, [ { rule: Joi.string().required(), msg: "No _to attribute given." } ] ) ); tableContent.push( window.modalView.createTextEntry( 'new-edge-key-attr', '_key', undefined, "the edges unique key(optional attribute, leave empty for autogenerated key", 'is optional: leave empty for autogenerated key', false, [ {/*optional validation rules for joi*/} ] ) ); buttons.push( window.modalView.createSuccessButton('Create', this.addEdge.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Create edge', buttons, tableContent ); return; } else { tableContent.push( window.modalView.createTextEntry( 'new-document-key-attr', '_key', undefined, "the documents unique key(optional attribute, leave empty for autogenerated key", 'is optional: leave empty for autogenerated key', false, [ {/*optional validation rules for joi*/} ] ) ); buttons.push( window.modalView.createSuccessButton('Create', this.addDocument.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Create document', buttons, tableContent ); } }, addEdge: function () { var collid = window.location.hash.split("/")[1]; var from = $('.modal-body #new-edge-from-attr').last().val(); var to = $('.modal-body #new-edge-to').last().val(); var key = $('.modal-body #new-edge-key-attr').last().val(); var result; if (key !== '' || key !== undefined) { result = this.documentStore.createTypeEdge(collid, from, to, key); } else { result = this.documentStore.createTypeEdge(collid, from, to); } if (result !== false) { //$('#edgeCreateModal').modal('hide'); window.modalView.hide(); window.location.hash = "collection/"+result; } //Error else { arangoHelper.arangoError('Creating edge failed'); } }, addDocument: function() { var collid = window.location.hash.split("/")[1]; var key = $('.modal-body #new-document-key-attr').last().val(); var result; if (key !== '' || key !== undefined) { result = this.documentStore.createTypeDocument(collid, key); } else { result = this.documentStore.createTypeDocument(collid); } //Success if (result !== false) { window.modalView.hide(); window.location.hash = "collection/" + result; } else { arangoHelper.arangoError('Creating document failed'); } }, moveSelectedDocs: function() { var buttons = [], tableContent = [], toDelete = this.getSelectedDocs(); if (toDelete.length === 0) { return; } tableContent.push( window.modalView.createTextEntry( 'move-documents-to', 'Move to', '', false, 'collection-name', true, [ { rule: Joi.string().regex(/^[a-zA-Z]/), msg: "Collection name must always start with a letter." }, { rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/), msg: 'Only Symbols "_" and "-" are allowed.' }, { rule: Joi.string().required(), msg: "No collection name given." } ] ) ); buttons.push( window.modalView.createSuccessButton('Move', this.confirmMoveSelectedDocs.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Move documents', buttons, tableContent ); }, confirmMoveSelectedDocs: function() { var toMove = this.getSelectedDocs(), self = this, toCollection = $('.modal-body').last().find('#move-documents-to').val(); var callback = function() { this.collection.getDocuments(this.getDocsCallback.bind(this)); $('#markDocuments').click(); window.modalView.hide(); }.bind(this); _.each(toMove, function(key) { self.collection.moveDocument(key, self.collection.collectionID, toCollection, callback); }); }, deleteSelectedDocs: function() { var buttons = [], tableContent = []; var toDelete = this.getSelectedDocs(); if (toDelete.length === 0) { return; } tableContent.push( window.modalView.createReadOnlyEntry( undefined, toDelete.length + ' documents selected', 'Do you want to delete all selected documents?', undefined, undefined, false, undefined ) ); buttons.push( window.modalView.createDeleteButton('Delete', this.confirmDeleteSelectedDocs.bind(this)) ); window.modalView.show( 'modalTable.ejs', 'Delete documents', buttons, tableContent ); }, confirmDeleteSelectedDocs: function() { var toDelete = this.getSelectedDocs(); var deleted = [], self = this; _.each(toDelete, function(key) { var result = false; if (self.type === 'document') { result = self.documentStore.deleteDocument( self.collection.collectionID, key ); if (result) { //on success deleted.push(true); self.collection.setTotalMinusOne(); } else { deleted.push(false); arangoHelper.arangoError('Document error', 'Could not delete document.'); } } else if (self.type === 'edge') { result = self.documentStore.deleteEdge(self.collection.collectionID, key); if (result === true) { //on success self.collection.setTotalMinusOne(); deleted.push(true); } else { deleted.push(false); arangoHelper.arangoError('Edge error', 'Could not delete edge'); } } }); this.collection.getDocuments(this.getDocsCallback.bind(this)); $('#markDocuments').click(); window.modalView.hide(); }, getSelectedDocs: function() { var toDelete = []; _.each($('#documentsTableID tbody tr'), function(element) { if ($(element).hasClass('selected-row')) { toDelete.push($($(element).children()[1]).find('.key').text()); } }); return toDelete; }, remove: function (a) { this.docid = $(a.currentTarget).closest("tr").attr("id").substr(4); $("#confirmDeleteBtn").attr("disabled", false); $('#docDeleteModal').modal('show'); }, confirmDelete: function () { $("#confirmDeleteBtn").attr("disabled", true); var hash = window.location.hash.split("/"); var check = hash[3]; //to_do - find wrong event handler if (check !== 'source') { this.reallyDelete(); } }, reallyDelete: function () { var self = this; var row = $(self.target).closest("tr").get(0); var deleted = false; var result; if (this.type === 'document') { result = this.documentStore.deleteDocument( this.collection.collectionID, this.docid ); if (result) { //on success this.collection.setTotalMinusOne(); deleted = true; } else { arangoHelper.arangoError('Doc error'); } } else if (this.type === 'edge') { result = this.documentStore.deleteEdge(this.collection.collectionID, this.docid); if (result === true) { //on success this.collection.setTotalMinusOne(); deleted = true; } else { arangoHelper.arangoError('Edge error'); } } if (deleted === true) { this.collection.getDocuments(this.getDocsCallback.bind(this)); $('#docDeleteModal').modal('hide'); } }, editModeClick: function(event) { var target = $(event.currentTarget); if(target.hasClass('selected-row')) { target.removeClass('selected-row'); } else { target.addClass('selected-row'); } var selected = this.getSelectedDocs(); $('.selectedCount').text(selected.length); _.each(this.editButtons, function(button) { if (selected.length > 0) { $(button).prop('disabled', false); $(button).removeClass('button-neutral'); $(button).removeClass('disabled'); if (button === "#moveSelected") { $(button).addClass('button-success'); } else { $(button).addClass('button-danger'); } } else { $(button).prop('disabled', true); $(button).addClass('disabled'); $(button).addClass('button-neutral'); if (button === "#moveSelected") { $(button).removeClass('button-success'); } else { $(button).removeClass('button-danger'); } } }); }, clicked: function (event) { var self = event.currentTarget; window.App.navigate("collection/" + this.collection.collectionID + "/" + $(self).attr("id").substr(4), true); }, drawTable: function() { this.tableView.setElement($(this.table)).render(); // we added some icons, so we need to fix their tooltips arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "top"); $(".prettify").snippet("javascript", { style: "nedit", menu: false, startText: false, transparent: true, showNum: false }); }, checkCollectionState: function() { if (this.lastCollectionName === this.collectionName) { if (this.activeFilter) { this.filterCollection(); this.restoreFilter(); } } else { if (this.lastCollectionName !== undefined) { this.collection.resetFilter(); this.collection.setSort('_key'); this.restoredFilters = []; this.activeFilter = false; } } }, render: function() { $(this.el).html(this.template.render({})); this.tableView.setElement($(this.table)).drawLoading(); this.collectionContext = this.collectionsStore.getPosition( this.collection.collectionID ); this.getIndex(); this.breadcrumb(); this.checkCollectionState(); //set last active collection name this.lastCollectionName = this.collectionName; /* if (this.collectionContext.prev === null) { $('#collectionPrev').parent().addClass('disabledPag'); } if (this.collectionContext.next === null) { $('#collectionNext').parent().addClass('disabledPag'); } */ this.uploadSetup(); $("[data-toggle=tooltip]").tooltip(); $('.upload-info').tooltip(); arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "top"); this.renderPaginationElements(); this.selectActivePagesize(); this.markFilterToggle(); return this; }, rerender : function () { this.collection.getDocuments(this.getDocsCallback.bind(this)); }, selectActivePagesize: function() { $('#documentSize').val(this.collection.getPageSize()); }, renderPaginationElements: function () { this.renderPagination(); var total = $('#totalDocuments'); if (total.length === 0) { $('#documentsToolbarFL').append( '<a id="totalDocuments" class="totalDocuments"></a>' ); total = $('#totalDocuments'); } total.html(this.collection.getTotal() + " document(s)"); }, breadcrumb: function () { this.collectionName = window.location.hash.split("/")[1]; $('#transparentHeader').append( '<div class="breadcrumb">'+ '<a class="activeBread" href="#collections">Collections</a>'+ '<span class="disabledBread">&gt</span>'+ '<a class="disabledBread">'+this.collectionName+'</a>'+ '</div>' ); }, resetIndexForms: function () { $('#indexHeader input').val('').prop("checked", false); $('#newIndexType').val('Cap').prop('selected',true); this.selectIndexType(); }, stringToArray: function (fieldString) { var fields = []; fieldString.split(',').forEach(function(field){ field = field.replace(/(^\s+|\s+$)/g,''); if (field !== '') { fields.push(field); } }); return fields; }, createIndex: function () { //e.preventDefault(); var self = this; var indexType = $('#newIndexType').val(); var result; var postParameter = {}; var fields; var unique; var sparse; switch (indexType) { case 'Cap': var size = parseInt($('#newCapSize').val(), 10) || 0; var byteSize = parseInt($('#newCapByteSize').val(), 10) || 0; postParameter = { type: 'cap', size: size, byteSize: byteSize }; break; case 'Geo': //HANDLE ARRAY building fields = $('#newGeoFields').val(); var geoJson = self.checkboxToValue('#newGeoJson'); var constraint = self.checkboxToValue('#newGeoConstraint'); var ignoreNull = self.checkboxToValue('#newGeoIgnoreNull'); postParameter = { type: 'geo', fields: self.stringToArray(fields), geoJson: geoJson, constraint: constraint, ignoreNull: ignoreNull }; break; case 'Hash': fields = $('#newHashFields').val(); unique = self.checkboxToValue('#newHashUnique'); sparse = self.checkboxToValue('#newHashSparse'); postParameter = { type: 'hash', fields: self.stringToArray(fields), unique: unique, sparse: sparse }; break; case 'Fulltext': fields = ($('#newFulltextFields').val()); var minLength = parseInt($('#newFulltextMinLength').val(), 10) || 0; postParameter = { type: 'fulltext', fields: self.stringToArray(fields), minLength: minLength }; break; case 'Skiplist': fields = $('#newSkiplistFields').val(); unique = self.checkboxToValue('#newSkiplistUnique'); sparse = self.checkboxToValue('#newSkiplistSparse'); postParameter = { type: 'skiplist', fields: self.stringToArray(fields), unique: unique, sparse: sparse }; break; } result = self.collectionModel.createIndex(postParameter); if (result === true) { $('#collectionEditIndexTable tbody tr').remove(); self.getIndex(); self.toggleNewIndexView(); self.resetIndexForms(); } else { if (result.responseText) { var message = JSON.parse(result.responseText); arangoHelper.arangoNotification("Document error", message.errorMessage); } else { arangoHelper.arangoNotification("Document error", "Could not create index."); } } }, prepDeleteIndex: function (e) { this.lastTarget = e; this.lastId = $(this.lastTarget.currentTarget). parent(). parent(). first(). children(). first(). text(); $("#indexDeleteModal").modal('show'); }, deleteIndex: function () { var result = this.collectionModel.deleteIndex(this.lastId); if (result === true) { $(this.lastTarget.currentTarget).parent().parent().remove(); } else { arangoHelper.arangoError("Could not delete index"); } $("#indexDeleteModal").modal('hide'); }, selectIndexType: function () { $('.newIndexClass').hide(); var type = $('#newIndexType').val(); $('#newIndexType'+type).show(); }, checkboxToValue: function (id) { return $(id).prop('checked'); }, getIndex: function () { this.index = this.collectionModel.getIndex(); var cssClass = 'collectionInfoTh modal-text'; if (this.index) { var fieldString = ''; var actionString = ''; $.each(this.index.indexes, function(k, v) { if (v.type === 'primary' || v.type === 'edge') { actionString = '<span class="icon_arangodb_locked" ' + 'data-original-title="No action"></span>'; } else { actionString = '<span class="deleteIndex icon_arangodb_roundminus" ' + 'data-original-title="Delete index" title="Delete index"></span>'; } if (v.fields !== undefined) { fieldString = v.fields.join(", "); } //cut index id var position = v.id.indexOf('/'); var indexId = v.id.substr(position + 1, v.id.length); var selectivity = ( v.hasOwnProperty("selectivityEstimate") ? (v.selectivityEstimate * 100).toFixed(2) + "%" : "n/a" ); var sparse = (v.hasOwnProperty("sparse") ? v.sparse : "n/a"); $('#collectionEditIndexTable').append( '<tr>' + '<th class=' + JSON.stringify(cssClass) + '>' + indexId + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + v.type + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + v.unique + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + sparse + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + selectivity + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + fieldString + '</th>' + '<th class=' + JSON.stringify(cssClass) + '>' + actionString + '</th>' + '</tr>' ); }); arangoHelper.fixTooltips("deleteIndex", "left"); } } }); }());
apache-2.0
MatsMaker/sliderNumber
README.md
41
sliderNumber ============ ![](prew.png)
apache-2.0
google/tf-quant-finance
api_docs/tf_quant_finance/math/pde/fd_solvers.md
1033
<!-- This file is generated by a tool. Do not edit directly. For open-source contributions the docs will be updated automatically. --> *Last updated: 2022-03-09.* <div itemscope itemtype="http://developers.google.com/ReferenceObject"> <meta itemprop="name" content="tf_quant_finance.math.pde.fd_solvers" /> <meta itemprop="path" content="Stable" /> </div> # Module: tf_quant_finance.math.pde.fd_solvers <!-- Insert buttons and diff --> <table class="tfo-notebook-buttons tfo-api" align="left"> </table> <a target="_blank" href="https://github.com/google/tf-quant-finance/blob/master/tf_quant_finance/math/pde/fd_solvers.py">View source</a> Functions for solving linear parabolic PDEs. ## Functions [`solve_backward(...)`](../../../tf_quant_finance/math/pde/fd_solvers/solve_backward.md): Evolves a grid of function values backwards in time according to a PDE. [`solve_forward(...)`](../../../tf_quant_finance/math/pde/fd_solvers/solve_forward.md): Evolves a grid of function values forward in time according to a PDE.
apache-2.0
fstahnke/arx
doc/gui/org/deidentifier/arx/metric/v2/package-tree.html
17305
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <title>org.deidentifier.arx.metric.v2 Class Hierarchy (ARX GUI Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.deidentifier.arx.metric.v2 Class Hierarchy (ARX GUI Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/deidentifier/arx/metric/package-tree.html">Prev</a></li> <li><a href="../../../../../org/deidentifier/arx/risk/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/deidentifier/arx/metric/v2/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.deidentifier.arx.metric.v2</h1> <span class="strong">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/__MetricV2.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">__MetricV2</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/Cardinalities.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">Cardinalities</span></a> (implements java.io.Serializable)</li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/DomainShareMaterialized.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">DomainShareMaterialized</span></a> (implements org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/DomainShare.html" title="interface in org.deidentifier.arx.metric.v2">DomainShare</a>)</li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/DomainShareRedaction.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">DomainShareRedaction</span></a> (implements org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/DomainShare.html" title="interface in org.deidentifier.arx.metric.v2">DomainShare</a>)</li> <li type="circle">org.deidentifier.arx.aggregates.<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilder.html" title="class in org.deidentifier.arx.aggregates"><span class="strong">HierarchyBuilder</span></a>&lt;T&gt; (implements java.io.Serializable) <ul> <li type="circle">org.deidentifier.arx.aggregates.<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderGroupingBased.html" title="class in org.deidentifier.arx.aggregates"><span class="strong">HierarchyBuilderGroupingBased</span></a>&lt;T&gt; (implements java.io.Serializable) <ul> <li type="circle">org.deidentifier.arx.aggregates.<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderIntervalBased.html" title="class in org.deidentifier.arx.aggregates"><span class="strong">HierarchyBuilderIntervalBased</span></a>&lt;T&gt; <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/DomainShareInterval.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">DomainShareInterval</span></a>&lt;T&gt; (implements org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/DomainShare.html" title="interface in org.deidentifier.arx.metric.v2">DomainShare</a>)</li> </ul> </li> </ul> </li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.<a href="../../../../../org/deidentifier/arx/metric/InformationLoss.html" title="class in org.deidentifier.arx.metric"><span class="strong">InformationLoss</span></a>&lt;T&gt; (implements java.lang.Comparable&lt;T&gt;, java.io.Serializable) <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/AbstractILMultiDimensional.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">AbstractILMultiDimensional</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/AbstractILMultiDimensionalReduced.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">AbstractILMultiDimensionalReduced</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILMultiDimensionalArithmeticMean.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILMultiDimensionalArithmeticMean</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILMultiDimensionalGeometricMean.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILMultiDimensionalGeometricMean</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILMultiDimensionalMax.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILMultiDimensionalMax</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILMultiDimensionalSum.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILMultiDimensionalSum</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILMultiDimensionalRank.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILMultiDimensionalRank</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILSingleDimensional.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILSingleDimensional</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.<a href="../../../../../org/deidentifier/arx/metric/InformationLossWithBound.html" title="class in org.deidentifier.arx.metric"><span class="strong">InformationLossWithBound</span></a>&lt;T&gt; <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILMultiDimensionalWithBound.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILMultiDimensionalWithBound</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/ILSingleDimensionalWithBound.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">ILSingleDimensionalWithBound</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/IO.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">IO</span></a></li> <li type="circle">org.deidentifier.arx.metric.<a href="../../../../../org/deidentifier/arx/metric/Metric.html" title="class in org.deidentifier.arx.metric"><span class="strong">Metric</span></a>&lt;T&gt; (implements java.io.Serializable) <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/AbstractMetricMultiDimensional.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">AbstractMetricMultiDimensional</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/AbstractMetricMultiDimensionalPotentiallyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">AbstractMetricMultiDimensionalPotentiallyPrecomputed</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNMLossPotentiallyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNMLossPotentiallyPrecomputed</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUEntropyPotentiallyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUEntropyPotentiallyPrecomputed</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUNMEntropyPotentiallyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUNMEntropyPotentiallyPrecomputed</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUNMNormalizedEntropyPotentiallyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUNMNormalizedEntropyPotentiallyPrecomputed</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDHeight.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDHeight</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNMLoss.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNMLoss</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNMLossPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNMLossPrecomputed</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNMPrecision.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNMPrecision</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDPrecision.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDPrecision</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUEntropyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUEntropyPrecomputed</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUEntropy.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUEntropy</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUNMEntropyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUNMEntropyPrecomputed</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUNMEntropy.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUNMEntropy</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUNMNormalizedEntropyPrecomputed.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUNMNormalizedEntropyPrecomputed</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDNUNMNormalizedEntropy.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDNUNMNormalizedEntropy</span></a></li> </ul> </li> </ul> </li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricMDStatic.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricMDStatic</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/AbstractMetricSingleDimensional.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">AbstractMetricSingleDimensional</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricSDAECS.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricSDAECS</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricSDNMAmbiguity.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricSDNMAmbiguity</span></a></li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricSDNMDiscernability.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricSDNMDiscernability</span></a> <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricSDDiscernability.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricSDDiscernability</span></a></li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/MetricSDNMKLDivergence.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">MetricSDNMKLDivergence</span></a></li> </ul> </li> </ul> </li> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/TupleMatcher.html" title="class in org.deidentifier.arx.metric.v2"><span class="strong">TupleMatcher</span></a> (implements java.io.Serializable)</li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">java.io.Serializable <ul> <li type="circle">org.deidentifier.arx.metric.v2.<a href="../../../../../org/deidentifier/arx/metric/v2/DomainShare.html" title="interface in org.deidentifier.arx.metric.v2"><span class="strong">DomainShare</span></a></li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/deidentifier/arx/metric/package-tree.html">Prev</a></li> <li><a href="../../../../../org/deidentifier/arx/risk/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/deidentifier/arx/metric/v2/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
apache-2.0
mdoering/backbone
life/Plantae/Bryophyta/Bryopsida/Dicranales/Dicranaceae/Dicranum/Dicranum brevifolium/ Syn. Dicranum muehlenbeckii brevifolium/README.md
203
# Dicranum muehlenbeckii var. brevifolium Lindb. VARIETY #### Status SYNONYM #### According to Integrated Taxonomic Information System #### Published in null #### Original name null ### Remarks null
apache-2.0
maguero/killbill
subscription/src/test/java/org/killbill/billing/subscription/engine/dao/MockSubscriptionDaoMemory.java
23275
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2015 Groupon, Inc * Copyright 2014-2015 The Billing Project, LLC * * The Billing Project licenses this file to you 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 org.killbill.billing.subscription.engine.dao; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeSet; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.billing.callcontext.InternalCallContext; import org.killbill.billing.callcontext.InternalTenantContext; import org.killbill.billing.catalog.api.CatalogApiException; import org.killbill.billing.catalog.api.CatalogService; import org.killbill.billing.catalog.api.ProductCategory; import org.killbill.billing.catalog.api.TimeUnit; import org.killbill.billing.dao.MockNonEntityDao; import org.killbill.billing.entitlement.api.SubscriptionApiException; import org.killbill.billing.subscription.api.SubscriptionBase; import org.killbill.billing.subscription.api.migration.AccountMigrationData; import org.killbill.billing.subscription.api.migration.AccountMigrationData.BundleMigrationData; import org.killbill.billing.subscription.api.migration.AccountMigrationData.SubscriptionMigrationData; import org.killbill.billing.subscription.api.transfer.TransferCancelData; import org.killbill.billing.subscription.api.user.DefaultSubscriptionBase; import org.killbill.billing.subscription.api.user.DefaultSubscriptionBaseBundle; import org.killbill.billing.subscription.api.user.SubscriptionBaseBundle; import org.killbill.billing.subscription.api.user.SubscriptionBuilder; import org.killbill.billing.subscription.engine.core.DefaultSubscriptionBaseService; import org.killbill.billing.subscription.engine.core.SubscriptionNotificationKey; import org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao; import org.killbill.billing.subscription.events.SubscriptionBaseEvent; import org.killbill.billing.subscription.events.SubscriptionBaseEvent.EventType; import org.killbill.billing.subscription.events.user.ApiEvent; import org.killbill.billing.subscription.events.user.ApiEventType; import org.killbill.billing.util.entity.DefaultPagination; import org.killbill.billing.util.entity.Pagination; import org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory; import org.killbill.billing.util.entity.dao.MockEntityDaoBase; import org.killbill.clock.Clock; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueService; import org.killbill.notificationq.api.NotificationQueueService.NoSuchNotificationQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; public class MockSubscriptionDaoMemory extends MockEntityDaoBase<SubscriptionBundleModelDao, SubscriptionBaseBundle, SubscriptionApiException> implements SubscriptionDao { protected static final Logger log = LoggerFactory.getLogger(SubscriptionDao.class); private final List<SubscriptionBaseBundle> bundles; private final List<SubscriptionBase> subscriptions; private final TreeSet<SubscriptionBaseEvent> events; private final MockNonEntityDao mockNonEntityDao; private final Clock clock; private final NotificationQueueService notificationQueueService; private final CatalogService catalogService; @Inject public MockSubscriptionDaoMemory(final MockNonEntityDao mockNonEntityDao, final Clock clock, final NotificationQueueService notificationQueueService, final CatalogService catalogService) { super(); this.mockNonEntityDao = mockNonEntityDao; this.clock = clock; this.catalogService = catalogService; this.notificationQueueService = notificationQueueService; this.bundles = new ArrayList<SubscriptionBaseBundle>(); this.subscriptions = new ArrayList<SubscriptionBase>(); this.events = new TreeSet<SubscriptionBaseEvent>(); } public void reset() { bundles.clear(); subscriptions.clear(); events.clear(); } @Override public List<SubscriptionBaseBundle> getSubscriptionBundleForAccount(final UUID accountId, final InternalTenantContext context) { final List<SubscriptionBaseBundle> results = new ArrayList<SubscriptionBaseBundle>(); for (final SubscriptionBaseBundle cur : bundles) { if (cur.getAccountId().equals(accountId)) { results.add(cur); } } return results; } @Override public List<SubscriptionBaseBundle> getSubscriptionBundlesForKey(final String bundleKey, final InternalTenantContext context) { final List<SubscriptionBaseBundle> results = new ArrayList<SubscriptionBaseBundle>(); for (final SubscriptionBaseBundle cur : bundles) { if (cur.getExternalKey().equals(bundleKey)) { results.add(cur); } } return results; } @Override public Pagination<SubscriptionBundleModelDao> searchSubscriptionBundles(final String searchKey, final Long offset, final Long limit, final InternalTenantContext context) { final List<SubscriptionBundleModelDao> results = new LinkedList<SubscriptionBundleModelDao>(); for (final SubscriptionBundleModelDao bundleModelDao : getAll(context)) { if (bundleModelDao.getId().toString().equals(searchKey) || bundleModelDao.getExternalKey().equals(searchKey) || bundleModelDao.getAccountId().toString().equals(searchKey)) { results.add(bundleModelDao); } } return DefaultPagination.<SubscriptionBundleModelDao>build(offset, limit, results); } @Override public List<UUID> getNonAOSubscriptionIdsForKey(final String bundleKey, final InternalTenantContext context) { throw new UnsupportedOperationException(); } @Override public SubscriptionBaseBundle getSubscriptionBundleFromId(final UUID bundleId, final InternalTenantContext context) { for (final SubscriptionBaseBundle cur : bundles) { if (cur.getId().equals(bundleId)) { return cur; } } return null; } @Override public List<SubscriptionBaseBundle> getSubscriptionBundlesForAccountAndKey(final UUID accountId, final String bundleKey, final InternalTenantContext context) { final List<SubscriptionBaseBundle> results = new ArrayList<SubscriptionBaseBundle>(); for (final SubscriptionBaseBundle cur : bundles) { if (cur.getExternalKey().equals(bundleKey) && cur.getAccountId().equals(accountId)) { results.add(cur); } } return results; } @Override public SubscriptionBaseBundle createSubscriptionBundle(final DefaultSubscriptionBaseBundle bundle, final InternalCallContext context) { bundles.add(bundle); mockNonEntityDao.addTenantRecordIdMapping(bundle.getId(), context); return getSubscriptionBundleFromId(bundle.getId(), context); } @Override public SubscriptionBase getSubscriptionFromId(final UUID subscriptionId, final InternalTenantContext context) { for (final SubscriptionBase cur : subscriptions) { if (cur.getId().equals(subscriptionId)) { return buildSubscription((DefaultSubscriptionBase) cur, context); } } return null; } @Override public UUID getAccountIdFromSubscriptionId(final UUID subscriptionId, final InternalTenantContext context) { throw new UnsupportedOperationException(); } /* @Override public List<SubscriptionBase> getSubscriptionsForAccountAndKey(final UUID accountId, final String bundleKey, final InternalTenantContext callcontext) { for (final SubscriptionBaseBundle cur : bundles) { if (cur.getExternalKey().equals(bundleKey) && cur.getAccountId().equals(bundleKey)) { return getSubscriptions(cur.getId(), callcontext); } } return Collections.emptyList(); } */ @Override public void createSubscription(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> initialEvents, final InternalCallContext context) { synchronized (events) { events.addAll(initialEvents); for (final SubscriptionBaseEvent cur : initialEvents) { recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context); } } final SubscriptionBase updatedSubscription = buildSubscription(subscription, context); subscriptions.add(updatedSubscription); mockNonEntityDao.addTenantRecordIdMapping(updatedSubscription.getId(), context); } @Override public void createSubscriptionWithAddOns(final List<DefaultSubscriptionBase> subscriptions, final Map<UUID, List<SubscriptionBaseEvent>> initialEventsMap, final InternalCallContext context) { synchronized (events) { for (DefaultSubscriptionBase subscription : subscriptions) { final List<SubscriptionBaseEvent> initialEvents = initialEventsMap.get(subscription.getId()); events.addAll(initialEvents); for (final SubscriptionBaseEvent cur : initialEvents) { recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context); } final SubscriptionBase updatedSubscription = buildSubscription(subscription, context); this.subscriptions.add(updatedSubscription); mockNonEntityDao.addTenantRecordIdMapping(updatedSubscription.getId(), context); } } } @Override public void recreateSubscription(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> recreateEvents, final InternalCallContext context) { synchronized (events) { events.addAll(recreateEvents); for (final SubscriptionBaseEvent cur : recreateEvents) { recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context); } } } @Override public List<SubscriptionBase> getSubscriptions(final UUID bundleId, final List<SubscriptionBaseEvent> dryRunEvents, final InternalTenantContext context) { final List<SubscriptionBase> results = new ArrayList<SubscriptionBase>(); for (final SubscriptionBase cur : subscriptions) { if (cur.getBundleId().equals(bundleId)) { results.add(buildSubscription((DefaultSubscriptionBase) cur, context)); } } return results; } @Override public Map<UUID, List<SubscriptionBase>> getSubscriptionsForAccount(final InternalTenantContext context) { final Map<UUID, List<SubscriptionBase>> results = new HashMap<UUID, List<SubscriptionBase>>(); for (final SubscriptionBase cur : subscriptions) { if (results.get(cur.getBundleId()) == null) { results.put(cur.getBundleId(), new LinkedList<SubscriptionBase>()); } results.get(cur.getBundleId()).add(buildSubscription((DefaultSubscriptionBase) cur, context)); } return results; } @Override public List<SubscriptionBaseEvent> getEventsForSubscription(final UUID subscriptionId, final InternalTenantContext context) { synchronized (events) { final List<SubscriptionBaseEvent> results = new LinkedList<SubscriptionBaseEvent>(); for (final SubscriptionBaseEvent cur : events) { if (cur.getSubscriptionId().equals(subscriptionId)) { results.add(cur); } } return results; } } @Override public List<SubscriptionBaseEvent> getPendingEventsForSubscription(final UUID subscriptionId, final InternalTenantContext context) { synchronized (events) { final List<SubscriptionBaseEvent> results = new LinkedList<SubscriptionBaseEvent>(); for (final SubscriptionBaseEvent cur : events) { if (cur.isActive() && cur.getEffectiveDate().isAfter(clock.getUTCNow()) && cur.getSubscriptionId().equals(subscriptionId)) { results.add(cur); } } return results; } } @Override public SubscriptionBase getBaseSubscription(final UUID bundleId, final InternalTenantContext context) { for (final SubscriptionBase cur : subscriptions) { if (cur.getBundleId().equals(bundleId) && cur.getCurrentPlan().getProduct().getCategory() == ProductCategory.BASE) { return buildSubscription((DefaultSubscriptionBase) cur, context); } } return null; } @Override public void createNextPhaseEvent(final DefaultSubscriptionBase subscription, final SubscriptionBaseEvent nextPhase, final InternalCallContext context) { cancelNextPhaseEvent(subscription.getId(), context); insertEvent(nextPhase, context); } private SubscriptionBase buildSubscription(final DefaultSubscriptionBase in, final InternalTenantContext context) { final DefaultSubscriptionBase subscription = new DefaultSubscriptionBase(new SubscriptionBuilder(in), null, clock); if (events.size() > 0) { try { subscription.rebuildTransitions(getEventsForSubscription(in.getId(), context), catalogService.getFullCatalog(context)); } catch (final CatalogApiException e) { log.warn("Failed to rebuild subscription", e); } } return subscription; } @Override public void updateChargedThroughDate(final DefaultSubscriptionBase subscription, final InternalCallContext context) { boolean found = false; final Iterator<SubscriptionBase> it = subscriptions.iterator(); while (it.hasNext()) { final SubscriptionBase cur = it.next(); if (cur.getId().equals(subscription.getId())) { found = true; it.remove(); break; } } if (found) { subscriptions.add(subscription); } } @Override public void cancelSubscription(final DefaultSubscriptionBase subscription, final SubscriptionBaseEvent cancelEvent, final InternalCallContext context, final int seqId) { synchronized (events) { cancelNextPhaseEvent(subscription.getId(), context); insertEvent(cancelEvent, context); } } @Override public void cancelSubscriptions(final List<DefaultSubscriptionBase> subscriptions, final List<SubscriptionBaseEvent> cancelEvents, final InternalCallContext context) { synchronized (events) { for (int i = 0; i < subscriptions.size(); i++) { cancelSubscription(subscriptions.get(i), cancelEvents.get(i), context, 0); } } } @Override public void changePlan(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> changeEvents, final InternalCallContext context) { synchronized (events) { cancelNextChangeEvent(subscription.getId()); cancelNextPhaseEvent(subscription.getId(), context); events.addAll(changeEvents); for (final SubscriptionBaseEvent cur : changeEvents) { recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context); } } } private void insertEvent(final SubscriptionBaseEvent event, final InternalCallContext context) { synchronized (events) { events.add(event); mockNonEntityDao.addTenantRecordIdMapping(event.getId(), context); recordFutureNotificationFromTransaction(null, event.getEffectiveDate(), new SubscriptionNotificationKey(event.getId()), context); } } private void cancelNextPhaseEvent(final UUID subscriptionId, final InternalTenantContext context) { final SubscriptionBase curSubscription = getSubscriptionFromId(subscriptionId, context); if (curSubscription.getCurrentPhase() == null || curSubscription.getCurrentPhase().getDuration().getUnit() == TimeUnit.UNLIMITED) { return; } synchronized (events) { final Iterator<SubscriptionBaseEvent> it = events.descendingIterator(); while (it.hasNext()) { final SubscriptionBaseEvent cur = it.next(); if (cur.getSubscriptionId() != subscriptionId) { continue; } if (cur.getType() == EventType.PHASE && cur.getEffectiveDate().isAfter(clock.getUTCNow())) { it.remove(); break; } } } } private void cancelNextChangeEvent(final UUID subscriptionId) { synchronized (events) { final Iterator<SubscriptionBaseEvent> it = events.descendingIterator(); while (it.hasNext()) { final SubscriptionBaseEvent cur = it.next(); if (cur.getSubscriptionId() != subscriptionId) { continue; } if (cur.getType() == EventType.API_USER && ApiEventType.CHANGE == ((ApiEvent) cur).getApiEventType() && cur.getEffectiveDate().isAfter(clock.getUTCNow())) { it.remove(); break; } } } } @Override public void uncancelSubscription(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> uncancelEvents, final InternalCallContext context) { synchronized (events) { boolean foundCancel = false; final Iterator<SubscriptionBaseEvent> it = events.descendingIterator(); while (it.hasNext()) { final SubscriptionBaseEvent cur = it.next(); if (cur.getSubscriptionId() != subscription.getId()) { continue; } if (cur.getType() == EventType.API_USER && ((ApiEvent) cur).getApiEventType() == ApiEventType.CANCEL) { it.remove(); foundCancel = true; break; } } if (foundCancel) { for (final SubscriptionBaseEvent cur : uncancelEvents) { insertEvent(cur, context); } } } } @Override public void migrate(final UUID accountId, final AccountMigrationData accountData, final InternalCallContext context) { synchronized (events) { for (final BundleMigrationData curBundle : accountData.getData()) { final DefaultSubscriptionBaseBundle bundleData = curBundle.getData(); for (final SubscriptionMigrationData curSubscription : curBundle.getSubscriptions()) { final DefaultSubscriptionBase subData = curSubscription.getData(); for (final SubscriptionBaseEvent curEvent : curSubscription.getInitialEvents()) { events.add(curEvent); mockNonEntityDao.addTenantRecordIdMapping(curEvent.getId(), context); recordFutureNotificationFromTransaction(null, curEvent.getEffectiveDate(), new SubscriptionNotificationKey(curEvent.getId()), context); } subscriptions.add(subData); mockNonEntityDao.addTenantRecordIdMapping(subData.getId(), context); } bundles.add(bundleData); mockNonEntityDao.addTenantRecordIdMapping(bundleData.getId(), context); } } } @Override public SubscriptionBaseEvent getEventById(final UUID eventId, final InternalTenantContext context) { synchronized (events) { for (final SubscriptionBaseEvent cur : events) { if (cur.getId().equals(eventId)) { return cur; } } } return null; } private void recordFutureNotificationFromTransaction(final EntitySqlDaoWrapperFactory transactionalDao, final DateTime effectiveDate, final NotificationEvent notificationKey, final InternalCallContext context) { try { final NotificationQueue subscriptionEventQueue = notificationQueueService.getNotificationQueue(DefaultSubscriptionBaseService.SUBSCRIPTION_SERVICE_NAME, DefaultSubscriptionBaseService.NOTIFICATION_QUEUE_NAME); subscriptionEventQueue.recordFutureNotificationFromTransaction(null, effectiveDate, notificationKey, context.getUserToken(), context.getAccountRecordId(), context.getTenantRecordId()); } catch (final NoSuchNotificationQueue e) { throw new RuntimeException(e); } catch (final IOException e) { throw new RuntimeException(e); } } @Override public Iterable<SubscriptionBaseEvent> getFutureEventsForAccount(final InternalTenantContext context) { return null; } @Override public void transfer(final UUID srcAccountId, final UUID destAccountId, final BundleMigrationData data, final List<TransferCancelData> transferCancelData, final InternalCallContext fromContext, final InternalCallContext toContext) { } @Override public void updateBundleExternalKey(final UUID bundleId, final String externalKey, final InternalCallContext context) { } }
apache-2.0
rene-anderes/edu
oo.basics/src/main/java/org/anderes/edu/gui/pm/gui/View.java
2276
package org.anderes.edu.gui.pm.gui; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; /** * View für das Presentation-Model-Pattern * * @author René Anderes */ public class View { private final JFrame f; private final JTextField textField; private final JTextArea textArea; private final PresentationModel presentationModel; /** * Konstruktor */ public View(final PresentationModel presentationModel) { this.presentationModel = presentationModel; f = new JFrame( "Taschenrechner" ); f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); f.setSize(300, 200); JPanel panel = new JPanel(new GridBagLayout()); textField = new JTextField(20); textField.setBackground(Color.WHITE); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String text = textField.getText(); textField.setText(""); if (text.matches("\\d+")) { presentationModel.input(text); updateStack(); } else if (presentationModel.isCommandEnabled()) { presentationModel.command(text); updateStack(); } else { textField.setText("Ung�ltige Funktion"); textField.selectAll(); } } }); textArea = new JTextArea(5, 20); textArea.setEditable(false); textArea.setBackground(Color.LIGHT_GRAY); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; panel.add(textField, c); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; panel.add(textArea, c); f.add(panel); f.setVisible(true); } /** * Die Anzeige des Stacks wird aktualisiert. */ private void updateStack() { textArea.setText(""); for (Double d : presentationModel.getStack()) { textArea.append(String.format("%1$f", d)); textArea.append("\n"); } } }
apache-2.0
epam-debrecen-rft-2015/atsy
web/src/main/java/com/epam/rft/atsy/web/configuration/WebAppInitializer.java
532
package com.epam.rft.atsy.web.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfiguration.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override protected Class<?>[] getRootConfigClasses() { return null; } }
apache-2.0
gyj1109/gyj1109.github.io
_posts/2017-02-26-Chinese-ZiXing.md
5173
--- title: 字形 layout: post date: 2017-02-26 tags: - 语文复习笔记 catalog: true --- ### 以音辨形 随声附合(和) “合”没有hè的读音,应为“和” ### 以形辨形 干燥 - 火 - 被火烤得十分干燥 急躁 - 足 - 急得直跺脚 ### 以义辨形 - 穷愁潦倒 潦:颓唐 缭:缭绕 撩:撩拨 - 墨守成规 现成的规定 ### 结构辨形 并列结构的词语(尤其是成语) 山清水秀 - 清秀 青山绿水 - 青绿 ### 字词搭配 - 部署 布置 - 刻苦 克服 ### 易错字 #### A 哀**(唉)**声叹气 暗**(黯)**然失色 #### B 搬**(班)**门弄斧 永保**(葆)**青春 报**(抱)**怨别人 以德抱**(报)**怨 自抱**(暴)**自弃 推崇倍**(备)**至 不屑置辨**(辩)** 英雄备**(辈)**出 刚腹**(愎)**自用 必**(毕)**竟 针贬**(砭)**时弊 明辩**(辨)**是非 按步**(部)**就班 战略布**(部)**署 #### C 残**(惨)**无人道 璀灿**(璨)**夺目 明查**(察)**暗访 常**(长)**年累月 相辅相承**(成)** 计日成**(程)**功 一张一驰**(弛)** 一愁**(筹)**莫展 穿**(川)**流不息 相形见拙**(绌)** 理屈辞**(词)**穷 冲**(充)**耳不闻 #### D 披星带**(戴)**月 惮**(殚)**精竭虑 锐不可挡**(当)** 根深地**(蒂)**固 沾**(玷)**污清白 提心掉**(吊)**胆 吊**(掉)**以轻心 影牒**(碟)**机 坠**(堕)**落腐化 #### F 三翻**(番)**五次 要言不繁**(烦)** 义无返**(反)**顾 严加防犯**(范)** 获益非**(匪)**浅 流言诽**(蜚)**语 煞废**(费)**苦心 发愤**(奋)**图强 入不付**(敷)**出 破斧**(釜)**沉舟 名付**(副)**其实 #### G 言简意骇**(赅)** 气慨**(概)** 立杆**(竿)**见影 金钢**(刚)**钻 鬼斧神功**(工)** 一笔钩**(勾)**销 鬼**(诡)**计 #### H 貌和**(合)**神离 随声附合**(和)** 轰**(哄)**堂大笑 宏**(弘)**扬文化 病入膏盲**(肓)** 张惶**(皇)**失措 飞皇**(黄)**腾达 融汇**(会)**贯通 #### J 反唇相击**(讥)** 急**(亟)**待解决 迫不急**(及)**待 痛心急**(疾)**首 不记**(计)**其数 狼籍**(藉)** 故技**(伎)**重演 坚**(艰)**难困苦 明枪暗剑**(箭)** 不娇**(骄)**不躁 开源截**(节)**流 直接**(截)**了当 弱不经**(禁)**风 告戒**(诫)** 各届**(界)**人士 跌落陷井**(阱)** 不径**(胫)**而走 既往不究**(咎)** 声色具**(俱)**厉 #### K 同仇敌慨**(忾)** 功亏一匮**(篑)** 溃**(匮)**乏 #### L 陈词烂**(滥)**调 再接再励**(厉)** 变本加利**(厉)** 流恋**(连)**忘返 盛气临**(凌)**人 随便流**(浏)**览 留**(流)**芳百世 蒸溜**(馏)**水 #### M 轻歌漫**(曼)**舞 火势漫**(蔓)**延 满**(漫)**山遍野 名列前矛**(茅)** 风糜**(靡)**一时 贸**(冒)**失 密**(秘)**诀 泄秘**(密)** 棉**(绵)**里藏针 市场扫瞄**(描)** 虚无缥渺**(缈)** 莫明**(名)**其妙 莫**(漠)**不关心 谋**(牟)**取暴利 #### P 如法泡**(炮)**制 篷**(蓬)**荜生辉 养成僻**(癖)**好 浮想联篇**(翩)** 砰**(怦)**然心动 凭**(平)**添 #### Q 山青**(清)**水秀 欠**(歉)**收 并驾齐趋**(驱)** 委屈**(曲)**求全 入场卷**(券)** #### R 当人**(仁)**不让 一视同人**(仁)** 水乳交容**(融)** 儒**(孺)**子可教 含辛如**(茹)**苦 #### S 传诵**(颂)** 跚跚**(姗姗)**来迟 善**(擅)**长 毛骨耸**(悚)**然 至高无尚**(上)** 各行其事**(是)** 摆正姿式**(势)** 谈笑风声**(生)** 共商国事**(是)** 撕**(厮)**杀打斗 众口烁**(铄)**金 鬼鬼崇崇**(祟祟)** #### T 纷至踏**(沓)**来 糟塌**(蹋)** 煤碳**(炭)** 惊滔**(涛)**骇浪 题**(提)**纲挈领 金榜提**(题)**名 妥贴**(帖)** 走头**(投)**无路 拖**(托)**运行李 #### W 名门旺**(望)**族 互相推委**(诿)** 闻**(文)**过饰非 好高鹜**(骛)**远 污**(诬)**告 #### X 息**(熄)**灭 迁徒**(徙)** 面容安祥**(详)** 消**(销)**毁 歪门斜**(邪)**道 协**(胁)**从不问 水泻**(泄)**不通 一泄**(泻)**千里 别出新**(心)**裁 形**(行)**迹可疑 寒喧**(暄)**客套 循**(徇)**私舞弊 气喘嘘嘘**(吁吁)** 来势凶凶**(汹汹)** 不醒**(省)**人事 #### Y 天崖**(涯)**海角 掩**(偃)**旗息鼓 膺**(赝)**品 甘之如贻**(饴)** 遗**(贻)**笑大方 一**(异)**口同声 义**(意)**气相投 苦心孤旨**(诣)** 绿树成阴**(荫)** 绿草如荫**(茵)** 蜂涌**(拥)**而上 记忆尤**(犹)**新 竭泽而鱼**(渔)** 渔**(鱼)**肉乡里 原**(元)**气大伤 坐收鱼**(渔)**利 世外桃园**(源)** 殒**(陨)**落 断壁残园**(垣)** 蕴**(孕)**育 #### Z 暂**(崭)**露头角 贪脏**(赃)**枉法 戒骄戒燥**(躁)** 以身作责**(则)** 通货膨涨**(胀)** 坐阵**(镇)**指挥 振**(震)**撼 仗义直**(执)**言 出奇致**(制)**胜 真知卓**(灼)**见 闲情逸志**(致)** 咀**(诅)**咒 乔妆**(装)**打扮 毋庸质**(置)**疑 九洲**(州)**方圆 躁**(燥)**热
apache-2.0
XiaoningDing/UbernetesPOC
pkg/serviceaccount/jwt_test.go
9089
/* Copyright 2014 The Kubernetes Authors All rights reserved. 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 serviceaccount_test import ( "crypto/rsa" "io/ioutil" "os" "reflect" "testing" "github.com/dgrijalva/jwt-go" "k8s.io/kubernetes/pkg/api" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_1" "k8s.io/kubernetes/pkg/client/testing/fake" serviceaccountcontroller "k8s.io/kubernetes/pkg/controller/serviceaccount" "k8s.io/kubernetes/pkg/serviceaccount" ) const otherPublicKey = `-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArXz0QkIG1B5Bj2/W69GH rsm5e+RC3kE+VTgocge0atqlLBek35tRqLgUi3AcIrBZ/0YctMSWDVcRt5fkhWwe Lqjj6qvAyNyOkrkBi1NFDpJBjYJtuKHgRhNxXbOzTSNpdSKXTfOkzqv56MwHOP25 yP/NNAODUtr92D5ySI5QX8RbXW+uDn+ixul286PBW/BCrE4tuS88dA0tYJPf8LCu sqQOwlXYH/rNUg4Pyl9xxhR5DIJR0OzNNfChjw60zieRIt2LfM83fXhwk8IxRGkc gPZm7ZsipmfbZK2Tkhnpsa4QxDg7zHJPMsB5kxRXW0cQipXcC3baDyN9KBApNXa0 PwIDAQAB -----END PUBLIC KEY-----` const publicKey = `-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA249XwEo9k4tM8fMxV7zx OhcrP+WvXn917koM5Qr2ZXs4vo26e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecI zshKuv1gKIxbbLQMOuK1eA/4HALyEkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG 51RoiMgbQxaCyYxGfNLpLAZK9L0Tctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJU j7OTh/AjjCnMnkgvKT2tpKxYQ59PgDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEi B4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRM WwIDAQAB -----END PUBLIC KEY----- ` const privateKey = `-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA249XwEo9k4tM8fMxV7zxOhcrP+WvXn917koM5Qr2ZXs4vo26 e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecIzshKuv1gKIxbbLQMOuK1eA/4HALy EkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG51RoiMgbQxaCyYxGfNLpLAZK9L0T ctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJUj7OTh/AjjCnMnkgvKT2tpKxYQ59P gDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEiB4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp 1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRMWwIDAQABAoIBAHJx8GqyCBDNbqk7 e7/hI9iE1S10Wwol5GH2RWxqX28cYMKq+8aE2LI1vPiXO89xOgelk4DN6urX6xjK ZBF8RRIMQy/e/O2F4+3wl+Nl4vOXV1u6iVXMsD6JRg137mqJf1Fr9elg1bsaRofL Q7CxPoB8dhS+Qb+hj0DhlqhgA9zG345CQCAds0ZYAZe8fP7bkwrLqZpMn7Dz9WVm ++YgYYKjuE95kPuup/LtWfA9rJyE/Fws8/jGvRSpVn1XglMLSMKhLd27sE8ZUSV0 2KUzbfRGE0+AnRULRrjpYaPu0XQ2JjdNvtkjBnv27RB89W9Gklxq821eH1Y8got8 FZodjxECgYEA93pz7AQZ2xDs67d1XLCzpX84GxKzttirmyj3OIlxgzVHjEMsvw8v sjFiBU5xEEQDosrBdSknnlJqyiq1YwWG/WDckr13d8G2RQWoySN7JVmTQfXcLoTu YGRiiTuoEi3ab3ZqrgGrFgX7T/cHuasbYvzCvhM2b4VIR3aSxU2DTUMCgYEA4x7J T/ErP6GkU5nKstu/mIXwNzayEO1BJvPYsy7i7EsxTm3xe/b8/6cYOz5fvJLGH5mT Q8YvuLqBcMwZardrYcwokD55UvNLOyfADDFZ6l3WntIqbA640Ok2g1X4U8J09xIq ZLIWK1yWbbvi4QCeN5hvWq47e8sIj5QHjIIjRwkCgYEAyNqjltxFN9zmzPDa2d24 EAvOt3pYTYBQ1t9KtqImdL0bUqV6fZ6PsWoPCgt+DBuHb+prVPGP7Bkr/uTmznU/ +AlTO+12NsYLbr2HHagkXE31DEXE7CSLa8RNjN/UKtz4Ohq7vnowJvG35FCz/mb3 FUHbtHTXa2+bGBUOTf/5Hw0CgYBxw0r9EwUhw1qnUYJ5op7OzFAtp+T7m4ul8kCa SCL8TxGsgl+SQ34opE775dtYfoBk9a0RJqVit3D8yg71KFjOTNAIqHJm/Vyyjc+h i9rJDSXiuczsAVfLtPVMRfS0J9QkqeG4PIfkQmVLI/CZ2ZBmsqEcX+eFs4ZfPLun Qsxe2QKBgGuPilIbLeIBDIaPiUI0FwU8v2j8CEQBYvoQn34c95hVQsig/o5z7zlo UsO0wlTngXKlWdOcCs1kqEhTLrstf48djDxAYAxkw40nzeJOt7q52ib/fvf4/UBy X024wzbiw1q07jFCyfQmODzURAx1VNT7QVUMdz/N8vy47/H40AZJ -----END RSA PRIVATE KEY----- ` func getPrivateKey(data string) *rsa.PrivateKey { key, _ := jwt.ParseRSAPrivateKeyFromPEM([]byte(data)) return key } func getPublicKey(data string) *rsa.PublicKey { key, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(data)) return key } func TestReadPrivateKey(t *testing.T) { f, err := ioutil.TempFile("", "") if err != nil { t.Fatalf("error creating tmpfile: %v", err) } defer os.Remove(f.Name()) if err := ioutil.WriteFile(f.Name(), []byte(privateKey), os.FileMode(0600)); err != nil { t.Fatalf("error creating tmpfile: %v", err) } if _, err := serviceaccount.ReadPrivateKey(f.Name()); err != nil { t.Fatalf("error reading key: %v", err) } } func TestReadPublicKey(t *testing.T) { f, err := ioutil.TempFile("", "") if err != nil { t.Fatalf("error creating tmpfile: %v", err) } defer os.Remove(f.Name()) if err := ioutil.WriteFile(f.Name(), []byte(publicKey), os.FileMode(0600)); err != nil { t.Fatalf("error creating tmpfile: %v", err) } if _, err := serviceaccount.ReadPublicKey(f.Name()); err != nil { t.Fatalf("error reading key: %v", err) } } func TestTokenGenerateAndValidate(t *testing.T) { expectedUserName := "system:serviceaccount:test:my-service-account" expectedUserUID := "12345" // Related API objects serviceAccount := &api.ServiceAccount{ ObjectMeta: api.ObjectMeta{ Name: "my-service-account", UID: "12345", Namespace: "test", }, } secret := &api.Secret{ ObjectMeta: api.ObjectMeta{ Name: "my-secret", Namespace: "test", }, } // Generate the token generator := serviceaccount.JWTTokenGenerator(getPrivateKey(privateKey)) token, err := generator.GenerateToken(*serviceAccount, *secret) if err != nil { t.Fatalf("error generating token: %v", err) } if len(token) == 0 { t.Fatalf("no token generated") } // "Save" the token secret.Data = map[string][]byte{ "token": []byte(token), } testCases := map[string]struct { Client clientset.Interface Keys []*rsa.PublicKey ExpectedErr bool ExpectedOK bool ExpectedUserName string ExpectedUserUID string ExpectedGroups []string }{ "no keys": { Client: nil, Keys: []*rsa.PublicKey{}, ExpectedErr: false, ExpectedOK: false, }, "invalid keys": { Client: nil, Keys: []*rsa.PublicKey{getPublicKey(otherPublicKey)}, ExpectedErr: true, ExpectedOK: false, }, "valid key": { Client: nil, Keys: []*rsa.PublicKey{getPublicKey(publicKey)}, ExpectedErr: false, ExpectedOK: true, ExpectedUserName: expectedUserName, ExpectedUserUID: expectedUserUID, ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, }, "rotated keys": { Client: nil, Keys: []*rsa.PublicKey{getPublicKey(otherPublicKey), getPublicKey(publicKey)}, ExpectedErr: false, ExpectedOK: true, ExpectedUserName: expectedUserName, ExpectedUserUID: expectedUserUID, ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, }, "valid lookup": { Client: fake.NewSimpleClientset(serviceAccount, secret), Keys: []*rsa.PublicKey{getPublicKey(publicKey)}, ExpectedErr: false, ExpectedOK: true, ExpectedUserName: expectedUserName, ExpectedUserUID: expectedUserUID, ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, }, "invalid secret lookup": { Client: fake.NewSimpleClientset(serviceAccount), Keys: []*rsa.PublicKey{getPublicKey(publicKey)}, ExpectedErr: true, ExpectedOK: false, }, "invalid serviceaccount lookup": { Client: fake.NewSimpleClientset(secret), Keys: []*rsa.PublicKey{getPublicKey(publicKey)}, ExpectedErr: true, ExpectedOK: false, }, } for k, tc := range testCases { getter := serviceaccountcontroller.NewGetterFromClient(tc.Client) authenticator := serviceaccount.JWTTokenAuthenticator(tc.Keys, tc.Client != nil, getter) user, ok, err := authenticator.AuthenticateToken(token) if (err != nil) != tc.ExpectedErr { t.Errorf("%s: Expected error=%v, got %v", k, tc.ExpectedErr, err) continue } if ok != tc.ExpectedOK { t.Errorf("%s: Expected ok=%v, got %v", k, tc.ExpectedOK, ok) continue } if err != nil || !ok { continue } if user.GetName() != tc.ExpectedUserName { t.Errorf("%s: Expected username=%v, got %v", k, tc.ExpectedUserName, user.GetName()) continue } if user.GetUID() != tc.ExpectedUserUID { t.Errorf("%s: Expected userUID=%v, got %v", k, tc.ExpectedUserUID, user.GetUID()) continue } if !reflect.DeepEqual(user.GetGroups(), tc.ExpectedGroups) { t.Errorf("%s: Expected groups=%v, got %v", k, tc.ExpectedGroups, user.GetGroups()) continue } } } func TestMakeSplitUsername(t *testing.T) { username := serviceaccount.MakeUsername("ns", "name") ns, name, err := serviceaccount.SplitUsername(username) if err != nil { t.Errorf("Unexpected error %v", err) } if ns != "ns" || name != "name" { t.Errorf("Expected ns/name, got %s/%s", ns, name) } invalid := []string{"test", "system:serviceaccount", "system:serviceaccount:", "system:serviceaccount:ns", "system:serviceaccount:ns:name:extra"} for _, n := range invalid { _, _, err := serviceaccount.SplitUsername("test") if err == nil { t.Errorf("Expected error for %s", n) } } }
apache-2.0
winchram/mc
ls.go
5848
/* * Minio Client (C) 2015 Minio, 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 main import ( "encoding/json" "fmt" "os" "path/filepath" "runtime" "strings" "time" "github.com/dustin/go-humanize" "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio-xl/pkg/probe" ) /// ls - related internal functions const ( printDate = "2006-01-02 15:04:05 MST" ) // ContentMessage container for content message structure. type ContentMessage struct { Filetype string `json:"type"` Time time.Time `json:"lastModified"` Size int64 `json:"size"` Name string `json:"name"` } // String colorized string message func (c ContentMessage) String() string { message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate))) message = message + console.Colorize("Size", fmt.Sprintf("%6s ", humanize.IBytes(uint64(c.Size)))) message = func() string { if c.Filetype == "folder" { return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Name)) } return message + console.Colorize("File", fmt.Sprintf("%s", c.Name)) }() return message } // JSON jsonified content message func (c ContentMessage) JSON() string { jsonMessageBytes, e := json.Marshal(c) fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(jsonMessageBytes) } // parseContent parse client Content container into printer struct. func parseContent(c *client.Content) ContentMessage { content := ContentMessage{} content.Time = c.Time.Local() // guess file type content.Filetype = func() string { if c.Type.IsDir() { return "folder" } return "file" }() content.Size = c.Size // Convert OS Type to match console file printing style. content.Name = func() string { switch { case runtime.GOOS == "windows": c.Name = strings.Replace(c.Name, "/", "\\", -1) c.Name = strings.TrimSuffix(c.Name, "\\") default: c.Name = strings.TrimSuffix(c.Name, "/") } if c.Type.IsDir() { switch { case runtime.GOOS == "windows": return fmt.Sprintf("%s\\", c.Name) default: return fmt.Sprintf("%s/", c.Name) } } return c.Name }() return content } // doList - list all entities inside a folder. func doList(clnt client.Client, recursive, multipleArgs bool) *probe.Error { var err *probe.Error var parentContent *client.Content urlStr := clnt.URL().String() parentDir := url2Dir(urlStr) parentClnt, err := url2Client(parentDir) if err != nil { return err.Trace(clnt.URL().String()) } parentContent, err = parentClnt.Stat() if err != nil { return err.Trace(clnt.URL().String()) } for contentCh := range clnt.List(recursive, false) { if contentCh.Err != nil { switch contentCh.Err.ToGoError().(type) { // handle this specifically for filesystem case client.BrokenSymlink: errorIf(contentCh.Err.Trace(), "Unable to list broken link.") continue case client.TooManyLevelsSymlink: errorIf(contentCh.Err.Trace(), "Unable to list too many levels link.") continue } if os.IsNotExist(contentCh.Err.ToGoError()) || os.IsPermission(contentCh.Err.ToGoError()) { if contentCh.Content != nil { if contentCh.Content.Type.IsDir() { if contentCh.Content.Type&os.ModeSymlink == os.ModeSymlink { errorIf(contentCh.Err.Trace(), "Unable to list broken folder link.") continue } errorIf(contentCh.Err.Trace(), "Unable to list folder.") } } else { errorIf(contentCh.Err.Trace(), "Unable to list.") continue } } err = contentCh.Err.Trace() break } if multipleArgs && parentContent.Type.IsDir() { contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name)) } Prints("%s\n", parseContent(contentCh.Content)) } if err != nil { return err.Trace() } return nil } // doListIncomplete - list all incomplete uploads entities inside a folder. func doListIncomplete(clnt client.Client, recursive, multipleArgs bool) *probe.Error { var err *probe.Error var parentContent *client.Content parentContent, err = clnt.Stat() if err != nil { return err.Trace(clnt.URL().String()) } for contentCh := range clnt.List(recursive, true) { if contentCh.Err != nil { switch contentCh.Err.ToGoError().(type) { // handle this specifically for filesystem case client.BrokenSymlink: errorIf(contentCh.Err.Trace(), "Unable to list broken link.") continue case client.TooManyLevelsSymlink: errorIf(contentCh.Err.Trace(), "Unable to list too many levels link.") continue } if os.IsNotExist(contentCh.Err.ToGoError()) || os.IsPermission(contentCh.Err.ToGoError()) { if contentCh.Content != nil { if contentCh.Content.Type.IsDir() && (contentCh.Content.Type&os.ModeSymlink == os.ModeSymlink) { errorIf(contentCh.Err.Trace(), "Unable to list broken folder link.") continue } } errorIf(contentCh.Err.Trace(), "Unable to list.") continue } err = contentCh.Err.Trace() break } if multipleArgs && parentContent.Type.IsDir() { contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name)) } Prints("%s\n", parseContent(contentCh.Content)) } if err != nil { return err.Trace() } return nil }
apache-2.0
OpenConext/Mujina
mujina-idp/src/main/resources/templates/login.html
3360
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>Login page</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="/main.css"/> <script th:src="@{/main.js}"></script> </head> <body> <aside id="explanation" class="explain hide"> <div class="container"> <header class="title"> <h2>SAML Attribute Manipulation</h2> <a href="/close" id="close" class="close"><span class="sr-only">Close </span>&#9747;</a> </header> <div class="explanation-content"> <p> When the Mujina IDP sends a SAML assertion back to the service provider, all the attributes will be added as SAML AttributeStatement elements. </p> <p> Based on the Attribute Release Policy of the service provider they will be included in the authenticated user identity. </p> <p>If you want to add multiple values for one attribute - for example isMemberOf - then add them multiple times. </p> <hr/> <p> If you add attributes and check the 'Persist me' box then the attributes will be saved under the 'Username' you have entered. </p> <p> On subsequent logins with the same username the same set of attributes will be send to the Service Provider. </p> </div> </div> </aside> <main class="login-container"> <div class="login"> <h1>Mujina Identity Provider</h1> <p th:if="${param.error}" class="error">Wrong user or password</p> <form class="login-form" th:action="@{/login}" method="post"> <label for="username" class="sr-only">Username</label> <input type="text" id="username" name="username" autofocus="autofocus" placeholder="Username"/> <label for="password" class="sr-only">Password</label> <input type="password" id="password" name="password" placeholder="Password"/> <input class="button" type="submit" value="Log in"/> <div> <input id="persist-me" name="persist-me" type="checkbox"/> <label class="persist-me" for="persist-me">Persist me?</label> </div> <div class="add-attribute"> <label for="add-attribute" class="sr-only">Select attributes</label> <select class="attribute-select" id="add-attribute"> <option value="Add attribute...">Add attribute...</option> <option th:each="attr : ${samlAttributes}" th:value="${attr.get('name')}" th:text="${attr.get('id')}" th:attr="data-multiplicity=${attr.get('multiplicity')}"></option> </select> <div class="help"><span class="explain-link">?</span></div> </div> <ul id="attribute-list" class="attribute-list"></ul> <section class="powered-by"> <a href="https://openconext.org/" target="_blank" rel="noreferrer noopener">Copyright © 2018 OpenConext</a> </section> </form> </div> </main> </body> </html>
apache-2.0
garrettwong/GDashboard
client/app/components/d3visualizations/forcegraph/forcegraph.js
510
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import uiModal from 'angular-ui-bootstrap/src/modal'; import forcegraphComponent from './forcegraph.component'; let forcegraphModule = angular.module('forcegraph', [ uiRouter, uiModal ]) .config(($stateProvider) => { "ngInject"; $stateProvider .state('forcegraph', { url: '/forcegraph', component: 'forcegraph' }); }) .component('forcegraph', forcegraphComponent) .name; export default forcegraphModule;
apache-2.0
toddmowen/maestro
maestro-schema/src/main/scala/au/com/cba/omnia/maestro/schema/Squash.scala
9413
// Copyright 2014 Commonwealth Bank of Australia // // 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 au.com.cba.omnia.maestro.schema import scala.collection._ import au.com.cba.omnia.maestro.schema._ import au.com.cba.omnia.maestro.schema.syntax._ import au.com.cba.omnia.maestro.schema.tope._ /** Histogram squasher */ object Squash { /** Given a histogram of how many values in a column match each classifier, * remove the counts that don't provide any extra type information. * * We do three types of squashing: * * 1) Squash Parents. * If we have a child count classifier that has the same count as the parent, * then we remove the count for the parent. * * As parent classifiers are guaranteed to match all values that their * children do, the count for the parent doesn't tell use anything * more than the count for the child. * * For example, if we have Real:100 and Digits:100 we only keep * Digits:100 because digit strings are also real numbers. * * 2) Squash Partitioned. * For some parents node with count N, if there are child nodes that are * partitions of the parent, all the partitions have counts, and the sum * of those counts sum to N, then we can remove *all* child nodes reachable * from the parent. * * For example, if we have Real:100, PosReal:70 and NegReal:30, we only keep * Real:100. The fact that a certain percentage of values are Positive * or Negative is useful information in itself, but we don't need it when * deciding what type the values are. All we want is the name of the set * that contains all the values in the column (ie Real). * * 3) Squash Separate. (TODO: this case subsumes Squash Parents above.) * For some parent node with count N, if there is a set of child nodes * that are mutually separate, and the the sum of the counts for the child * nodes is N, then remove the count for the parent. * * For example, if we have Digits:100, Exact("0"):40, Exact("1"):60, * then we only keep Exact("0"):40 and Exact("1"):60. * * As parent classifiers are guaranteed to match all values that their * children do, then the count of the parent doesn't tell us anything * more than the count for the child. */ def squash(hist: Histogram): Histogram = { // Squash all the things. val squashSet = squashParents(hist) ++ squashPartitioned(hist) ++ squashSeparate(hist) // Remove all the unneeded classifiers in one go. val histS = Histogram(hist.counts.filterKeys { k => ! squashSet.contains (k) }) // If we're making progress, then keep squashing. if (hist.size == histS.size) hist else squash(histS) } // ---------------------------------------------------------------- /** If we have a child count classifier that has the same count as the parent, then we remove the count for the parent. */ def squashParents(hist: Histogram): Set[Classifier] = hist.counts .flatMap { tChild => squashSetOfParent(hist, tChild._1) } .toSet /** Collect the set of parent classifiers to remove, given a single child classifier. */ def squashSetOfParent(hist: Histogram, child: Classifier): Set[Classifier] = child match { case ClasSyntax(sChild) => sChild.parents .flatMap { sParent => squashSetOfParentChild(hist, ClasSyntax(sParent), child) } .toSet case ClasTope (_, sChild) => sChild.parents .flatMap { sParent => squashSetOfParentChild(hist, ClasSyntax(sParent), child) } .toSet } /** Collect the set of parent classifiers to remove, given a single parent-child relationship. */ def squashSetOfParentChild( hist: Histogram, parent: Classifier, child: Classifier): Set[Classifier] = if (hist.counts.isDefinedAt(parent) && hist.counts.isDefinedAt(child)) { if (hist.counts(parent) == hist.counts(child)) Set(parent) else Set() } else Set() // ---------------------------------------------------------------- /** For some parents node with count N, if there are child nodes that are * partitions of the parent, all the partitions have counts, and the sum * of those counts sum to N, then we can remove *all* child nodes reachable * from the parent. */ def squashPartitioned(hist: Histogram): Set[Classifier] = hist.counts .flatMap { tNode => squashPartitionedOfParent(hist, tNode._1) } .toSet /** When squashing partitions, get the children to remove given a single parent classifier. */ def squashPartitionedOfParent(hist: Histogram, master: Classifier): Set[Classifier] = master match { case ClasTope(_, _) => Set.empty case ClasSyntax(sMaster) => { // All the children of this master node. val ssChildren: Set[Syntax] = Syntaxes.children(sMaster) // The children that are partitions of the master. val ssPartitions: Set[Syntax] = Syntaxes.partitions(sMaster) val csPartitions: Set[(Syntax, Int)] = ssPartitions.flatMap { s => if (hist.counts.isDefinedAt(ClasSyntax(s))) Seq((s, hist.counts(ClasSyntax(s)))) else Seq((s, 0)) } // Sum of counts of for all the partition nodes. val countPartitions = csPartitions.toSeq.map { cn => cn._2 }.sum // The total number of partitions. val nPartitions = csPartitions.size // Number of partition nodes that have counts associated with them. val nPartitionsActive = csPartitions.filter { cn => cn._2 > 0}.size // Count for the master node. val countMaster = hist.counts.getOrElse(master, 0) // All the desendents of the master node. val ssDescendants: Set[Syntax] = Syntaxes.descendants(sMaster) // If partitions have the same counts of the master then, // we want to remove all descendants. if ((nPartitions > 0) && (countMaster == countPartitions) && (nPartitions == nPartitionsActive)) ssDescendants.map { s => ClasSyntax(s) }.toSet else Set.empty } } // ---------------------------------------------------------------- /** For some parent node with count N, if there is a set of child nodes that * are mutually separate, and the sum of all those nodes is N, then remove * the parent. */ def squashSeparate(hist: Histogram): Set[Classifier] = hist.counts .flatMap { tNode => squashSeparateOfParent(hist, tNode._1) } .toSet /** When squashing separate, get the classifiers to remove given the starting parent classifier. */ def squashSeparateOfParent(hist: Histogram, parent: Classifier): Set[Classifier] = parent match { case ClasTope(_, _) => Set.empty case ClasSyntax(sParent) => { // All the children of the master node. val ssDescendants: Set[Syntax] = Syntaxes.descendants(sParent) val histS: Map[Syntax, Int] = hist.counts.map { case (ClasSyntax(s), n) => (s, n) case (ClasTope(_, s), n) => (s, n) } // The descendants along with their counts. val snDescendants: Set[(Syntax, Int)] = ssDescendants.flatMap { s => if (histS.isDefinedAt(s)) Seq((s, histS(s))) else Seq((s, 0)) } .toSet // The active descendants. val snDescendantsActive: Set[(Syntax, Int)] = snDescendants.filter { sn => sn._2 > 0 }.toSet // Sum of counts of all the active descendants. val countDescendants: Int = snDescendantsActive.map { sn => sn._2 }.sum // Flags saying whether each active descendant is separate from all the others. val fsSeparate: Set[Boolean] = snDescendantsActive.flatMap { sn1 => snDescendantsActive.map { sn2 => if (sn1 == sn2) true else (Syntaxes.separate(sn1._1, sn2._1)) }} // Count for the parent node. val countParent = if (hist.counts.isDefinedAt(parent)) hist.counts(parent) else 0 // If there is at least one child, and all the children are separate, // and the counts on the children sum to the counts on the parent, // then we can remove the parent. if ( (snDescendantsActive.size > 0) && (fsSeparate == Set(true)) && (countDescendants == countParent)) Set(parent) else Set() } } }
apache-2.0
chendongMarch/QuickRv
lightadapter/build/docs/javadoc/com/zfy/lxadapter/animation/BindAnimator.html
13121
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_91) on Fri Sep 27 15:49:15 CST 2019 --> <title>BindAnimator (lightadapter API)</title> <meta name="date" content="2019-09-27"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="BindAnimator (lightadapter API)"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10}; var tabs = {65535:["t0","所有方法"],2:["t2","实例方法"],8:["t4","具体方法"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>您的浏览器已禁用 JavaScript。</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li class="navBarCell1Rev">类</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../index-all.html">索引</a></li> <li><a href="../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/zfy/lxadapter/animation/BindAlphaAnimator.html" title="com.zfy.lxadapter.animation中的类"><span class="typeNameLink">上一个类</span></a></li> <li><a href="../../../../com/zfy/lxadapter/animation/BindScaleAnimator.html" title="com.zfy.lxadapter.animation中的类"><span class="typeNameLink">下一个类</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/zfy/lxadapter/animation/BindAnimator.html" target="_top">框架</a></li> <li><a href="BindAnimator.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>概要:&nbsp;</li> <li>嵌套&nbsp;|&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">构造器</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">方法</a></li> </ul> <ul class="subNavList"> <li>详细资料:&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">构造器</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">方法</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.zfy.lxadapter.animation</div> <h2 title="类 BindAnimator" class="title">类 BindAnimator</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.zfy.lxadapter.animation.BindAnimator</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>所有已实现的接口:</dt> <dd><a href="../../../../com/zfy/lxadapter/animation/IAnimator.html" title="com.zfy.lxadapter.animation中的接口">IAnimator</a></dd> </dl> <dl> <dt>直接已知子类:</dt> <dd><a href="../../../../com/zfy/lxadapter/animation/BindAlphaAnimator.html" title="com.zfy.lxadapter.animation中的类">BindAlphaAnimator</a>, <a href="../../../../com/zfy/lxadapter/animation/BindScaleAnimator.html" title="com.zfy.lxadapter.animation中的类">BindScaleAnimator</a>, <a href="../../../../com/zfy/lxadapter/animation/BindSlideAnimator.html" title="com.zfy.lxadapter.animation中的类">BindSlideAnimator</a></dd> </dl> <hr> <br> <pre>public abstract class <span class="typeNameLabel">BindAnimator</span> extends java.lang.Object implements <a href="../../../../com/zfy/lxadapter/animation/IAnimator.html" title="com.zfy.lxadapter.animation中的接口">IAnimator</a></pre> <div class="block">CreateAt : 2018/11/13 Describe :</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>构造器概要</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="构造器概要表, 列表构造器和解释"> <caption><span>构造器</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">构造器和说明</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html#BindAnimator--">BindAnimator</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>方法概要</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="方法概要表, 列表方法和解释"> <caption><span id="t0" class="activeTableTab"><span>所有方法</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">实例方法</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">具体方法</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">限定符和类型</th> <th class="colLast" scope="col">方法和说明</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html" title="com.zfy.lxadapter.animation中的类">BindAnimator</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html#duration-int-">duration</a></span>(int&nbsp;duration)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html#getDuration--">getDuration</a></span>()</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>android.view.animation.Interpolator</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html#getInterceptor--">getInterceptor</a></span>()</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code><a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html" title="com.zfy.lxadapter.animation中的类">BindAnimator</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html#interceptor-android.view.animation.Interpolator-">interceptor</a></span>(android.view.animation.Interpolator&nbsp;interceptor)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>从类继承的方法&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.zfy.lxadapter.animation.IAnimator"> <!-- --> </a> <h3>从接口继承的方法&nbsp;com.zfy.lxadapter.animation.<a href="../../../../com/zfy/lxadapter/animation/IAnimator.html" title="com.zfy.lxadapter.animation中的接口">IAnimator</a></h3> <code><a href="../../../../com/zfy/lxadapter/animation/IAnimator.html#getAnimators-android.view.View-">getAnimators</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>构造器详细资料</h3> <a name="BindAnimator--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>BindAnimator</h4> <pre>public&nbsp;BindAnimator()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>方法详细资料</h3> <a name="getDuration--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDuration</h4> <pre>public&nbsp;int&nbsp;getDuration()</pre> </li> </ul> <a name="getInterceptor--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getInterceptor</h4> <pre>public&nbsp;android.view.animation.Interpolator&nbsp;getInterceptor()</pre> </li> </ul> <a name="duration-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>duration</h4> <pre>public&nbsp;<a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html" title="com.zfy.lxadapter.animation中的类">BindAnimator</a>&nbsp;duration(int&nbsp;duration)</pre> <dl> <dt><span class="overrideSpecifyLabel">指定者:</span></dt> <dd><code><a href="../../../../com/zfy/lxadapter/animation/IAnimator.html#duration-int-">duration</a></code>&nbsp;在接口中&nbsp;<code><a href="../../../../com/zfy/lxadapter/animation/IAnimator.html" title="com.zfy.lxadapter.animation中的接口">IAnimator</a></code></dd> </dl> </li> </ul> <a name="interceptor-android.view.animation.Interpolator-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>interceptor</h4> <pre>public&nbsp;<a href="../../../../com/zfy/lxadapter/animation/BindAnimator.html" title="com.zfy.lxadapter.animation中的类">BindAnimator</a>&nbsp;interceptor(android.view.animation.Interpolator&nbsp;interceptor)</pre> <dl> <dt><span class="overrideSpecifyLabel">指定者:</span></dt> <dd><code><a href="../../../../com/zfy/lxadapter/animation/IAnimator.html#interceptor-android.view.animation.Interpolator-">interceptor</a></code>&nbsp;在接口中&nbsp;<code><a href="../../../../com/zfy/lxadapter/animation/IAnimator.html" title="com.zfy.lxadapter.animation中的接口">IAnimator</a></code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../overview-summary.html">概览</a></li> <li><a href="package-summary.html">程序包</a></li> <li class="navBarCell1Rev">类</li> <li><a href="package-tree.html">树</a></li> <li><a href="../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../index-all.html">索引</a></li> <li><a href="../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/zfy/lxadapter/animation/BindAlphaAnimator.html" title="com.zfy.lxadapter.animation中的类"><span class="typeNameLink">上一个类</span></a></li> <li><a href="../../../../com/zfy/lxadapter/animation/BindScaleAnimator.html" title="com.zfy.lxadapter.animation中的类"><span class="typeNameLink">下一个类</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/zfy/lxadapter/animation/BindAnimator.html" target="_top">框架</a></li> <li><a href="BindAnimator.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>概要:&nbsp;</li> <li>嵌套&nbsp;|&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">构造器</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">方法</a></li> </ul> <ul class="subNavList"> <li>详细资料:&nbsp;</li> <li>字段&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">构造器</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">方法</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
apache-2.0
googleapis/google-cloud-cpp
google/cloud/internal/oauth2_access_token_credentials.h
1676
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_OAUTH2_ACCESS_TOKEN_CREDENTIALS_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_OAUTH2_ACCESS_TOKEN_CREDENTIALS_H #include "google/cloud/internal/credentials_impl.h" #include "google/cloud/internal/oauth2_credentials.h" #include "google/cloud/status_or.h" #include "google/cloud/version.h" #include <string> #include <utility> namespace google { namespace cloud { namespace oauth2_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /** * A `Credentials` type representing a Bearer Token OAuth 2.0 credentials. */ class AccessTokenCredentials : public oauth2_internal::Credentials { public: explicit AccessTokenCredentials( google::cloud::internal::AccessToken const& access_token); StatusOr<std::pair<std::string, std::string>> AuthorizationHeader() override; private: std::pair<std::string, std::string> header_; }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace oauth2_internal } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_OAUTH2_ACCESS_TOKEN_CREDENTIALS_H
apache-2.0
googleapis/google-cloud-cpp
google/cloud/iap/identity_aware_proxy_o_auth_connection_idempotency_policy.cc
3353
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/iap/v1/service.proto #include "google/cloud/iap/identity_aware_proxy_o_auth_connection_idempotency_policy.h" #include "absl/memory/memory.h" #include <memory> namespace google { namespace cloud { namespace iap { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using ::google::cloud::Idempotency; IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy:: ~IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() = default; namespace { class DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy : public IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy { public: ~DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() override = default; /// Create a new copy of this object. std::unique_ptr<IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy> clone() const override { return absl::make_unique< DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>( *this); } Idempotency ListBrands( google::cloud::iap::v1::ListBrandsRequest const&) override { return Idempotency::kIdempotent; } Idempotency CreateBrand( google::cloud::iap::v1::CreateBrandRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency GetBrand( google::cloud::iap::v1::GetBrandRequest const&) override { return Idempotency::kIdempotent; } Idempotency CreateIdentityAwareProxyClient( google::cloud::iap::v1::CreateIdentityAwareProxyClientRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency ListIdentityAwareProxyClients( google::cloud::iap::v1::ListIdentityAwareProxyClientsRequest) override { return Idempotency::kIdempotent; } Idempotency GetIdentityAwareProxyClient( google::cloud::iap::v1::GetIdentityAwareProxyClientRequest const&) override { return Idempotency::kIdempotent; } Idempotency ResetIdentityAwareProxyClientSecret( google::cloud::iap::v1::ResetIdentityAwareProxyClientSecretRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency DeleteIdentityAwareProxyClient( google::cloud::iap::v1::DeleteIdentityAwareProxyClientRequest const&) override { return Idempotency::kNonIdempotent; } }; } // namespace std::unique_ptr<IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy> MakeDefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() { return absl::make_unique< DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>(); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace iap } // namespace cloud } // namespace google
apache-2.0
desruisseaux/sis
core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/DefaultConcatenatedOperationTest.java
8998
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.sis.referencing.operation; import java.util.Collections; import javax.xml.bind.JAXBException; import org.opengis.util.FactoryException; import org.opengis.referencing.crs.GeodeticCRS; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.CoordinateOperation; import org.opengis.referencing.operation.MathTransformFactory; import org.opengis.referencing.operation.NoninvertibleTransformException; import org.apache.sis.referencing.operation.transform.EllipsoidToCentricTransform; import org.apache.sis.referencing.datum.HardCodedDatum; import org.apache.sis.referencing.crs.HardCodedCRS; import org.apache.sis.internal.system.DefaultFactories; import org.apache.sis.io.wkt.Convention; import org.opengis.test.Validators; import org.apache.sis.test.DependsOn; import org.apache.sis.test.XMLTestCase; import org.junit.Test; import static org.apache.sis.test.MetadataAssert.*; import static org.apache.sis.test.TestUtilities.getSingleton; /** * Tests the {@link DefaultConcatenatedOperation} class. * * @author Martin Desruisseaux (Geomatys) * @since 0.7 * @version 0.7 * @module */ @DependsOn({ DefaultTransformationTest.class, SingleOperationMarshallingTest.class }) public final strictfp class DefaultConcatenatedOperationTest extends XMLTestCase { /** * An XML file in this package containing a projected CRS definition. */ private static final String XML_FILE = "ConcatenatedOperation.xml"; /** * Creates a “Tokyo to JGD2000” transformation. * * @see DefaultTransformationTest#createGeocentricTranslation() */ private static DefaultConcatenatedOperation createGeocentricTranslation() throws FactoryException, NoninvertibleTransformException { final MathTransformFactory mtFactory = DefaultFactories.forBuildin(MathTransformFactory.class); final DefaultTransformation op = DefaultTransformationTest.createGeocentricTranslation(); final DefaultConversion before = new DefaultConversion( Collections.singletonMap(DefaultConversion.NAME_KEY, "Geographic to geocentric"), HardCodedCRS.TOKYO, // SourceCRS op.getSourceCRS(), // TargetCRS null, // InterpolationCRS DefaultOperationMethodTest.create("Geographic/geocentric conversions", "9602", "EPSG guidance note #7-2", 3), EllipsoidToCentricTransform.createGeodeticConversion(mtFactory, HardCodedDatum.TOKYO.getEllipsoid(), true)); final DefaultConversion after = new DefaultConversion( Collections.singletonMap(DefaultConversion.NAME_KEY, "Geocentric to geographic"), op.getTargetCRS(), // SourceCRS HardCodedCRS.JGD2000, // TargetCRS null, // InterpolationCRS DefaultOperationMethodTest.create("Geographic/geocentric conversions", "9602", "EPSG guidance note #7-2", 3), EllipsoidToCentricTransform.createGeodeticConversion(mtFactory, HardCodedDatum.JGD2000.getEllipsoid(), true).inverse()); return new DefaultConcatenatedOperation( Collections.singletonMap(DefaultConversion.NAME_KEY, "Tokyo to JGD2000"), new AbstractSingleOperation[] {before, op, after}, mtFactory); } /** * Tests WKT formatting. The WKT format used here is not defined in OGC/ISO standards; * this is a SIS-specific extension. * * @throws FactoryException if an error occurred while creating the test operation. * @throws NoninvertibleTransformException if an error occurred while creating the test operation. */ @Test public void testWKT() throws FactoryException, NoninvertibleTransformException { final DefaultConcatenatedOperation op = createGeocentricTranslation(); assertWktEquals(Convention.WKT2_SIMPLIFIED, // Pseudo-WKT actually. "ConcatenatedOperation[“Tokyo to JGD2000”,\n" + " SourceCRS[GeodeticCRS[“Tokyo”,\n" + " Datum[“Tokyo 1918”,\n" + " Ellipsoid[“Bessel 1841”, 6377397.155, 299.1528128]],\n" + " CS[ellipsoidal, 3],\n" + " Axis[“Longitude (L)”, east, Unit[“degree”, 0.017453292519943295]],\n" + " Axis[“Latitude (B)”, north, Unit[“degree”, 0.017453292519943295]],\n" + " Axis[“Ellipsoidal height (h)”, up, Unit[“metre”, 1]]]],\n" + " TargetCRS[GeodeticCRS[“JGD2000”,\n" + " Datum[“Japanese Geodetic Datum 2000”,\n" + " Ellipsoid[“GRS 1980”, 6378137.0, 298.257222101]],\n" + " CS[ellipsoidal, 3],\n" + " Axis[“Longitude (L)”, east, Unit[“degree”, 0.017453292519943295]],\n" + " Axis[“Latitude (B)”, north, Unit[“degree”, 0.017453292519943295]],\n" + " Axis[“Ellipsoidal height (h)”, up, Unit[“metre”, 1]]]],\n" + " CoordinateOperationStep[“Geographic to geocentric”,\n" + " Method[“Geographic/geocentric conversions”],\n" + " Parameter[“semi_major”, 6377397.155, Unit[“metre”, 1]],\n" + " Parameter[“semi_minor”, 6356078.962818189, Unit[“metre”, 1]]],\n" + " CoordinateOperationStep[“Tokyo to JGD2000 (GSI)”,\n" + " Method[“Geocentric translations”],\n" + " Parameter[“X-axis translation”, -146.414],\n" + " Parameter[“Y-axis translation”, 507.337],\n" + " Parameter[“Z-axis translation”, 680.507]],\n" + " CoordinateOperationStep[“Geocentric to geographic”,\n" + " Method[“Geographic/geocentric conversions”],\n" + " Parameter[“semi_major”, 6378137.0, Unit[“metre”, 1]],\n" + " Parameter[“semi_minor”, 6356752.314140356, Unit[“metre”, 1]]]]", op); } /** * Tests (un)marshalling of a concatenated operation. * * @throws JAXBException if an error occurred during (un)marshalling. */ @Test public void testXML() throws JAXBException { final DefaultConcatenatedOperation op = unmarshalFile(DefaultConcatenatedOperation.class, XML_FILE); Validators.validate(op); assertEquals("operations.size()", 2, op.getOperations().size()); final CoordinateOperation step1 = op.getOperations().get(0); final CoordinateOperation step2 = op.getOperations().get(1); final CoordinateReferenceSystem sourceCRS = op.getSourceCRS(); final CoordinateReferenceSystem targetCRS = op.getTargetCRS(); assertIdentifierEquals( "identifier", "test", "test", null, "concatenated", getSingleton(op .getIdentifiers())); assertIdentifierEquals("sourceCRS.identifier", "test", "test", null, "source", getSingleton(sourceCRS.getIdentifiers())); assertIdentifierEquals("targetCRS.identifier", "test", "test", null, "target", getSingleton(targetCRS.getIdentifiers())); assertIdentifierEquals( "step1.identifier", "test", "test", null, "step-1", getSingleton(step1 .getIdentifiers())); assertIdentifierEquals( "step2.identifier", "test", "test", null, "step-2", getSingleton(step2 .getIdentifiers())); assertInstanceOf("sourceCRS", GeodeticCRS.class, sourceCRS); assertInstanceOf("targetCRS", GeodeticCRS.class, targetCRS); assertSame("sourceCRS", step1.getSourceCRS(), sourceCRS); assertSame("targetCRS", step2.getTargetCRS(), targetCRS); assertSame("tmp CRS", step1.getTargetCRS(), step2.getSourceCRS()); /* * Test marshalling and compare with the original file. */ assertMarshalEqualsFile(XML_FILE, op, "xmlns:*", "xsi:schemaLocation"); } }
apache-2.0
hudson3-plugins/gearman-plugin
src/main/java/hudson/plugins/gearman/NodeAvailabilityMonitor.java
5039
/* * * Copyright 2013 OpenStack Foundation * * 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 hudson.plugins.gearman; import hudson.model.Hudson; import hudson.model.Queue; import hudson.model.Computer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NodeAvailabilityMonitor implements AvailabilityMonitor { private final Queue queue; private final Hudson hudson; private final Computer computer; private MyGearmanWorkerImpl workerHoldingLock = null; private String expectedUUID = null; private static final Logger logger = LoggerFactory .getLogger(Constants.PLUGIN_LOGGER_NAME); NodeAvailabilityMonitor(Computer computer) { this.computer = computer; queue = Queue.getInstance(); hudson = Hudson.getInstance(); } public Computer getComputer() { return computer; } public void lock(MyGearmanWorkerImpl worker) throws InterruptedException { logger.debug("AvailabilityMonitor lock request: " + worker); while (true) { boolean busy = false; // Synchronize on the Jenkins queue so that Jenkins is // unable to schedule builds while we try to acquire the // lock. synchronized(queue) { if (workerHoldingLock == null) { if (computer.countIdle() == 0) { // If there are no idle executors, we can not // schedule a build. busy = true; } else if (hudson.isQuietingDown()) { busy = true; } else { logger.debug("AvailabilityMonitor got lock: " + worker); workerHoldingLock = worker; return; } } else { busy = true; } } if (busy) { synchronized(this) { // We get synchronous notification when a // build finishes, but there are lots of other // reasons circumstances could change (adding // an executor, canceling shutdown, etc), so // we slowly busy wait to cover all those // reasons. this.wait(5000); } } } } public void unlock(MyGearmanWorkerImpl worker) { logger.debug("AvailabilityMonitor unlock request: " + worker); synchronized(queue) { if (workerHoldingLock == worker) { workerHoldingLock = null; expectedUUID = null; logger.debug("AvailabilityMonitor unlocked: " + worker); } else { logger.debug("Worker does not own AvailabilityMonitor lock: " + worker); } } wake(); } public void wake() { // Called when we know circumstances may have changed in a way // that may allow someone to get the lock. logger.debug("AvailabilityMonitor wake request"); synchronized(this) { logger.debug("AvailabilityMonitor woken"); notifyAll(); } } public void expectUUID(String UUID) { // The Gearman worker which holds the lock is about to // schedule this build, so when Jenkins asks to run it, say // "yes". if (expectedUUID != null) { logger.error("AvailabilityMonitor told to expect UUID " + UUID + "while already expecting " + expectedUUID); } expectedUUID = UUID; } public boolean canTake(Queue.BuildableItem item) { // Jenkins calls this from within the scheduler maintenance // function (while owning the queue monitor). If we are // locked, only allow the build we are expecting to run. logger.debug("AvailabilityMonitor canTake request for " + workerHoldingLock); NodeParametersAction param = item.getAction(NodeParametersAction.class); if (param != null) { logger.debug("AvailabilityMonitor canTake request for UUID " + param.getUuid() + " expecting " + expectedUUID); if (expectedUUID == param.getUuid()) { return true; } } return (workerHoldingLock == null); } }
apache-2.0
pierrybos/nodejs
slides.html
84270
<!DOCTYPE html> <html> <head> <title>NodeJS</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <style type="text/css"> @import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz); @import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic); @import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic); body { font-family: 'Droid Serif'; } h1, h2, h3 { font-family: 'Yanone Kaffeesatz'; font-weight: normal; } .remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; } .remark-slide-content{background: transparent;} .remark-slide { background: url(http://lab.empirio.no/media/images/background.png) #fff center center no-repeat; background-size: cover; } .remark-slide-number{color: #fff;font-size: 1rem;font-weight: bold;} </style> </head> <body> <textarea id="source" style="display:none;"> class: center, middle # NodeJS ![NodeJS](https://raw.githubusercontent.com/cerebrobr/adesivos/master/view/nodejs.png) --- # NodeJS ###Intro Event-driven I/O server-side JavaScript environment based on V8. --- # O que é Node.js? Muitos iniciantes em Node tem a dúvida de o quê exatamente ele é, e a descrição em nodejs.org definitivamente não ajuda. Uma coisa importante de se perceber é que o Node não é um servidor web. Por ele próprio, não se tem nada. Ele não funciona como o Apache. Não existe um arquivo de configuração onde você o aponta para seus arquivos html. Se você quer que o Node seja um servidor HTTP, você tem que escrever um servidor HTTP (com a ajuda das bibliotecas incluídas). O Node.js é somente outra forma de executar código em seu computador. Ele é simplesmente um JavaScript runtime(ambiente de execução de código JavaScript). --- # Conceito O Node JS é um interpretador Javascript do lado do servidor que altera a noção de como um servidor deveria funcionar. Seu objetivo é possibilitar que um programador crie aplicativos altamente escaláveise escreva código que manipule dezenas de milhares de conexões simultâneas. Muito útil para criar aplicações Real-time. Portanto, possibilita que o Client-side e o Server-side sejam escritosinteiramente útilizando apenas Javascript. --- # Programação orientada a eventos As linguagens tradicionais normalmente vão executar comandos um atrás do outro, um de cada vez, executando de forma mais lenta pois o comando "2" só executará após o "1" terminar. Diferente dessas linguagens que seguem um fluxo de controle padronizado, com o Node desenvolvemos orientado a eventos. Então em vez de aguardar um comando terminar sua execução para ir ao próximo, o Node possui um laço de repetição que recebe as informações e dispara uma função de acordo com o evento. Esses eventos podem ser dos mais diversos. Você vai utilizar os eventos que o Node já possui e criar os seus de acordo com sua aplicação. E isso é muito bom, pois nos permite um sistema assíncrono. --- # Programação orientada a eventos ![NodeJS](http://matheusazzi.com/img/post/assincrono.png) --- # E assim nasceu o Node.js Foi baseado neste problema que, no final de 2009, Ryan Dahl com a ajuda inicial de 14 colaboradores criou o Node.js. Esta tecnologia possui um modelo inovador, sua arquitetura é totalmente non-blocking thread (não-bloqueante), apresentando uma boa performance com consumo de memória e utilizando ao máximo e de forma eficiente o poder de processamento dos servidores, principalmente em sistemas que produzem uma alta carga de processamento. --- # E assim nasceu o Node.js Esta é uma plataforma altamente escalável e de baixo nível, pois você vai programar diretamente com diversos protocolos de rede e internet ou utilizar bibliotecas que acessam recursos do sistema operacional, principalmente recursos de sistemas baseado em Unix. O Javascript é a sua linguagem de programação, e isso foi possível graças à engine Javascript V8, a mesma utilizada no navegador Google Chrome. --- # Single-thread Suas aplicações serão single-thread, ou seja, cada aplicação terá instância de um único processo. Se você esta acostumado a trabalhar com programação concorrente em plataforma multi-thread, infelizmente não será possível com Node, mas saiba que existem outras maneiras de se criar um sistema concorrente, como por exemplo, utilizando clusters, que é um módulo nativo do Node.js e é super fácil de implementá-lo. Outra maneira é utilizar ao máximo a programação assíncrona. --- # Event-Loop Node.js é orientado a eventos, ele segue a mesma filosofia de orientação de eventos do Javascript client-side; a única diferença é que não existem eventos de click do mouse, keyup do teclado ou qualquer evento de componentes HTML. Na verdade trabalhamos comeventos de I/O do servidor, como por exemplo: o evento connect de um banco de dados, um open de um arquivo, um data de um streaming de dados e muitos outros. O Event-Loop é o agente responsável por escutar e emitir eventos no sistema. Na prática ele é um loop infinito que a cada iteração verifica em sua fila de eventos se um determinado evento foi emitido. Quando ocorre, é emitido um evento. Ele o executa e envia para fila de executados. Quando um evento está em execução, nós podemos programar qualquer lógica dentro dele e isso tudo acontece graças aomecanismo de função callback do Javascript. --- # Event-Loop O design event-driven doNode.js foi inspirado pelos frameworks EventMachine do Ruby (http://rubyeventmachine.com) e Twisted do Python (http://twistedmatrix. com) . Porém, o Event-loop do Node é mais performático por que seu mecanismo é nativamente executado de forma não-bloqueante. Isso faz deleumgrande diferencial em relação aos seus concorrentes que realizamchamadas bloqueantes para iniciar os seus respectivos Event-loops. --- # Instalação e configuração Para configurar o ambiente Node.js, independente de qual sistema operacional você utilizar, as dicas serão asmesmas. É claro que os procedimentos serão diferentes para cada sistema (principalmente para oWindows, mas não será nada grave). Instalando Node.js: Primeiro passo, acesse o site oficial: (http://nodejs.org) e clique em Download, para usuários do Windows e MacOSX, basta baixar os seus instaladores e executá-los normalmente. Para quem já utiliza Linux com Package Manager instalado, acesse esse link (https://github.com/joyent/node/wiki/ Installing-Node.js-via-package-manager) que é referente as instruções sobre como instalá-lo em diferentes sistemas. Instale o Node.js de acordo com seu sistema, caso não ocorra problemas, basta abrir o seu terminal console ou prompt de comando e digitar o comando: node -v && npm -v para ver as respectivas versões do Node.js e NPM (Node Package Manager) que foram instaladas. --- # Já tenho o Node instalado, e agora o que fazer? Uma vez instalado, agora você tem acesso a um novo comando chamado node. Você pode usar o comando node de duas formas diferentes. A primeira é sem argumentos. Isto irá abrir um shell interativo (REPL: read-eval-print-loop), onde você pode executar código JavaScript puro. $ node > console.log('Hello World'); Hello World undefined No exemplo acima eu digitei console.log('Hello World') dentro do shell e apertei enter. O Node vai então executar o código e nós podemos ver nossa mensagem registrada. Ele também imprimi undefined pelo fato de sempre mostrar o valor de retorno de cada comando, e console.log não retorna nada. --- # Já tenho o Node instalado, e agora o que fazer? A outra forma de rodar o Node é fornecendo a ele um arquivo JavaScript para execução. Isto será na maioria das vezes a maneira como você irá utilizá-lo. ***hello.js*** ``` console.log('Hello World'); $ node hello.js Hello World ``` Neste exemplo, eu movi o comando console.log() para dentro de um arquivo e então passei este arquivo para o comando node como um argumento. O Node então roda o JavaScript contido neste arquivo e imprimi "Hello World". --- # Gerenciando módulos com NPM Assim como o Gems do Ruby ou o Maven do Java, o Node.js também possui o seu próprio gerenciador de pacotes, ele se chama NPM (Node Package Manager). Ele se tornou tão popular pela comunidade, que foi a partir da versão 0.6.0 do Node.js que ele se integrou no instalador do Node.js, tornando-se o gerenciador default. Isto simplificou a vida dos desenvolvedores na época, pois fez com que diversos projetos se convergissem para esta plataforma. --- # NPM Abaixo os comandos principais para que você tenha noções de como gerenciar módulos nele: - npm install nome_do_módulo: instala um módulo no projeto. - npm install -g nome_do_módulo: instala um módulo global. - npm install nome_do_módulo --save: instala o módulo no projeto, atualizando o package.json na lista de dependências. - npm list: lista todos os módulos do projeto. - npm list -g: lista todos os módulos globais. - npm remove nome_do_módulo: desinstala um módulo do projeto. --- # NPM - npm remove -g nome_do_módulo: desinstala um módulo global. - npm update nome_do_módulo: atualiza a versão do módulo. - npm update -g nome_do_módulo: atualiza a versão do módulo global. - npm -v: exibe a versão atual do npm. - npm adduser nome_do_usuário: cria uma conta no npm, através do site (https://npmjs.org) . - npm whoami: exibe detalhes do seu perfil público npm (é necessário criar uma conta antes). - npm publish: publica um módulo no site do npm, é necessário ter uma conta antes. --- # Entendendo o package.json Todo projeto Node.js é chamado de módulo, mas o que é um módulo? O termo módulo surgiu do conceito de que a arquitetura do Node.js é modular. E todo módulo é acompanhado de um arquivo descritor, conhecido pelo nome de package.json. Este arquivo é essencial para um projeto Node.js. Um package.json mal escrito pode causar bugs ou impedir o funcionamento correto do seumódulo, pois ele possui alguns atributos chaves que são compreendidos pelo Node.js e NPM. --- # Modulos { "name": "meu-primero-node-app", "description": "Meu primeiro app em Node.js", "author": "Jackson Mafra <[email protected]>", "version": "1.2.3", "private": true, "dependencies": { "modulo-1": "1.0.0", "modulo-2": "~1.0.0", "modulo-3": ">=1.0.0" }, "devDependencies": { "modulo-4": "*" } } Com esses atributos, você já descreve o mínimo possível o que será sua aplicação. O atributo name é o principal, com ele você descreve o nome do projeto, nome pelo qual seu módulo será chamado via função require('meu-primeiro-node-app'). Em description descrevemos o que será este módulo. Ele deve ser escrito de forma curta e clara explicando um resumo do módulo. --- # Modulos O author é um atributo para informar o nome e email do autor, utilize o formato: Nome <email> para que sites como (https://npmjs.org) reconheça corretamente esses dados. Outro atributo principal é o version, é com ele que definimos a versão atual do módulo, é extremamente recomendado que tenha este atributo, senão será impossível instalar o módulo via comando npm. O atributo private é um booleano, e determina se o projeto terá código aberto ou privado para download no (https://npmjs.org) . --- # Modulos - Versionamento Os módulos no Node.js trabalham com 3 níveis de versionamento. Por exemplo, a versão 1.2.3 esta dividida nos níveis: Major (1),Minor (2) e Patch (3). Repare que no campo dependencies foram incluídos 4 módulos, cada módulo utilizou uma forma diferente de definir a versão que será adicionada no projeto. O primeiro, o modulo-1 somente será incluído sua versão fixa, a 1.0.0. Utilize este tipo versão para instalar dependências cuja suas atualizações possamquebrar o projeto pelo simples fato de que certas funcionalidades foram removidas e ainda as utilizamos na aplicação. O segundo módulo já possui uma certa flexibilidade de update. Ele utiliza o caractere ~ que faz atualizações a nível de patch (1.0.x), geralmente essas atualizações são seguras, trazendo apenasmelhorias ou correções de bugs. --- # Modulos - Versionamento O modulo-3 atualiza versões que seja maior ou igual a 1.0.0 em todos os níveis de versão. Em muitos casos utilizar ”>=” pode ser perigoso, por que a dependência pode ser atualizada a nível major ou minor, contendo grandes modificações que podem quebrar um sistema em produção, comprometendo seu funcionamento e exigindo que você atualize todo código até voltar ao normal. O último, o modulo-4, utiliza o caractere "*”, este sempre pegará a última versão do módulo em qualquer nível. Ele também pode causar problemas nas atualizações e tem o mesmo comportamento do versionamento do modulo-3. Geralmente ele é utilizado em devDependencies, que são dependências focadas para testes automatizados, e as atualizações dos módulos não prejudicam o comportamento do sistema que já está no ar. --- # Modulos - Versionamento Depois de um tempo escrevendo código Javascript, você começa a perceber que algumas coisas começam a se repetir, outras você precisa reutilizar, então você pensa: Como eu posso modularizar isso, para que esse componente seja reutilizado em vários projetos diferentes? Para responder a essa pergunta, entram em cena duas especificações de módulo: **AMD** e **CommonJS** (ou **CJS**). Eles permitem que você escreva seus códigos de forma modular, seguindo algumas definições. Vamos falar sobre cada um deles. --- # Modulos - AMD Asynchronous Module Definition (AMD) ficou bastante conhecido por causa do RequireJS. O formato de utilização do AMD é o seguinte: define( 'moduleName', [ 'jquery' ], function( $ ) { return 'Hello World!'; }); Essa é a estrutura mais básica de um módulo escrito no formato AMD. A função define será usada para todo novo módulo que você criar. Como primeiro parâmetro dessa função, você pode passar o nome do módulo - opcional - (que será usado para você fazer o “include” dele em outro lugar). O segundo parâmetro é um array de dependências desse módulo, também opcional. No nosso exemplo, colocamos como dependência a biblioteca jQuery. --- # Modulos - AMD E o terceiro parâmetro é a função de callback que define o módulo e retorna o seu conteúdo. Essa função é obrigatória. Ela será chamada assim que todas as dependências do array no segundo parâmetro forem baixadas, e estiverem prontas para uso. As dependências normalmente retornam valores. Para usar os valores retornados, você deve passar como parâmetros da função as variáveis que irão receber os valores das dependências, sempre na mesma ordem do array. --- # Modulos - AMD Por exemplo, se no seu módulo você vai precisar utilizar o jQuery e a LoDash, você pode fazer a chamada da seguinte forma: define([ 'jquery', 'lodash' ], function( $, _ ) { // código do seu módulo }); Se não houver dependências, a função já será executada assim que ela for chamada: define(function() { // código do seu módulo }); --- # Modulos - CommonJS Usando o exemplo dado quando falamos sobre AMD, nós podemos escrevê-lo assim, usando CJS: var $ = require( 'jquery' ); function myModule() { // código do seu módulo } module.exports = myModule; Nesse formato as coisas ficam muito explícitas. Na variável $, estamos importando através do require o módulo jquery. Na função myModule(), você vai escrever seu módulo, que será exportado através do module.exports, para que possa ser importado para outro arquivo usando o require. --- # Modulos - CommonJS E o módulo jquery, para ser importado com o require, terá uma estrutura mais ou menos assim (arquivo jquery.js): function jQuery() { // código da jQuery } module.exports = jQuery; Bem fácil de entender, não? --- # Modulos - CommonJS O CommonJS também dispõe de um objeto exports, que nada mais é que um alias para module.exports. Usando o exports, você consegue exportar vários métodos separadamente: exports.method1 = function method1() { // método 1 do seu módulo }; exports.method2 = function method2() { // método 2 do seu módulo }; --- # Modulos - CommonJS Que também pode ser escrito dessa forma: module.exports = function() { return { method1: function method1() { // método 1 do seu módulo }, method2: function method2() { // método 2 do seu módulo } } }; Os dois retornam exatamente a mesma coisa. Na verdade, no segundo exemplo é necessário executar a função antes de poder usar os métodos, mas os dois são formatos padrão de objetos Javascript, que você já está acostumado --- # Modulos - CommonJS Podemos usar o CommonJS tanto no servidor, com NodeJS, por exemplo, como no browser, com o browserify. Bom, vimos que, usando tanto AMD como o CommonJS, fica fácil de modularizar qualquer código JS. Mas pensando em um cenário mais amplo: como eu vou saber se o desenvolvedor que vai usar meu módulo está usando AMD ou CommonJS? Vou ter que disponibilizar duas versões? Criar duas versões do mesmo código é praticamente uma heresia! ***DON’T REPEAT YOURSELF***! --- # Modulos - UMD ## O Capitão Planeta dos módulos Universal Module Definition (UMD), é o cara que vai unir os poderes do AMD e do CommonJS em um único componente! Na verdade, ele é responsável por verificar qual dos formatos está sendo usado, para que você não precise duplicar o seu código :) Seu código usando UMD vai ficar mais ou menos assim: ;(function( root, factory ) { if( typeof define === 'function' && define.amd ) { define([ 'jquery' ], factory ); } else if( typeof exports === 'object' ) { module.exports = factory( require( 'jquery' ) ); } else { root.myModule = factory( root.jQuery ); } })(this, function( $ ) { return 'Hello World'! }); --- # Modulos - UMD Eu sei, o código é bem feio, e à primeira vista é meio ruim de entender. Mas vou quebrá-lo em partes para explicar melhor o que ele faz, ok? Vamos lá! Basicamente, você vai iniciar com uma IIFE (Immediately-Invoked Function Expression), ou função imediata, que é uma função auto-executável: ;(function() { })(); Essa função vai receber dois parâmetros: o primeiro é o this, definido como root. Todo mundo sabe como o this em Javascript é polêmico, pois ele varia o seu valor conforme o escopo em que ele se encontra. No caso, estamos chamando o this no escopo global, logo, se eu estiver no client (browser), ele vai ser o objeto window. E se eu estiver no server (usando Node, por exemplo), ele será o objeto global. --- # Modulos - UMD O segundo parâmetro, definido como factory, é a função que vai executar seu módulo. Sabemos que, em Javascript, funções são objetos de primeira classe. Elas são tratadas como qualquer outro tipo de valor, logo, elas também podem ser passadas por parâmetro para outra função. O UMD se aproveita disso para deixar o negócio um pouco mais ilegível e difícil de entender. Mas olhando pelo lado bom, assim que você entende isso, fica fácil identificar cada parte :D Então, passando os parâmetros, vai ficar assim: ;(function( root, factory ) { })( this, function() {} ); Dentro da função passada como parâmetro vai o código do seu módulo: ;(function( root, factory ) { })( this, function() { // Código do seu módulo }); --- # Modulos - UMD Agora vamos ver o que acontece por dentro da função principal. Como o UMD identifica se você está usando AMD ou CommonJS. O formato AMD tem por padrão a função define e uma propriedade amd nessa função. É isso que é verificado no primeiro if: if( typeof define === 'function' && define.amd ) { // ... } Ou seja, se existir um define e este for uma função, e a propriedade amd estiver definida para essa função, então o desenvolvedor está usando alguma lib no formato AMD. Sabendo disso, é só eu usar essa função define para “definir” meu módulo, passar as dependências no array e chamar a função que executa o módulo: if( typeof define === 'function' && define.amd ) { define([ 'jquery' ], factory ); } --- # Modulos - UMD Lembra quando falamos sobre AMD? Cada parâmetro da função do módulo representa uma depência do array, mantendo a ordem. Então a função que é passada como parâmetro (factory), precisa receber o parâmetro para chamar o jQuery dentro do nosso módulo, já que ele é uma dependência: ;(function( root, factory ) { if( typeof define === 'function' && define.amd ) { define([ 'jquery' ], factory ); } })( this, function( $ ) { // Código do seu módulo }); Já resolvemos o problema do ***AMD***... --- # Modulos - UMD Agora, se o usuário não estiver usando AMD, vamos ver se ele está usando CommonJS, na próxima verificação: else if( typeof exports === 'object' ) { // ... } Vimos que uma das coisas que define o formato CommonJS é que ele tem um objeto exports. Então é isso que iremos verificar. Se exports existir, e for um objeto, exportamos nosso módulo: // ... else if( typeof exports === 'object' ) { module.exports = factory( require( 'jquery' ) ); } // ... Como precisamos passar o jQuery como parâmetro ao nosso módulo, usamos o require, pois já vimos que é assim que uma dependência é incluída usando esse formato. Resolvido também o ***CommonJS***! --- # Modulos - UMD Mas e se o desenvolvedor quiser usar nosso módulo, mas não estiver usando nem AMD, e nem CommonJS? Nesse caso, podemos dar um nome ao nosso módulo, exportando-o no escopo global, usando o root, que vai ser o objeto window, se ele estiver no browser, ou global, se ele estiver usando Node. Passamos também o objeto jQuery, que já deve estar também no escopo global: else { root.myModule = factory( root.jQuery ); } --- # Modulos - UMD Existem algumas outras variações do UMD. Então a solução é usar UMD pra tudo o que eu fizer? Não jovem. Para tudo o que for referente à sua aplicação em específico, você vai usar um único padrão: ou ***AMD***, ou ***CommonJS***, ou então algum pattern próprio. Agora, quando você tiver um módulo genérico, que você quiser reutilizar em qualquer ambiente, e em qualquer projeto, é a hora de usar ***UMD***. --- # Escopos de variáveis globais Assim como no browser, utilizamos o mesmo Javascript no Node.js, ele também utiliza escopos locais e globais de variáveis. A única diferença é como são implementados esses escopos. No client-side as variáveis globais são criadas da seguinte maneira: window.hoje = new Date(); alert(window.hoje); Em qualquer browser a palavra-chave window permite criar variáveis globais que são acessadas em qualquer lugar. Já no Node.js utilizamos uma outra keyword para aplicar essa mesma técnica: global.hoje = new Date(); console.log(global.hoje); --- # Escopos de variáveis globais Ao utilizar global mantemos uma variável global, acessível em qualquer parte do projeto sem a necessidade de chamá-la via require ou passá-la por parâmetro em uma função. Esse conceito de variável global é existente na maioria das linguagens de programação, assim como sua utilização, pelo qual é recomendado trabalhar como mínimo possível de variáveis globais, para evitar futuros gargalos de memória na aplicação. --- # CommonJS, Como ele funciona? O Node.js utiliza nativamente o padrão CommonJS para organização e carregamento de módulos. Na prática, diversas funções deste padrão será utilizada comfrequência em um projeto Node.js. A função require('nome-do-modulo') é um exemplo disso, ela carrega um módulo. E para criar um código Javascript que seja modular e carregável pelo require, utilizam-se as variáveis globais: exports ou module.exports. Abaixo apresento-lhe dois exemplos de códigos que utilizam esse padrão do CommonJS, primeiro crie o código hello.js: module.exports = function(msg) { console.log(msg); }; --- # CommonJS E também crie o código human.js com o seguinte código: exports.hello = function(msg) { console.log(msg); }; A diferença entre o hello.js e o human.js esta na maneira de como eles serão carregados. Em hello.js carregamos uma única função modular e em human.js é carregado um objeto comfunçõesmodulares. Essa é a grande diferença entre eles. --- # CommonJS Para entendermelhor na prática crie o código app.js para carregar esses módulos, seguindo o código abaixo: var hello = require('./hello'); var human = require('./human'); hello('Olá pessoal!'); human.hello('Olá galera!'); Tenha certeza de que os códigos hello.js, human.js e app.js estejam na mesma pasta e rode no console o comando: node app.js. --- # Aplicação web Node.js é multiprotocolo, ou seja, com ele será possível trabalhar com os protocolos: HTTP, HTTPS, FTP, SSH, DNS, TCP, UDP,WebSockets e também existem outros protocolos, que são disponíveis através de módulos não-oficiais criados pela comunidade. Um dos mais utilizados para desenvolver sistemas web é o protocolo HTTP. De fato, é o protocolo comamaior quantidade de módulos disponíveis para trabalhar no Node.js. Toda aplicação web necessita de um servidor para disponibilizar todos os seus recursos. Na prática, comoNode.js você desenvolve uma "aplicação middleware”, ou seja, além de programar as funcionalidades da sua aplicação, você também programa códigos de configuração de infraestrutura da sua aplicação. --- # Aplicação web Existem alguns módulos adicionais que já vêm com o mínimo necessário de configurações prontas para você não perder tempo trabalhando comisso. Alguns módulos conhecidos são: Connect(https://github.com/senchalabs/connect), Express (http://expressjs.com), Geddy (http://geddyjs.org) , CompoundJS (http://compoundjs.com) , Sails (http://balderdashy.github.io/sails) . Esses módulos já são preparados para trabalhar desde uma infraestrutura mínima até uma mais enxuta, permitindo trabalhar desde arquiteturas RESTFul, padrão MVC (Model-View-Controller) e também com conexões real-time utilizando WebSockets. --- # Servidor HTTP Primeiro usaremos apenas o módulo nativo HTTP, pois precisamos entender todo o conceito desse módulo, visto que todos os frameworks citados acima o utilizam como estrutura inicial em seus projetos. Abaixo mostro a vocês uma clássica aplicação Hello World. Crie o arquivo hello_server.js com o seguinte conteúdo: var http = require('http'); var server = http.createServer(function(request, response){ response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello World!</h1>"); response.end(); }); server.listen(3000); Esse é um exemplo clássico e simples de um servidor node.js. Ele está sendo executado na porta 3000, por padrão ele responde através da rota raiz “/” um resultado em formato html com a mensagem: Hello World!. Vá para a linha de comando e rode _node hello_server.js_. Faça o teste acessando, no seu navegador, o endereço _http://localhost:3000_ . --- # Como funciona um servidor http? Um servidor node.js utiliza o mecanismo Event loop, sendo responsável por lidar coma emissão de eventos. Na prática, a função http.createServer() é responsável por levantar ums ervidor e o seu callback function(request, response) apenas é executado quando o servidor recebe uma requisição. Para isso, o Event loop constantemente verifica se o servidor foi requisitado e, quando ele recebe uma requisição, ele emite um evento para que seja executado o seu callback. --- # Como funciona um servidor http? Se você ainda está começando com JavaScript, pode estranhar um pouco ficar passando como parâmetro uma function por todos os lados,mas isso é algo muito comum no mundo Javascript. Como sintaxe alternativa, caso o seu código fique muito complicado em encadeamentos de diversos blocos, podemos isolá-lo em funções com nomes mais significativos, por exemplo: var http = require('http'); var atendeRequisicao = function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Hello World!</h1>"); response.end(); } var server = http.createServer(atendeRequisicao); var servidorLigou = function() { console.log('Servidor Hello World rodando!'); } server.listen(3000, servidorLigou); --- # Rotas Até agora respondemos apenas o endereço /, mas queremos possibilitar que nosso servidor também responda a outros endereços. Utilizando um palavreado comum entre desenvolvedores rails, queremos adicionar novas rotas. Vamos adicionar duas novas rotas, uma rota /bemvindo para página de “Bemvindo ao Node.js!” e uma rota genérica, que leva para uma página de erro. var http = require('http'); var server = http.createServer(function(request, response){ response.writeHead(200, {"Content-Type": "text/html"}); if(request.url == "/"){ response.write("<h1>Página principal</h1>"); }else if(request.url == "/bemvindo"){ response.write("<h1>Bem-vindo :)</h1>"); }else{ response.write("<h1>Página não encontrada :(</h1>"); } response.end(); }); server.listen(3000, function(){ console.log('Servidor rodando!'); }); --- # URL a leitura de url é obtida através da função request.url() que retorna uma string sobre o que foi digitado na barra de endereço do browser. Esses endereços utilizam padrões para capturar valores na url. Esses padrões são: query strings ( ?nome=joao) e path ( /admin). Em um projeto maior, tratar todas as urls dessa maneira seria trabalhoso e confuso demais. NoNode.js, existe omódulo nativo chamado url, que é responsável por fazer parser e formatação de urls. Acompanhe como capturamos valores de uma query string no exemplo abaixo. var http = require('http'); var url = require('url'); var server = http.createServer(function(request, response){ response.writeHead(200, {"Content-Type": "text/html"}); response.write("<h1>Dados da query string</h1>"); var result = url.parse(request.url, true); for(var key in result.query){ response.write("<h2>"+key+" : "+result.query[key]+"</h2>"); } response.end(); }); server.listen(3000, function(){ console.log('Servidor http.'); }); --- # URL Neste exemplo, a função url.parse(request.url, true) fez um parser da url obtida pela requisição do cliente (request.url). Esse módulo identifica através do retorno da função url.parser() os seguintes atributos: - ***href:*** Retorna a url completa: _‘http://user:[email protected]:8080/p/a/t/h?query=string#hash’_ - ***protocol:*** Retorna o protocolo: _‘http’_ - ***host:*** Retorna o domínio com a porta: _‘host.com:8080’_ - ***auth:*** Retorna dados de autenticação: _‘user:pass’_ - ***hostname:*** Retorna o domínio: _‘host.com’_ - ***port:*** Retorna a porta: _‘8080’_ - ***pathname:*** Retorna os pathnames da url: _‘/p/a/t/h’_ - ***search:*** Retorna uma query string: _‘?query=string’_ - ***path:*** Retorna a concatenação de pathname com query string: _‘/p/a/t/h?query=string’_ - ***query:*** Retorna uma query string em JSON: _{‘query’:’string’}_ - ***hash:*** Retorna ancora da url: _‘#hash’_ --- # File System Agora precisamos organizar os códigos HTML, e uma boa prática é separá-los do Javascript, fazendo com que a aplicação renderize código HTML quando o usuário solicitar uma determinada rota. Para isso, utilizaremos outromódulo nativo FS (File System). Ele é responsável por manipular arquivos e diretórios do sistema operacional. O mais interessante desse módulo é que ele possui diversas funções de manipulação tanto de forma assíncrona como de forma síncrona. Por padrão, as funções nomeadas com o final Sync() são para tratamento síncrono. No exemplo abaixo, apresento as duas maneiras de ler um arquivo utilizando File System: var fs = require('fs'); fs.readFile('/index.html', function(erro, arquivo){ if (erro) throw erro; console.log(arquivo); }); var arquivo = fs.readFileSync('/index.html'); console.log(arquivo); --- # File System Diversos módulos do Node.js possuem funções com versões assíncronas e síncronas. O fs.readFile() faz uma leitura assíncrona do arquivo index.html. Depois que o arquivo foi carregado, é invocadouma função callback para fazer os tratamentos finais, seja de erro ou de retorno do arquivo. Já o fs.readFileSync() realizou uma leitura síncrona, bloqueando a aplicação até terminar sua leitura e retornar o arquivo. --- # File System ## Limitações do File System nos sistemas operacionais > Um detalhe importante sobre o módulo File System é que ele não é 100% consistente entre os sistemas operacionais. > Algumas funções são específicas para sistemas Linux, OS X,Unix e outras são apenas para Windows. Para melhores informações leia sua documentação: http://nodejs.org/api/fs.html --- # I/O Assíncrono O código abaixo exemplifica as diferenças entre uma função síncrona e assíncrona em relação a linha do tempo que ela são executadas. Basicamente criaremos um loop de 5 iterações, a cada iteração será criado um arquivo texto com o mesmo conteúdo Hello Node.js!. _text_sync.js_ var fs = require('fs'); for(var i = 1; i <= 5; i++) { var file = "sync-txt" + i + ".txt"; var out = fs.writeFileSync(file, "Hello Node.js!"); console.log(out); } _text_async.js_ var fs = require('fs'); for(var i = 1; i <= 5; i++) { var file = "async-txt" + i + ".txt"; fs.writeFile(file, "Hello Node.js!", function(err, out) { console.log(out); }); } --- # Threads vs Assincronismos Por mais que as funções assíncronas possamexecutar em paralelo várias tarefas, elas jamais serão consideradas umaThread (por exemploThreads do Java). A diferença é queThreads são manipuláveis pelo desenvolvedor, ou seja, você pode pausar a execução de umaThread ou fazê-laesperar o término de uma outra. Chamadas assíncronas apenas invocam suas funções numa ordem de que você não tem controle, e você só sabe quando uma chamada terminou quando seu callback é executado. Pode parecer vantajoso ter o controle sobre asThreads a favor de um sistema que executa tarefas em paralelo, mas pouco domínio sobre eles pode transformar seu sistema em um caos de travamentos dead-locks, afinal Threads são executadas de forma bloqueante. Este é o grande diferencial das chamadas assíncronas, elas executam em paralelo suas funções sem travar processamento das outras e principalmente sem bloquear o sistema principal. --- # Entendendo o Event-Loop Realmente trabalhar de forma assíncrona tem ótimos benefícios em relação a processamento I/O. Isso acontece devido ao fato, de queuma chamada de I/O é considerada um tarefa muito custosa para um computador realizar. Vendo o contexto de um servidor, pormais potente que seja seu hardware, eles terão os mesmos bloqueios perceptíveis pelo usuário, a diferença é que um servidor estará lidando com milhares usuários requisitando I/O, com a grande probabilidade de ser ao mesmo tempo. É por isso que o Node.js trabalha com assincronismo. Ele permite que você desenvolva um sistema totalmente orientado a eventos, tudo isso graças ao Event-loop. --- # Entendendo o Event-Loop Ele é um mecanismo interno, dependente das bibliotecas da linguagem C: libev (http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod) e libeio (http://software.schmorp.de/pkg/libeio.html),responsáveis por prover o assíncrono I/O no Node.js. Basicamente ele é um loop infinito, que em cada iteração verifica se existem novos eventos em sua fila de eventos. Tais eventos somente aparecem nesta fila quando são emitidos durante suas interações na aplicação. O EventEmitter, é o módulo responsável por emitir eventos e a maioria das bibliotecas do Node.js herdam deste módulo suas funcionalidades de eventos. --- # Entendendo o Event-Loop Quando um determinado código emite um evento, omesmo é enviado para a fila de eventos para que o Event-loop executeo, e em seguida retorne seu callback. Tal callback pode ser executado através de uma função de escuta, semanticamente conhecida pelo nome: on(). Programar orientado a eventos vai manter sua aplicação mais robusta e estruturada para lidar com eventos que são executados de forma assíncrona não bloqueantes. Para conhecer mais sobre as funcionalidades do EventEmitter acesse sua documentação: http://nodejs.org/api/events.html --- # Callbacks Hell De fato, vimos o quanto é vantajoso e performático trabalhar de forma assíncrona, porém em certosmomentos, inevitavelmente implementaremos diversas funções assíncronas, que serão encadeadas uma na outra através das suas funções callback. var fs = require('fs'); fs.readdir(__dirname, function(erro, contents) { if (erro) { throw erro; } contents.forEach(function(content) { var path = './' + content; fs.stat(path, function(erro, stat) { if (erro) { throw erro; } if (stat.isFile()) { console.log('%s %d bytes', content, stat.size); } }); }); }); --- # Callbacks Hell Reparem na quantidade de callbacks encadeados que existem em nosso código. Detalhe: ele apenas faz uma simples leitura dos arquivos de seu diretório e imprime na tela seu nome e tamanho em bytes. Um pequena tarefa como essa deveria ter menos encadeamentos, concorda? Agora, imagine como seria a organização disso para realizar tarefasmas complexas? Praticamente o seu código seria um caos e totalmente difícil de fazermanutenções. Por ser assíncrono, você perde o controle do que está executando em troca de ganhos com performance, porém, um detalhe importante sobre assincronismo é que na maioria dos casos os callbacks bem elaborados possuem como parâmetro uma variável de erro. --- # Callback Heaven Uma boa prática de código Javascript é criar funções que expressem seu objetivo e de forma isoladas, salvando em variável e passando-as como callback. var fs = require('fs'); var lerDiretorio = function() { fs.readdir(__dirname, function(erro, diretorio) { if (erro) return erro; diretorio.forEach(function(arquivo) { ler(arquivo); }); }); }; var ler = function(arquivo) { var path = './' + arquivo; fs.stat(path, function(erro, stat) { if (erro) return erro; if (stat.isFile()) { console.log('%s %d bytes', arquivo, stat.size); } }); }; lerDiretorio(); --- # Express Programar utilizando apenas a API HTTP nativa é muito trabalhoso! Conforme surgem necessidades de implementar novas funcionalidades, códigos gigantescos seriam acrescentados, aumentando a complexidade do projeto e dificultando futuras manutenções. Foi a partir desse problema que surgiu um framework muito popular, que se chama Express. Ele é um módulo para desenvolvimento de aplicações web de grande escala. Sua filosofia de trabalho foi inspirada pelo framework Sinatra da linguagem Ruby. O site oficial do projeto é: (http://expressjs.com) . --- # Express Ele possui as seguintes características: - MVR (Model-View-Routes); - MVC (Model-View-Controller); - Roteamento de urls via callbacks; - Middleware; - Interface RESTFul; - Suporte a File Uploads; - Configuração baseado em variáveis de ambiente; - Suporte a helpers dinâmicos; - Integração com Template Engines; - Integração com SQL e NoSQL; --- # Instalação e configuração Sua instalação é muito simples e há algumas opções de configurações para começar um projeto. Para aproveitar todos os seus recursos, recomendo que instale-o em modo global: npm install -g express Feito isso, será necessário fechar e abrir seu terminal para habilitar o comando express, que é um CLI (Command Line Interface) do framework. Ele permite gerar um projeto inicial com suporte a sessões, Template engine (por padrão ele inclui o framework Jade) e um CSS engine (por padrão ele utiliza CSS puro). Para visualizar todas as opções execute o comando: express -h --- # Instalação mkdir lab0201 cd lab0201 Use o comando npm init para criar um arquivo package.json para o seu aplicativo. Para obter mais informações sobre como o package.json funciona, consulte [Detalhes do tratamento de package.json](https://docs.npmjs.com/files/package.json) do npm. $ npm init Este comando solicita por várias coisas, como o nome e versão do seu aplicativo. Por enquanto, é possível simplesmente pressionar RETURN para aceitar os padrões para a maioria deles, com as seguintes exceções: entry point: (index.js) Insira app.js, ou qualquer nome que deseje para o arquivo principal. Se desejar que seja index.js, pressione RETURN para aceitar o nome de arquivo padrão sugerido. --- # Instalação Agora instale o Express no diretório app e salve-o na lista de dependências. Por exemplo: npm install express --save --- # Instalação Inclua o seguinte código: var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); }); O aplicativo inicia um servidor e escuta a porta 3000 por conexões. O aplicativo responde com “Hello World!” à solicitações para a URL raiz (/) ou rota. Para todos os outros caminhos, ele irá responder com um 404 Não Encontrado. --- # Gerador de aplicativos do Express Use a ferramenta geradora de aplicativos, express, para rapidamente criar uma estrutura básica de aplicativo. Instale o express com o comando a seguir: npm install express-generator -g Exiba as opções de comando com a opção -h: $ express -h Usage: express [options][dir] Options: -h, --help output usage information -V, --version output the version number -e, --ejs add ejs engine support (defaults to jade) --hbs add handlebars engine support -H, --hogan add hogan.js engine support -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory --- # Gerador de aplicativos do Express Por exemplo, o seguinte cria um aplicativo do Express chamado lab0203 no diretório atualmente em funcionamento: $ express lab0203 create : lab0203 create : lab0203/package.json create : lab0203/app.js create : lab0203/public create : lab0203/public/javascripts create : lab0203/public/images create : lab0203/routes create : lab0203/routes/index.js create : lab0203/routes/users.js create : lab0203/public/stylesheets create : lab0203/public/stylesheets/style.css create : lab0203/views create : lab0203/views/index.jade create : lab0203/views/layout.jade create : lab0203/views/error.jade create : lab0203/bin create : lab0203/bin/www --- # Gerador de aplicativos do Express Em seguida instale as dependências: $ cd lab0203 $ npm install No MacOS ou Linux, execute o aplicativo com este comando: $ DEBUG=lab0203:* npm start No Windows, use este comando: > set DEBUG=lab0203:* & npm start Em seguida carregue http://localhost:3000/ no seu navegador para acessar o aplicativo. --- # Gerador de aplicativos do Express O aplicativo gerado possui a seguinte estrutura de diretórios: . ├── app.js ├── bin │ └── www ├── package.json ├── public │ ├── images │ ├── javascripts │ └── stylesheets │ └── style.css ├── routes │ ├── index.js │ └── users.js └── views ├── error.jade ├── index.jade └── layout.jade 7 directories, 9 files --- # Roteamento Básico O Roteamento refere-se à determinação de como um aplicativo responde a uma solicitação do cliente por um endpoint específico, que é uma URI (ou caminho) e um método de solicitação HTTP específico (GET, POST, e assim por diante). Cada rota pode ter uma ou mais funções de manipulação, que são executadas quando a rota é correspondida. A definição de rotas aceita a seguinte estrutura: app.METHOD(PATH, HANDLER) Onde: - _app_ é uma instância do express. - _METHOD_ é um método de solicitação HTTP. - _PATH_ é um caminho no servidor. - _HANDLER_ é a função executada quando a rota é correspondida. --- # Roteamento Básico Os seguintes exemplos ilustram a definição de rotas simples. Responder com Hello World! na página inicial: app.get('/', function (req, res) { res.send('Hello World!'); }); Responder a uma solicitação POST na rota raiz (/) com a página inicial do aplicativo: app.post('/', function (req, res) { res.send('Got a POST request'); }); --- # Roteamento Básico Responder a uma solicitação PUT para a rota /user: app.put('/user', function (req, res) { res.send('Got a PUT request at /user'); }); Responder a uma solicitação DELETE para a rota /user: app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user'); }); --- # Roteamento Básico Existe um método de roteamento especial, app.all(), que não é derivado de nenhum método HTTP. Este método é usado para carregar funções de middleware em um caminho para todos os métodos de solicitação. No exemplo a seguir, o manipulador irá ser executado para solicitações para “/secret” se você estiver usando GET, POST, PUT, DELETE, ou qualquer outro método de solicitação HTTP que é suportado no módulo http. app.all('/secret', function (req, res, next) { console.log('Accessing the secret section ...'); next(); // pass control to the next handler }); --- # Caminhos de rota Caminhos de rota, em combinação com os métodos de solicitação, definem os terminais em que as solicitações podem ser feitas. Caminhos de rota podem ser sequências de caracteres, padrões de sequência, ou expressões regulares. Aqui estão alguns exemplos de caminhos de rota baseados em sequências de caracteres Este caminho de rota corresponde a solicitações à rota raiz, /. app.get('/', function (req, res) { res.send('root'); }); --- # Caminhos de rota Este caminho de rota irá corresponder a solicitações ao /about. app.get('/about', function (req, res) { res.send('about'); }); Este caminho de rota irá corresponder a solicitações ao /random.text. app.get('/random.text', function (req, res) { res.send('random.text'); }); > _Os caracteres ?, +, *, e () são subconjuntos de suas contrapartes em expressões regulares._ > _O hífen (-) e o ponto (.) são interpretados literalmente por caminhos baseados em sequências de caracteres._ --- # Caminhos de rota Exemplos de caminhos de rota baseados em expressões regulares: Este caminho de rota irá corresponder a qualquer coisa com um “a” no nome. app.get(/a/, function(req, res) { res.send('/a/'); }); Este caminho de rota irá corresponder a butterfly e dragonfly, mas não a butterflyman, dragonfly man, e assim por diante. app.get(/.*fly$/, function(req, res) { res.send('/.*fly$/'); }); --- # Métodos de resposta Os métodos do objeto de resposta (res) na seguinte tabela podem enviar uma resposta ao cliente, e finalizar o ciclo solicitação-resposta. Se nenhum destes métodos forem chamados a partir de um manipulador de rota, a solicitação do cliente será deixada em suspenso. - res.download() - Solicita que seja efetuado o download de um arquivo - res.end() - Termina o processo de resposta. - res.json() - Envia uma resposta JSON. - res.jsonp() Envia uma resposta JSON com suporta ao JSONP. - res.redirect() - Redireciona uma solicitação. - res.render() - Renderiza um modelo de visualização. - res.send() - Envia uma resposta de vários tipos. - res.sendFile Envia um arquivo como um fluxo de octeto. - res.sendStatus() - Configura o código do status de resposta e envia a sua representação em sequência de caracteres como o corpo de resposta. --- # app.route() É possível criar manipuladores de rota encadeáveis para um caminho de rota usando o app.route(). Como o caminho é especificado em uma localização única, criar rotas modulares é útil, já que reduz redundâncias e erros tipográficos. Para obter mais informações sobre rotas, consulte: documentação do Router(). Aqui está um exemplo de manipuladores de rotas encadeáveis que são definidos usando app.route(). app.route('/book') .get(function(req, res) { res.send('Get a random book'); }) .post(function(req, res) { res.send('Add a book'); }) .put(function(req, res) { res.send('Update the book'); }); --- # express.Router Use a classe express.Router para criar manipuladores de rota modulares e montáveis. Uma instância de Router é um middleware e sistema de roteamento completo; por essa razão, ela é frequentemente referida como um “mini-aplicativo” O seguinte exemplo cria um roteador como um módulo, carrega uma função de middleware nele, define algumas rotas, e monta o módulo router em um caminho no aplicativo principal. --- # express.Router Crie um arquivo de roteador com um arquivo chamado clientes.js no diretório do aplicativo, com o seguinte conteúdo: var express = require('express'); var router = express.Router(); // middleware that is specific to this router router.use(function timeLog(req, res, next) { console.log('Time: ', Date.now()); next(); }); // define the home page route router.get('/', function(req, res) { res.send('Clientes - Home'); }); // define the about route router.get('/about', function(req, res) { res.send('Sobre - Clientes'); }); module.exports = router; --- # express.Router Em seguida, carregue o módulo roteador no aplicativo: var clientes = require('./clientes'); ... app.use('/clientes', clientes); O aplicativo será agora capaz de manipular solicitações aos caminhos /clientes e /clientes/about, assim como chamar a função de middleware timeLog que é específica para a rota. --- # Usando middlewares O Express é uma estrutura web de roteamento e middlewares que tem uma funcionalidade mínima por si só: Um aplicativo do Express é essencialmente uma série de chamadas de funções de middleware. Funções de Middleware são funções que tem acesso ao objeto de solicitação (req), o objeto de resposta (res), e a próxima função de middleware no ciclo solicitação-resposta do aplicativo. A próxima função middleware é comumente denotada por uma variável chamada next. Funções de middleware podem executar as seguintes tarefas: - Executar qualquer código. - Fazer mudanças nos objetos de solicitação e resposta. - Encerrar o ciclo de solicitação-resposta. - Chamar a próxima função de middleware na pilha. --- # Usando middlewares Se a atual função de middleware não terminar o ciclo de solicitação-resposta, ela precisa chamar next() para passar o controle para a próxima função de middleware. Caso contrário, a solicitação ficará suspensa. Um aplicativo Express pode usar os seguintes tipos de middleware: - Middleware de nível do aplicativo - Middleware de nível de roteador - Middleware de manipulação de erros - Middleware integrado - Middleware de Terceiros É possível carregar middlewares de nível de roteador e de nível do aplicativo com um caminho de montagem opcional. É possível também carregar uma série de funções de middleware juntas, o que cria uma sub-pilha do sistema de middleware em um ponto de montagem. --- # Middleware de nível do aplicativo Vincule middlewares de nível do aplicativo a uma instância do objeto app usando as funções app.use() e app.METHOD(), onde METHOD é o método HTTP da solicitação que a função de middleware manipula (como GET, PUT, ou POST) em letras minúsculas. Este exemplo mostra uma função de middleware sem um caminho de montagem. A função é executada sempre que o aplicativo receber uma solicitação. var app = express(); app.use(function (req, res, next) { console.log('Time:', Date.now()); next(); }); --- # Middleware de nível do aplicativo Este exemplo mostra uma função de middleware montada no caminho /user/:id. A função é executada para qualquer tipo de solicitação HTTP no caminho /user/:id. app.use('/user/:id', function (req, res, next) { console.log('Request Type:', req.method); next(); }); Este exemplo mostra uma rota e sua função manipuladora (sistema de middleware). A função manipula solicitações GET ao caminho /user/:id. app.get('/user/:id', function (req, res, next) { res.send('USER'); }); --- # Middleware de nível do aplicativo Aqui está um exemplo de carregamento de um série de funções de middleware em um ponto de montagem, com um caminho de montagem. Ele ilustra uma sub-pilha de middleware que imprime informações de solicitação para qualquer tipo de solicitação HTTP no caminho /user/:id. app.use('/user/:id', function(req, res, next) { console.log('Request URL:', req.originalUrl); next(); }, function (req, res, next) { console.log('Request Type:', req.method); next(); }); --- # Middleware de nível do aplicativo Manipuladores de rota permitem a você definir várias rotas para um caminho. O exemplo abaixo define duas rotas para solicitações GET no caminho /user/:id. A segunda rota não irá causar nenhum problema, mas ela nunca será chamada pois a primeira rota termina o ciclo solicitação-resposta. Este exemplo mostra uma sub-pilha de middleware que manipula solicitações GET no caminho /user/:id. app.get('/user/:id', function (req, res, next) { console.log('ID:', req.params.id); next(); }, function (req, res, next) { res.send('User Info'); }); // handler for the /user/:id path, which prints the user ID app.get('/user/:id', function (req, res, next) { res.end(req.params.id); }); --- # Middleware de nível do aplicativo Para pular o restante das funções de middleware de uma pilha de middlewares do roteador, chame next('route') para passar o controle para a próxima rota. NOTA: O next('route') irá funcionar apenas em funções de middleware que são carregadas usando as funções app.METHOD() ou router.METHOD(). Este exemplo mostra uma sub-pilha de middleware que manipula solicitações GET no caminho /user/:id. app.get('/user/:id', function (req, res, next) { // if the user ID is 0, skip to the next route if (req.params.id == 0) next('route'); // otherwise pass the control to the next middleware function in this stack else next(); // }, function (req, res, next) { // render a regular page res.render('regular'); }); // handler for the /user/:id path, which renders a special page app.get('/user/:id', function (req, res, next) { res.render('special'); }); --- # Middleware de nível de roteador Middlewares de nível de roteador funcionam da mesma forma que os middlewares de nível do aplicativo, mas estão vinculados a uma instância do express.Router(). var router = express.Router(); Carregue os middlewares de nível de roteador usando as funções router.use() e router.METHOD(). --- # Middleware de nível de roteador O seguinte código de exemplo replica o sistema de middleware que é mostrado acima para o middleware de nível do aplicativo, usando um middleware de nível de roteador: var app = express(); var router = express.Router(); // a middleware function with no mount path. This code is executed for // every request to the router router.use(function (req, res, next) { console.log('Time:', Date.now()); next(); }); // a middleware sub-stack shows request info for // any type of HTTP request to the /user/:id path router.use('/user/:id', function(req, res, next) { console.log('Request URL:', req.originalUrl); next(); }, function (req, res, next) { console.log('Request Type:', req.method); next(); }); --- # Middleware de nível de roteador // a middleware sub-stack that handles GET requests to the /user/:id path router.get('/user/:id', function (req, res, next) { // if the user ID is 0, skip to the next router if (req.params.id == 0) next('route'); // otherwise pass control to the next middleware function in this stack else next(); // }, function (req, res, next) { // render a regular page res.render('regular'); }); // handler for the /user/:id path, which renders a special page router.get('/user/:id', function (req, res, next) { console.log(req.params.id); res.render('special'); }); // mount the router on the app app.use('/', router); --- # Middleware de manipulação de erros > _Middlewares de manipulação de erros sempre levam quatro argumentos. Você deve fornecer quatro argumentos para identificá-lo como uma função de middleware de manipulação de erros. Mesmo se você não precisar usar o objeto next, você deve especificá-lo para manter a assinatura. Caso contrário, o objeto next será interpretado como um middleware comum e a manipulação de erros falhará._ Defina funções de middleware de manipulação de erros da mesma forma que outras funções de middleware, exceto que com quatro argumentos ao invés de três, especificamente com a assinatura (err, req, res, next)): app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send('Something broke!'); }); --- # Middleware integrado Desde a versão 4.x, o Express não depende mais do Connect. Com exceção da express.static, todas as funções de middleware que eram previamente incluídas com o Express estão agora em módulos separados. Visualize a lista de funções de middleware. express.static(root, [options]) A única função de middleware integrada no Express é a express.static. Esta função é baseada no serve-static, e é responsável por entregar os ativos estáticos de um aplicativo do Express. O argumento root especifica o diretório raiz a partir do qual entregar os ativos estáticos. --- # Middleware integrado Aqui está um exemplo de uso da função de middleware express.static com um objeto options elaborado: var options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders: function (res, path, stat) { res.set('x-timestamp', Date.now()); } } app.use(express.static('public', options)); É possível ter mais do que um diretório estático por aplicativo: app.use(express.static('public')); app.use(express.static('uploads')); app.use(express.static('files')); --- # Middleware de Terceiros Use middlewares de terceiros para incluir funcionalidades aos aplicativos do Express Instale o módulo Node.js para a funcionalidade requerida, em seguida carregue-a no seu aplicativo no nível do aplicativo ou no nível de roteador. O exemplo a seguir ilustra a instalação e carregamento da função de middleware para análise sintática de cookies cookie-parser. $ npm install cookie-parser var express = require('express'); var app = express(); var cookieParser = require('cookie-parser'); // load the cookie-parsing middleware app.use(cookieParser()); --- # Entregando arquivos estáticos no Express Para entregar arquivos estáticos como imagens, arquivos CSS, e arquivos JavaScript, use a função de middleware express.static integrada no Express. Passe o nome do diretório que contém os ativos estáticos para a função de middleware express.static para iniciar a entregar os arquivos diretamente. Por exemplo, use o código a seguir para entregar imagens, arquivos CSS, e arquivos JavaScript em um diretório chamado public: app.use(express.static('public')); Agora, é possível carregar os arquivos que estão no diretório public: http://localhost:3000/images/kitten.jpg http://localhost:3000/css/style.css http://localhost:3000/js/app.js http://localhost:3000/images/bg.png http://localhost:3000/hello.html > _O Express consulta os arquivos em relação ao diretório estático, para que o nome do diretório estático não faça parte da URL._ --- # Entregando arquivos estáticos no Express Para usar vários diretórios de ativos estáticos, chame a função de middleware express.static várias vezes: app.use(express.static('public')); app.use(express.static('files')); O Express consulta os arquivos na ordem em que você configurar os diretórios estáticos com a função de middleware express.static. Para criar um prefixo de caminho virtual (onde o caminho não existe realmente no sistema de arquivos) para arquivos que são entregues pela função express.static, especifique um caminho de montagem para o diretório estático, como mostrado abaixo: app.use('/static', express.static('public')); --- # Entregando arquivos estáticos no Express Agora, é possível carregar os arquivos que estão no diretório public a partir do prefixo do caminho /static. http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html Entretanto, o caminho fornecido para a função express.static é relativa ao diretório a partir do qual você inicia o seu node de processo. Se você executar o aplicativo express a partir de outro diretório, é mais seguro utilizar o caminho absoluto do diretório para o qual deseja entregar. app.use('/static', express.static(__dirname + '/public')); --- # Integração de Banco de dados A inclusão da capacidade de se conectar à banco de dados em aplicativos do Express é apenas uma questão de se carregar um driver Node.js apropriado para o banco de dados no seu aplicativo. Este documento explica brevemente como incluir e utilizar alguns dos mais populares módulos do Node.js para sistemas de bancos de dados no seu aplicativo do Express: - Cassandra - CouchDB - LevelDB - MySQL - MongoDB - Neo4j - PostgreSQL - Redis - SQLite - ElasticSearch --- # LevelDB Módulo: [levelup](https://github.com/Level/levelup?_ga=1.116155779.422133707.1462294138) Instalação $ npm install level levelup leveldown Exemplo var levelup = require('levelup'); var db = levelup('./mydb'); db.put('name', 'LevelUP', function (err) { if (err) return console.log('Ooops!', err); db.get('name', function (err, value) { if (err) return console.log('Ooops!', err); console.log('name=' + value); }); }); --- # MySQL Módulo: mysql Instalação $ npm install mysql Exemplo var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'dbuser', password : 's3kreee7' }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); connection.end(); --- # MongoDB Módulo: mongodb Instalação $ npm install mongodb Exemplo var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) { if (err) { throw err; } db.collection('mammals').find().toArray(function(err, result) { if (err) { throw err; } console.log(result); }); }); Se desejar um driver de modelo de objeto para o MongoDB, consulte em Mongoose. --- # Redis Módulo: redis Instalação $ npm install redis Exemplo var client = require('redis').createClient(); client.on('error', function (err) { console.log('Error ' + err); }); client.set('string key', 'string val', redis.print); client.hset('hash key', 'hashtest 1', 'some value', redis.print); client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print); client.hkeys('hash key', function (err, replies) { console.log(replies.length + ' replies:'); replies.forEach(function (reply, i) { console.log(' ' + i + ': ' + reply); }); client.quit(); }); --- # SQLite Módulo: sqlite3 Instalação $ npm install sqlite3 Exemplo var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database(':memory:'); db.serialize(function() { db.run('CREATE TABLE lorem (info TEXT)'); var stmt = db.prepare('INSERT INTO lorem VALUES (?)'); for (var i = 0; i < 10; i++) { stmt.run('Ipsum ' + i); } stmt.finalize(); db.each('SELECT rowid AS id, info FROM lorem', function(err, row) { console.log(row.id + ': ' + row.info); }); }); db.close(); --- # Migrando do MySQL para Mongo Baseado no [SQL to MongoDB Mapping Chart](https://docs.mongodb.org/manual/reference/sql-comparison/) SQL Terms/Concepts MongoDB Terms/Concepts database database table collection row document or BSON document column field index index table joins embedded documents and linking primary key primary key aggregation aggregation pipeline (e.g. group by) --- # Migrando do MySQL para Mongo ### Criando uma coleção db.createCollection( "agenda" ) ### Inseriando registro na coleção db.agenda.insert({nome:"Tiozinho" , email: "[email protected]" , telefone: "9999-9999" }); ### Buscando registro na coleção //Lista todos os registros db.agenda.find() //Lista apenas o definido no parâmetro db.agenda.find({id:1}) // {id:1} é o parâmetro --- # Migrando do MySQL para Mongo ### Excluindo registro da coleção db.agenda.remove({id:1}); ### Atualizando um registro na coleção //Buscando o Tiozinho var agd = db.agenda.find({id:1}); //Alterando apenas o email agd.email = "[email protected]"; //Atualizando na coleção db.agenda.save(agd); --- # Migrando do MySQL para Mongo - drop() - dropDataBase() - update() - count() - limit() - sort() --- # MongoDB no Node.js utilizando Mongoose O Mongoose possui uma interfacemuito fácil de aprender. Em poucos códigos, você vai conseguir criar uma conexão no banco de dados e executar uma query ou persistir dados. Com o MongoDB instalado e funcionando em sua máquina, vamos instalar omódulo mongoose, que é um framework responsável pormapear objetos do Node.js para MongoDB. --- # Mongoose var express = require('express') , app = express() , mongoose = require('mongoose'); global.db = mongoose.connect('mongodb://localhost/agenda'); Quando é executada a função mongoose.connect cria-se uma conexão com o banco de dados MongoDB para o Node.js. Como o MongoDB é schemaless, na primeira vez que a aplicação se conecta com o banco através da url 'mongodb://localhost/agenda' automaticamente em run-time é criada uma base de dados com o nome agenda. --- # Modelando com Mongoose O Mongoose é um módulo focado para a criação de models, isso significa que com ele criaremos objetos persistentes modelando seus atributos através do objeto mongoose.Schema. Após a implementação de um modelo, temos que registrálo no banco de dados, utilizando a função db.model('nome-do-model',modelSchema), que recebeummodelo e cria sua respectiva collection no MongoDB. --- # Socket.IO O Socket.IO fornece comunicação em tempo real entre seu servidor e clientes do node.js. Para quem não conhece, o WebSocket era parte da especificação do HTML5 que descreve a comunicação bidirecional (envie e recebe mensagens) entre canais através de TCP/IP. Não faz mais parte do HTML5 e ganhou vida própria, sendo o protocolo padronizado pela IETF como RFC 6455 e a API padronizada pela W3C. --- # Socket.IO O Socket.IO abstrai e utiliza o WebSocket como o seu principal mecanismo. E se não for compatível com o meu ambiente? Então o próprio Socket.IO se encarrega de providenciar outros mecanismos de transporte, como fallback: - Adobe® Flash® Socket - AJAX long polling - AJAX multipart streaming - Forever Iframe - JSONP Polling Você não precisa se preocupar, por que tudo é transparente para você! Dá para entender por que o módulo é tão popular – pois garante compatibilidade entre diferentes clientes e servidores, sejam através de dispositivos móveis ou desktops, independente de versão de browser e sistema operacional. --- # E como o WebSocket funciona? Basicamente ouvimos e transmitimos mensagens. Neste caso, você tem basicamente dois métodos que vão ditar todo o restante: on e emit. Simples assim. No on você deixa o servidor ou o client aguardando uma mensagem chegar e no emit você transmite esta mensagem. ![](https://evenancio.files.wordpress.com/2013/12/websocket-chat.png?w=527) --- # TDD e Node.js – Introdução ao Mocha Independente da linguagem utilizada ou onde sua aplicação é executada, no cliente (browser) ou servidor, escrever testes é sempre uma ótima prática! Com JavaScript e Node.js não é diferente. Existem vários frameworks que facilitam a escrita, execução e análise dos testes, o que mais me agradou até o momento é o Mocha. A instalação do Mocha é simples, utilizamos o NPM que é responsável por fazer o download e instalar o pacote escolhido. Para quem conhece o NuGet disponível para .NET no Visual Studio, o NPM é o equivalente no mundo Node.js. npm install mocha --- # Mocha Após instalado vamos começar com a primeira boa prática. Por padrão o comando mocha procura os arquivos de teste em um diretório chamado test. Então no diretório da sua aplicação crie um diretório chamado test e coloque lá seus arquivos de teste. Podemos agora começar a desenvolver os testes da nossa aplicação, nesse primeiro momento vamos criar dois testes bem simples. var assert = require('assert'); describe('Alguns testes de exemplo', function(){ it('2 + 2 deve ser igual a 4', function(){ assert.equal(4, 2 + 2); }); it('2 * 2 deve ser igual a 8 (nota 0 em matemática)', function(){ assert.equal(8, 2 * 2); }); }); --- # Mocha Na primeira linha do código referenciamos a biblioteca assert que está disponível no Node.js. No exemplo utilizamos só o método assert.equal mas na documentação você encontrará os outros métodos disponíveis. Os métodos describe e it fazem parte do Mocha, mais especificamente da API de BDD do Mocha. Com o teste criado basta executar o comando mocha no ser Terminal (OSX) ou Command Prompt (Windows) e ver que um teste passou e outro não. --- # Um projeto testável Vamos iniciar um projeto simples, mas que tenha a capacidade de mostrar o Mocha atuando. Primeiramente vamos instalar todas as dependências: # Crie um projeto em uma pasta vazia mkdir meu-projeto && cd meu-projeto && npm init # Logo após instale o Mocha globalmente sudo npm install -g mocha # Criamos as pastas principais do projeto mkdir test lib # Assim como o arquivo principal touch index.js test/general-test.js # Logo após abra o arquivo general-test.js # com o seu editor favorito vim general-test.js --- # Mocha Nesta aplicação, construiremos uma biblioteca capaz de executar os cálculos que são passados via linha de comando. Primeiramente vamos aos testes: --- # Mocha // Vamos usar a lib assert, que já // vem no core do Node.js var assert = require('assert'); // E também vamos incluir a lib // da calculador, que criaremos mais tarde var calculadora = require('../lib/calculadora'); // Descrevemos um tópico inicial usando // o método describe() do Mocha describe('Testes gerais da calculadora', function(){ // Dentro do tópico criamos os testes relacionados // aos mesmos, fazemos isso usando o método it() it('A calculadora deve ser uma função', function(){ // Usamos o assert.equal() para verificar se // o tipo da variável 'calculadora' realmente // é uma função assert.equal(typeof calculadora, 'function'); }); it('O cálculo 191 * 7 deve ser igual a 1337', function(){ assert.equal(calculadora('191 * 7'), 1337); }); }); --- # Mocha Fácil e rápido, você já pode usar o comando mocha ./test/*-test.js para ver o que está de errado com sua aplicação, ou utilizar o parâmetro –reporter spec para ter um relatório mais agradável. Certamente o teste reclamou da ausência do arquivo../lib/calculadora.js, então vamos criá-lo: // Vamos usar o módulo VM para compilar o input // do usuário, lembre-se: evite o eval() var vm = require('vm'); module.exports = function(calculo){ // Vamos executar o código que fora passado // e retornar o seu resultado return vm.runInNewContext('(function(){ return ' + calculo + '})()'); }; --- # Mocha Agora, usando o Mocha, seus testes devem passar. Só está faltando o programa principal, vamos editar o index.js: var calculador = require('./lib/calculadora'); var resultado = calculador(process.argv[2]); console.log(resultado); Executando node ./ ‘1 + 1’, você deve ver o output 2 em seu terminal. --- # Monitorando aplicação através de logs Quando colocamos um sistema em produção, aumentamos os riscos de acontecerem bugs que não foram identificados durante os testes no desenvolvimento. Isso é normal, e toda aplicação já passou ou vai passar por esta situação. O importante neste caso é ter ummeio demonitorar todo comportamento da aplicação, através de arquivos de logs. Tanto o Express quanto o Socket.IO possuem um middleware para monitorar e gerar logs. Sua instalação é simples, abra o app.js e adicione no topo da stack de configurações do Express a função app.use(express.logger()): app.use(express.logger()); app.use(express.json()); app.use(express.urlencoded()); --- # Aplicando Singleton nas conexões do Mongoose No Mongoose, apenas aplicaremos o design pattern Singleton para instanciar as conexões do banco de dados. Isso será implementado com o objetivo de garantir que apenas uma única conexão seja instanciada e compartilhada por toda aplicação. No arquivo lib/db_connect.js, codifique aplicando as seguintes mudanças: var mongoose = require('mongoose') , single_connection , env_url = { "test": "mongodb://localhost/ntalk_test", "development": "mongodb://localhost/ntalk" }; module.exports = function() { var env = process.env.NODE_ENV || "development" , url = env_url[env]; if(!single_connection) { single_connection = mongoose.connect(url); } return single_connection; }; --- # Mantendo o sistema no ar com Forever O Node.js é praticamente uma plataforma de baixo nível, com ele temos bibliotecas com acesso direto aos recursos do sistema operacional, e programamos entre diversos protocolos, como por exemplo, o protocolo http. Para trabalhar com http, temos que programar como será o servidor http e também sua aplicação. Quando colocamos uma aplicação Node em produção diversos problemas e bugs são encontrados com o passar do tempo, e quando surge um bug grave o servidor cai, deixando a aplicação fora do ar. De fato, programar em Node.js requer lidar com esses detalhes de servidor. --- # Mantendo o sistema no ar com Forever O Forever é uma ferramenta que surgiu para resolver esse problema de queda do servidor. Seu objetivo émonitorarumservidor realizando pings a cada curto período predeterminado pelo desenvolvedor. Quando ele detecta que a aplicação está fora do ar, automaticamente ele dá um restart nela. Ele consegue fazer isso por que mantém a aplicação rodando em background no sistema operacional. </textarea> <script src="https://gnab.github.io/remark/downloads/remark-latest.min.js"> </script> <script> var slideshow = remark.create(); </script> </body> </html>
apache-2.0
yeastrc/msdapl
MS_LIBRARY/src/MS2FileValidator.java
2486
import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import org.apache.log4j.Logger; import org.yeastrc.ms.parser.DataProviderException; import org.yeastrc.ms.parser.ms2File.Ms2FileReader; import org.yeastrc.ms.util.Sha1SumCalculator; /** * */ public class MS2FileValidator { private static final Logger log = Logger.getLogger(MS2FileValidator.class); public static final int VALIDATION_ERR_SHA1SUM = 1; public static final int VALIDATION_ERR_READ = 2; public static final int VALIDATION_ERR_HEADER = 3; public static final int VALIDATION_ERR_SCAN = 4; public static final int VALID = 0; public int validateFile(String filePath) { log.info("VALIDATING file: "+filePath); Ms2FileReader dataProvider = new Ms2FileReader(); String sha1sum = getSha1Sum(filePath); if (sha1sum == null) { log.error("ERROR calculating sha1sum for file: "+filePath+". EXITING..."); return VALIDATION_ERR_SHA1SUM; } // open the file try { dataProvider.open(filePath, sha1sum); } catch (DataProviderException e) { log.error("ERROR reading file: "+filePath+". EXITING...", e); dataProvider.close(); return VALIDATION_ERR_READ; } // read the header try { dataProvider.getRunHeader(); } catch (DataProviderException e) { log.error("ERROR reading file: "+filePath+". EXITING...", e); dataProvider.close(); return VALIDATION_ERR_HEADER; } // read the scans while (true) { try { if(dataProvider.getNextScan() == null) break; } catch (DataProviderException e) { log.error("ERROR reading file: "+filePath+". EXITING...", e); dataProvider.close(); return VALIDATION_ERR_SCAN; } } dataProvider.close(); return VALID; } private String getSha1Sum(String filePath) { try { return Sha1SumCalculator.instance().sha1SumFor(new File(filePath)); } catch (IOException e) { log.error(e.getMessage(), e); return null; } catch (NoSuchAlgorithmException e) { log.error(e.getMessage(), e); return null; } } }
apache-2.0
bennetelli/activemq-artemis
artemis-server/src/main/java/org/apache/activemq/artemis/core/config/Configuration.java
37644
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.activemq.artemis.core.config; import java.io.File; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.activemq.artemis.api.core.BroadcastGroupConfiguration; import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.core.server.SecuritySettingPlugin; import org.apache.activemq.artemis.core.server.group.impl.GroupingHandlerConfiguration; import org.apache.activemq.artemis.core.server.plugin.ActiveMQServerPlugin; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.core.settings.impl.ResourceLimitSettings; /** * A Configuration is used to configure ActiveMQ Artemis servers. */ public interface Configuration { /** * To be used on dependency management on the application server */ String getName(); /** * To be used on dependency management on the application server */ Configuration setName(String name); /** * We use Bean-utils to pass in System.properties that start with {@link #setSystemPropertyPrefix(String)}. * The default should be 'brokerconfig.' (Including the "."). * For example if you want to set clustered through a system property you must do: * * -Dbrokerconfig.clustered=true * * The prefix is configured here. * @param systemPropertyPrefix * @return */ Configuration setSystemPropertyPrefix(String systemPropertyPrefix); /** * See doc at {@link #setSystemPropertyPrefix(String)}. * @return */ String getSystemPropertyPrefix(); Configuration parseSystemProperties() throws Exception; Configuration parseSystemProperties(Properties properties) throws Exception; /** * Returns whether this server is clustered. <br> * {@code true} if {@link #getClusterConfigurations()} is not empty. */ boolean isClustered(); /** * Returns whether delivery count is persisted before messages are delivered to the consumers. <br> * Default value is * {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY} */ boolean isPersistDeliveryCountBeforeDelivery(); /** * Sets whether delivery count is persisted before messages are delivered to consumers. */ Configuration setPersistDeliveryCountBeforeDelivery(boolean persistDeliveryCountBeforeDelivery); /** * Returns whether this server is using persistence and store data. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PERSISTENCE_ENABLED}. */ boolean isPersistenceEnabled(); /** * Sets whether this server is using persistence and store data. */ Configuration setPersistenceEnabled(boolean enable); /** * Should use fdatasync on journal files. * * @see <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html">fdatasync</a> * * @return a boolean */ boolean isJournalDatasync(); /** * documented at {@link #isJournalDatasync()} ()} * * @param enable * @return this */ Configuration setJournalDatasync(boolean enable); /** * @return usernames mapped to ResourceLimitSettings */ Map<String, ResourceLimitSettings> getResourceLimitSettings(); /** * @param resourceLimitSettings usernames mapped to ResourceLimitSettings */ Configuration setResourceLimitSettings(Map<String, ResourceLimitSettings> resourceLimitSettings); /** * @param resourceLimitSettings usernames mapped to ResourceLimitSettings */ Configuration addResourceLimitSettings(ResourceLimitSettings resourceLimitSettings); /** * Returns the period (in milliseconds) to scan configuration files used by deployment. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_FILE_DEPLOYER_SCAN_PERIOD}. */ long getFileDeployerScanPeriod(); /** * Sets the period to scan configuration files used by deployment. */ Configuration setFileDeployerScanPeriod(long period); /** * Returns the maximum number of threads in the thread pool of this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_THREAD_POOL_MAX_SIZE}. */ int getThreadPoolMaxSize(); /** * Sets the maximum number of threads in the thread pool of this server. */ Configuration setThreadPoolMaxSize(int maxSize); /** * Returns the maximum number of threads in the <em>scheduled</em> thread pool of this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE}. */ int getScheduledThreadPoolMaxSize(); /** * Sets the maximum number of threads in the <em>scheduled</em> thread pool of this server. */ Configuration setScheduledThreadPoolMaxSize(int maxSize); /** * Returns the interval time (in milliseconds) to invalidate security credentials. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SECURITY_INVALIDATION_INTERVAL}. */ long getSecurityInvalidationInterval(); /** * Sets the interval time (in milliseconds) to invalidate security credentials. */ Configuration setSecurityInvalidationInterval(long interval); /** * Returns whether security is enabled for this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SECURITY_ENABLED}. */ boolean isSecurityEnabled(); /** * Sets whether security is enabled for this server. */ Configuration setSecurityEnabled(boolean enabled); /** * Returns whether graceful shutdown is enabled for this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SECURITY_ENABLED}. */ boolean isGracefulShutdownEnabled(); /** * Sets whether security is enabled for this server. */ Configuration setGracefulShutdownEnabled(boolean enabled); /** * Returns the graceful shutdown timeout for this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT}. */ long getGracefulShutdownTimeout(); /** * Sets the graceful shutdown timeout */ Configuration setGracefulShutdownTimeout(long timeout); /** * Returns whether this server is manageable using JMX or not. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JMX_MANAGEMENT_ENABLED}. */ boolean isJMXManagementEnabled(); /** * Sets whether this server is manageable using JMX or not. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JMX_MANAGEMENT_ENABLED}. */ Configuration setJMXManagementEnabled(boolean enabled); /** * Returns the domain used by JMX MBeans (provided JMX management is enabled). <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JMX_DOMAIN}. */ String getJMXDomain(); /** * Sets the domain used by JMX MBeans (provided JMX management is enabled). * <p> * Changing this JMX domain is required if multiple ActiveMQ Artemis servers are run inside * the same JVM and all servers are using the same MBeanServer. */ Configuration setJMXDomain(String domain); /** * whether or not to use the broker name in the JMX tree */ boolean isJMXUseBrokerName(); /** * whether or not to use the broker name in the JMX tree */ ConfigurationImpl setJMXUseBrokerName(boolean jmxUseBrokerName); /** * Returns the list of interceptors classes used by this server for incoming messages (i.e. those being delivered to * the server from clients). */ List<String> getIncomingInterceptorClassNames(); /** * Returns the list of interceptors classes used by this server for outgoing messages (i.e. those being delivered to * clients from the server). */ List<String> getOutgoingInterceptorClassNames(); /** * Sets the list of interceptors classes used by this server for incoming messages (i.e. those being delivered to * the server from clients). * <br> * Classes must implement {@link org.apache.activemq.artemis.api.core.Interceptor}. */ Configuration setIncomingInterceptorClassNames(List<String> interceptors); /** * Sets the list of interceptors classes used by this server for outgoing messages (i.e. those being delivered to * clients from the server). * <br> * Classes must implement {@link org.apache.activemq.artemis.api.core.Interceptor}. */ Configuration setOutgoingInterceptorClassNames(List<String> interceptors); /** * Returns the connection time to live. <br> * This value overrides the connection time to live <em>sent by the client</em>. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CONNECTION_TTL_OVERRIDE}. */ long getConnectionTTLOverride(); /** * Sets the connection time to live. */ Configuration setConnectionTTLOverride(long ttl); /** * Returns whether code coming from connection is executed asynchronously or not. <br> * Default value is * {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_ASYNC_CONNECTION_EXECUTION_ENABLED}. */ boolean isAsyncConnectionExecutionEnabled(); /** * Sets whether code coming from connection is executed asynchronously or not. */ Configuration setEnabledAsyncConnectionExecution(boolean enabled); /** * Returns the acceptors configured for this server. */ Set<TransportConfiguration> getAcceptorConfigurations(); /** * Sets the acceptors configured for this server. */ Configuration setAcceptorConfigurations(Set<TransportConfiguration> infos); Configuration addAcceptorConfiguration(TransportConfiguration infos); /** * Add an acceptor to the config * * @param name the name of the acceptor * @param uri the URI of the acceptor * @return this * @throws Exception in case of Parsing errors on the URI */ Configuration addAcceptorConfiguration(String name, String uri) throws Exception; Configuration clearAcceptorConfigurations(); /** * Returns the connectors configured for this server. */ Map<String, TransportConfiguration> getConnectorConfigurations(); /** * Sets the connectors configured for this server. */ Configuration setConnectorConfigurations(Map<String, TransportConfiguration> infos); Configuration addConnectorConfiguration(String key, TransportConfiguration info); Configuration addConnectorConfiguration(String name, String uri) throws Exception; Configuration clearConnectorConfigurations(); /** * Returns the broadcast groups configured for this server. */ List<BroadcastGroupConfiguration> getBroadcastGroupConfigurations(); /** * Sets the broadcast groups configured for this server. */ Configuration setBroadcastGroupConfigurations(List<BroadcastGroupConfiguration> configs); Configuration addBroadcastGroupConfiguration(BroadcastGroupConfiguration config); /** * Returns the discovery groups configured for this server. */ Map<String, DiscoveryGroupConfiguration> getDiscoveryGroupConfigurations(); /** * Sets the discovery groups configured for this server. */ Configuration setDiscoveryGroupConfigurations(Map<String, DiscoveryGroupConfiguration> configs); Configuration addDiscoveryGroupConfiguration(String key, DiscoveryGroupConfiguration discoveryGroupConfiguration); /** * Returns the grouping handler configured for this server. */ GroupingHandlerConfiguration getGroupingHandlerConfiguration(); /** * Sets the grouping handler configured for this server. */ Configuration setGroupingHandlerConfiguration(GroupingHandlerConfiguration groupingHandlerConfiguration); /** * Returns the bridges configured for this server. */ List<BridgeConfiguration> getBridgeConfigurations(); /** * Sets the bridges configured for this server. */ Configuration setBridgeConfigurations(List<BridgeConfiguration> configs); /** * Returns the diverts configured for this server. */ List<DivertConfiguration> getDivertConfigurations(); /** * Sets the diverts configured for this server. */ Configuration setDivertConfigurations(List<DivertConfiguration> configs); Configuration addDivertConfiguration(DivertConfiguration config); /** * Returns the cluster connections configured for this server. * <p> * Modifying the returned list will modify the list of {@link ClusterConnectionConfiguration} * used by this configuration. */ List<ClusterConnectionConfiguration> getClusterConfigurations(); /** * Sets the cluster connections configured for this server. */ Configuration setClusterConfigurations(List<ClusterConnectionConfiguration> configs); Configuration addClusterConfiguration(ClusterConnectionConfiguration config); ClusterConnectionConfiguration addClusterConfiguration(String name, String uri) throws Exception; Configuration clearClusterConfigurations(); /** * Returns the queues configured for this server. */ List<CoreQueueConfiguration> getQueueConfigurations(); /** * Sets the queues configured for this server. */ Configuration setQueueConfigurations(List<CoreQueueConfiguration> configs); Configuration addQueueConfiguration(CoreQueueConfiguration config); /** * Returns the addresses configured for this server. */ List<CoreAddressConfiguration> getAddressConfigurations(); /** * Sets the addresses configured for this server. */ Configuration setAddressConfigurations(List<CoreAddressConfiguration> configs); /** * Adds an addresses configuration */ Configuration addAddressConfiguration(CoreAddressConfiguration config); /** * Returns the management address of this server. <br> * Clients can send management messages to this address to manage this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MANAGEMENT_ADDRESS}. */ SimpleString getManagementAddress(); /** * Sets the management address of this server. */ Configuration setManagementAddress(SimpleString address); /** * Returns the management notification address of this server. <br> * Clients can bind queues to this address to receive management notifications emitted by this * server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MANAGEMENT_NOTIFICATION_ADDRESS}. */ SimpleString getManagementNotificationAddress(); /** * Sets the management notification address of this server. */ Configuration setManagementNotificationAddress(SimpleString address); /** * Returns the cluster user for this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CLUSTER_USER}. */ String getClusterUser(); /** * Sets the cluster user for this server. */ Configuration setClusterUser(String user); /** * Returns the cluster password for this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CLUSTER_PASSWORD}. */ String getClusterPassword(); /** * Sets the cluster password for this server. */ Configuration setClusterPassword(String password); /** * Returns the size of the cache for pre-creating message IDs. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_ID_CACHE_SIZE}. */ int getIDCacheSize(); /** * Sets the size of the cache for pre-creating message IDs. */ Configuration setIDCacheSize(int idCacheSize); /** * Returns whether message ID cache is persisted. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PERSIST_ID_CACHE}. */ boolean isPersistIDCache(); /** * Sets whether message ID cache is persisted. */ Configuration setPersistIDCache(boolean persist); // Journal related attributes ------------------------------------------------------------ /** * Returns the file system directory used to store bindings. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_BINDINGS_DIRECTORY}. */ String getBindingsDirectory(); /** * The binding location related to artemis.instance. */ File getBindingsLocation(); /** * Sets the file system directory used to store bindings. */ Configuration setBindingsDirectory(String dir); /** * The max number of concurrent reads allowed on paging. * <p> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MAX_CONCURRENT_PAGE_IO}. */ int getPageMaxConcurrentIO(); /** * The max number of concurrent reads allowed on paging. * <p> * Default = 5 */ Configuration setPageMaxConcurrentIO(int maxIO); /** * Returns the file system directory used to store journal log. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_DIR}. */ String getJournalDirectory(); /** * The location of the journal related to artemis.instance. * * @return */ File getJournalLocation(); /** * Sets the file system directory used to store journal log. */ Configuration setJournalDirectory(String dir); /** * Returns the type of journal used by this server ({@code NIO}, {@code ASYNCIO} or {@code MAPPED}). * <br> * Default value is ASYNCIO. */ JournalType getJournalType(); /** * Sets the type of journal used by this server (either {@code NIO} or {@code ASYNCIO}). */ Configuration setJournalType(JournalType type); /** * Returns whether the journal is synchronized when receiving transactional data. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_SYNC_TRANSACTIONAL}. */ boolean isJournalSyncTransactional(); /** * Sets whether the journal is synchronized when receiving transactional data. */ Configuration setJournalSyncTransactional(boolean sync); /** * Returns whether the journal is synchronized when receiving non-transactional data. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_SYNC_NON_TRANSACTIONAL}. */ boolean isJournalSyncNonTransactional(); /** * Sets whether the journal is synchronized when receiving non-transactional data. */ Configuration setJournalSyncNonTransactional(boolean sync); /** * Returns the size (in bytes) of each journal files. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_FILE_SIZE}. */ int getJournalFileSize(); /** * Sets the size (in bytes) of each journal files. */ Configuration setJournalFileSize(int size); /** * Returns the minimal number of journal files before compacting. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_COMPACT_MIN_FILES}. */ int getJournalCompactMinFiles(); /** * Sets the minimal number of journal files before compacting. */ Configuration setJournalCompactMinFiles(int minFiles); /** * Number of files that would be acceptable to keep on a pool. Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_POOL_FILES}. */ int getJournalPoolFiles(); /** * Number of files that would be acceptable to keep on a pool. Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_POOL_FILES}. */ Configuration setJournalPoolFiles(int poolSize); /** * Returns the percentage of live data before compacting the journal. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_COMPACT_PERCENTAGE}. */ int getJournalCompactPercentage(); /** * Sets the percentage of live data before compacting the journal. */ Configuration setJournalCompactPercentage(int percentage); /** * Returns the number of journal files to pre-create. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_MIN_FILES}. */ int getJournalMinFiles(); /** * Sets the number of journal files to pre-create. */ Configuration setJournalMinFiles(int files); // AIO and NIO need different values for these params /** * Returns the maximum number of write requests that can be in the AIO queue at any given time. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_MAX_IO_AIO}. */ int getJournalMaxIO_AIO(); /** * Sets the maximum number of write requests that can be in the AIO queue at any given time. */ Configuration setJournalMaxIO_AIO(int journalMaxIO); /** * Returns the timeout (in nanoseconds) used to flush buffers in the AIO queue. * <br> * Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO}. */ int getJournalBufferTimeout_AIO(); /** * Sets the timeout (in nanoseconds) used to flush buffers in the AIO queue. */ Configuration setJournalBufferTimeout_AIO(int journalBufferTimeout); /** * Returns the buffer size (in bytes) for AIO. * <br> * Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_SIZE_AIO}. */ int getJournalBufferSize_AIO(); /** * Sets the buffer size (in bytes) for AIO. */ Configuration setJournalBufferSize_AIO(int journalBufferSize); /** * Returns the maximum number of write requests for NIO journal. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_MAX_IO_NIO}. */ int getJournalMaxIO_NIO(); /** * Sets the maximum number of write requests for NIO journal. */ Configuration setJournalMaxIO_NIO(int journalMaxIO); /** * Returns the timeout (in nanoseconds) used to flush buffers in the NIO. * <br> * Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO}. */ int getJournalBufferTimeout_NIO(); /** * Sets the timeout (in nanoseconds) used to flush buffers in the NIO. */ Configuration setJournalBufferTimeout_NIO(int journalBufferTimeout); /** * Returns the buffer size (in bytes) for NIO. * <br> * Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_SIZE_NIO}. */ int getJournalBufferSize_NIO(); /** * Sets the buffer size (in bytes) for NIO. */ Configuration setJournalBufferSize_NIO(int journalBufferSize); /** * Returns whether the bindings directory is created on this server startup. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CREATE_BINDINGS_DIR}. */ boolean isCreateBindingsDir(); /** * Sets whether the bindings directory is created on this server startup. */ Configuration setCreateBindingsDir(boolean create); /** * Returns whether the journal directory is created on this server startup. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CREATE_JOURNAL_DIR}. */ boolean isCreateJournalDir(); /** * Sets whether the journal directory is created on this server startup. */ Configuration setCreateJournalDir(boolean create); // Undocumented attributes boolean isLogJournalWriteRate(); Configuration setLogJournalWriteRate(boolean rate); long getServerDumpInterval(); Configuration setServerDumpInterval(long interval); int getMemoryWarningThreshold(); Configuration setMemoryWarningThreshold(int memoryWarningThreshold); long getMemoryMeasureInterval(); Configuration setMemoryMeasureInterval(long memoryMeasureInterval); // Paging Properties -------------------------------------------------------------------- /** * Returns the file system directory used to store paging files. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PAGING_DIR}. */ String getPagingDirectory(); /** * Sets the file system directory used to store paging files. */ Configuration setPagingDirectory(String dir); /** * The paging location related to artemis.instance */ File getPagingLocation(); // Large Messages Properties ------------------------------------------------------------ /** * Returns the file system directory used to store large messages. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_LARGE_MESSAGES_DIR}. */ String getLargeMessagesDirectory(); /** * The large message location related to artemis.instance */ File getLargeMessagesLocation(); /** * Sets the file system directory used to store large messages. */ Configuration setLargeMessagesDirectory(String directory); // Other Properties --------------------------------------------------------------------- /** * Returns whether wildcard routing is supported by this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_WILDCARD_ROUTING_ENABLED}. */ boolean isWildcardRoutingEnabled(); /** * Sets whether wildcard routing is supported by this server. */ Configuration setWildcardRoutingEnabled(boolean enabled); WildcardConfiguration getWildcardConfiguration(); Configuration setWildCardConfiguration(WildcardConfiguration wildcardConfiguration); /** * Returns the timeout (in milliseconds) after which transactions is removed from the resource * manager after it was created. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_TRANSACTION_TIMEOUT}. */ long getTransactionTimeout(); /** * Sets the timeout (in milliseconds) after which transactions is removed * from the resource manager after it was created. */ Configuration setTransactionTimeout(long timeout); /** * Returns whether message counter is enabled for this server. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_COUNTER_ENABLED}. */ boolean isMessageCounterEnabled(); /** * Sets whether message counter is enabled for this server. */ Configuration setMessageCounterEnabled(boolean enabled); /** * Returns the sample period (in milliseconds) to take message counter snapshot. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_COUNTER_SAMPLE_PERIOD}. */ long getMessageCounterSamplePeriod(); /** * Sets the sample period to take message counter snapshot. * * @param period value must be greater than 1000ms */ Configuration setMessageCounterSamplePeriod(long period); /** * Returns the maximum number of days kept in memory for message counter. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_COUNTER_MAX_DAY_HISTORY}. */ int getMessageCounterMaxDayHistory(); /** * Sets the maximum number of days kept in memory for message counter. * * @param maxDayHistory value must be greater than 0 */ Configuration setMessageCounterMaxDayHistory(int maxDayHistory); /** * Returns the frequency (in milliseconds) to scan transactions to detect which transactions have * timed out. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_TRANSACTION_TIMEOUT_SCAN_PERIOD}. */ long getTransactionTimeoutScanPeriod(); /** * Sets the frequency (in milliseconds) to scan transactions to detect which transactions * have timed out. */ Configuration setTransactionTimeoutScanPeriod(long period); /** * Returns the frequency (in milliseconds) to scan messages to detect which messages have * expired. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_EXPIRY_SCAN_PERIOD}. */ long getMessageExpiryScanPeriod(); /** * Sets the frequency (in milliseconds) to scan messages to detect which messages * have expired. */ Configuration setMessageExpiryScanPeriod(long messageExpiryScanPeriod); /** * Returns the priority of the thread used to scan message expiration. <br> * Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_EXPIRY_THREAD_PRIORITY}. */ int getMessageExpiryThreadPriority(); /** * Sets the priority of the thread used to scan message expiration. */ Configuration setMessageExpiryThreadPriority(int messageExpiryThreadPriority); /** * @return A list of AddressSettings per matching to be deployed to the address settings repository */ Map<String, AddressSettings> getAddressesSettings(); /** * @param addressesSettings list of AddressSettings per matching to be deployed to the address * settings repository */ Configuration setAddressesSettings(Map<String, AddressSettings> addressesSettings); Configuration addAddressesSetting(String key, AddressSettings addressesSetting); Configuration clearAddressesSettings(); /** * @param roles a list of roles per matching */ Configuration setSecurityRoles(Map<String, Set<Role>> roles); /** * @return a list of roles per matching */ Map<String, Set<Role>> getSecurityRoles(); Configuration addSecurityRoleNameMapping(String internalRole, Set<String> externalRoles); Map<String, Set<String>> getSecurityRoleNameMappings(); Configuration putSecurityRoles(String match, Set<Role> roles); Configuration setConnectorServiceConfigurations(List<ConnectorServiceConfiguration> configs); Configuration addConnectorServiceConfiguration(ConnectorServiceConfiguration config); Configuration setSecuritySettingPlugins(List<SecuritySettingPlugin> plugins); Configuration addSecuritySettingPlugin(SecuritySettingPlugin plugin); /** * @return list of {@link ConnectorServiceConfiguration} */ List<ConnectorServiceConfiguration> getConnectorServiceConfigurations(); List<SecuritySettingPlugin> getSecuritySettingPlugins(); /** * The default password decoder */ Configuration setPasswordCodec(String codec); /** * Gets the default password decoder */ String getPasswordCodec(); /** * Sets if passwords should be masked or not. True means the passwords should be masked. */ Configuration setMaskPassword(boolean maskPassword); /** * If passwords are masked. True means the passwords are masked. */ boolean isMaskPassword(); /* * Whether or not that ActiveMQ Artemis should use all protocols available on the classpath. If false only the core protocol will * be set, any other protocols will need to be set directly on the ActiveMQServer * */ Configuration setResolveProtocols(boolean resolveProtocols); TransportConfiguration[] getTransportConfigurations(String... connectorNames); TransportConfiguration[] getTransportConfigurations(List<String> connectorNames); /* * @see #setResolveProtocols() * @return whether ActiveMQ Artemis should resolve and use any Protocols available on the classpath * Default value is {@link org.apache.activemq.artemis.api.config.org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_RESOLVE_PROTOCOLS}. * */ boolean isResolveProtocols(); Configuration copy() throws Exception; Configuration setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout); long getJournalLockAcquisitionTimeout(); HAPolicyConfiguration getHAPolicyConfiguration(); Configuration setHAPolicyConfiguration(HAPolicyConfiguration haPolicyConfiguration); /** * Set the Artemis instance relative folder for data and stuff. */ void setBrokerInstance(File directory); /** * Set the Artemis instance relative folder for data and stuff. */ File getBrokerInstance(); StoreConfiguration getStoreConfiguration(); Configuration setStoreConfiguration(StoreConfiguration storeConfiguration); boolean isPopulateValidatedUser(); Configuration setPopulateValidatedUser(boolean populateValidatedUser); /** * It will return all the connectors in a toString manner for debug purposes. */ String debugConnectors(); Configuration setConnectionTtlCheckInterval(long connectionTtlCheckInterval); long getConnectionTtlCheckInterval(); URL getConfigurationUrl(); Configuration setConfigurationUrl(URL configurationUrl); long getConfigurationFileRefreshPeriod(); Configuration setConfigurationFileRefreshPeriod(long configurationFileRefreshPeriod); long getGlobalMaxSize(); Configuration setGlobalMaxSize(long globalMaxSize); int getMaxDiskUsage(); Configuration setMaxDiskUsage(int maxDiskUsage); ConfigurationImpl setInternalNamingPrefix(String internalNamingPrefix); Configuration setDiskScanPeriod(int diskScanPeriod); int getDiskScanPeriod(); /** A comma separated list of IPs we could use to validate if the network is UP. * In case of none of these Ips are reached (if configured) the server will be shutdown. */ Configuration setNetworkCheckList(String list); String getNetworkCheckList(); /** A comma separated list of URIs we could use to validate if the network is UP. * In case of none of these Ips are reached (if configured) the server will be shutdown. * The difference from networkCheckList is that we will use HTTP to make this validation. */ Configuration setNetworkCheckURLList(String uris); String getNetworkCheckURLList(); /** The interval on which we will perform network checks. */ Configuration setNetworkCheckPeriod(long period); long getNetworkCheckPeriod(); /** Time in ms for how long we should wait for a ping to finish. */ Configuration setNetworkCheckTimeout(int timeout); int getNetworkCheckTimeout(); /** The NIC name to be used on network checks */ Configuration setNetworCheckNIC(String nic); String getNetworkCheckNIC(); String getNetworkCheckPingCommand(); Configuration setNetworkCheckPingCommand(String command); String getNetworkCheckPing6Command(); Configuration setNetworkCheckPing6Command(String command); String getInternalNamingPrefix(); /** * @param plugins */ void registerBrokerPlugins(List<ActiveMQServerPlugin> plugins); /** * @param plugin */ void registerBrokerPlugin(ActiveMQServerPlugin plugin); /** * @param plugin */ void unRegisterBrokerPlugin(ActiveMQServerPlugin plugin); /** * @return */ List<ActiveMQServerPlugin> getBrokerPlugins(); }
apache-2.0
yekevin/JavaPractise
src/loadBalance/IpMap.java
563
package loadBalance; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.zip.Inflater; /** * Created by Administrator on 2017/1/17. */ public class IpMap { public static Map<String, Integer> serverMap = new HashMap<String, Integer>(); static { serverMap.put("192.168.1.1", 1); serverMap.put("192.168.1.2", 2); serverMap.put("192.168.1.3", 3); } public static Map<String, Integer> copy() { return new HashMap<String, Integer>(serverMap); } }
apache-2.0
jmekstrom/Portfolio
assets/php/contactForm.php
628
<?php // Contact $to = '[email protected]'; $subject = 'Job Opportunity'; if(isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_message'])){ $name = $_POST['c_name']; $from = $_POST['c_email']; $message = $_POST['c_message']; if (mail($to, $subject, $message, $from)) { $result = array( 'message' => 'Thanks for contacting me!', 'sendstatus' => 1 ); echo json_encode($result); } else { $result = array( 'message' => 'Sorry, something is wrong', 'sendstatus' => 1 ); echo json_encode($result); } } ?>
apache-2.0
arrowli/RsyncHadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/target/org/apache/hadoop/mapred/join/class-use/ComposableInputFormat.html
7107
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_27) on Mon Dec 16 23:53:27 EST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface org.apache.hadoop.mapred.join.ComposableInputFormat (hadoop-mapreduce-client-core 2.2.0 API)</title> <meta name="date" content="2013-12-16"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.apache.hadoop.mapred.join.ComposableInputFormat (hadoop-mapreduce-client-core 2.2.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/mapred/join/ComposableInputFormat.html" title="interface in org.apache.hadoop.mapred.join">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/mapred/join//class-useComposableInputFormat.html" target="_top">FRAMES</a></li> <li><a href="ComposableInputFormat.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.apache.hadoop.mapred.join.ComposableInputFormat" class="title">Uses of Interface<br>org.apache.hadoop.mapred.join.ComposableInputFormat</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/hadoop/mapred/join/ComposableInputFormat.html" title="interface in org.apache.hadoop.mapred.join">ComposableInputFormat</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.hadoop.mapred.join">org.apache.hadoop.mapred.join</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.hadoop.mapred.join"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/hadoop/mapred/join/ComposableInputFormat.html" title="interface in org.apache.hadoop.mapred.join">ComposableInputFormat</a> in <a href="../../../../../../org/apache/hadoop/mapred/join/package-summary.html">org.apache.hadoop.mapred.join</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../org/apache/hadoop/mapred/join/package-summary.html">org.apache.hadoop.mapred.join</a> that implement <a href="../../../../../../org/apache/hadoop/mapred/join/ComposableInputFormat.html" title="interface in org.apache.hadoop.mapred.join">ComposableInputFormat</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/mapred/join/CompositeInputFormat.html" title="class in org.apache.hadoop.mapred.join">CompositeInputFormat&lt;K extends WritableComparable&gt;</a></strong></code> <div class="block">An InputFormat capable of performing joins over a set of data sources sorted and partitioned the same way.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/mapred/join/Parser.Node.html" title="class in org.apache.hadoop.mapred.join">Parser.Node</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/mapred/join/ComposableInputFormat.html" title="interface in org.apache.hadoop.mapred.join">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/mapred/join//class-useComposableInputFormat.html" target="_top">FRAMES</a></li> <li><a href="ComposableInputFormat.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2013 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.</small></p> </body> </html>
apache-2.0
scalatest/scalatest-website
public/scaladoc/3.0.1-2.12/org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html
41201
<!DOCTYPE html > <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>ScalaTest 3.0.1 - org.scalatest.fixture.FunSuiteLike.ResultOfIgnoreInvocation</title> <meta name="description" content="ScalaTest 3.0.1 - org.scalatest.fixture.FunSuiteLike.ResultOfIgnoreInvocation" /> <meta name="keywords" content="ScalaTest 3.0.1 org.scalatest.fixture.FunSuiteLike.ResultOfIgnoreInvocation" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js"></script> <script type="text/javascript" src="../../../lib/jquery.panzoom.min.js"></script> <script type="text/javascript" src="../../../lib/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="../../../lib/index.js"></script> <script type="text/javascript" src="../../../index.js"></script> <script type="text/javascript" src="../../../lib/scheduler.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> /* this variable can be used by the JS to determine the path to the root document */ var toRoot = '../../../'; </script> </head> <body> <div id="search"> <span id="doc-title">ScalaTest 3.0.1<span id="doc-version"></span></span> <span class="close-results"><span class="left">&lt;</span> Back</span> <div id="textfilter"> <span class="input"> <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" /> <i class="clear material-icons"></i> <i id="search-icon" class="material-icons"></i> </span> </div> </div> <div id="search-results"> <div id="search-progress"> <div id="progress-fill"></div> </div> <div id="results-content"> <div id="entity-results"></div> <div id="member-results"></div> </div> </div> <div id="content-scroll-container" style="-webkit-overflow-scrolling: touch;"> <div id="content-container" style="-webkit-overflow-scrolling: touch;"> <div id="subpackage-spacer"> <div id="packages"> <h1>Packages</h1> <ul> <li name="_root_.root" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="_root_"></a><a id="root:_root_"></a> <span class="permalink"> <a href="index.html#_root_" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="" href="../../../index.html"> <span class="name">root</span> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div> </li><li name="_root_.org" visbl="pub" class="indented1 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="org"></a><a id="org:org"></a> <span class="permalink"> <a href="index.html#org" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="" href="../../index.html"> <span class="name">org</span> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div> </li><li name="org.scalatest" visbl="pub" class="indented2 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="scalatest"></a><a id="scalatest:scalatest"></a> <span class="permalink"> <a href="../org/index.html#scalatest" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter." href="../index.html"> <span class="name">scalatest</span> </a> </span> <p class="shortcomment cmt">ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.</p><div class="fullcomment"><div class="comment cmt"><p>ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter. </p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../index.html" class="extype" name="org">org</a></dd></dl></div> </li><li name="org.scalatest.fixture" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="fixture"></a><a id="fixture:fixture"></a> <span class="permalink"> <a href="../../org/scalatest/index.html#fixture" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="" href="index.html"> <span class="name">fixture</span> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div> </li><li name="org.scalatest.fixture.FunSuiteLike" visbl="pub" class="indented4 " data-isabs="true" fullComment="yes" group="Ungrouped"> <a id="FunSuiteLikeextendsTestSuitewithTestRegistrationwithInformingwithNotifyingwithAlertingwithDocumenting"></a><a id="FunSuiteLike:FunSuiteLike"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/index.html#FunSuiteLikeextendsTestSuitewithTestRegistrationwithInformingwithNotifyingwithAlertingwithDocumenting" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">trait</span> </span> <span class="symbol"> <a title="Implementation trait for class HtmlTag(&lt;code&gt;fixture.FunSuite&lt;/code&gt;), which is a sister class to HtmlTag(&lt;code&gt;org.scalatest.FunSuite&lt;/code&gt;) that can pass a fixture object into its tests.HtmlTag(&lt;/code&gt;)HtmlTag(&lt;/code&gt;)" href="FunSuiteLike.html"> <span class="name">FunSuiteLike</span> </a><span class="result"> extends <a href="TestSuite.html" class="extype" name="org.scalatest.fixture.TestSuite">TestSuite</a> with <a href="TestRegistration.html" class="extype" name="org.scalatest.fixture.TestRegistration">TestRegistration</a> with <a href="../Informing.html" class="extype" name="org.scalatest.Informing">Informing</a> with <a href="../Notifying.html" class="extype" name="org.scalatest.Notifying">Notifying</a> with <a href="../Alerting.html" class="extype" name="org.scalatest.Alerting">Alerting</a> with <a href="../Documenting.html" class="extype" name="org.scalatest.Documenting">Documenting</a></span> </span> <p class="shortcomment cmt">Implementation trait for class <code>fixture.FunSuite</code>, which is a sister class to <code>org.scalatest.FunSuite</code> that can pass a fixture object into its tests.</code></code></p><div class="fullcomment"><div class="comment cmt"><p>Implementation trait for class <code>fixture.FunSuite</code>, which is a sister class to <code>org.scalatest.FunSuite</code> that can pass a fixture object into its tests.</p><p><a href="FunSuite.html"><code>fixture.FunSuite</code></a> is a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior of <code>fixture.FunSuite</code> into some other class, you can use this trait instead, because class <code>fixture.FunSuite</code> does nothing more than extend this trait and add a nice <code>toString</code> implementation.</p><p>See the documentation of the class for a <a href="FunSuite.html">detailed overview of <code>fixture.FunSuite</code></a>.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="org.scalatest.fixture">fixture</a></dd></dl></div> </li><li class="current-entities indented4"> <span class="separator"></span> <a class="class" href="../Assertions$AssertionsHelper.html" title="Helper class used by code generated by the HtmlTag(&lt;code&gt;assert&lt;/code&gt;) macro.HtmlTag(&lt;/code&gt;)"></a> <a href="../Assertions$AssertionsHelper.html" title="Helper class used by code generated by the HtmlTag(&lt;code&gt;assert&lt;/code&gt;) macro.HtmlTag(&lt;/code&gt;)"> AssertionsHelper </a> </li><li class="current-entities indented4"> <span class="separator"></span> <a class="class" href="FunSuiteLike$CheckingEqualizer.html" title=""></a> <a href="FunSuiteLike$CheckingEqualizer.html" title=""> CheckingEqualizer </a> </li><li class="current-entities indented4"> <span class="separator"></span> <a class="class" href="FunSuiteLike$Equalizer.html" title=""></a> <a href="FunSuiteLike$Equalizer.html" title=""> Equalizer </a> </li><li class="current-entities indented4"> <span class="separator"></span> <a class="abstract type" href="FunSuiteLike$FixtureParam.html" title="The type of the fixture parameter that can be passed into tests in this suite."></a> <a href="FunSuiteLike$FixtureParam.html" title="The type of the fixture parameter that can be passed into tests in this suite."> FixtureParam </a> </li><li class="current-entities indented4"> <span class="separator"></span> <a class="trait" href="../TestSuite$NoArgTest.html" title="A test function taking no arguments and returning an HtmlTag(&lt;code&gt;Outcome&lt;/code&gt;).HtmlTag(&lt;/code&gt;)"></a> <a href="../TestSuite$NoArgTest.html" title="A test function taking no arguments and returning an HtmlTag(&lt;code&gt;Outcome&lt;/code&gt;).HtmlTag(&lt;/code&gt;)"> NoArgTest </a> </li><li class="current-entities indented4"> <a class="object" href="TestSuite$OneArgTest$.html" title="Companion object for HtmlTag(&lt;code&gt;OneArgTest&lt;/code&gt;) that provides factory method to create new HtmlTag(&lt;code&gt;OneArgTest&lt;/code&gt;) instance by passing in a HtmlTag(&lt;code&gt;OneArgTest&lt;/code&gt;) and a HtmlTag(&lt;code&gt;FixtureParam&lt;/code&gt;) =&gt; HtmlTag(&lt;code&gt;Outcome&lt;/code&gt;) function.HtmlTag(&lt;/code&gt;)HtmlTag(&lt;/code&gt;)HtmlTag(&lt;/code&gt;)HtmlTag(&lt;/code&gt;)HtmlTag(&lt;/code&gt;)"></a> <a class="trait" href="TestSuite$OneArgTest.html" title="A test function taking a fixture parameter and returning an HtmlTag(&lt;code&gt;Outcome&lt;/code&gt;).HtmlTag(&lt;/code&gt;)"></a> <a href="TestSuite$OneArgTest.html" title="A test function taking a fixture parameter and returning an HtmlTag(&lt;code&gt;Outcome&lt;/code&gt;).HtmlTag(&lt;/code&gt;)"> OneArgTest </a> </li><li class="current-entities indented4"> <span class="separator"></span> <a class="class" href="" title=""></a> <a href="" title=""> ResultOfIgnoreInvocation </a> </li><li class="current-entities indented4"> <span class="separator"></span> <a class="class" href="FunSuiteLike$ResultOfTestInvocation.html" title=""></a> <a href="FunSuiteLike$ResultOfTestInvocation.html" title=""> ResultOfTestInvocation </a> </li> </ul> </div> </div> <div id="content"> <body class="class type"> <!-- Top of doc.scalatest.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204546 = window.pid204546 || rnd; var plc204546 = window.plc204546 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <div class="big-circle class">c</div> <p id="owner"><a href="../../index.html" class="extype" name="org">org</a>.<a href="../index.html" class="extype" name="org.scalatest">scalatest</a>.<a href="index.html" class="extype" name="org.scalatest.fixture">fixture</a>.<a href="FunSuiteLike.html" class="extype" name="org.scalatest.fixture.FunSuiteLike">FunSuiteLike</a></p> <h1>ResultOfIgnoreInvocation<span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html" title="Permalink"> <i class="material-icons"></i> </a> </span></h1> <h3><span class="morelinks"></span></h3> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <span class="name">ResultOfIgnoreInvocation</span><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div id="comment" class="fullcommenttop"><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-3.0.1/scalatest//src/main/scala/org/scalatest/fixture/FunSuiteLike.scala" target="_blank">FunSuiteLike.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle"> Linear Supertypes </span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div class="toggle"></div> <div id="memberfilter"> <i class="material-icons arrow"></i> <span class="input"> <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" /> </span> <i class="clear material-icons"></i> </div> <div id="filterby"> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By Inheritance</span></li> </ol> </div> <div class="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalatest.fixture.FunSuiteLike.ResultOfIgnoreInvocation"><span>ResultOfIgnoreInvocation</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div class="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show All</span></li> </ol> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="org.scalatest.fixture.FunSuiteLike.ResultOfIgnoreInvocation#&lt;init&gt;" visbl="pub" class="indented0 " data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(testName:String,testTags:org.scalatest.Tag*):FunSuiteLike.this.ResultOfIgnoreInvocation"></a><a id="&lt;init&gt;:ResultOfIgnoreInvocation"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#&lt;init&gt;(testName:String,testTags:org.scalatest.Tag*):FunSuiteLike.this.ResultOfIgnoreInvocation" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">ResultOfIgnoreInvocation</span><span class="params">(<span name="testName">testName: <span class="extype" name="scala.Predef.String">String</span></span>, <span name="testTags">testTags: <a href="../Tag.html" class="extype" name="org.scalatest.Tag">Tag</a>*</span>)</span> </span> </li></ol> </div> <div class="values members"> <h3>Value Members</h3> <ol> <li name="scala.AnyRef#!=" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a><a id="!=(Any):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#!=(x$1:Any):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html###():Int" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a><a id="==(Any):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#==(x$1:Any):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="org.scalatest.fixture.FunSuiteLike.ResultOfIgnoreInvocation#apply" visbl="pub" class="indented0 " data-isabs="false" fullComment="no" group="Ungrouped"> <a id="apply(testFun:()=&gt;Any)(implicitpos:org.scalactic.source.Position):Unit"></a><a id="apply(()⇒Any)(Position):Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#apply(testFun:()=&gt;Any)(implicitpos:org.scalactic.source.Position):Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">apply</span><span class="params">(<span name="testFun">testFun: () ⇒ <span class="extype" name="scala.Any">Any</span></span>)</span><span class="params">(<span class="implicit">implicit </span><span name="pos">pos: <span class="extype" name="org.scalactic.source.Position">Position</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </li><li name="org.scalatest.fixture.FunSuiteLike.ResultOfIgnoreInvocation#apply" visbl="pub" class="indented0 " data-isabs="false" fullComment="no" group="Ungrouped"> <a id="apply(testFun:FunSuiteLike.this.FixtureParam=&gt;Any)(implicitpos:org.scalactic.source.Position):Unit"></a><a id="apply((FunSuiteLike.FixtureParam)⇒Any)(Position):Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#apply(testFun:FunSuiteLike.this.FixtureParam=&gt;Any)(implicitpos:org.scalactic.source.Position):Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">apply</span><span class="params">(<span name="testFun">testFun: (<a href="FunSuiteLike.html#FixtureParam" class="extmbr" name="org.scalatest.fixture.FunSuiteLike.FixtureParam">FunSuiteLike.FixtureParam</a>) ⇒ <span class="extype" name="scala.Any">Any</span></span>)</span><span class="params">(<span class="implicit">implicit </span><span name="pos">pos: <span class="extype" name="org.scalactic.source.Position">Position</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </li><li name="scala.Any#asInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#asInstanceOf[T0]:T0" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a><a id="clone():AnyRef"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#clone():Object" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a><a id="eq(AnyRef):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#eq(x$1:AnyRef):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a><a id="equals(Any):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#equals(x$1:Any):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#finalize():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#getClass():Class[_]" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#hashCode():Int" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#isInstanceOf[T0]:Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a><a id="ne(AnyRef):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#ne(x$1:AnyRef):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#notify():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#notifyAll():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a><a id="synchronized[T0](⇒T0):T0"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#synchronized[T0](x$1:=&gt;T0):T0" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#toString():String" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#wait():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a><a id="wait(Long,Int):Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#wait(x$1:Long,x$2:Int):Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a><a id="wait(Long):Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/fixture/FunSuiteLike$ResultOfIgnoreInvocation.html#wait(x$1:Long):Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li> </ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </div> </div> </div> </body> </html>
apache-2.0
gaowanyao/trading
App/Home/View/Public/header.html
11137
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" > <meta name="renderer" content="webkit"> <meta name="keywords" content=""/> <meta name="description" content=""/> <meta property="wb:webmaster" content="8af72a3a7309f0ee"> <title><notempty name='article'>{$article.title}-</notempty>{$config.title|default="虚拟币交易网站"}</title> <link rel="Shortcut Icon" type="image/x-icon" href="/favicon.ico"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/css/base.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/css/layout.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/css/subpage.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/css/user.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/css/coin.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/css/zcpc.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/iconfont/demo.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/iconfont/iconfont.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/Home/css/jb_style.css"> <script src="__PUBLIC__/Home/js/hm.js"> </script><script type="text/javascript" src="__PUBLIC__/Home/js/jquery-1.js"></script> <script type="text/javascript" src="__PUBLIC__/Home/js/downList.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.2.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery-2.1.1.min.js"></script> <script src="__PUBLIC__/js/bootstrap.min.js?v=3.4.0"></script> <script type="text/javascript" src="__PUBLIC__/js/layer/layer.js"></script> <script src="__PUBLIC__/js/jquery.validate.min.js"></script> <script src="__PUBLIC__/js/messages_zh.min.js"></script> <script src="__PUBLIC__/js/base.js"></script> </head> <body> <!--<div class="clearfix phone_top" id="phone_top_div" style="display:none;"> <div class="left"> <p class="left phone_logo"><img src="/images/phone_logo01.png"/></p> <p class="left phone_title">第一数字货币众筹交易平台</p> </div> <a href="javascript:hidephone();" class="phone_x">X</a> </div>--> <!--top start--> <div style="background:#f9f9f9; height:30px;"> <div style="width:1000px; margin:0 auto;"> <ul class="qqkf left" style="line-height:30px; color:#999;"> <li class="phone" style="cursor: pointer;" ><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin={$config['qq1']}&site=qq&menu=yes" class="qq_qq"></a>{$config.qq1|default="暂无"}</li> <li class="phone400">{$config.tel|default="暂无"}</li> <li class="phone_email"><a href="mailto:{$config['email']}">{$config.email|default="暂无"}</a></li> <li>&nbsp;&nbsp;工作日:9-19时 节假日:9-18时</li> </ul> <if condition="!empty($_SESSION['USER_KEY_ID'])"> <div class="person right"> <a class="left myhome" href="{:U('ModifyMember/modify')}" style=" height:30px; line-height:30px; margin-right:5px;"> {$username} </a> <div style="display: none;" class="mywallet_list"><div class="clear"><ul class="balance_list"><h4>可用余额</h4><li><a href="javascript:void(0)"><em style="margin-top: 5px;" class="deal_list_pic_cny"></em><strong>人民币:</strong><span>{$member.rmb}</span></a></li></ul><ul class="freeze_list"><h4>委托冻结</h4><li><a href="javascript:void(0)"><em style="margin-top: 5px;" class="deal_list_pic_cny"></em><strong>人民币:</strong><span>{$member.forzen_rmb}</span></a></li></ul></div><div class="mywallet_btn_box"><a href="{:U('User/pay')}">充值</a><a href="{:U('User/draw')}">提现</a><a href="{:U('User/index')}">转入</a><a href="{:U('User/index')}">转出</a><a href="{:U('Entrust/manage')}">委托管理</a><a href="{:U('Trade/myDeal')}">成交查询</a></div></div> <span class="left" style="height:30px; line-height:30px; color:#999; margin-right:5px;">(UID: {$Think.session.USER_KEY_ID} )</span> <a class="left" href="{:U('Login/loginOut')}" style="height:30px; line-height:30px; margin:0 5px;">退出</a> <div id="my" class="account left" href="javascript:void(0)" style="z-index:9997; margin-right:5px;"> <a class="user_me" href="{:U('User/index')}">我的账户</a> <ul class="accountList" style="padding: 6px 0px; background: rgb(85, 85, 85) none repeat scroll 0% 0%; border-radius: 5px 0px 5px 5px; display: none;"> <!--<li class="accountico no"></li>--> <li><a href="{:U('User/index')}">我的资产</a></li> <li><a href="{:U('Entrust/manage')}">我的交易</a></li> <li><a href="{:U('User/zhongchou')}">我的众筹</a></li> <li style="border-top:1px solid #666;"><a href="{:U('User/pay')}">人民币充值</a></li> <li><a href="{:U('User/draw')}">人民币提现</a></li> <li style="border-bottom:1px solid #444;"><a href="{:U('User/index')}">充币提币</a></li> <li><a href="{:U('User/updatePassword')}">修改密码</a></li> <li><a href="{:U('User/sysMassage')}">系统消息<if condition="$newMessageCount"><span class="messagenum">{$newMessageCount}</span></if></a></li> </ul> </div> </div> </if> </if> <if condition="empty($_SESSION['USER_KEY_ID'])"> <div class="loginArea right" style=" margin-right:5px;"> <a href="{:U('Login/index')}" style="color:#f60; font-size:14px;">登录</a> <span class="sep">&nbsp;|&nbsp;</span> <a href="{:U('Reg/reg')}" style="color:#f60; font-size:14px;">注册</a> </div> </if> </div> </div> <div class="top"> <div class="wapper clearfix"> <h1 class="left"><a href="{:U('Index/index')}"><img style=" width:280px; height:70px;" src="{$config.logo}" alt="虚拟币" title="虚拟币"></a></h1> <ul class="nav right" style="z-index:9995;"> <li><a href="{:U('Index/index')}">首页</a></li> <li><a href="{:U('Orders/currency_trade')}">交易大厅</a></li> <li><a href="{:U('Zhongchou/index')}">认购中心<!--hr--></a></li> <li><a href="{:U('Safe/index')}">用户中心</a></li> <li><a href="{:U('Help/index',array('id'=>60))}">帮助中心</a></li> <li><a href="{:U('Art/index',array('ramdon_id'=>'1'))}">最新动态</a></li> <li><a href="{:U('Market/index')}">行情中心</a></li> <li><a href="{:U('Dow/index')}">下载中心</a></li> </ul> </div> </div> <div class="pclxfsbox"> <ul> <li id="opensq"> <i class="pcicon1 iscion6" ></i> <div class="pcicon1box"> <div class="iscionbox" > <p>在线咨询</p> <p>{$config['worktime']|default="暂无"}</p> </div> <i></i> </div> </li> <li> <i class="pcicon1 iscion1"></i> <div class="pcicon1box"> <div class="iscionbox"> <p><img src="{$config['weixin']}" alt="投筹网微信公众号" width="108"></p> <p>{$config.name|default="虚拟网"}微信群</p> </div> <i></i> </div> </li> <li> <i class="pcicon1 iscion2"></i> <div class="pcicon1box"> <div class="iscionbox"> <p>{$config['tel']|default="暂无"}</p> <p>{$config.name|default="虚拟网"}</p> </div> <i></i> </div> </li> <li> <i class="pcicon1 iscion3"><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin={$config['qq1']}&site=qq&menu=yes"></a></i> <div class="pcicon1box"> <div class="iscionbox"> <p>{$config.qq1|default="暂无"}</p> <p>{$config.name|default="虚拟网"}QQ在线客服1</p> </div> <i></i> </div> </li> <li> <i class="pcicon1 iscion3" style="background:url(__PUBLIC__/Home/images/kefu2.png) no-repeat #9b9b9b;background-position:-144px 11px;"><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin={$config['qq2']}&site=qq&menu=yes"></a></i> <div class="pcicon1box"> <div class="iscionbox"> <p>{$config.qq2|default="暂无"}</p> <p>{$config.name|default="虚拟网"}QQ在线客服2</p> </div> <i></i> </div> </li> <li> <i class="pcicon1 iscion3" style="background:url(__PUBLIC__/Home/images/kefu3.png) no-repeat #9b9b9b;background-position:-144px 11px;"><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin={$config['qq3']}&site=qq&menu=yes"></a></i> <div class="pcicon1box"> <div class="iscionbox"> <p>{$config.qq3|default="暂无"}</p> <p>{$config.name|default="虚拟网"}QQ在线客服3</p> </div> <i></i> </div> </li> <li> <i class="pcicon1 iscion4"></i> <div class="pcicon1box"> <div class="iscionbox"> <p>返回顶部</p> </div> <i></i> </div> </li> </ul> </div> <script type="text/javascript"> $(function(){ $(".pcicon1").on("mouseover",function(){ $(this).addClass("lbnora").next(".pcicon1box").css({"width":"148px"}); }).on("mouseout",function(){ $(this).removeClass("lbnora").next(".pcicon1box").css("width","0px"); }); $(".iscion4").on("click",function(){ $("html, body").animate({ scrollTop: 0 }) }); var objWin; $("#opensq").on("click",function(){ var top = window.screen.height/2 - 250; var left = window.screen.width/2 - 390; var target = "http://p.qiao.baidu.com//im/index?siteid=8050707&ucid=18622305"; var cans = 'width=780,height=550,left='+left+',top='+top+',toolbar=no, status=no, menubar=no, resizable=yes, scrollbars=yes' ; if((navigator.userAgent.indexOf('MSIE') >= 0)&&(navigator.userAgent.indexOf('Opera') < 0)){ //objWin = window.open ('','baidubridge',cans) ; if (objWin === undefined || objWin === null || objWin.closed) { objWin = window.open (target,'baidubridge',cans) ; }else { objWin.focus(); } }else{ var win = window.open('','baidubridge',cans ); if (win.location.href == "about:blank") { //窗口不存在 win = window.open(target,'baidubridge',cans); } else { win.focus(); } } return false; }) }) </script> <!--top end--> <script> $(".myhome").hover(function(){ $(".mywallet_list").show(); },function(){ $(".mywallet_list").hover(function(){ $(".mywallet_list").show(); },function(){ $(".mywallet_list").hide(); }); $(".mywallet_list").hide(); }); </script>
apache-2.0
MICommunity/psi-jami
docs/psidev/psi/mi/jami/xml/io/writer/compact/extended/class-use/CompactXmlModelledWriter.html
5305
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_252) on Fri Aug 20 17:47:57 BST 2021 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class psidev.psi.mi.jami.xml.io.writer.compact.extended.CompactXmlModelledWriter (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)</title> <meta name="date" content="2021-08-20"> <link rel="stylesheet" type="text/css" href="../../../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class psidev.psi.mi.jami.xml.io.writer.compact.extended.CompactXmlModelledWriter (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../../../psidev/psi/mi/jami/xml/io/writer/compact/extended/CompactXmlModelledWriter.html" title="class in psidev.psi.mi.jami.xml.io.writer.compact.extended">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../../../index.html?psidev/psi/mi/jami/xml/io/writer/compact/extended/class-use/CompactXmlModelledWriter.html" target="_top">Frames</a></li> <li><a href="CompactXmlModelledWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class psidev.psi.mi.jami.xml.io.writer.compact.extended.CompactXmlModelledWriter" class="title">Uses of Class<br>psidev.psi.mi.jami.xml.io.writer.compact.extended.CompactXmlModelledWriter</h2> </div> <div class="classUseContainer">No usage of psidev.psi.mi.jami.xml.io.writer.compact.extended.CompactXmlModelledWriter</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../../../psidev/psi/mi/jami/xml/io/writer/compact/extended/CompactXmlModelledWriter.html" title="class in psidev.psi.mi.jami.xml.io.writer.compact.extended">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../../../index.html?psidev/psi/mi/jami/xml/io/writer/compact/extended/class-use/CompactXmlModelledWriter.html" target="_top">Frames</a></li> <li><a href="CompactXmlModelledWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </body> </html>
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Indigofera/Indigofera trifoliata/Indigofera trifoliata glandulifera/README.md
233
# Indigofera trifoliata var. glandulifera (Hayata) S.S.Ying VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Indigofera glandulifera Hayata ### Remarks null
apache-2.0
olehmberg/winter
docs/javadoc/de/uni_mannheim/informatik/dws/winter/webtables/features/class-use/HorizontallyStackedFeature.html
5333
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_162) on Tue Oct 02 11:58:29 CEST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class de.uni_mannheim.informatik.dws.winter.webtables.features.HorizontallyStackedFeature (WInte.r 1.3 API)</title> <meta name="date" content="2018-10-02"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class de.uni_mannheim.informatik.dws.winter.webtables.features.HorizontallyStackedFeature (WInte.r 1.3 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/features/HorizontallyStackedFeature.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables.features">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?de/uni_mannheim/informatik/dws/winter/webtables/features/class-use/HorizontallyStackedFeature.html" target="_top">Frames</a></li> <li><a href="HorizontallyStackedFeature.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class de.uni_mannheim.informatik.dws.winter.webtables.features.HorizontallyStackedFeature" class="title">Uses of Class<br>de.uni_mannheim.informatik.dws.winter.webtables.features.HorizontallyStackedFeature</h2> </div> <div class="classUseContainer">No usage of de.uni_mannheim.informatik.dws.winter.webtables.features.HorizontallyStackedFeature</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/features/HorizontallyStackedFeature.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables.features">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?de/uni_mannheim/informatik/dws/winter/webtables/features/class-use/HorizontallyStackedFeature.html" target="_top">Frames</a></li> <li><a href="HorizontallyStackedFeature.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018. All rights reserved.</small></p> </body> </html>
apache-2.0
dthagard/opschef-cookbook-visualstudio
recipes/install.rb
2479
# # Author:: Shawn Neal <[email protected]> # Cookbook Name:: visualstudio # Recipe:: install # # Copyright 2013, Daptiv Solutions, LLC. # # 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. # ::Chef::Recipe.send(:include, Visualstudio::Helper) vs_is_installed = is_vs_installed?() # Ensure the installation ISO url has been set by the user if !node['visualstudio']['source'] raise 'visualstudio source attribute must be set before running this cookbook' end version = 'vs' + node['visualstudio']['version'] edition = node['visualstudio']['edition'] install_url = File.join(node['visualstudio']['source'], node['visualstudio'][edition]['filename']) install_log_file = win_friendly_path( File.join(node['visualstudio']['install_dir'], 'vsinstall.log')) iso_extraction_dir = win_friendly_path(File.join(Chef::Config[:file_cache_path], version)) setup_exe_path = File.join(iso_extraction_dir, node['visualstudio'][edition]['installer_file']) admin_deployment_xml_file = win_friendly_path(File.join(iso_extraction_dir, 'AdminDeployment.xml')) # Extract the ISO image to the tmp dir seven_zip_archive 'extract_vs_iso' do path iso_extraction_dir source install_url overwrite true checksum node['visualstudio'][edition]['checksum'] not_if { vs_is_installed } end # Create installation config file cookbook_file admin_deployment_xml_file do source version + '/AdminDeployment-' + edition + '.xml' action :create not_if { vs_is_installed } end # Install Visual Studio windows_package node['visualstudio'][edition]['package_name'] do source setup_exe_path installer_type :custom options "/Q /norestart /Log \"#{install_log_file}\" /AdminFile \"#{admin_deployment_xml_file}\"" notifies :delete, "directory[#{iso_extraction_dir}]" timeout 3600 # 1hour not_if { vs_is_installed } end # Cleanup extracted ISO files from tmp dir directory iso_extraction_dir do action :nothing recursive true not_if { node['visualstudio']['preserve_extracted_files'] } end
apache-2.0
scaleway/scaleway-cli
docs/commands/dns.md
19302
<!-- DO NOT EDIT: this file is automatically generated using scw-doc-gen --> # Documentation for `scw dns` Manage your DNS zones and records. - [TLS certificate management](#tls-certificate-management) - [Create or return the zone TLS certificate](#create-or-return-the-zone-tls-certificate) - [Delete an TLS certificate](#delete-an-tls-certificate) - [Get the zone TLS certificate if it exists](#get-the-zone-tls-certificate-if-it-exists) - [List all user TLS certificates](#list-all-user-tls-certificates) - [DNS records management](#dns-records-management) - [Add a new DNS record](#add-a-new-dns-record) - [Update DNS zone records](#update-dns-zone-records) - [Clear DNS zone records](#clear-dns-zone-records) - [Delete a DNS record](#delete-a-dns-record) - [List DNS zone records](#list-dns-zone-records) - [List DNS zone nameservers](#list-dns-zone-nameservers) - [Update a DNS record](#update-a-dns-record) - [Update DNS zone nameservers](#update-dns-zone-nameservers) - [Transaction SIGnature key management](#transaction-signature-key-management) - [Delete the DNS zone TSIG Key](#delete-the-dns-zone-tsig-key) - [Get the DNS zone TSIG Key](#get-the-dns-zone-tsig-key) - [DNS zones version management](#dns-zones-version-management) - [Get DNS zone version diff](#get-dns-zone-version-diff) - [List DNS zone versions](#list-dns-zone-versions) - [Restore DNS zone version](#restore-dns-zone-version) - [List DNS zone version records](#list-dns-zone-version-records) - [DNS Zones management](#dns-zones-management) - [Clone a DNS zone](#clone-a-dns-zone) - [Create a DNS zone](#create-a-dns-zone) - [Delete DNS zone](#delete-dns-zone) - [Export raw DNS zone](#export-raw-dns-zone) - [Import raw DNS zone](#import-raw-dns-zone) - [List DNS zones](#list-dns-zones) - [Refresh DNS zone](#refresh-dns-zone) - [Update a DNS zone](#update-a-dns-zone) ## TLS certificate management TLS certificate management. ### Create or return the zone TLS certificate Create or return the zone TLS certificate. **Usage:** ``` scw dns certificate create <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | | | alternative-dns-zones.{index} | | | ### Delete an TLS certificate Delete an TLS certificate. **Usage:** ``` scw dns certificate delete <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | | ### Get the zone TLS certificate if it exists Get the zone TLS certificate if it exists. **Usage:** ``` scw dns certificate get <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | | ### List all user TLS certificates List all user TLS certificates. **Usage:** ``` scw dns certificate list <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | | | project-id | | | ## DNS records management DNS records management. ### Add a new DNS record **Usage:** ``` scw dns record add <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | DNS zone in which to add the record | | data | Required | | | name | | | | priority | | | | ttl | Required<br />Default: `300` | | | type | Required<br />One of: `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR` | | | comment | | | | geo-ip-config.matches.{index}.countries.{index} | | | | geo-ip-config.matches.{index}.continents.{index} | | | | geo-ip-config.matches.{index}.data | | | | geo-ip-config.default | | | | http-service-config.ips.{index} | | | | http-service-config.must-contain | | | | http-service-config.url | | | | http-service-config.user-agent | | | | http-service-config.strategy | One of: `random`, `hashed` | | | weighted-config.weighted-ips.{index}.ip | | | | weighted-config.weighted-ips.{index}.weight | | | | view-config.views.{index}.subnet | | | | view-config.views.{index}.data | | | **Examples:** Add a CNAME ``` scw dns record add my-domain.tld data=www name=www2 type=CNAME ``` Add an IP ``` scw dns record add my-domain.tld data=1.2.3.4 name=vpn type=A ``` ### Update DNS zone records Only available with default NS.<br/> Send a list of actions and records. Action can be: - add: - Add new record - Can be more specific and add a new IP to an existing A record for example - set: - Edit a record - Can be more specific and edit an IP from an existing A record for example - delete: - Delete a record - Can be more specific and delete an IP from an existing A record for example - clear: - Delete all records from a DNS zone All edits will be versioned. **Usage:** ``` scw dns record bulk-update <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone where the DNS zone records will be updated | | changes.{index}.add.records.{index}.data | | | | changes.{index}.add.records.{index}.name | | | | changes.{index}.add.records.{index}.priority | | | | changes.{index}.add.records.{index}.ttl | | | | changes.{index}.add.records.{index}.type | One of: `unknown`, `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR`, `DNAME` | | | changes.{index}.add.records.{index}.comment | | | | changes.{index}.add.records.{index}.geo-ip-config.matches.{index}.countries.{index} | | | | changes.{index}.add.records.{index}.geo-ip-config.matches.{index}.continents.{index} | | | | changes.{index}.add.records.{index}.geo-ip-config.matches.{index}.data | | | | changes.{index}.add.records.{index}.geo-ip-config.default | | | | changes.{index}.add.records.{index}.http-service-config.ips.{index} | | | | changes.{index}.add.records.{index}.http-service-config.must-contain | | | | changes.{index}.add.records.{index}.http-service-config.url | | | | changes.{index}.add.records.{index}.http-service-config.user-agent | | | | changes.{index}.add.records.{index}.http-service-config.strategy | One of: `random`, `hashed`, `all` | | | changes.{index}.add.records.{index}.weighted-config.weighted-ips.{index}.ip | | | | changes.{index}.add.records.{index}.weighted-config.weighted-ips.{index}.weight | | | | changes.{index}.add.records.{index}.view-config.views.{index}.subnet | | | | changes.{index}.add.records.{index}.view-config.views.{index}.data | | | | changes.{index}.add.records.{index}.id | | | | changes.{index}.set.id | | | | changes.{index}.set.id-fields.name | | | | changes.{index}.set.id-fields.type | One of: `unknown`, `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR`, `DNAME` | | | changes.{index}.set.id-fields.data | | | | changes.{index}.set.id-fields.ttl | | | | changes.{index}.set.records.{index}.data | | | | changes.{index}.set.records.{index}.name | | | | changes.{index}.set.records.{index}.priority | | | | changes.{index}.set.records.{index}.ttl | | | | changes.{index}.set.records.{index}.type | One of: `unknown`, `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR`, `DNAME` | | | changes.{index}.set.records.{index}.comment | | | | changes.{index}.set.records.{index}.geo-ip-config.matches.{index}.countries.{index} | | | | changes.{index}.set.records.{index}.geo-ip-config.matches.{index}.continents.{index} | | | | changes.{index}.set.records.{index}.geo-ip-config.matches.{index}.data | | | | changes.{index}.set.records.{index}.geo-ip-config.default | | | | changes.{index}.set.records.{index}.http-service-config.ips.{index} | | | | changes.{index}.set.records.{index}.http-service-config.must-contain | | | | changes.{index}.set.records.{index}.http-service-config.url | | | | changes.{index}.set.records.{index}.http-service-config.user-agent | | | | changes.{index}.set.records.{index}.http-service-config.strategy | One of: `random`, `hashed`, `all` | | | changes.{index}.set.records.{index}.weighted-config.weighted-ips.{index}.ip | | | | changes.{index}.set.records.{index}.weighted-config.weighted-ips.{index}.weight | | | | changes.{index}.set.records.{index}.view-config.views.{index}.subnet | | | | changes.{index}.set.records.{index}.view-config.views.{index}.data | | | | changes.{index}.set.records.{index}.id | | | | changes.{index}.delete.id | | | | changes.{index}.delete.id-fields.name | | | | changes.{index}.delete.id-fields.type | One of: `unknown`, `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR`, `DNAME` | | | changes.{index}.delete.id-fields.data | | | | changes.{index}.delete.id-fields.ttl | | | | return-all-records | | Whether or not to return all the records | | disallow-new-zone-creation | | Forbid the creation of the target zone if not existing (default action is yes) | | serial | | Don't use the autoincremenent serial but the provided one (0 to keep the same) | ### Clear DNS zone records Only available with default NS.<br/> Delete all the records from a DNS zone. All edits will be versioned. **Usage:** ``` scw dns record clear <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone to clear | ### Delete a DNS record **Usage:** ``` scw dns record delete <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | DNS zone in which to delete the record | | data | | | | name | | | | ttl | | | | type | Required<br />One of: `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR` | | **Examples:** Delete a CNAME ``` scw dns record delete my-domain.tld name=www type=CNAME ``` Delete a single IP from a record with more than one ``` scw dns record delete my-domain.tld data=1.2.3.4 name=vpn type=A ``` ### List DNS zone records Returns a list of DNS records of a DNS zone with default NS. You can filter the records by type and name. **Usage:** ``` scw dns record list <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | project-id | | The project ID on which to filter the returned DNS zone records | | order-by | One of: `name_asc`, `name_desc` | The sort order of the returned DNS zone records | | dns-zone | Required | The DNS zone on which to filter the returned DNS zone records | | name | | The name on which to filter the returned DNS zone records | | type | One of: `unknown`, `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR`, `DNAME` | The record type on which to filter the returned DNS zone records | | id | | The record ID on which to filter the returned DNS zone records | ### List DNS zone nameservers Returns a list of Nameservers and their optional glue records for a DNS zone. **Usage:** ``` scw dns record list-nameservers <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | project-id | | The project ID on which to filter the returned DNS zone nameservers | | dns-zone | Required | The DNS zone on which to filter the returned DNS zone nameservers | ### Update a DNS record This command will replace all the data for this record with the given values. **Usage:** ``` scw dns record set <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | DNS zone in which to set the record | | values.{index} | Required | A list of values for replacing the record data. (multiple values cannot be used for all type) | | name | Required | | | priority | | | | ttl | Required<br />Default: `300` | | | type | Required<br />One of: `A`, `AAAA`, `CNAME`, `TXT`, `SRV`, `TLSA`, `MX`, `NS`, `PTR`, `CAA`, `ALIAS`, `LOC`, `SSHFP`, `HINFO`, `RP`, `URI`, `DS`, `NAPTR` | | | comment | | | | geo-ip-config.matches.{index}.countries.{index} | | | | geo-ip-config.matches.{index}.continents.{index} | | | | geo-ip-config.matches.{index}.data | | | | geo-ip-config.default | | | | http-service-config.ips.{index} | | | | http-service-config.must-contain | | | | http-service-config.url | | | | http-service-config.user-agent | | | | http-service-config.strategy | One of: `random`, `hashed` | | | weighted-config.weighted-ips.{index}.ip | | | | weighted-config.weighted-ips.{index}.weight | | | | view-config.views.{index}.subnet | | | | view-config.views.{index}.data | | | **Examples:** Add or replace a CNAME ``` scw dns record set my-domain.tld values.0=www name=www2 type=CNAME ``` Add or replace a list of IP ``` scw dns record set my-domain.tld values.0=1.2.3.4 values.1=1.2.3.5 name=vpn type=A ``` ### Update DNS zone nameservers Update DNS zone nameservers and set optional glue records. **Usage:** ``` scw dns record update-nameservers <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone where the DNS zone nameservers will be updated | | ns.{index}.name | | | | ns.{index}.ip.{index} | | | ## Transaction SIGnature key management Transaction SIGnature key management. ### Delete the DNS zone TSIG Key Delete the DNS zone TSIG Key. **Usage:** ``` scw dns tsig-key delete <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | | ### Get the DNS zone TSIG Key Get the DNS zone TSIG Key to allow AXFR request. **Usage:** ``` scw dns tsig-key get <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | | ## DNS zones version management DNS zones version management. ### Get DNS zone version diff Get all differences from a previous DNS zone version. **Usage:** ``` scw dns version diff <dns-zone-version-id ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone-version-id | Required | | ### List DNS zone versions Get a list of DNS zone versions.<br/> The maximum version count is 100.<br/> If the count reaches this limit, the oldest version will be deleted after each new modification. **Usage:** ``` scw dns version list <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | | ### Restore DNS zone version Restore and activate a previous DNS zone version. **Usage:** ``` scw dns version restore <dns-zone-version-id ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone-version-id | Required | | ### List DNS zone version records Get a list of records from a previous DNS zone version. **Usage:** ``` scw dns version show <dns-zone-version-id ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone-version-id | Required | | ## DNS Zones management DNS Zones management. ### Clone a DNS zone Clone an existed DNS zone with all its records into a new one. **Usage:** ``` scw dns zone clone [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone to clone | | dest-dns-zone | Required | The destinaton DNS zone | | overwrite | | Whether or not the destination DNS zone will be overwritten | | project-id | | The project ID of the destination DNS zone | ### Create a DNS zone Create a new DNS zone. **Usage:** ``` scw dns zone create [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | domain | Required | The domain of the DNS zone to create | | subdomain | Required | The subdomain of the DNS zone to create | | project-id | | Project ID to use. If none is passed the default project ID will be used | ### Delete DNS zone Delete a DNS zone and all it's records. **Usage:** ``` scw dns zone delete <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone to delete | | project-id | | Project ID to use. If none is passed the default project ID will be used | ### Export raw DNS zone Get a DNS zone in a given format with default NS. **Usage:** ``` scw dns zone export <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone to export | | format | Default: `bind`<br />One of: `unknown_raw_format`, `bind` | Format for DNS zone | ### Import raw DNS zone Import and replace records from a given provider format with default NS. **Usage:** ``` scw dns zone import <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone to import | | ~~content~~ | Deprecated | | | project-id | | Project ID to use. If none is passed the default project ID will be used | | ~~format~~ | Deprecated<br />One of: `unknown_raw_format`, `bind` | | | bind-source.content | | | | axfr-source.name-server | | | | axfr-source.tsig-key.name | | | | axfr-source.tsig-key.key | | | | axfr-source.tsig-key.algorithm | | | ### List DNS zones Returns a list of manageable DNS zones. You can filter the DNS zones by domain name. **Usage:** ``` scw dns zone list [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | project-id | | The project ID on which to filter the returned DNS zones | | order-by | One of: `domain_asc`, `domain_desc`, `subdomain_asc`, `subdomain_desc` | The sort order of the returned DNS zones | | domain | | The domain on which to filter the returned DNS zones | | dns-zone | | The DNS zone on which to filter the returned DNS zones | | organization-id | | The organization ID on which to filter the returned DNS zones | ### Refresh DNS zone Refresh SOA DNS zone. You can recreate the given DNS zone and its sub DNS zone if needed. **Usage:** ``` scw dns zone refresh <dns-zone ...> [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone to refresh | | recreate-dns-zone | | Whether or not to recreate the DNS zone | | recreate-sub-dns-zone | | Whether or not to recreate the sub DNS zone | ### Update a DNS zone Update the name and/or the organizations for a DNS zone. **Usage:** ``` scw dns zone update [arg=value ...] ``` **Args:** | Name | | Description | |------|---|-------------| | dns-zone | Required | The DNS zone to update | | new-dns-zone | Required | The new DNS zone | | project-id | | Project ID to use. If none is passed the default project ID will be used |
apache-2.0
EvanDylan/node
base/mods/inhertis/student.js
318
/** * class for student */ 'use strict' const util = require('util') const Person = require('./person'); function Student() { Person.call(this); } // student继承自person util.inherits(Student, Person); Student.prototype.study = function() { console.log('i am learning...'); }; module.exports = Student;
apache-2.0
swordhell/go_server
src/td.com/module/module.go
210
package module import ( "net" "sync" ) type TCP_server struct { Port uint16 NewAgent func(*TCPConn) Agent ln net.Listener mutexConns sync.Mutex } func (server *TCP_server) Start() { }
apache-2.0
jpettitt/amphtml
extensions/amp-twitter/1.0/storybook/Basic.amp.js
3469
import * as Preact from '#preact'; import {boolean, number, select, withKnobs} from '@storybook/addon-knobs'; import {withAmp} from '@ampproject/storybook-addon'; export default { title: 'amp-twitter-1_0', decorators: [withKnobs, withAmp], parameters: { extensions: [ { name: 'amp-twitter', version: '1.0', }, { name: 'amp-bind', version: '0.1', }, ], experiments: ['bento'], }, }; export const Default = () => { const tweetId = select( 'tweet id', ['1356304203044499462', '495719809695621121', '463440424141459456'], '1356304203044499462' ); const cards = boolean('show cards', true) ? undefined : 'hidden'; const conversation = boolean('show conversation', false) ? undefined : 'none'; return ( <amp-twitter width="300" height="200" data-tweetid={tweetId} data-cards={cards} data-conversation={conversation} /> ); }; export const Moments = () => { const limit = number('limit to', 2); return ( <amp-twitter data-limit={limit} data-momentid="1009149991452135424" width="300" height="200" /> ); }; export const Timelines = () => { const tweetLimit = number('limit to', 5); const timelineSourceType = select( 'source type', ['profile', 'likes', 'list', 'source', 'collection', 'url', 'widget'], 'profile' ); const timelineScreenName = 'amphtml'; const timelineUserId = '3450662892'; return ( <amp-twitter data-tweet-limit={tweetLimit} data-timeline-source-type={timelineSourceType} data-timeline-scree-name={timelineScreenName} data-timeline-user-id={timelineUserId} width="300" height="200" /> ); }; export const DeletedTweet = () => { const withFallback = boolean('include fallback?', true); return ( <amp-twitter width="390" height="330" layout="fixed" data-tweetid="882818033403789316" data-cards="hidden" > <blockquote placeholder> <p lang="en" dir="ltr"> In case you missed it last week, check out our recap of AMP in 2020 ⚡🙌 </p> <p> Watch here ➡️ <br /> <a href="https://t.co/eaxT3MuSAK">https://t.co/eaxT3MuSAK</a> </p> </blockquote> {withFallback && ( <div fallback> An error occurred while retrieving the tweet. It might have been deleted. </div> )} </amp-twitter> ); }; export const InvalidTweet = () => { return ( <amp-twitter width="390" height="330" layout="fixed" data-tweetid="1111111111111641653602164060160" data-cards="hidden" > <blockquote placeholder class="twitter-tweet" data-lang="en"> <p> This placeholder should never change because given tweet-id is invalid. </p> </blockquote> </amp-twitter> ); }; export const MutatedTweetId = () => { return ( <> <button on="tap:AMP.setState({tweetid: '495719809695621121'})"> Change tweet </button> <amp-state id="tweetid"> <script type="application/json">1356304203044499462</script> </amp-state> <amp-twitter width="375" height="472" layout="responsive" data-tweetid="1356304203044499462" data-amp-bind-data-tweetid="tweetid" ></amp-twitter> </> ); };
apache-2.0
imluxin/tp-company-site-demo
Apps/Admin/View/Default/User/verify.html
4271
<!DOCTYPE html> <h2 class="page-header"> 用户姓名认证 </h2> <form action="<?php echo U('User/verify_refuse')?>" id="verifyUserForm" method="post" name="verifyUserForm"> <input hidden="true" name="user_guid" value="<?php echo $user_info['guid']?>"> <table class="table table-bordered"> <tr> <th>用户姓名</th> <td><?php echo $user_attribute_info['real_name']?></td> </tr> <tr> <th>用户邮箱</th> <td><?php echo $user_info['email']?></td> </tr> <tr> <th>用户手机</th> <td><?php echo $user_info['mobile']?></td> </tr> <tr> <th>用户所在公司</th> <td><?php echo $user_company_name?></td> </tr> <tr> <th>用户所在社团</th> <td><?php echo $user_org_name?></td> </tr> <tr> <th>身份证正面</th> <td> <img style="width: 300px;height: 200px;" src="<?php echo get_image_path($user_attribute_info['identity_card_front']);?>"> </td> </tr> <tr> <th>身份证反面</th> <td> <img style="width: 300px;height: 200px;" src="<?php echo get_image_path($user_attribute_info['identity_card_back']);?>"> </td> </tr> <!--<tr>--> <!--<th>更新时间</th>--> <!--<td><?php echo date('Y-m-d H:i',$user_info['updated_at'])?></td>--> <!--</tr>--> <!--str_replace("&lt;br/&gt;","\n",$org_info['description'])保留回车输出--> <tr id="hidden_tr" hidden="true"> <th>拒绝理由</th> <td><textarea id="identity_refuse_reason" name="identity_refuse_reason" placeholder="必填项"></textarea></td> </tr> <div></div> <input type="hidden" name="org_guid" value="<?php echo $org_info['guid']?>"> </table> </form> <tfoot> <input type="button" value="通过审核" id="pass" name="pass" onclick="verify_pass()" class="btn-default"> <input type="button" value="拒绝通过" id="not_pass" name="not_pass" onclick="verify_refuse()" class="btn-default"> <input type="button" value="提交" id="verify_refuse" name="not_pass_submit" onclick="verify_refuse_submit()" hidden="true" class="btn-default"> <input type="button" value="返回" id="return_index" name="return_index" onclick="return_index()" class="btn-default"> <input type="button" value="返回" id="return_verify" name="return_index" onclick="return_verify()" hidden="true" class="btn-default"> </tfoot> <script type="text/javascript"> //返回 function return_index(){ location.href = "<?php echo U('User/index')?>"; } //审核通过 function verify_pass(){ location.href = "<?php echo U('User/verify_pass',array('user_guid'=>$user_info['guid']))?>"; } //审核拒绝通过 function verify_refuse(){ $("#hidden_tr").removeAttr("hidden"); $("#pass").attr("hidden",true); $("#not_pass").attr("hidden",true); $("#verify_refuse").removeAttr("hidden"); $("#return_index").attr("hidden",true); $("#return_verify").removeAttr("hidden"); // location.href = "<?php echo U('Org/verify_not_pass',array('org_guid'=>$org_info['guid']))?>"; } function verify_refuse_submit(){ $("#verifyUserForm").submit(); } function return_verify(){ $("#hidden_tr").attr("hidden",true); $("#pass").removeAttr("hidden"); $("#not_pass").removeAttr("hidden"); $("#return_index").removeAttr("hidden"); $("#verify_refuse").attr("hidden",true); $("#return_verify").attr("hidden",true); } $(document).ready(function () { //表单验证 $('#verifyUserForm').validate({ rules: { identity_refuse_reason: { required: true, rangelength: [1, 30] } }, messages: { identity_refuse_reason: { required: "拒绝理由不能为空", rangelength: "拒绝理由不得多于30字" } } }); }); </script>
apache-2.0
joshholl/intellij-csharp
gen/com/github/joshholl/intellij/csharp/lang/psi/impl/CSharpImplicitAnonymousFunctionParameterListImpl.java
1220
// This is a generated file. Not intended for manual editing. package com.github.joshholl.intellij.csharp.lang.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.github.joshholl.intellij.csharp.lang.lexer.CSharpTokenTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.github.joshholl.intellij.csharp.lang.psi.*; public class CSharpImplicitAnonymousFunctionParameterListImpl extends ASTWrapperPsiElement implements CSharpImplicitAnonymousFunctionParameterList { public CSharpImplicitAnonymousFunctionParameterListImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof CSharpVisitor) ((CSharpVisitor)visitor).visitImplicitAnonymousFunctionParameterList(this); else super.accept(visitor); } @Override @NotNull public List<CSharpImplicitAnonymousFunctionParameter> getImplicitAnonymousFunctionParameterList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, CSharpImplicitAnonymousFunctionParameter.class); } }
apache-2.0
toroso/ruibarbo
ruibarbo.core/Wpf/Helpers/ComboBoxExtensions.cs
879
using System; using ruibarbo.core.Search; using ruibarbo.core.Wpf.Base; namespace ruibarbo.core.Wpf.Helpers { public static class ComboBoxExtensions { public static void OpenAndClickFirst<TItem>(this IComboBox me) where TItem : class, IComboBoxItem { OpenAndClickFirst<TItem>(me, By.Empty); } public static void OpenAndClickFirst<TItem>(this IComboBox me, params Func<IByBuilder<TItem>, By>[] byBuilders) where TItem : class, IComboBoxItem { OpenAndClickFirst<TItem>(me, byBuilders.Build()); } public static void OpenAndClickFirst<TItem>(this IComboBox me, params By[] bys) where TItem : class, IComboBoxItem { var item = me.FindFirstItem<TItem>(bys); item.OpenAndClick(); } } }
apache-2.0
jaadds/product-apim
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/api/lifecycle/APISecurityTestCase.java
14024
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 org.wso2.am.integration.tests.api.lifecycle; import org.json.JSONException; import org.json.JSONObject; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.am.integration.clients.publisher.api.ApiException; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIOperationsDTO; import org.wso2.am.integration.clients.store.api.v1.dto.APIKeyDTO; import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO; import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO; import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO; import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException; import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants; import org.wso2.am.integration.test.utils.bean.APILifeCycleAction; import org.wso2.am.integration.test.utils.bean.APIRequest; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException; import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; import javax.xml.xpath.XPathExpressionException; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; /** * This class tests the behaviour of API when there is choice of selection between oauth2 and mutual ssl in API Manager. */ @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE}) public class APISecurityTestCase extends APIManagerLifecycleBaseTest { private final String API_NAME = "mutualsslAPI"; private final String API_NAME_2 = "mutualsslAPI2"; private final String API_CONTEXT = "mutualsslAPI"; private final String API_CONTEXT_2 = "mutualsslAPI2"; private final String API_END_POINT_METHOD = "/customers/123"; private final String API_VERSION_1_0_0 = "1.0.0"; private final String APPLICATION_NAME = "AccessibilityOfDeprecatedOldAPIAndPublishedCopyAPITestCase"; private String accessToken; private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/"; private String apiEndPointUrl; private String applicationId; private String apiId1, apiId2; @BeforeClass(alwaysRun = true) public void initialize() throws APIManagerIntegrationTestException, IOException, ApiException, org.wso2.am.integration.clients.store.api.ApiException, XPathExpressionException, AutomationUtilException { super.init(); apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL; APIRequest apiRequest1 = new APIRequest(API_NAME, API_CONTEXT, new URL(apiEndPointUrl)); apiRequest1.setVersion(API_VERSION_1_0_0); apiRequest1.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest1.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest1.setTags(API_TAGS); apiRequest1.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue()); APIOperationsDTO apiOperationsDTO1 = new APIOperationsDTO(); apiOperationsDTO1.setVerb("GET"); apiOperationsDTO1.setTarget("/customers/{id}"); apiOperationsDTO1.setAuthType("Application & Application User"); apiOperationsDTO1.setThrottlingPolicy("Unlimited"); List<APIOperationsDTO> operationsDTOS = new ArrayList<>(); operationsDTOS.add(apiOperationsDTO1); apiRequest1.setOperationsDTOS(operationsDTOS); List<String> securitySchemes = new ArrayList<>(); securitySchemes.add("mutualssl"); apiRequest1.setSecurityScheme(securitySchemes); HttpResponse response1 = restAPIPublisher.addAPI(apiRequest1); apiId1 = response1.getData(); String certOne = getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl" + File.separator + "example.crt"; restAPIPublisher.uploadCertificate(new File(certOne), "example", apiId1, APIMIntegrationConstants.API_TIER.UNLIMITED); APIRequest apiRequest2 = new APIRequest(API_NAME_2, API_CONTEXT_2, new URL(apiEndPointUrl)); apiRequest2.setVersion(API_VERSION_1_0_0); apiRequest2.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest2.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest2.setTags(API_TAGS); apiRequest2.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue()); apiRequest2.setOperationsDTOS(operationsDTOS); List<String> securitySchemes2 = new ArrayList<>(); securitySchemes2.add("mutualssl"); securitySchemes2.add("oauth2"); securitySchemes2.add("api_key"); apiRequest2.setSecurityScheme(securitySchemes2); HttpResponse response2 = restAPIPublisher.addAPI(apiRequest2); apiId2 = response2.getData(); String certTwo = getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl" + File.separator + "abcde.crt"; restAPIPublisher.uploadCertificate(new File(certTwo), "abcde", apiId2, APIMIntegrationConstants.API_TIER.UNLIMITED); restAPIPublisher.changeAPILifeCycleStatus(apiId1, APILifeCycleAction.PUBLISH.getAction()); restAPIPublisher.changeAPILifeCycleStatus(apiId2, APILifeCycleAction.PUBLISH.getAction()); HttpResponse applicationResponse = restAPIStore.createApplication(APPLICATION_NAME, "Test Application", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, ApplicationDTO.TokenTypeEnum.JWT); applicationId = applicationResponse.getData(); restAPIStore.subscribeToAPI(apiId2, applicationId, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED); ArrayList grantTypes = new ArrayList(); grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.PASSWORD); grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL); ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(applicationId, "36000", "", ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes); //get access token accessToken = applicationKeyDTO.getToken().getAccessToken(); } @Test(description = "This test case tests the behaviour of APIs that are protected with mutual SSL and OAuth2 " + "when the client certificate is not presented but OAuth2 token is presented.") public void testCreateAndPublishAPIWithOAuth2() throws XPathExpressionException, IOException, JSONException { // Create requestHeaders Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("accept", "application/json"); requestHeaders.put("Authorization", "Bearer " + accessToken); HttpResponse apiResponse = HttpRequestUtil .doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders); JSONObject response = new JSONObject(apiResponse.getData()); //fix test failure due to error code changes introduced in product-apim pull #7106 assertEquals(response.getJSONObject("fault").getInt("code"), 900901, "API invocation succeeded with the access token without need for mutual ssl"); apiResponse = HttpRequestUtil .doGet(getAPIInvocationURLHttp(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders); assertEquals(apiResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "API invocation failed for a test case with valid access token when the API is protected with " + "both mutual sso and oauth2"); } @Test(description = "Testing the invocation with API Keys", dependsOnMethods = {"testCreateAndPublishAPIWithOAuth2"}) public void testInvocationWithApiKeys() throws Exception { APIKeyDTO apiKeyDTO = restAPIStore .generateAPIKeys(applicationId, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION.toString(), -1); assertNotNull(apiKeyDTO, "API Key generation failed"); Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("accept", "application/json"); requestHeaders.put("apikey", apiKeyDTO.getApikey()); HttpResponse apiResponse = HttpRequestUtil .doGet(getAPIInvocationURLHttp(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders); assertEquals(apiResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "API invocation failed for a test case with valid api key when the API is protected with " + "API Keys"); } // @Test(description = "This method tests the behaviour of APIs that are protected with mutual SSL and when the " // + "authentication is done using mutual SSL", dependsOnMethods = "testCreateAndPublishAPIWithOAuth2") // public void testAPIInvocationWithMutualSSL() // throws IOException, XPathExpressionException, InterruptedException, // NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException { // String expectedResponseData = "<id>123</id><name>John</name></Customer>"; // // We need to wait till the relevant listener reloads. // Thread.sleep(60000); // Map<String, String> requestHeaders = new HashMap<>(); // requestHeaders.put("accept", "text/xml"); // // Check with the correct client certificate for an API that is only protected with mutual ssl. // HttpResponse response = HTTPSClientUtils.doMutulSSLGet( // getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl" // + File.separator + "new-keystore.jks", // getAPIInvocationURLHttps(API_CONTEXT, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders); // Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK, // "Mutual SSL Authentication has not succeeded"); // Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match"); // /* Check with the wrong client certificate for an API that is protected with mutual ssl and oauth2, without // an access token.*/ // response = HTTPSClientUtils.doMutulSSLGet( // getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl" // + File.separator + "new-keystore.jks", // getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders); // Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED, // "Mutual SSL Authentication has succeeded for a different certificate"); // /* Check with the correct client certificate for an API that is protected with mutual ssl and oauth2, without // an access token.*/ // response = HTTPSClientUtils.doMutulSSLGet( // getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl" // + File.separator + "test.jks", // getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders); // Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK, // "Mutual SSL Authentication has not succeeded"); // Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match"); // // /* Check with the wrong client certificate for an API that is protected with mutual ssl and oauth2, with a // correct access token.*/ // requestHeaders.put("Authorization", "Bearer " + accessToken); // response = HTTPSClientUtils.doMutulSSLGet( // getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl" // + File.separator + "new-keystore.jks", // getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders); // Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK, // "OAuth2 authentication was not checked in the event of mutual SSL failure"); // Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match"); // } @AfterClass(alwaysRun = true) public void cleanUpArtifacts() throws IOException, AutomationUtilException, ApiException { restAPIStore.deleteApplication(applicationId); restAPIPublisher.deleteAPI(apiId1); restAPIPublisher.deleteAPI(apiId2); } }
apache-2.0
adamzolotarev/Exceptionless
Source/Api/Controllers/Base/PermissionResult.cs
1762
using System; using System.Net; namespace Exceptionless.Api.Controllers { public class PermissionResult { public bool Allowed { get; set; } public string Id { get; set; } public string Message { get; set; } public HttpStatusCode StatusCode { get; set; } public static PermissionResult Allow = new PermissionResult { Allowed = true, StatusCode = HttpStatusCode.OK }; public static PermissionResult Deny = new PermissionResult { Allowed = false, StatusCode = HttpStatusCode.BadRequest }; public static PermissionResult DenyWithNotFound(string id = null) { return new PermissionResult { Allowed = false, Id = id, StatusCode = HttpStatusCode.NotFound }; } public static PermissionResult DenyWithMessage(string message, string id = null) { return new PermissionResult { Allowed = false, Id = id, Message = message, StatusCode = HttpStatusCode.BadRequest }; } public static PermissionResult DenyWithStatus(HttpStatusCode statusCode, string message = null, string id = null) { return new PermissionResult { Allowed = false, Id = id, Message = message, StatusCode = statusCode }; } public static PermissionResult DenyWithPlanLimitReached(string message, string id = null) { return new PermissionResult { Allowed = false, Id = id, Message = message, StatusCode = HttpStatusCode.UpgradeRequired }; } } }
apache-2.0
nghiant2710/base-images
balena-base-images/node/aio-3288c/ubuntu/disco/15.7.0/build/Dockerfile
2758
# AUTOGENERATED FILE FROM balenalib/aio-3288c-ubuntu:disco-build ENV NODE_VERSION 15.7.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "aa65f287bfe060321ee5e0b4f7134bd17690abb911c6fc1173ddbedddbf2c060 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu disco \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
apache-2.0
DmitryKey/luke-gwt
src/main/java/org/apache/luke/client/LukeInspector.java
17271
package org.apache.luke.client; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.lucene.analysis.core.WhitespaceAnalyzer; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexDeletionPolicy; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.MultiReader; import org.apache.lucene.index.SegmentInfos; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.LockFactory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Version; import org.apache.luke.client.data.FieldsDummyData; import org.getopt.luke.KeepAllIndexDeletionPolicy; import org.getopt.luke.KeepLastIndexDeletionPolicy; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.GWT.UncaughtExceptionHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler; import com.google.gwt.user.cellview.client.ColumnSortList; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CaptionPanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.SplitLayoutPanel; import com.google.gwt.user.client.ui.StackPanel; import com.google.gwt.user.client.ui.TabPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.view.client.AsyncDataProvider; import com.google.gwt.view.client.HasData; import com.google.gwt.view.client.Range; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class LukeInspector implements EntryPoint { public static Version LV = Version.LUCENE_46; private final static String solrIndexDir = "D:\\Projects\\information_retrieval\\solr\\solr-4.6.0\\solr-4.6.0\\example\\solr\\collection1\\data\\index"; private String pName = null; private Directory dir = null; private IndexReader ir = null; private IndexSearcher is = null; public void onModuleLoad() { final RootPanel rootPanel = RootPanel.get(); CaptionPanel cptnpnlNewPanel = new CaptionPanel("New panel"); cptnpnlNewPanel.setCaptionHTML("Luke version 5.0"); rootPanel.add(cptnpnlNewPanel, 10, 10); cptnpnlNewPanel.setSize("959px", "652px"); TabPanel tabPanel = new TabPanel(); cptnpnlNewPanel.setContentWidget(tabPanel); tabPanel.setSize("5cm", "636px"); //LuceneIndexLoader.loadIndex(pName, this); SplitLayoutPanel splitLayoutPanel = new SplitLayoutPanel(); tabPanel.add(splitLayoutPanel, "Index overview", false); tabPanel.setVisible(true); splitLayoutPanel.setSize("652px", "590px"); SplitLayoutPanel splitLayoutPanel_1 = new SplitLayoutPanel(); splitLayoutPanel.addNorth(splitLayoutPanel_1, 288.0); Label lblIndexStatistics = new Label("Index statistics"); lblIndexStatistics.setDirectionEstimator(true); lblIndexStatistics.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); splitLayoutPanel_1.addNorth(lblIndexStatistics, 26.0); VerticalPanel verticalPanel = new VerticalPanel(); splitLayoutPanel_1.addWest(verticalPanel, 125.0); Label lblTest = new Label("Index name:"); verticalPanel.add(lblTest); lblTest.setWidth("109px"); Label lblTest_1 = new Label("# fields:"); verticalPanel.add(lblTest_1); Label lblNumber = new Label("# documents:"); verticalPanel.add(lblNumber); lblNumber.setWidth("101px"); Label lblTerms = new Label("# terms:"); verticalPanel.add(lblTerms); Label lblHasDeletions = new Label("Has deletions?"); verticalPanel.add(lblHasDeletions); Label lblNewLabel = new Label("Optimised?"); verticalPanel.add(lblNewLabel); Label lblIndexVersion = new Label("Index version:"); verticalPanel.add(lblIndexVersion); SplitLayoutPanel splitLayoutPanel_2 = new SplitLayoutPanel(); splitLayoutPanel.addWest(splitLayoutPanel_2, 240.0); // Create name column. TextColumn<Field> nameColumn = new TextColumn<Field>() { @Override public String getValue(Field field) { return field.getName(); } }; // Make the name column sortable. nameColumn.setSortable(true); // Create termCount column. TextColumn<Field> termCountColumn = new TextColumn<Field>() { @Override public String getValue(Field contact) { return contact.getTermCount(); } }; // Create decoder column. TextColumn<Field> decoderColumn = new TextColumn<Field>() { @Override public String getValue(Field contact) { return contact.getDecoder(); } }; final CellTable<Field> cellTable = new CellTable<Field>(); cellTable.addColumn(nameColumn, "Name"); cellTable.addColumn(termCountColumn, "Term count"); cellTable.addColumn(decoderColumn, "Decoder"); cellTable.setRowCount(FieldsDummyData.Fields.size(), true); // Set the range to display. In this case, our visible range is smaller than // the data set. cellTable.setVisibleRange(0, 3); // Create a data provider. AsyncDataProvider<Field> dataProvider = new AsyncDataProvider<Field>() { @Override protected void onRangeChanged(HasData<Field> display) { final Range range = display.getVisibleRange(); // Get the ColumnSortInfo from the table. final ColumnSortList sortList = cellTable.getColumnSortList(); // This timer is here to illustrate the asynchronous nature of this data // provider. In practice, you would use an asynchronous RPC call to // request data in the specified range. new Timer() { @Override public void run() { int start = range.getStart(); int end = start + range.getLength(); // This sorting code is here so the example works. In practice, you // would sort on the server. Collections.sort(FieldsDummyData.Fields, new Comparator<Field>() { public int compare(Field o1, Field o2) { if (o1 == o2) { return 0; } // Compare the name columns. int diff = -1; if (o1 != null) { diff = (o2 != null) ? o1.getName().compareTo(o2.getName()) : 1; } return sortList.get(0).isAscending() ? diff : -diff; } }); List<Field> dataInRange = FieldsDummyData.Fields.subList(start, end); // Push the data back into the list. cellTable.setRowData(start, dataInRange); } }.schedule(2000); } }; // Connect the list to the data provider. dataProvider.addDataDisplay(cellTable); // Add a ColumnSortEvent.AsyncHandler to connect sorting to the // AsyncDataPRrovider. AsyncHandler columnSortHandler = new AsyncHandler(cellTable); cellTable.addColumnSortHandler(columnSortHandler); // We know that the data is sorted alphabetically by default. cellTable.getColumnSortList().push(nameColumn); splitLayoutPanel_2.add(cellTable); SplitLayoutPanel splitLayoutPanel_3 = new SplitLayoutPanel(); splitLayoutPanel.addEast(splitLayoutPanel_3, 215.0); StackPanel stackPanel = new StackPanel(); rootPanel.add(stackPanel, 714, 184); stackPanel.setSize("259px", "239px"); FlowPanel flowPanel = new FlowPanel(); stackPanel.add(flowPanel, "Open index", false); flowPanel.setSize("100%", "100%"); TextBox textBox = new TextBox(); flowPanel.add(textBox); Button btnNewButton = new Button("..."); btnNewButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { DirectoryLister directoryLister = new DirectoryLister(); directoryLister.setPopupPosition(rootPanel.getAbsoluteLeft() + rootPanel.getOffsetWidth() / 2, rootPanel.getAbsoluteTop() + rootPanel.getOffsetHeight() / 2); directoryLister.show(); } }); flowPanel.add(btnNewButton); // exception handling // credits: http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void onUncaughtException(Throwable e) { Window.alert("uncaught: " + e.getMessage()); String s = buildStackTrace(e, "RuntimeExceotion:\n"); Window.alert(s); e.printStackTrace(); } }); } // showing the stacktrace // credits: http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase final String buildStackTrace(Throwable t, String log) { // return "disabled"; if (t != null) { log += t.getClass().toString(); log += t.getMessage(); // StackTraceElement[] stackTrace = t.getStackTrace(); if (stackTrace != null) { StringBuffer trace = new StringBuffer(); for (int i = 0; i < stackTrace.length; i++) { trace.append(stackTrace[i].getClassName() + "." + stackTrace[i].getMethodName() + "(" + stackTrace[i].getFileName() + ":" + stackTrace[i].getLineNumber()); } log += trace.toString(); } // Throwable cause = t.getCause(); if (cause != null && cause != t) { log += buildStackTrace(cause, "CausedBy:\n"); } } return log; } public Directory openDirectory(String dirImpl, String file, boolean create) throws Exception { File f = new File(file); if (!f.exists()) { throw new Exception("Index directory doesn't exist."); } Directory res = null; if (dirImpl == null || dirImpl.equals(Directory.class.getName()) || dirImpl.equals(FSDirectory.class.getName())) { return FSDirectory.open(f); } try { Class implClass = Class.forName(dirImpl); Constructor<Directory> constr = implClass.getConstructor(File.class); if (constr != null) { res = constr.newInstance(f); } else { constr = implClass.getConstructor(File.class, LockFactory.class); res = constr.newInstance(f, (LockFactory)null); } } catch (Throwable e) { //errorMsg("Invalid directory implementation class: " + dirImpl + " " + e); return null; } if (res != null) return res; // fall-back to FSDirectory. if (res == null) return FSDirectory.open(f); return null; } /** * open Lucene index and re-init all the sub-widgets * @param name * @param force * @param dirImpl * @param ro * @param ramdir * @param keepCommits * @param point * @param tiiDivisor */ public void openIndex(String name, boolean force, String dirImpl, boolean ro, boolean ramdir, boolean keepCommits, IndexCommit point, int tiiDivisor) { pName = name; File baseFileDir = new File(name); ArrayList<Directory> dirs = new ArrayList<Directory>(); Throwable lastException = null; try { Directory d = openDirectory(dirImpl, pName, false); if (IndexWriter.isLocked(d)) { if (!ro) { if (force) { IndexWriter.unlock(d); } else { //errorMsg("Index is locked. Try 'Force unlock' when opening."); d.close(); d = null; return; } } } boolean existsSingle = false; // IR.indexExists doesn't report the cause of error try { new SegmentInfos().read(d); existsSingle = true; } catch (Throwable e) { e.printStackTrace(); lastException = e; // } if (!existsSingle) { // try multi File[] files = baseFileDir.listFiles(); for (File f : files) { if (f.isFile()) { continue; } Directory d1 = openDirectory(dirImpl, f.toString(), false); if (IndexWriter.isLocked(d1)) { if (!ro) { if (force) { IndexWriter.unlock(d1); } else { //errorMsg("Index is locked. Try 'Force unlock' when opening."); d1.close(); d1 = null; return; } } } existsSingle = false; try { new SegmentInfos().read(d1); existsSingle = true; } catch (Throwable e) { lastException = e; e.printStackTrace(); } if (!existsSingle) { d1.close(); continue; } dirs.add(d1); } } else { dirs.add(d); } if (dirs.size() == 0) { if (lastException != null) { //errorMsg("Invalid directory at the location, check console for more information. Last exception:\n" + lastException.toString()); } else { //errorMsg("No valid directory at the location, try another location.\nCheck console for other possible causes."); } return; } if (ramdir) { //showStatus("Loading index into RAMDirectory ..."); Directory dir1 = new RAMDirectory(); IndexWriterConfig cfg = new IndexWriterConfig(LV, new WhitespaceAnalyzer(LV)); IndexWriter iw1 = new IndexWriter(dir1, cfg); iw1.addIndexes((Directory[])dirs.toArray(new Directory[dirs.size()])); iw1.close(); //showStatus("RAMDirectory loading done!"); if (dir != null) dir.close(); dirs.clear(); dirs.add(dir1); } IndexDeletionPolicy policy; if (keepCommits) { policy = new KeepAllIndexDeletionPolicy(); } else { policy = new KeepLastIndexDeletionPolicy(); } ArrayList<DirectoryReader> readers = new ArrayList<DirectoryReader>(); for (Directory dd : dirs) { DirectoryReader reader; if (tiiDivisor > 1) { reader = DirectoryReader.open(dd, tiiDivisor); } else { reader = DirectoryReader.open(dd); } readers.add(reader); } if (readers.size() == 1) { ir = readers.get(0); dir = ((DirectoryReader)ir).directory(); } else { ir = new MultiReader((IndexReader[])readers.toArray(new IndexReader[readers.size()])); } is = new IndexSearcher(ir); // XXX //slowAccess = false; //initOverview(); //initPlugins(); //showStatus("Index successfully open."); } catch (Exception e) { e.printStackTrace(); //errorMsg(e.getMessage()); return; } } }
apache-2.0
JoelMarcey/buck
test/com/facebook/buck/util/network/AbstractBatchingLoggerTest.java
2949
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 com.facebook.buck.util.network; import static org.hamcrest.MatcherAssert.assertThat; import com.facebook.buck.util.types.Unit; import com.google.common.collect.ImmutableCollection; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.ArrayList; import java.util.List; import org.hamcrest.Matchers; import org.junit.Test; public class AbstractBatchingLoggerTest { private static class TestBatchingLogger extends AbstractBatchingLogger { private final List<ImmutableCollection<BatchEntry>> uploadedBatches = new ArrayList<>(); public TestBatchingLogger(int minBatchSize) { super(minBatchSize); } public List<ImmutableCollection<AbstractBatchingLogger.BatchEntry>> getUploadedBatches() { return uploadedBatches; } @Override protected ListenableFuture<Unit> logMultiple( ImmutableCollection<AbstractBatchingLogger.BatchEntry> data) { uploadedBatches.add(data); return Futures.immediateFuture(Unit.UNIT); } } @Test public void testBatchingLogger() { String shortData = "data"; String longData = "datdatdatdatdatdatdataaaaaaadata"; AbstractBatchingLogger.BatchEntry shortDataBatch = new AbstractBatchingLogger.BatchEntry(shortData); AbstractBatchingLogger.BatchEntry longDataBatch = new AbstractBatchingLogger.BatchEntry(longData); TestBatchingLogger testBatchingLogger = new TestBatchingLogger(longData.length() + 1); testBatchingLogger.log(longData); // Data should still be buffered at this point. assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(0)); // This one should tip it over. testBatchingLogger.log(shortData); assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(1)); testBatchingLogger.log(shortData); testBatchingLogger.log(shortData); assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(1)); testBatchingLogger.forceFlush(); assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(2)); assertThat( testBatchingLogger.getUploadedBatches(), Matchers.contains( Matchers.contains(longDataBatch, shortDataBatch), Matchers.contains(shortDataBatch, shortDataBatch))); } }
apache-2.0
nghiant2710/base-images
balena-base-images/golang/nitrogen8mm/fedora/32/1.15.7/build/Dockerfile
1994
# AUTOGENERATED FILE FROM balenalib/nitrogen8mm-fedora:32-build ENV GO_VERSION 1.15.7 RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "bca4af0c20f86521dfabf3b39fa2f1ceeeb11cebf7e90bdf1de2618c40628539 go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@golang" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 32 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.7 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
apache-2.0
census-instrumentation/opencensus-php
ext/opencensus_trace_message_event.c
5961
/* * Copyright 2017 OpenCensus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This is the implementation of the OpenCensus\Trace\Ext\MessageEvent class. The PHP * equivalent is: * * namespace OpenCensus\Trace\Ext; * * class MessageEvent { * protected $type; * protected $id; * protected $time; * protected $options; * * public function type() * { * return $this->type; * } * * public function id() * { * return $this->id; * } * * public function time() * { * return $this->time; * } * * public function options() * { * return $this->options; * } * } */ #include "php_opencensus.h" #include "opencensus_trace_message_event.h" #include "Zend/zend_alloc.h" zend_class_entry* opencensus_trace_message_event_ce = NULL; ZEND_BEGIN_ARG_INFO_EX(arginfo_void, 0, 0, 0) ZEND_END_ARG_INFO(); /** * Fetch the message_event type * * @return string */ static PHP_METHOD(OpenCensusTraceMessageEvent, type) { zval *val, rv; if (zend_parse_parameters_none() == FAILURE) { return; } val = zend_read_property(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(getThis()), "type", sizeof("type") - 1, 1, &rv); RETURN_ZVAL(val, 1, 0); } /** * Fetch the message_event id * * @return string */ static PHP_METHOD(OpenCensusTraceMessageEvent, id) { zval *val, rv; if (zend_parse_parameters_none() == FAILURE) { return; } val = zend_read_property(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(getThis()), "id", sizeof("id") - 1, 1, &rv); RETURN_ZVAL(val, 1, 0); } /** * Fetch the message_event time * * @return float */ static PHP_METHOD(OpenCensusTraceMessageEvent, time) { zval *val, rv; if (zend_parse_parameters_none() == FAILURE) { return; } val = zend_read_property(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(getThis()), "time", sizeof("time") - 1, 1, &rv); RETURN_ZVAL(val, 1, 0); } /** * Fetch the message_event options * * @return float */ static PHP_METHOD(OpenCensusTraceMessageEvent, options) { zval *val, rv; if (zend_parse_parameters_none() == FAILURE) { return; } val = zend_read_property(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(getThis()), "options", sizeof("options") - 1, 1, &rv); RETURN_ZVAL(val, 1, 0); } /* Declare method entries for the OpenCensus\Trace\Ext\MessageEvent class */ static zend_function_entry opencensus_trace_message_event_methods[] = { PHP_ME(OpenCensusTraceMessageEvent, type, arginfo_void, ZEND_ACC_PUBLIC) PHP_ME(OpenCensusTraceMessageEvent, id, arginfo_void, ZEND_ACC_PUBLIC) PHP_ME(OpenCensusTraceMessageEvent, time, arginfo_void, ZEND_ACC_PUBLIC) PHP_ME(OpenCensusTraceMessageEvent, options, arginfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; /* Module init handler for registering the OpenCensus\Trace\Ext\MessageEvent class */ int opencensus_trace_message_event_minit(INIT_FUNC_ARGS) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "OpenCensus\\Trace\\Ext\\MessageEvent", opencensus_trace_message_event_methods); opencensus_trace_message_event_ce = zend_register_internal_class(&ce); zend_declare_property_null(opencensus_trace_message_event_ce, "type", sizeof("type") - 1, ZEND_ACC_PROTECTED); zend_declare_property_null(opencensus_trace_message_event_ce, "id", sizeof("id") - 1, ZEND_ACC_PROTECTED); zend_declare_property_null(opencensus_trace_message_event_ce, "time", sizeof("time") - 1, ZEND_ACC_PROTECTED); zend_declare_property_null(opencensus_trace_message_event_ce, "options", sizeof("options") - 1, ZEND_ACC_PROTECTED); return SUCCESS; } /** * Returns an allocated initialized pointer to a opencensus_trace_message_event_t * struct. * * Note that you will have to call opencensus_trace_message_event_span_free * yourself when it's time to clean up the memory. */ opencensus_trace_message_event_t *opencensus_trace_message_event_alloc() { opencensus_trace_message_event_t *message_event = emalloc(sizeof(opencensus_trace_message_event_t)); message_event->time_event.type = OPENCENSUS_TRACE_TIME_EVENT_MESSAGE_EVENT; message_event->type = NULL; message_event->id = NULL; array_init(&message_event->options); return message_event; } void opencensus_trace_message_event_free(opencensus_trace_message_event_t *message_event) { if (message_event->type) { zend_string_release(message_event->type); } if (message_event->id) { zend_string_release(message_event->id); } if (Z_TYPE(message_event->options) != IS_NULL) { zval_dtor(&message_event->options); } efree(message_event); } int opencensus_trace_message_event_to_zval(opencensus_trace_message_event_t *message_event, zval *zv) { object_init_ex(zv, opencensus_trace_message_event_ce); zend_update_property_str(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(zv), "type", sizeof("type") - 1, message_event->type); zend_update_property_str(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(zv), "id", sizeof("id") - 1, message_event->id); zend_update_property_double(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(zv), "time", sizeof("time") - 1, message_event->time_event.time); zend_update_property(opencensus_trace_message_event_ce, OPENCENSUS_OBJ_P(zv), "options", sizeof("options") - 1, &message_event->options); return SUCCESS; }
apache-2.0
kodero/generic-angular-frontend
app/common/services/EntityFactory.js
2708
angular.module('app').factory('Entity', function ($resource) { var __apiBase__ = 'http://localhost:8080/GenericBackend/'; return { Model : $resource(__apiBase__ + 'api/models/fqns'), User : $resource(__apiBase__ + 'api/users/:id', {id: '@id', profileId :'@profileId'},{ getPermissions : {method : 'GET', url : __apiBase__ + 'api/userProfileRules/:profileId/allowedPermissions', isArray : true}, changePassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/changePassword', isArray : false}, resetPassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/resetPassword', isArray : false}, activate : {method : 'POST', url : __apiBase__ + 'api/users/:id/activate', isArray : false}, deactivate : {method : 'POST', url : __apiBase__ + 'api/users/:id/deactivate', isArray : false} }), Authentication : $resource(__apiBase__ + 'api/authentication/:id', {id: '@id', newStatus:'@newStatus'},{ login : {method : 'POST', url : __apiBase__ + 'api/authentication/login'}, logout : {method : 'POST', url : __apiBase__ + 'api/authentication/logout'}, getLoggedInUser : {method : 'GET', url : __apiBase__ + 'api/authentication/loggedinUser'} }), Role : $resource(__apiBase__ + 'api/roles/:id', {id: '@id'}), Profile : $resource(__apiBase__ + 'api/profiles/:id', {id: '@id'}), UserProfileRule : $resource(__apiBase__ + 'api/userProfileRules/:id', {id: '@id', newStatus:'@newStatus'},{ togglePermission : {method : 'POST', url : __apiBase__ + 'api/userProfileRules/:id/toggleStatus'} }), SchemeAccess : $resource(__apiBase__ + 'api/schemeAccess/:id', {id: '@id'}, { toggleAccess : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/toggleAccess'}, switchOrganization : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/switchScheme'}, }), UserOrganization : $resource(__apiBase__ + 'api/userOrganizations/:id', {id: '@id'}), Permission : $resource(__apiBase__ + 'api/permissions/:id', {id: '@id'}, { createPermissions : {method : 'POST', url : 'api/permissions/createPermissions'} }), UserPermission : $resource(__apiBase__ + 'api/user_permissions/:userId', {id: '@userId'}), SQLExecutor : $resource(__apiBase__ + 'api/sqlExecutor/:id', {id: '@id'},{ execute : {method : 'POST', url : __apiBase__ + 'api/sqlExecutor/execute', isArray: true} }) } } );
apache-2.0
nornagon/ninja
src/subprocess-win32.cc
5723
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "subprocess.h" #include <stdio.h> #include <algorithm> #include "util.h" namespace { void Win32Fatal(const char* function) { Fatal("%s: %s", function, GetLastErrorString().c_str()); } } // anonymous namespace Subprocess::Subprocess() : child_(NULL) , overlapped_() { } Subprocess::~Subprocess() { // Reap child if forgotten. if (child_) Finish(); } HANDLE Subprocess::SetupPipe(HANDLE ioport) { char pipe_name[100]; snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this); pipe_ = ::CreateNamedPipeA(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (pipe_ == INVALID_HANDLE_VALUE) Win32Fatal("CreateNamedPipe"); if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0)) Win32Fatal("CreateIoCompletionPort"); memset(&overlapped_, 0, sizeof(overlapped_)); if (!ConnectNamedPipe(pipe_, &overlapped_) && GetLastError() != ERROR_IO_PENDING) { Win32Fatal("ConnectNamedPipe"); } // Get the write end of the pipe as a handle inheritable across processes. HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); HANDLE output_write_child; if (!DuplicateHandle(GetCurrentProcess(), output_write_handle, GetCurrentProcess(), &output_write_child, 0, TRUE, DUPLICATE_SAME_ACCESS)) { Win32Fatal("DuplicateHandle"); } CloseHandle(output_write_handle); return output_write_child; } bool Subprocess::Start(SubprocessSet* set, const string& command) { HANDLE child_pipe = SetupPipe(set->ioport_); STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(STARTUPINFO); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdOutput = child_pipe; // TODO: what does this hook up stdin to? startup_info.hStdInput = NULL; // TODO: is it ok to reuse pipe like this? startup_info.hStdError = child_pipe; PROCESS_INFORMATION process_info; memset(&process_info, 0, sizeof(process_info)); // Do not prepend 'cmd /c' on Windows, this breaks command // lines greater than 8,191 chars. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, /* inherit handles */ TRUE, 0, NULL, NULL, &startup_info, &process_info)) { Win32Fatal("CreateProcess"); } // Close pipe channel only used by the child. if (child_pipe) CloseHandle(child_pipe); CloseHandle(process_info.hThread); child_ = process_info.hProcess; return true; } void Subprocess::OnPipeReady() { DWORD bytes; if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } Win32Fatal("GetOverlappedResult"); } if (bytes) buf_.append(overlapped_buf_, bytes); memset(&overlapped_, 0, sizeof(overlapped_)); if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_), &bytes, &overlapped_)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } if (GetLastError() != ERROR_IO_PENDING) Win32Fatal("ReadFile"); } // Even if we read any bytes in the readfile call, we'll enter this // function again later and get them at that point. } bool Subprocess::Finish() { // TODO: add error handling for all of these. WaitForSingleObject(child_, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(child_, &exit_code); CloseHandle(child_); child_ = NULL; return exit_code == 0; } bool Subprocess::Done() const { return pipe_ == NULL; } const string& Subprocess::GetOutput() const { return buf_; } SubprocessSet::SubprocessSet() { ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (!ioport_) Win32Fatal("CreateIoCompletionPort"); } SubprocessSet::~SubprocessSet() { CloseHandle(ioport_); } void SubprocessSet::Add(Subprocess* subprocess) { running_.push_back(subprocess); } void SubprocessSet::DoWork() { DWORD bytes_read; Subprocess* subproc; OVERLAPPED* overlapped; if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc, &overlapped, INFINITE)) { if (GetLastError() != ERROR_BROKEN_PIPE) Win32Fatal("GetQueuedCompletionStatus"); } subproc->OnPipeReady(); if (subproc->Done()) { vector<Subprocess*>::iterator end = std::remove(running_.begin(), running_.end(), subproc); if (running_.end() != end) { finished_.push(subproc); running_.resize(end - running_.begin()); } } } Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; }
apache-2.0
wangsongpeng/jdk-src
src/main/java/org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java
2045
package org.omg.CosNaming.NamingContextPackage; /** * org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/org/omg/CosNaming/nameservice.idl * Monday, December 12, 2016 4:37:46 PM PST */ abstract public class NotEmptyHelper { private static String _id = "IDL:omg.org/CosNaming/NamingContext/NotEmpty:1.0"; public static void insert (org.omg.CORBA.Any a, NotEmpty that) { org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); a.type (type ()); write (out, that); a.read_value (out.create_input_stream (), type ()); } public static NotEmpty extract (org.omg.CORBA.Any a) { return read (a.create_input_stream ()); } private static org.omg.CORBA.TypeCode __typeCode = null; private static boolean __active = false; synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { synchronized (org.omg.CORBA.TypeCode.class) { if (__typeCode == null) { if (__active) { return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); } __active = true; org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0]; org.omg.CORBA.TypeCode _tcOf_members0 = null; __typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (NotEmptyHelper.id (), "NotEmpty", _members0); __active = false; } } } return __typeCode; } public static String id () { return _id; } public static NotEmpty read (org.omg.CORBA.portable.InputStream istream) { NotEmpty value = new NotEmpty (); // read and discard the repository ID istream.read_string (); return value; } public static void write (org.omg.CORBA.portable.OutputStream ostream, NotEmpty value) { // write the repository ID ostream.write_string (id ()); } }
apache-2.0
hongyuhong/flink
flink-runtime/src/test/java/org/apache/flink/runtime/blob/BlobClientSslTest.java
9674
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.runtime.blob; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.security.MessageDigest; import java.util.Collections; import java.util.List; import org.apache.flink.configuration.BlobServerOptions; import org.apache.flink.configuration.Configuration; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.SecurityOptions; import org.apache.flink.core.fs.Path; import org.apache.flink.util.TestLogger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * This class contains unit tests for the {@link BlobClient} with ssl enabled. */ public class BlobClientSslTest extends TestLogger { /** The buffer size used during the tests in bytes. */ private static final int TEST_BUFFER_SIZE = 17 * 1000; /** The instance of the SSL BLOB server used during the tests. */ private static BlobServer BLOB_SSL_SERVER; /** The SSL blob service client configuration */ private static Configuration sslClientConfig; /** The instance of the non-SSL BLOB server used during the tests. */ private static BlobServer BLOB_SERVER; /** The non-ssl blob service client configuration */ private static Configuration clientConfig; /** * Starts the SSL enabled BLOB server. */ @BeforeClass public static void startSSLServer() throws IOException { Configuration config = new Configuration(); config.setBoolean(SecurityOptions.SSL_ENABLED, true); config.setString(SecurityOptions.SSL_KEYSTORE, "src/test/resources/local127.keystore"); config.setString(SecurityOptions.SSL_KEYSTORE_PASSWORD, "password"); config.setString(SecurityOptions.SSL_KEY_PASSWORD, "password"); BLOB_SSL_SERVER = new BlobServer(config, new VoidBlobStore()); sslClientConfig = new Configuration(); sslClientConfig.setBoolean(SecurityOptions.SSL_ENABLED, true); sslClientConfig.setString(SecurityOptions.SSL_TRUSTSTORE, "src/test/resources/local127.truststore"); sslClientConfig.setString(SecurityOptions.SSL_TRUSTSTORE_PASSWORD, "password"); } /** * Starts the SSL disabled BLOB server. */ @BeforeClass public static void startNonSSLServer() throws IOException { Configuration config = new Configuration(); config.setBoolean(SecurityOptions.SSL_ENABLED, true); config.setBoolean(BlobServerOptions.SSL_ENABLED, false); config.setString(SecurityOptions.SSL_KEYSTORE, "src/test/resources/local127.keystore"); config.setString(SecurityOptions.SSL_KEYSTORE_PASSWORD, "password"); config.setString(SecurityOptions.SSL_KEY_PASSWORD, "password"); BLOB_SERVER = new BlobServer(config, new VoidBlobStore()); clientConfig = new Configuration(); clientConfig.setBoolean(SecurityOptions.SSL_ENABLED, true); clientConfig.setBoolean(BlobServerOptions.SSL_ENABLED, false); clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE, "src/test/resources/local127.truststore"); clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE_PASSWORD, "password"); } /** * Shuts the BLOB server down. */ @AfterClass public static void stopServers() throws IOException { if (BLOB_SSL_SERVER != null) { BLOB_SSL_SERVER.close(); } if (BLOB_SERVER != null) { BLOB_SERVER.close(); } } /** * Prepares a test file for the unit tests, i.e. the methods fills the file with a particular byte patterns and * computes the file's BLOB key. * * @param file * the file to prepare for the unit tests * @return the BLOB key of the prepared file * @throws IOException * thrown if an I/O error occurs while writing to the test file */ private static BlobKey prepareTestFile(File file) throws IOException { MessageDigest md = BlobUtils.createMessageDigest(); final byte[] buf = new byte[TEST_BUFFER_SIZE]; for (int i = 0; i < buf.length; ++i) { buf[i] = (byte) (i % 128); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); for (int i = 0; i < 20; ++i) { fos.write(buf); md.update(buf); } } finally { if (fos != null) { fos.close(); } } return new BlobKey(md.digest()); } /** * Validates the result of a GET operation by comparing the data from the retrieved input stream to the content of * the specified file. * * @param inputStream * the input stream returned from the GET operation * @param file * the file to compare the input stream's data to * @throws IOException * thrown if an I/O error occurs while reading the input stream or the file */ private static void validateGet(final InputStream inputStream, final File file) throws IOException { InputStream inputStream2 = null; try { inputStream2 = new FileInputStream(file); while (true) { final int r1 = inputStream.read(); final int r2 = inputStream2.read(); assertEquals(r2, r1); if (r1 < 0) { break; } } } finally { if (inputStream2 != null) { inputStream2.close(); } } } /** * Tests the PUT/GET operations for content-addressable streams. */ @Test public void testContentAddressableStream() { BlobClient client = null; InputStream is = null; try { File testFile = File.createTempFile("testfile", ".dat"); testFile.deleteOnExit(); BlobKey origKey = prepareTestFile(testFile); InetSocketAddress serverAddress = new InetSocketAddress("localhost", BLOB_SSL_SERVER.getPort()); client = new BlobClient(serverAddress, sslClientConfig); // Store the data is = new FileInputStream(testFile); BlobKey receivedKey = client.put(is); assertEquals(origKey, receivedKey); is.close(); is = null; // Retrieve the data is = client.get(receivedKey); validateGet(is, testFile); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (Throwable t) {} } if (client != null) { try { client.close(); } catch (Throwable t) {} } } } /** * Tests the PUT/GET operations for regular (non-content-addressable) streams. */ @Test public void testRegularStream() { final JobID jobID = JobID.generate(); final String key = "testkey3"; try { final File testFile = File.createTempFile("testfile", ".dat"); testFile.deleteOnExit(); prepareTestFile(testFile); BlobClient client = null; InputStream is = null; try { final InetSocketAddress serverAddress = new InetSocketAddress("localhost", BLOB_SSL_SERVER.getPort()); client = new BlobClient(serverAddress, sslClientConfig); // Store the data is = new FileInputStream(testFile); client.put(jobID, key, is); is.close(); is = null; // Retrieve the data is = client.get(jobID, key); validateGet(is, testFile); } finally { if (is != null) { is.close(); } if (client != null) { client.close(); } } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * Tests the static {@link BlobClient#uploadJarFiles(InetSocketAddress, Configuration, List)} helper. */ private void uploadJarFile(BlobServer blobServer, Configuration blobClientConfig) throws Exception { final File testFile = File.createTempFile("testfile", ".dat"); testFile.deleteOnExit(); prepareTestFile(testFile); InetSocketAddress serverAddress = new InetSocketAddress("localhost", blobServer.getPort()); List<BlobKey> blobKeys = BlobClient.uploadJarFiles(serverAddress, blobClientConfig, Collections.singletonList(new Path(testFile.toURI()))); assertEquals(1, blobKeys.size()); try (BlobClient blobClient = new BlobClient(serverAddress, blobClientConfig)) { InputStream is = blobClient.get(blobKeys.get(0)); validateGet(is, testFile); } } /** * Verify ssl client to ssl server upload */ @Test public void testUploadJarFilesHelper() throws Exception { uploadJarFile(BLOB_SSL_SERVER, sslClientConfig); } /** * Verify ssl client to non-ssl server failure */ @Test public void testSSLClientFailure() throws Exception { try { uploadJarFile(BLOB_SERVER, sslClientConfig); fail("SSL client connected to non-ssl server"); } catch (Exception e) { // Exception expected } } /** * Verify non-ssl client to ssl server failure */ @Test public void testSSLServerFailure() throws Exception { try { uploadJarFile(BLOB_SSL_SERVER, clientConfig); fail("Non-SSL client connected to ssl server"); } catch (Exception e) { // Exception expected } } /** * Verify non-ssl connection sanity */ @Test public void testNonSSLConnection() throws Exception { uploadJarFile(BLOB_SERVER, clientConfig); } }
apache-2.0
ww44ss/relevance
README.md
1058
# relevance this is the relevance prediction ## Kaggle prelude So many of our favorite daily activities are mediated by proprietary search algorithms. Whether you're trying to find a stream of that reality TV show on cat herding or shopping an eCommerce site for a new set of Japanese sushi knives, the relevance of search results is often responsible for your (un)happiness. Currently, small online businesses have no good way of evaluating the performance of their search algorithms, making it difficult for them to provide an exceptional customer experience. The goal of this competition is to create an open-source model that can be used to measure the relevance of search results. In doing so, you'll be helping enable small business owners to match the experience provided by more resource rich competitors. It will also provide more established businesses a model to test against. Given the queries and resulting product descriptions from leading eCommerce sites, this competition asks you to evaluate the accuracy of their search algorithms.
apache-2.0
froko/SimpleDomain
src/SimpleDomain/Common/InMemoryTraceListener.cs
2853
//------------------------------------------------------------------------------- // <copyright file="InMemoryTraceListener.cs" company="frokonet.ch"> // Copyright (C) frokonet.ch, 2014-2020 // // 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. // </copyright> //------------------------------------------------------------------------------- namespace SimpleDomain.Common { using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; /// <summary> /// A trace listener which holds all traced messages in a list /// </summary> public class InMemoryTraceListener : TraceListener { private static readonly Lazy<InMemoryTraceListener> InternalInstance = new Lazy<InMemoryTraceListener>(() => new InMemoryTraceListener()); private static readonly List<string> InternalLogMessages = new List<string>(); private static bool locked; /// <summary> /// Gets a singleton instance of this class /// </summary> public static TraceListener Instance => InternalInstance.Value; /// <summary> /// Gets all recorded log messages /// </summary> public static IEnumerable<string> LogMessages => InternalLogMessages; /// <summary> /// Clears all recorded log messages /// </summary> public static void ClearLogMessages() { WaitForUnlock(); InternalLogMessages.Clear(); } /// <summary> /// Locks the listener /// </summary> public static void Lock() { locked = true; } /// <summary> /// Unlocks the listener /// </summary> public static void Unlock() { locked = false; } /// <inheritdoc /> public override void Write(string message) { WaitForUnlock(); InternalLogMessages.Add(message); } /// <inheritdoc /> public override void WriteLine(string message) { WaitForUnlock(); InternalLogMessages.Add(message); } private static void WaitForUnlock() { while (locked) { Thread.Sleep(100); } } } }
apache-2.0
romatixo/rtishenko
README.md
11
# rtishenko
apache-2.0
spotify/bigtop
bigtop-deploy/vm/vagrant-puppet/provision.sh
458
# Install puppet agent yum -y install http://yum.puppetlabs.com/puppetlabs-release-el-6.noarch.rpm yum -y install puppet-2.7.23-1.el6.noarch # Prepare puppet configuration file cat > /bigtop-puppet/config/site.csv << EOF hadoop_head_node,$1 hadoop_storage_dirs,/data/1,/data/2 bigtop_yumrepo_uri,http://bigtop.s3.amazonaws.com/releases/0.7.0/redhat/6/x86_64 jdk_package_name,java-1.7.0-openjdk-devel.x86_64 components,hadoop,hbase EOF mkdir -p /data/{1,2}
apache-2.0
djallalserradji/inject.property
README.md
2224
# Injecting external properties into Java EE 6/7 applications A set of 2 annotations that allow to simply inject properties from properties files. ## Features: * Inject a property by simply annotating a String attribute * Annotate a class to specify the properties files to load * Alternatively, properties files can be listed in a configuration file * Supports field injection and method injection * Uses CDI to perform the injection ## Technologies * Java EE 6 with CDI 1.0 enabled ## How to build ### To build the jar mvn clean compile package ### To run integration tests mvn verify ### To build the jar and run integration tests mvn clean install ## How to use annotations * Build the jar and drop it with dependencies * Annotate the class where the injection will be performed with the @PropertiesFiles annotation, this annotation will list all the properties files that will be loaded ``` @PropertiesFiles({"file1.properties", "file2.properties"}) public MyClass { .... } ``` * alternatively you can list the files in a configuration file named inject.property.xml, this file must be available in the classpath ``` <propertiesfiles> <file>file1.properties</file> <file>file2.properties</file> .... <file>fileN.properties</file> </propertiesfiles> ``` * Annotate a String attribute (the type string is mandatory as of current version) that will receive the value of the property with the annotations @Inject and @Property("${property.key}") where ${property.key} is the key of the property in the properties file ``` @PropertiesFiles({"emails.properties"}) public MyClass { @Inject @Property("admin.email") private String adminEmail; .... } ``` * Method injection can also be used ``` @PropertiesFiles({"emails.properties"}) public MyClass { private String adminEmail; @Inject public void setAdminEmail(@Property("admin.email") String adminEmail) { this.adminEmail = adminEmail; } .... } ``` ### How it works * The files listed in the annotation @PropertiesFiles are loaded and used for the injection, the files listed in the configuration file inject.property.xml are ignored * If @PropertiesFiles is not present then inject.property.xml is used
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Brachyglottis monroi elongata/README.md
218
# Brachyglottis monroi (Hook.f.) B.Nord. var. elongata (Allan) B.Nord. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
uzmakinaruto/FirstLineCode
app/src/main/java/com/jan/flc/firstlinecode/activity/UIActivity.java
2700
package com.jan.flc.firstlinecode.activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.jan.flc.firstlinecode.R; /** * Created by huangje on 17-3-8. */ public class UIActivity extends BaseActivity { public static final String[] UI_SECTIONS = new String[]{ "常用控件", "布局-百分比布局", "ListView", "RecyclerView", "聊天界面" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chapter_ui); ListView lv = (ListView) findViewById(R.id.uiChapterList); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, UI_SECTIONS); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { switch (position) { case 0: startActivity(new Intent(UIActivity.this, BaseUIActivity.class)); break; case 1: startActivity(new Intent(UIActivity.this, PercentLayoutActivity.class)); break; case 2: startActivity(new Intent(UIActivity.this, ListViewActivity.class)); break; case 3: setRecyclerViewStyle(); break; case 4: startActivity(new Intent(UIActivity.this, ChatActivity.class)); break; default: break; } } }); } private void setRecyclerViewStyle() { AlertDialog.Builder builder = new AlertDialog.Builder(this) .setItems(new String[]{"纵向", "横向", "表格", "瀑布流"}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(UIActivity.this, RecyclerViewActivity.class); intent.putExtra("style", i); startActivity(intent); } }); builder.create().show(); } }
apache-2.0
nagyist/marketcetera
photon/photon/plugins/org.marketcetera.photon.testfragment/src/test/java/org/marketcetera/photon/quickfix/QuickFIXTest.java
2808
package org.marketcetera.photon.quickfix; import junit.framework.TestCase; import org.marketcetera.quickfix.FIXVersion; import quickfix.ConfigError; import quickfix.DataDictionary; import quickfix.FieldNotFound; import quickfix.FieldType; import quickfix.InvalidMessage; import quickfix.Message; import quickfix.field.OrderQty; import quickfix.field.Side; import quickfix.field.Symbol; public class QuickFIXTest extends TestCase { public void testMessageConstructor() throws InvalidMessage, FieldNotFound { String messageString = "8=FIX.4.29=12035=W31=17.5955=asdf268=2269=0270=17.58271=200273=01:20:04275=BGUS269=1270=17.59271=300273=01:20:04275=BGUS10=207"; Message aMessage = new Message(messageString, false); assertEquals("asdf",aMessage.getString(Symbol.FIELD)); } public void testQuickFIXAssumptions() throws ConfigError { boolean orderQtyIsInt; DataDictionary dictionary; FIXVersion version; version = FIXVersion.FIX40; dictionary = new DataDictionary(version.getDataDictionaryURL()); orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD)); assertEquals(true, orderQtyIsInt); assertTrue(FieldType.String.equals(dictionary.getFieldTypeEnum(Side.FIELD))); version = FIXVersion.FIX41; dictionary = new DataDictionary(version.getDataDictionaryURL()); orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD)); assertEquals(true, orderQtyIsInt); assertTrue(FieldType.String.equals(dictionary.getFieldTypeEnum(Side.FIELD))); version = FIXVersion.FIX42; dictionary = new DataDictionary(version.getDataDictionaryURL()); orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD)); assertEquals(false, orderQtyIsInt); assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD))); version = FIXVersion.FIX43; dictionary = new DataDictionary(version.getDataDictionaryURL()); orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD)); assertEquals(false, orderQtyIsInt); assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD))); version = FIXVersion.FIX44; dictionary = new DataDictionary(version.getDataDictionaryURL()); orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD)); assertEquals(false, orderQtyIsInt); assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD))); version = FIXVersion.FIX_SYSTEM; dictionary = new DataDictionary(version.getDataDictionaryURL()); orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD)); assertEquals(false, orderQtyIsInt); assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD))); } }
apache-2.0
sylow/google-adwords-api
examples/v201003/add_negative_campaign_criterion.rb
3158
#!/usr/bin/ruby # # Author:: [email protected] (Sérgio Gomes) # # Copyright:: Copyright 2011, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example illustrates how to create a negative campaign criterion for a # given campaign. To create a campaign, run add_campaign.rb. # # Tags: CampaignCriterionService.mutate require 'rubygems' gem 'google-adwords-api' require 'adwords_api' API_VERSION = :v201003 def add_negative_campaign_criterion() # AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml # when called without parameters. adwords = AdwordsApi::Api.new campaign_criterion_srv = adwords.service(:CampaignCriterionService, API_VERSION) campaign_id = 'INSERT_CAMPAIGN_ID_HERE'.to_i # Prepare for adding criterion. operation = { :operator => 'ADD', :operand => { # The 'xsi_type' field allows you to specify the xsi:type of the object # being created. It's only necessary when you must provide an explicit # type that the client library can't infer. :xsi_type => 'NegativeCampaignCriterion', :campaign_id => campaign_id, :criterion => { :xsi_type => 'Keyword', :text => 'jupiter cruise', :match_type => 'BROAD' } } } # Add criterion. response = campaign_criterion_srv.mutate([operation]) campaign_criterion = response[:value].first puts 'Campaign criterion id %d was successfully added.' % campaign_criterion[:criterion][:id] end if __FILE__ == $0 # To enable logging of SOAP requests, set the ADWORDSAPI_DEBUG environment # variable to 'true'. This can be done either from your operating system # environment or via code, as done below. ENV['ADWORDSAPI_DEBUG'] = 'false' begin add_negative_campaign_criterion() # Connection error. Likely transitory. rescue Errno::ECONNRESET, SOAP::HTTPStreamError, SocketError => e puts 'Connection Error: %s' % e puts 'Source: %s' % e.backtrace.first # API Error. rescue AdwordsApi::Errors::ApiException => e puts 'API Exception caught.' puts 'Message: %s' % e.message puts 'Code: %d' % e.code if e.code puts 'Trigger: %s' % e.trigger if e.trigger puts 'Errors:' if e.errors e.errors.each_with_index do |error, index| puts ' %d. Error type is %s. Fields:' % [index + 1, error[:xsi_type]] error.each_pair do |field, value| if field != :xsi_type puts ' %s: %s' % [field, value] end end end end end end
apache-2.0
vobruba-martin/closure-compiler
test/com/google/javascript/jscomp/RewriteNewDotTargetTest.java
4093
/* * Copyright 2019 The Closure Compiler Authors. * * 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 com.google.javascript.jscomp; import static com.google.javascript.jscomp.Es6ToEs3Util.CANNOT_CONVERT_YET; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link RewriteNewDotTarget}. */ @RunWith(JUnit4.class) @SuppressWarnings("RhinoNodeGetFirstFirstChild") public class RewriteNewDotTargetTest extends CompilerTestCase { @Before public void enableTypeCheckBeforePass() { enableTypeCheck(); enableTypeInfoValidation(); } @Override protected CompilerPass getProcessor(Compiler compiler) { return new RewriteNewDotTarget(compiler); } @Override protected CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.setLanguageIn(LanguageMode.ECMASCRIPT_NEXT_IN); options.setLanguageOut(LanguageMode.ECMASCRIPT5_STRICT); return options; } @Test public void testNewTargetInNonConstructorMethod() { testError( lines( "", // "/** @constructor */", "function Foo() { new.target; }", // not an ES6 class constructor ""), CANNOT_CONVERT_YET); testError( "function foo() { new.target; }", // not a constructor at all CANNOT_CONVERT_YET); testError( lines( "", // "class Foo {", " method() {", // not a constructor " new.target;", " }", "}", ""), CANNOT_CONVERT_YET); } @Test public void testNewTargetInEs6Constructor() { test( lines( "", // "class Foo {", " constructor() {", " new.target;", " () => new.target;", // works in arrow functions, too " }", "}", ""), lines( "", // "class Foo {", " constructor() {", " this.constructor;", " () => this.constructor;", // works in arrow functions, too " }", "}", "")); } @Test public void testNewTargetInEs6Constructor_superCtorReturnsObject() { // TODO(b/157140030): This is an unexpected behaviour change. test( lines( "/** @constructor */", "function Base() {", " return {};", "}", "", "class Child extends Base {", " constructor() {", " super();", " new.target;", // Child " }", "}"), lines( "/** @constructor */", "function Base() {", " return {};", "}", "", "class Child extends Base {", " constructor() {", " super();", " this.constructor;", // Object " }", "}")); } @Test public void testNewTargetInEs6Constructor_beforeSuper() { test( lines( "class Foo extends Object {", " constructor() {", " new.target;", " super();", " }", "}"), lines( "class Foo extends Object {", " constructor() {", " this.constructor;", // `this` before `super` " super();", " }", "}")); } }
apache-2.0
Kiandr/MS
Languages/CSharp/CPCWS_DotNet_Samples/REST/serviceinfo/GetOutletServiceInfo/GetOutletServiceInfo.cs
4631
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Xml.Serialization; using System.Configuration; using System.IO; namespace GetServiceInfo { class GetOutletServiceInfo { static void Main(string[] args) { // Your username, password and customer number are imported from the following file // CPCWS_ServiceInfo_DotNet_Samples\REST\serviceinfo\user.xml var username = ConfigurationSettings.AppSettings["username"]; var password = ConfigurationSettings.AppSettings["password"]; // REST URI String url = "https://ct.soa-gw.canadapost.ca/rs/serviceinfo/outlet"; var method = "GET"; // HTTP Method String responseAsString = ".NET Framework " + Environment.Version.ToString() + "\r\n\r\n"; try { // Create REST Request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; // Set Basic Authentication Header using username and password variables string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password)); request.Headers = new WebHeaderCollection(); request.Headers.Add("Authorization", auth); request.Headers.Add("Accept-Language", "en-CA"); request.Accept = "application/vnd.cpc.serviceinfo-v2+xml"; // Execute REST Request HttpWebResponse response = (HttpWebResponse)request.GetResponse(); responseAsString += "HTTP Response Status: " + (int)response.StatusCode + "\r\n\r\n"; // Deserialize xml response to customer object XmlSerializer serializer = new XmlSerializer(typeof(InfoMessagesType)); TextReader reader = new StreamReader(response.GetResponseStream()); InfoMessagesType infoMessages = (InfoMessagesType)serializer.Deserialize(reader); if (infoMessages.infomessage != null) { foreach (InfoMessageType infoMessage in infoMessages.infomessage) { responseAsString += " Message Type is :" + infoMessage.messagetype + "\r\n"; responseAsString += " Message Text is :" + infoMessage.messagetext + "\r\n"; responseAsString += " Message Start Time is :" + infoMessage.fromdatetime + "\r\n"; responseAsString += " Message End Time is :" + infoMessage.todatetime + "\r\n"; } } } catch (WebException webEx) { HttpWebResponse response = (HttpWebResponse)webEx.Response; if (response != null) { responseAsString += "HTTP Response Status: " + webEx.Message + "\r\n"; // Retrieve errors from messages object try { // Deserialize xml response to messages object XmlSerializer serializer = new XmlSerializer(typeof(messages)); TextReader reader = new StreamReader(response.GetResponseStream()); messages myMessages = (messages)serializer.Deserialize(reader); if (myMessages.message != null) { foreach (var item in myMessages.message) { responseAsString += "Error Code: " + item.code + "\r\n"; responseAsString += "Error Msg: " + item.description + "\r\n"; } } } catch (Exception ex) { // Misc Exception responseAsString += "ERROR: " + ex.Message; } } else { // Invalid Request responseAsString += "ERROR: " + webEx.Message; } } catch (Exception ex) { // Misc Exception responseAsString += "ERROR: " + ex.Message; } Console.WriteLine(responseAsString); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } } }
apache-2.0