language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 1,711 | 1.9375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2012 the original author or 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 org.openehealth.ipf.commons.ihe.xds.core.metadata;
import lombok.EqualsAndHashCode;
/**
* Type of a document entry.
* @author Dmytro Rud
*/
@EqualsAndHashCode(callSuper = true)
public class DocumentEntryType extends XdsEnum {
private static final long serialVersionUID = -5941669064647018977L;
public static final DocumentEntryType STABLE = new DocumentEntryType(Type.OFFICIAL, "urn:uuid:7edca82f-054d-47f2-a032-9b2a5b5186c1");
public static final DocumentEntryType ON_DEMAND = new DocumentEntryType(Type.OFFICIAL, "urn:uuid:34268e47-fdf5-41a6-ba33-82133c465248");
public static final DocumentEntryType[] OFFICIAL_VALUES = {STABLE, ON_DEMAND};
public static final String[] STABLE_OR_ON_DEMAND = {STABLE.getEbXML30(), ON_DEMAND.getEbXML30()};
public DocumentEntryType(Type type, String ebXML) {
super(type, ebXML);
}
@Override
public String getJaxbValue() {
if (this == STABLE) {
return "stable";
}
if (this == ON_DEMAND) {
return "on-demand";
}
return getEbXML30();
}
}
|
TypeScript
|
UTF-8
| 1,061 | 2.53125 | 3 |
[] |
no_license
|
const {ccclass, property} = cc._decorator;
@ccclass
export default class MyGame extends cc.Component {
@property(cc.Node)
private titleNode:cc.Node=null;
@property(cc.Node)
private selectLevelNode:cc.Node=null;
@property([cc.Node])
private levelIntroList:cc.Node[]=[];
@property(cc.Node)
private winUINode:cc.Node=null;
@property(cc.Node)
private failureUINode:cc.Node=null;
private _level:number=1;
private _score:number;
public start():void{
this.gotoTitle();
}
public gotoTitle():void{
this.titleNode.active=true;
}
public gotoSelectLevel():void{
this.selectLevelNode.active=true;
}
public gotoLevel(level:number):void{
this._score=0;
this._level=level;
this.levelIntroList[level-1].active=true;
}
public win():void{
this.winUINode.active=true;
}
public failure():void{
this.failureUINode.active=true;
}
public get level():number{return this._level;}
}
|
Java
|
UTF-8
| 2,847 | 2.140625 | 2 |
[] |
no_license
|
package com.honglu.quickcall.user.web.filter;
import com.alibaba.fastjson.JSONObject;
import com.honglu.quickcall.account.facade.code.AccountBizReturnCode;
import com.honglu.quickcall.common.api.exception.BizException;
import com.honglu.quickcall.common.api.util.ConstantUtils;
import com.honglu.quickcall.common.api.util.DES3Utils;
import com.honglu.quickcall.common.api.util.HttpHelper;
import com.honglu.quickcall.user.facade.code.UserBizReturnCode;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.Charset;
/**
* Created with antnest-platform
*/
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request, HttpServletResponse response) throws IOException {
super(request);
JSONObject object = null;
String str = "";
try {
String in = HttpHelper.getBodyString(request);
if (StringUtils.isBlank(in)) {
HttpHelper.getFailData(response, "参数不能为空");
throw new BizException(UserBizReturnCode.paramError);
}
if (in.indexOf("%") != -1) {
str = DES3Utils.decryptMode(URLDecoder.decode(in), ConstantUtils.THREEDES_KEY);
} else {
str = DES3Utils.decryptMode(in, ConstantUtils.THREEDES_KEY);
}
object = JSONObject.parseObject(str);
if (!object.containsKey("sign") || !object.containsKey("data")) {
HttpHelper.getFailData(response, "签名或data参数格式错误");
throw new BizException(UserBizReturnCode.paramError);
}
} catch (Exception e) {
HttpHelper.getFailData(response, "参数错误");
throw new BizException(UserBizReturnCode.paramError);
}
try {
if (!DES3Utils.checkSign(str, object.getString("sign"))) {
HttpHelper.getFailData(response, "验签不正确");
throw new BizException(UserBizReturnCode.CheckSignError);
}
} catch (Exception e) {
e.printStackTrace();
}
body = object.getString("data").getBytes(Charset.forName("UTF-8"));
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
};
}
}
|
Java
|
UTF-8
| 10,403 | 1.84375 | 2 |
[] |
no_license
|
package com.example.friedegg.adapter;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.friedegg.R;
import com.example.friedegg.activity.CommentListActivity;
import com.example.friedegg.activity.VideoDetailActivity;
import com.example.friedegg.base.BaseActivity;
import com.example.friedegg.base.ConstantString;
import com.example.friedegg.cache.MyVideoCache;
import com.example.friedegg.callback.LoadFinishCallBack;
import com.example.friedegg.callback.LoadResultCallBack;
import com.example.friedegg.modul.CommentNumber;
import com.example.friedegg.modul.Video;
import com.example.friedegg.net.JSONParser;
import com.example.friedegg.okhttp.CommentCountsParser;
import com.example.friedegg.okhttp.OkHttpCallback;
import com.example.friedegg.okhttp.OkHttpProxy;
import com.example.friedegg.okhttp.VideoParser;
import com.example.friedegg.utils.NetWorkUtil;
import com.example.friedegg.utils.ShareUtils;
import com.example.friedegg.utils.ShowToast;
import com.example.friedegg.view.imageloader.ImageLoaderProxy;
import java.util.ArrayList;
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {
private int page;
private ArrayList<Video> mVideos;
private int lastPosition = -1;
private Activity mActivity;
private LoadResultCallBack mLoadResultCallBack;
private LoadFinishCallBack mLoadFinisCallBack;
public VideoAdapter(Activity activity, LoadResultCallBack loadResultCallBack, LoadFinishCallBack loadFinisCallBack) {
mActivity = activity;
mLoadFinisCallBack = loadFinisCallBack;
mLoadResultCallBack = loadResultCallBack;
mVideos = new ArrayList<>();
}
private void setAnimation(View viewToAnimation, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(viewToAnimation.getContext(), R.anim.item_bottom_in);
viewToAnimation.setAnimation(animation);
lastPosition = position;
}
}
@Override
public void onViewDetachedFromWindow(VideoViewHolder holder) {
super.onViewDetachedFromWindow(holder);
holder.card.clearAnimation();
}
@Override
public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_video, parent, false);
return new VideoViewHolder(v);
}
@Override
public void onBindViewHolder(VideoViewHolder holder, int position) {
final Video video = mVideos.get(position);
holder.tv_title.setText(video.getTitle());
holder.tv_comment_count.setText(video.getComment_count());
ImageLoaderProxy.displayImageWithLoadingPicture(video.getImgUrl(), holder.img, R.drawable.ic_loading_small);
//用于恢复默认的文字
holder.tv_like.setText(video.getVote_positive());
holder.tv_like.setTypeface(Typeface.DEFAULT);
holder.tv_like.setTextColor(mActivity.getResources().getColor(R.color.secondary_text_default_material_light));
holder.tv_support_des.setTextColor(mActivity.getResources().getColor(R.color.secondary_text_default_material_light));
holder.tv_unlike.setText(video.getVote_negative());
holder.tv_unlike.setTypeface(Typeface.DEFAULT);
holder.tv_unlike.setTextColor(mActivity.getResources().getColor(R.color.secondary_text_default_material_light));
holder.tv_un_support_des.setTextColor(mActivity.getResources().getColor(R.color.secondary_text_default_material_light));
holder.ll_comment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, CommentListActivity.class);
intent.putExtra(BaseActivity.DATA_THREAD_KEY, "comment-" + video.getComment_ID());
mActivity.startActivity(intent);
}
});
holder.img_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new AlertDialog.Builder(mActivity).setItems(R.array.joke_dialog, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
ShareUtils.shareText(mActivity, video.getTitle().trim() + " " + video.getUrl());
break;
case 1:
ClipboardManager clip = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
clip.setPrimaryClip(ClipData.newPlainText(null, video.getUrl()));
ShowToast.Short(ConstantString.COPY_SUCCESS);
break;
}
}
}).show();
}
});
holder.card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, VideoDetailActivity.class);
intent.putExtra("url", video.getUrl());
mActivity.startActivity(intent);
}
});
setAnimation(holder.card, position);
}
@Override
public int getItemCount() {
return mVideos.size();
}
public void loadFirst() {
page = 1;
loadDataByNetworkType();
}
public void loadNextPage() {
page++;
loadDataByNetworkType();
}
private void loadDataByNetworkType() {
if (NetWorkUtil.isNetWorkConnected(mActivity)) {
loadData();
} else {
loadCache();
}
}
private void loadData() {
OkHttpProxy.get(Video.getUrlVideos(page), mActivity, new OkHttpCallback<ArrayList<Video>>(new VideoParser()) {
@Override
public void onSuccess(int code, ArrayList<Video> videos) {
getCommentCounts(videos);
}
@Override
public void onFailure(int code, String msg) {
mLoadFinisCallBack.loadFinish(null);
}
});
}
private void loadCache() {
mLoadResultCallBack.onSuccess(LoadResultCallBack.SUCCESS_OK, null);
mLoadFinisCallBack.loadFinish(null);
MyVideoCache videoCacheUtil = MyVideoCache.getInstance(mActivity);
if (page == 1) {
mVideos.clear();
ShowToast.Short(ConstantString.LOAD_NO_NETWORK);
}
mVideos.addAll(videoCacheUtil.getCacheByPage(page));
notifyDataSetChanged();
}
//获取评论数量
private void getCommentCounts(final ArrayList<Video> videos) {
StringBuilder sb = new StringBuilder();
for (Video video : videos) {
sb.append("comment-" + video.getComment_ID() + ",");
}
OkHttpProxy.get(CommentNumber.getCommentCountsURL(sb.toString()), mActivity, new OkHttpCallback<ArrayList<CommentNumber>>(new CommentCountsParser()) {
@Override
public void onSuccess(int code, ArrayList<CommentNumber> commentNumbers) {
mLoadResultCallBack.onSuccess(LoadResultCallBack.SUCCESS_OK, null);
mLoadFinisCallBack.loadFinish(null);
for (int i = 0; i < videos.size(); i++) {
videos.get(i).setComment_count(commentNumbers.get(i).getComments() + "");
}
if (page == 1) {
mVideos.clear();
MyVideoCache.getInstance(mActivity).clearAllCache();
}
mVideos.addAll(videos);
notifyDataSetChanged();
MyVideoCache.getInstance(mActivity).addResultCache(JSONParser.toString
(videos), page);
//防止加载不到一页的情况
if (mVideos.size() < 10) {
loadNextPage();
}
}
@Override
public void onFailure(int code, String msg) {
mLoadFinisCallBack.loadFinish(null);
mLoadResultCallBack.onError(LoadResultCallBack.ERROR_NET, msg);
}
});
}
static class VideoViewHolder extends RecyclerView.ViewHolder {
private TextView tv_title;
private TextView tv_like;
private TextView tv_unlike;
private TextView tv_comment_count;
private TextView tv_un_support_des;
private TextView tv_support_des;
private ImageView img_share;
private ImageView img;
private LinearLayout ll_comment;
private CardView card;
public VideoViewHolder(View contentView) {
super(contentView);
img = (ImageView) contentView.findViewById(R.id.img);
tv_title = (TextView) contentView.findViewById(R.id.tv_title);
tv_like = (TextView) contentView.findViewById(R.id.tv_like);
tv_unlike = (TextView) contentView.findViewById(R.id.tv_unlike);
tv_comment_count = (TextView) contentView.findViewById(R.id.tv_comment_count);
tv_un_support_des = (TextView) contentView.findViewById(R.id.tv_unsupport_des);
tv_support_des = (TextView) contentView.findViewById(R.id.tv_support_des);
img_share = (ImageView) contentView.findViewById(R.id.img_share);
ll_comment = (LinearLayout) contentView.findViewById(R.id.ll_comment);
card = (CardView) contentView.findViewById(R.id.card);
}
}
}
|
PHP
|
UTF-8
| 484 | 2.8125 | 3 |
[] |
no_license
|
<?php
namespace SimUDuck;
use SimUDuck\Fly\FlyWithWings;
use SimUDuck\Quack\Quack;
/**
* MallardDuck can swim, Quack, fly.
*/
class MallardDuck extends AbstractDuck
{
/**
* Init fly and quack behavior.
*/
public function __construct()
{
$this->flyBehavior = new FlyWithWings();
$this->quackBehavior = new Quack();
}
/**
* {@inheritdoc}
*/
public function display(): string
{
return 'I am Mallard Duck.';
}
}
|
PHP
|
UTF-8
| 3,053 | 2.9375 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace App\CryptoGatewayEngine\WalletGenerator\Util;
class TronHelper
{
public static function getBase58CheckAddress(string $addressBin): string
{
$checksum = substr(self::makeHash(self::makeHash($addressBin)), 0, 4);
$checksum = $addressBin . $checksum;
return self::encodeByNum(self::bin2bc($checksum));
}
public static function makeHash(string $data, bool $raw = true): string
{
return hash('sha256', $data, $raw);
}
public static function dec2base(string $dec, int $base, ?string $digits = null): string
{
if (extension_loaded('bcmath')) {
if ($base < 2 || $base > 256) {
die('Invalid Base: ' . $base);
}
bcscale(0);
$value = "";
if (!$digits) {
$digits = self::digits($base);
}
while ($dec > $base - 1) {
$rest = bcmod($dec, (string)$base);
$dec = bcdiv($dec, (string)$base);
$value = $digits[$rest] . $value;
}
return $digits[intval($dec)] . $value;
} else {
die('Please install BCMATH');
}
}
public static function base2dec(string $value, int $base, ?string $digits = null): string
{
if (extension_loaded('bcmath')) {
if ($base < 2 || $base > 256) {
die('Invalid Base: ' . $base);
}
bcscale(0);
if ($base < 37) {
$value = strtolower($value);
}
if (!$digits) {
$digits = self::digits($base);
}
$size = strlen($value);
$dec = '0';
for ($loop = 0; $loop < $size; $loop++) {
$element = strpos($digits, $value[$loop]);
$power = bcpow((string)$base, (string)($size - $loop - 1));
$dec = bcadd($dec, bcmul((string)$element, $power));
}
return $dec;
} else {
die('Please install BCMATH');
}
}
public static function digits(int $base): string
{
if ($base > 64) {
$digits = "";
for ($loop = 0; $loop < 256; $loop++) {
$digits .= chr($loop);
}
} else {
$digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
}
$digits = substr($digits, 0, $base);
return (string)$digits;
}
public static function bin2bc(string $num): string
{
return self::base2dec($num, 256);
}
public static function encodeByNum(string $num, int $length = 58): string
{
return self::dec2base($num, $length, '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
}
public static function decodeByAddress(string $address, int $length = 58): string
{
return self::base2dec($address, $length, '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
}
}
|
Java
|
UTF-8
| 306 | 1.796875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.glh.glwdialog;
/**
* <pre>
* author : 高磊华
* e-mail : 984992087@qq.com
* time : 2018/08/13
* desc : 拍照中的按钮 被点击后 的回调监听
* </pre>
*/
public interface OnTakePhotoDialogLitener {
void onTakePhotoDialogTypeClick(int mPlatform);
}
|
JavaScript
|
UTF-8
| 579 | 2.78125 | 3 |
[
"WTFPL"
] |
permissive
|
/* global document window */
// const ready = require('../../js/utils/documentReady.js');
// ready(function(){
//
// });
window.addEventListener('DOMContentLoaded', function () {
let likeBtn = document.querySelectorAll('.likeBtn');
likeBtn.forEach(function (elem) {
let span = elem.querySelector('.likeBtn__span');
if (+span.textContent > 10) {
span.classList.add('likeBtn__span--purple');
elem.classList.add('likeBtn--purple');
} else {
span.classList.remove('likeBtn__span--purple');
elem.classList.remove('likeBtn--purple');
}
});
});
|
Python
|
UTF-8
| 3,441 | 2.953125 | 3 |
[] |
no_license
|
from pymysql import *
from hashlib import *
from redis import *
class MYSQL(object):
def __init__(self):
self.con = connect(host='localhost', port=3306,
database='python_info', user='root',
password='mysql', charset='utf8')
self.cur = self.con.cursor()
self.flag = ["mysql", "登录成功", ""]
def close(self):
self.cur.close()
self.con.close()
def login(self, user_name, sha_pwd):
try:
cur = self.cur
param = [user_name]
select_sql = 'select upwd from py_users where uname = %s'
cur.execute(select_sql, param)
res = cur.fetchone()
# print(res)
if res:
if res[0] != sha_pwd:
self.flag[1] = "登录失败"
self.flag[2] = "密码错误"
data_man = DataMan(user_name, sha_pwd)
data_man.update()
else:
self.flag[1] = "登录失败"
self.flag[2] = "用户不存在"
# return self.flag
except Exception as e:
print(e)
self.flag[1] = "登录失败"
self.flag[2] = e
finally:
return self.flag
def get_right_pwd(self, user_name):
res = None
try:
cur = self.cur
param = [user_name]
select_sql = 'select upwd from py_users where uname = %s'
cur.execute(select_sql, param)
pwd = cur.fetchone()
if pwd:
res = pwd[0]
except Exception as e:
print(e)
finally:
return res
class REDIS(object):
def __init__(self):
self.client = StrictRedis()
self.flag = ["redis", "登录成功", ""]
def login(self, user_name, sha_pwd):
res = self.client.get(user_name)
if res:
if res.decode() != sha_pwd:
sql_pwd = DataMan(user_name, sha_pwd)
new_pwd = sql_pwd.get_right_pwd()
if new_pwd != sha_pwd:
self.flag[1] = "登录失败"
self.flag[2] = "密码错误"
else:
self.client.set(user_name, new_pwd)
else:
sql_sea = DataMan(user_name, sha_pwd)
self.flag = sql_sea.search()
return self.flag
class DataMan(object):
def __init__(self, user_name, sha_pwd):
self.user_name = user_name
self.sha_pwd = sha_pwd
def update(self):
redis_update = REDIS()
redis_update.client.set(self.user_name, self.sha_pwd)
def search(self):
sql_sea = MYSQL()
flag = sql_sea.login(self.user_name, self.sha_pwd)
sql_sea.close()
return flag
def get_right_pwd(self):
sql_pwd = MYSQL()
new_pwd = sql_pwd.get_right_pwd(self.user_name)
sql_pwd.close()
return new_pwd
def get_user():
usr_name = input("请输入用户名:")
usr_pwd = input("请输入密码:")
s1 = sha1()
s1.update(usr_pwd.encode())
sha_pwd = s1.hexdigest()
return usr_name, sha_pwd
if __name__ == '__main__':
user = get_user()
# sql_data = MYSQL()
redis_data = REDIS()
# sql_flag = sql_data.login(*user)
redis_flag = redis_data.login(*user)
print(redis_flag)
# print(sql_flag)
|
Markdown
|
UTF-8
| 922 | 3.125 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
# Discounts
Discounts can be:
* Temporary price markdowns - restricted by various chosen constraints.
* Coupon/Voucher codes - unique code entered at checkout, and can also be restriced to the same various constraints.
The discount actions can be either marking down by percent or a fixed amount.
These markdowns can apply to either each item, the items subtotal, or the shipping cost.
## Constraints
* Products
* Categories
* Date / time
* Membership group
* Number of uses
* Order value
* Address zone
### How it works
When the user enters a coupon at the checkout, the coupon will check that the given order matches
its criteria. First global criteria (like the current date) will be checked, and then it will
check that at least one item in the cart matches the item citeria (eg product is from particular category).
### System Restrictions
* Multiple coupons cannot be used for a single product.
|
Python
|
UTF-8
| 289 | 2.9375 | 3 |
[] |
no_license
|
#暴力
#hash表
def many(s:str):
dic = {}
for i in range(len(s)):
if s[i] not in dic:
dic[s[i]] = 1
else:
dic[s[i]] += 1
for i in s:
if dic[i] == 1:
return s.index(i)
return -1
print(many('aabcc'))
#count数组
|
SQL
|
WINDOWS-1251
| 2,228 | 3.46875 | 3 |
[] |
no_license
|
PROMPT =====================================================================================
PROMPT *** Run *** ========== Scripts /Sql/BARS/function/nbs_vp.sql =========*** Run *** ===
PROMPT =====================================================================================
CREATE OR REPLACE FUNCTION BARS.NBS_VP
(nbs_ accounts.nbs%type, --3800
ob22_ accounts.ob22%type, --OB22
kv_ accounts.kv%type) --KV
return accounts.nls%type is --3801
nls_ accounts.nls%type := null ;
branch_ branch.branch%type;
acc3800_ accounts.acc%type;
nls3801_ accounts.nls%type;
/*
3801 VP_LIST
3800/22
*/
begin
-- 3800 22
begin
branch_ := sys_context('bars_context','user_branch');
if length(branch_) = 8 then
branch_:= branch_||'000000/';
end if;
nls_ := nbs_ob22_null(nbs_, ob22_, branch_);
-------------------
if nls_ is null then
raise_application_error(
-20203,
'\9356 - ='|| NBS_||' OB22='||OB22_||' = ' || BRANCH_,
TRUE);
end if;
end;
-- 3800
Begin
select acc into acc3800_ from accounts
where nls=nls_ and kv=kv_;
if acc3800_ is null then
raise_application_error(
-20203,
'\9356 - '|| NLS_||' KV = ' || kv_,
TRUE);
end if;
end;
begin
select nls into nls3801_ from accounts
where acc = (select acc3801 from vp_list where acc3800=acc3800_);
if nls3801_ is null then
raise_application_error(
-20203,
'\9356 - 3801',
TRUE);
end if;
end;
return nls3801_;
end nbs_vp;
/
show err;
PROMPT =====================================================================================
PROMPT *** End *** ========== Scripts /Sql/BARS/function/nbs_vp.sql =========*** End *** ===
PROMPT =====================================================================================
|
Shell
|
UTF-8
| 3,122 | 3.8125 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
set -xv
#adam-BL# . BonnLogger.sh
#adam-BL# . log_start
# CVSId: $Id$
# 30.06.2008 (AvdL):
# normalizes images by the highest mode value of the
# individual chips
# the script creates normaliced images.
# It puts the result into new directories ..._norm.
# The script assumes a threshhold. Pixels under
# this threshhold will be assigned a value of threshhold
# in the resulting images.
#
# 30.05.04:
# temporary files go to a TEMPDIR directory
#
# 12.04.2005:
# - I rewrote the script so that it works with the
# 'imstats' program instead with the FLIPS based
# 'immode'.
# - I substituted XMIN etc. by STATSXMIN etc. that are
# now defined in the in the instrument initialisation
# files.
#
# 13.09.2005:
# If a camera has more than 10 chips, results were not correct.
# $1: main directory
# $2: directory from which normaliced images should be created
# $3: file prefix
# $4: file suffix
. ${INSTRUMENT:?}.ini
ls -1 $1/$2/$3*_2${4}.fits | sed s/_2${4}.fits//g > filelist_$$
# create the new directory for the normalized images if
# it does not exist already
if [ ! -d "/$1/$2_norm" ]; then
mkdir "/$1/$2_norm"
fi
cat filelist_$$ |\
{
while read image
do
base=`basename ${image}`
# first calculate the modes:
FILES=""
for ((i=1;i<=${NCHIPS};i+=1));
do
if [ ! -f $1/$2/${base}_${i}$4.fits ]; then
mode2=`imstats -s 800 1200 1800 2200 -t 0 22000 $1/$2/${base}_2$4.fits | awk '{if($1!~"#") print $2}'`
${P_IC} -c ${SIZEX[${i}]} ${SIZEY[${i}]} ${mode2} > $1/$2/${base}_${i}$4.fits
fi
FILES="${FILES} $1/$2/${base}_${i}${4}.fits"
done
echo $FILES
${P_IMSTATS} ${FILES} -s \
${STATSXMIN} ${STATSXMAX} ${STATSYMIN} ${STATSYMAX} -o \
${TEMPDIR}/immode.dat_$$
exit_code=$?
if [ $exit_code -ne 0 ]; then
#adam-BL# log_status $exit_code "IMSTATS failure"
echo "adam-look | error: IMSTATS failure"
exit $exit_code
fi
# set the normalization to the highest mode value
NORM=`${P_GAWK} 'BEGIN {max=0} ($1!="#") {if ($2>max) max=$2} END {print max}' \
${TEMPDIR}/immode.dat_$$`
# Set the threshold to 20% of the smallest mode value. Note
# that only the chips in the current parallelisation node
# contribute.
THRESH=`${P_GAWK} '($1!="#") {print $2}' ${TEMPDIR}/immode.dat_$$ |\
${P_GAWK} 'BEGIN{min=1000000} {if ($1<min) min=$1} END {print 0.2*min}'`
i=1
while [ ${i} -le ${NCHIPS} ]
do
# if [ -L "/$1/$2/$2_${i}.fits" ]; then
# LINK=`${P_READLINK} /$1/$2/$2_${i}.fits`
# RESULTDIR=`dirname ${LINK}`
# ln -s ${RESULTDIR}/$2_norm_${i}.fits /$1/$2_norm/$2_norm_${i}.fits
# else
RESULTDIR=/$1/$2_norm/
# fi
${P_IC} '%1 '${NORM}' / '${THRESH}' %1 '${THRESH}' > ?' /$1/$2/${base}_${i}${4}.fits > \
${RESULTDIR}/${base}_${i}${4}N.fits
exit_code=$?
if [ $exit_code -ne 0 ]; then
#adam-BL# log_status $exit_code 'IC Failure'
echo 'adam-look | error: IC Failure'
exit $exit_code
fi
i=$(( $i + 1 ))
done
rm -f ${TEMPDIR}/immode.dat_$$
done
}
#adam-BL# log_status $?
|
Java
|
UTF-8
| 991 | 2.625 | 3 |
[] |
no_license
|
package de.stevenschwenke.java.javafx.workLifeBalance.client;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Holds all the data for one day.
*
* @author Steven Schwenke
*
*/
public class DayRecord {
private Long id;
private Date date;
private List<TimeRecord> timeRecordsToday = new ArrayList<TimeRecord>(4);
private DayRecord() {
super();
}
public DayRecord(Date date) {
super();
this.date = date;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<TimeRecord> getTimeRecordsToday() {
return timeRecordsToday;
}
public void setTimeRecordsToday(List<TimeRecord> timeRecordsToday) {
this.timeRecordsToday = timeRecordsToday;
}
public void addTimeRecord(TimeRecord newRecord) {
timeRecordsToday.add(newRecord);
}
}
|
Markdown
|
UTF-8
| 990 | 3.40625 | 3 |
[] |
no_license
|
---
title: "The :target pseudo-class"
date: 2018-04-27T14:50:03-04:00
draft: false
---
I just learned about the `:target` pseudo-class in CSS and it is pretty amazing. It targets the element with an id equal to the URL's fragment (the hash part at the end.) This can be used with plain old links to create features that would normally require JavaScript. [This CodePen shows a hamburger menu implemented with it.](https://codepen.io/markcaron/pen/pPZVWO)
The way this works is brilliant. The hamburger icon is a link to `#main-menu`. When clicked, the URL changes to have the fragment `#main-menu` without reloading the page, as fragment changes don't trigger a reload. The element with the id `main-menu` is normally positioned 200px left of the page, so that it's hidden, but `#main-menu:target` is positioned on the page, so as that URL fragment changes, the menu appears. The menu can be closed by clicking a link that doesn't have that fragment, thereby making the menu disappear.
|
PHP
|
UTF-8
| 803 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Filters;
use Atnic\LaravelGenerator\Filters\BaseFilter;
/**
* DatumFilter Filter
*/
class DatumFilter extends BaseFilter
{
/**
* Searchable Field
* @var array
*/
protected $searchables = [
'dataset' => [ 'name' ],
'parameter' => [ 'name' ],
'value',
'logged_at',
];
/**
* Sortables Field
* @var array
*/
protected $sortables = [
'id',
'dataset.name',
'parameter.name',
'value',
'logged_at',
'created_at',
'updated_at',
];
/**
* Default Sort
* @var string|null
*/
protected $default_sort = 'logged_at,desc';
/**
* Default per page
* @var int|null
*/
protected $default_per_page = null;
}
|
Java
|
UTF-8
| 3,319 | 2.296875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.medibloc.vc.verifiable.jwt;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
import org.junit.Test;
import org.medibloc.vc.VerifiableCredentialException;
import org.medibloc.vc.model.Presentation;
import org.medibloc.vc.model.PresentationTest;
import java.net.MalformedURLException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class JwtVerifiablePresentationTest {
@Test
public void createAndVerify() throws MalformedURLException, VerifiableCredentialException, JOSEException {
Presentation presentation = PresentationTest.buildPresentation();
ECKey ecJWK = new ECKeyGenerator(Curve.SECP256K1).generate();
final String nonce = "this-is-random";
JwtVerifiablePresentation vp = new JwtVerifiablePresentation(
presentation, "ES256K", presentation.getHolder() + "#key1", ecJWK.toECPrivateKey(), nonce
);
assertNotNull(vp);
System.out.println(vp.serialize());
assertEquals(presentation, vp.getPresentation());
vp.verify(ecJWK.toECPublicKey(), presentation.getVerifier(), nonce);
assertEquals(vp.getJwt(), vp.serialize());
}
@Test(expected = VerifiableCredentialException.class)
public void signatureVerificationFailure() throws MalformedURLException, VerifiableCredentialException, JOSEException {
Presentation presentation = PresentationTest.buildPresentation();
ECKey ecJWK1 = new ECKeyGenerator(Curve.SECP256K1).generate();
final String nonce = "this-is-random";
JwtVerifiablePresentation vp = new JwtVerifiablePresentation(
presentation, "ES256K", presentation.getHolder() + "#key1", ecJWK1.toECPrivateKey(), nonce
);
ECKey ecJWK2 = new ECKeyGenerator(Curve.SECP256K1).generate();
vp.verify(ecJWK2.toECPublicKey(), presentation.getVerifier(), nonce);
}
@Test(expected = VerifiableCredentialException.class)
public void verifierVerificationFailure() throws MalformedURLException, VerifiableCredentialException, JOSEException {
Presentation presentation = PresentationTest.buildPresentation();
ECKey ecJWK = new ECKeyGenerator(Curve.SECP256K1).generate();
final String nonce = "this-is-random";
JwtVerifiablePresentation vp = new JwtVerifiablePresentation(
presentation, "ES256K", presentation.getHolder() + "#key1", ecJWK.toECPrivateKey(), nonce
);
vp.verify(ecJWK.toECPublicKey(), "wrong-verifier", nonce);
}
@Test(expected = VerifiableCredentialException.class)
public void nonceVerificationFailure() throws MalformedURLException, VerifiableCredentialException, JOSEException {
Presentation presentation = PresentationTest.buildPresentation();
ECKey ecJWK = new ECKeyGenerator(Curve.SECP256K1).generate();
final String nonce = "this-is-random";
JwtVerifiablePresentation vp = new JwtVerifiablePresentation(
presentation, "ES256K", presentation.getHolder() + "#key1", ecJWK.toECPrivateKey(), nonce
);
vp.verify(ecJWK.toECPublicKey(), presentation.getVerifier(), "wrong-nonce");
}
}
|
SQL
|
UTF-8
| 862 | 3.796875 | 4 |
[
"MIT"
] |
permissive
|
SELECT COUNT(*) FROM books;
SELECT released_year, COUNT(*) FROM books GROUP BY released_year;
SELECT SUM(stock_quantity) FROM books;
SELECT CONCAT(author_fname, ' ', author_lname) AS author, AVG(released_year)
FROM books
GROUP BY author;
SELECT CONCAT(author_fname, ' ', author_lname) AS full_name
FROM books
ORDER BY pages DESC
LIMIT 1;
SELECT released_year AS year, COUNT(*) AS '\# books' , AVG(pages) AS 'avg pages'
FROM books
GROUP BY released_year;
## ==============
CREATE TABLE inventory (
item_name VARCHAR(100),
price DECIMAL(8, 2),
quantity INT
);
SELECT NOW();
SELECT CURDATE();
SELECT DAYOFWEEK(CURDATE());
SELECT DAYNAME(CURDATE());
SELECT DATE_FORMAT(CURDATE(), '%m/%d/%Y');
SELECT DATE_FORMAT(NOW(), '%M %D at %h:%i');
CREATE TABLE tweets(
content VARCHAR(100),
username VARCHAR(100),
created_at TIMESTAMP DEFAULT NOW()
);
|
C#
|
UTF-8
| 1,927 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace SuperFastDB.Data
{
public class FastDBTransaction : IDbTransaction
{
public IDbConnection Connection => throw new NotImplementedException();
public IsolationLevel IsolationLevel => throw new NotImplementedException();
public void Commit()
{
throw new NotImplementedException();
}
public void Rollback()
{
throw new NotImplementedException();
}
#region IDisposable Support
private bool disposedValue = false; // Para detectar chamadas redundantes
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: descartar estado gerenciado (objetos gerenciados).
}
// TODO: liberar recursos não gerenciados (objetos não gerenciados) e substituir um finalizador abaixo.
// TODO: definir campos grandes como nulos.
disposedValue = true;
}
}
// TODO: substituir um finalizador somente se Dispose(bool disposing) acima tiver o código para liberar recursos não gerenciados.
// ~Transaction() {
// // Não altere este código. Coloque o código de limpeza em Dispose(bool disposing) acima.
// Dispose(false);
// }
// Código adicionado para implementar corretamente o padrão descartável.
public void Dispose()
{
// Não altere este código. Coloque o código de limpeza em Dispose(bool disposing) acima.
Dispose(true);
// TODO: remover marca de comentário da linha a seguir se o finalizador for substituído acima.
// GC.SuppressFinalize(this);
}
#endregion
}
}
|
Java
|
UTF-8
| 44,201 | 1.773438 | 2 |
[] |
no_license
|
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.util.*;
public class SystemSetup {
// variable to convert map scale to real length
private final double METER_CONVERSION = 0.05;
public static Junction rootNode;
public static Junction J2, J5, J6, J7, J8, J9, J10, J11, J12, J13, J15, J16,
J17, J18, J19, J22, J23, J24, J25, J28, J34,
J35, J37, J39, J40, J43, J44, J46, J49, J51, J52, J53;
private AV AV3, AV4, AV5, AV6, AV7, AV8, AV10, AV11, AV12, AV13, AV14, AV15, AV16, AV17, AV18, AV19, AV20, AV21, AV22, AV24, AV25;
public static Map<String,Inlet> inletsMap;
public static Map<Integer,InletCluster> inletClusters;
public static Map<Integer,AV> avs;
public static Map<Integer,Junction> junctions;
private Inlet I3_1, I3_2, I3_3, I3_4, I3_5, I3_6, I3_7, I3_8, I3_18, I3_19, I3_20,
I4_1, I4_2, I4_3, I4_4, I5_1, I5_2, I5_3, I5_4, I5_5,
I6_1, I6_2, I6_3, I6_4, I6_5, I6_6, I6_7, I6_8, I6_9, I6_10, I6_11, I6_12, I6_13, I6_14, I6_15,
I6_16, I6_17, I6_18, I7_1, I7_2, I7_3, I7_4, I7_5, I7_6, I7_7, I7_8, I7_9, I7_10, I8_1, I8_2,
I8_3, I8_4, I10_1, I10_2, I10_3, I10_4,I10_5, I11_1, I11_2, I11_3,
I11_4, I11_5, I11_6, I11_7, I11_8, I11_9, I11_10, I12_1, I12_2, I12_3, I13_1, I13_2, I13_3, I14_1,
I14_2, I14_3, I14_4, I14_5, I14_6, I14_7, I14_8, I14_9, I14_10, I14_11, I14_12, I15_1, I15_2, I15_3, I15_4,
I15_16, I16_1, I16_2, I16_3, I16_4, I16_5, I16_6, I16_7, I16_8, I16_9,
I16_10, I16_11, I17_1, I17_2, I17_3, I17_4, I17_5, I17_6, I18_1,
I18_2, I18_3, I18_4, I18_5, I18_6, I18_7, I18_8, I18_9, I19_1, I19_2, I19_3, I20_1, I20_2, I20_3,
I21_1, I21_2, I21_3, I21_4, I21_5, I21_6, I21_7, I21_8, I21_9, I21_10, I21_11, I21_12, I21_13, I21_14,
I21_15, I22_1, I22_2, I22_3, I24_1, I24_2, I24_3, I25_1, I25_2, I25_3;
private List<Inlet> inletList3_1, inletList3_2, inletList3_3, inletList4, inletList5, inletList6_1, inletList6_2,
inletList6_3, inletList6_4, inletList7_1, inletList7_2, inletList8_1,
inletList10_1, inletList10_2,
inletList11, inletList12_1, inletList13,
inletList14_1, inletList15_1, inletList15_3, inletList16_1, inletList16_2,
inletList17_1, inletList18_1,
inletList18_2, inletList19, inletList20, inletList21_1, inletList21_2, inletList21_3, inletList21_4, inletList22,
inletList24, inletList25;
private InletCluster inletCluster3_1, inletCluster3_2, inletCluster3_3, inletCluster4, inletCluster5, inletCluster6_1,
inletCluster6_2, inletCluster6_3, inletCluster6_4, inletCluster7_1, inletCluster7_2,
inletCluster8_1, inletCluster10_1, inletCluster10_2, inletCluster11, inletCluster12_1,
inletCluster13, inletCluster14_1, inletCluster15_1, inletCluster15_3, inletCluster16_1, inletCluster16_2,
inletCluster17_1, inletCluster18_1, inletCluster18_2,
inletCluster19, inletCluster20, inletCluster21_1, inletCluster21_2,
inletCluster21_3,inletCluster21_4, inletCluster22,
inletCluster24, inletCluster25;
public static Map<Integer, Boolean> AVIndicator;
public SystemSetup(){
inletsMap = new HashMap<>();
inletClusters = new HashMap<>();
avs = new HashMap<>();
junctions = new HashMap<>();
AVIndicator = new HashMap<>();
instantiateAllInlets();
instantiateAllInletLists();
refreshSystem();
}
public void refreshSystem() {
Algorithm.emptySeq = new ArrayList<>();
Algorithm.emptiedAVs = new ArrayList<>();
AVIndicator = new HashMap<>();
instantiateAllJunctions();
instantiateAllInletClusters();
instantiateAllAv();
setChildren();
setParents();
fillMaps();
setAllJunctionDepths(rootNode);
for (int avID : avs.keySet()) {
setPathList(avID, rootNode.getId());
}
}
public static void levelUpdate(String id, double newLevel){
inletsMap.get(id).setLevel(newLevel);
}
public static double getLevel(String id) {
return inletsMap.get(id).getLevel();
}
public static boolean shouldBeEmptied(AV av, int fraction) {
if (AVIndicator.get(av.getId()) != null) {
return AVIndicator.get(av.getId());
}
for (InletCluster ic : avs.get(av.getId()).getInlets()) {
for (Inlet i : inletClusters.get(ic.getId()).getInletList()) {
boolean correctFraction = inletsMap.get(i.getId()).getFraction() == fraction;
if (correctFraction && LevelHandler.inletsToEmpty.contains(i.getId())) { //(hasMaxLevel || hasMinLevel)) { // && possibleLevel > LevelHandler.MAX_LEVEL
Main.output.add("Inlet with level: " + i.getId());
AVIndicator.put(av.getId(), true);
return true;
}
}
}
AVIndicator.put(av.getId(), false);
return false;
}
/*public static boolean shouldBeEmptied(AV av, int fraction) {
for (InletCluster ic : avs.get(av.getId()).getInlets()) {
for (Inlet i : inletClusters.get(ic.getId()).getInletList()) {
boolean correctFraction = inletsMap.get(i.getId()).getFraction() == fraction;
double level = inletsMap.get(i.getId()).getLevel();
boolean hasMaxLevel = level >= LevelHandler.MAX_LEVEL;
boolean hasMinLevel = level >= LevelHandler.MIN_EMPTY_LEVEL;
double disposalAverage = Statistics.averageNbrOfDisposals(i.getId(), Main.currentEndTime, Main.currentEndTime.plusMinutes(Main.minutes));
double oldLevel = inletsMap.get(i.getId()).getLevel();
double addedLevel = (disposalAverage * LevelHandler.bagConverter) / LevelHandler.MAX_VOLUME;
double possibleLevel = oldLevel + addedLevel;
//System.out.println("disposalAverage: " + disposalAverage + ", addedLevel: " + addedLevel + ", possibleLevel: " + possibleLevel);
if (correctFraction && hasMaxLevel) {//(hasMaxLevel || possibleLevel > LevelHandler.MAX_LEVEL)) { // hasMinLevel
Main.output.add("Inlet with level: " + i.getId());
return true;
//inletClusters.get(ic.getId()).setInd(1);
}
}
}
return false;
}*/
public static void updateRelation(Vertex parent, Vertex leftChild, Vertex rightChild){
if(leftChild != null) {
if (leftChild instanceof InletCluster) {
junctions.get(parent.getId()).setLeftChild(inletClusters.get(leftChild.getId()));
inletClusters.get(leftChild.getId()).setParent(junctions.get(parent.getId()));
inletClusters.get(leftChild.getId()).setLengthToParent(inletClusters.get(leftChild.getId()).getLengthToRoot()-junctions.get(parent.getId()).getLengthToRoot());
}else if(leftChild instanceof Junction){
junctions.get(parent.getId()).setLeftChild(junctions.get(leftChild.getId()));
junctions.get(leftChild.getId()).setParent(junctions.get(parent.getId()));
junctions.get(leftChild.getId()).setLengthToParent(junctions.get(leftChild.getId()).getLengthToRoot()-junctions.get(parent.getId()).getLengthToRoot());
}
}
if(rightChild != null){
if (rightChild instanceof InletCluster) {
junctions.get(parent.getId()).setRightChild(inletClusters.get(rightChild.getId()));
inletClusters.get(rightChild.getId()).setParent(junctions.get(parent.getId()));
inletClusters.get(rightChild.getId()).setLengthToParent(inletClusters.get(rightChild.getId()).getLengthToRoot()-junctions.get(parent.getId()).getLengthToRoot());
}else if(rightChild instanceof Junction){
junctions.get(parent.getId()).setRightChild(junctions.get(rightChild.getId()));
junctions.get(rightChild.getId()).setParent(junctions.get(parent.getId()));
junctions.get(rightChild.getId()).setLengthToParent(junctions.get(rightChild.getId()).getLengthToRoot()-junctions.get(parent.getId()).getLengthToRoot());
}
}
}
public void instantiateAllInlets(){
I3_1 = new Inlet("3:1",0,3);
I3_2 = new Inlet("3:2",0,2);
I3_3 = new Inlet("3:3",0,2);
I3_4 = new Inlet("3:4",0,1);
I3_5 = new Inlet("3:5",0,1);
I3_6 = new Inlet("3:6",0,3);
I3_7 = new Inlet("3:7",0,2);
I3_8 = new Inlet("3:8",0,2);
I3_18 = new Inlet("3:18",0,3);
I3_19 = new Inlet("3:19",0,1);
I3_20 = new Inlet("3:20",0,1);
I4_1 = new Inlet("4:1",0,1);
I4_2 = new Inlet("4:2",0,2);
I4_3 = new Inlet("4:3",0,1);
I4_4 = new Inlet("4:4",0,3);
I5_1 = new Inlet("5:1",0,1);
I5_2 = new Inlet("5:2",0,1);
I5_3 = new Inlet("5:3",0,2);
I5_4 = new Inlet("5:4",0,2);
I5_5 = new Inlet("5:5",0,3);
I6_1 = new Inlet("6:1",0,3);
I6_2 = new Inlet("6:2",0,2);
I6_3 = new Inlet("6:3",0,2);
I6_4 = new Inlet("6:4",0,1);
I6_5 = new Inlet("6:5",0,1);
I6_6 = new Inlet("6:6",0,3);
I6_7 = new Inlet("6:7",0,2);
I6_8 = new Inlet("6:8",0,1);
I6_9 = new Inlet("6:9",0,1);
I6_10 = new Inlet("6:10",0,1);
I6_11 = new Inlet("6:11",0,3);
I6_12 = new Inlet("6:12",0,2);
I6_13 = new Inlet("6:13",0,2);
I6_14 = new Inlet("6:14",0,1);
I6_15 = new Inlet("6:15",0,1);
I6_16 = new Inlet("6:16",0,3);
I6_17 = new Inlet("6:17",0,2);
I6_18 = new Inlet("6:18",0,1);
I7_1 = new Inlet("7:1",0,1);
I7_2 = new Inlet("7:2",0,2);
I7_3 = new Inlet("7:3",0,3);
I7_4 = new Inlet("7:4",0,1);
I7_5 = new Inlet("7:5",0,1);
I7_6 = new Inlet("7:6",0,1);
I7_7 = new Inlet("7:7",0,2);
I7_8 = new Inlet("7:8",0,2);
I7_9 = new Inlet("7:9",0,3);
I7_10 = new Inlet("7:10",0,3);
//I7_11 = new Inlet("7:11",0,1);
//I7_12 = new Inlet("7:12",0,1);
I8_1 = new Inlet("8:1",0,3);
I8_2 = new Inlet("8:2",0,2);
I8_3 = new Inlet("8:3",0,1);
I8_4 = new Inlet("8:4",0,1);
//I8_5 = new Inlet("8:5",0,1);
//I8_6 = new Inlet("8:6",0,1);
//I8_7 = new Inlet("8:7",0,1);
//I8_8 = new Inlet("8:8",0,1);
//I8_9 = new Inlet("8:9",0,1);
//I9_3 = new Inlet("9:3",0, 1);
I10_1 = new Inlet("10:1",0,3);
I10_2 = new Inlet("10:2",0,2);
I10_3 = new Inlet("10:3",0,1);
I10_4 = new Inlet("10:4",0,1);
I10_5 = new Inlet("10:5",0,1);
//I10_6 = new Inlet("10:6",0,1);
//I10_7 = new Inlet("10:7",0,1);
I11_1 = new Inlet("11:1",0,2);
I11_2 = new Inlet("11:2",0,2);
I11_3 = new Inlet("11:3",0,2);
I11_4 = new Inlet("11:4",0,1);
I11_5 = new Inlet("11:5",0,1);
I11_6 = new Inlet("11:6",0,3);
I11_7 = new Inlet("11:7",0,3);
I11_8 = new Inlet("11:8",0,3);
I11_9 = new Inlet("11:9",0,1);
I11_10 = new Inlet("11:10",0,1);
I12_1 = new Inlet("12:1",0,3);
I12_2 = new Inlet("12:2",0,2);
I12_3 = new Inlet("12:3",0,1);
//I12_4 = new Inlet("12:4",0,1);
//I12_5 = new Inlet("12:5",0,1);
I13_1 = new Inlet("13:1",0,3);
I13_2 = new Inlet("13:2",0,2);
I13_3 = new Inlet("13:3",0,1);
I14_1 = new Inlet("14:1",0,1);
I14_2 = new Inlet("14:2",0,1);
I14_3 = new Inlet("14:3",0,1);
I14_4 = new Inlet("14:4",0,1);
I14_5 = new Inlet("14:5",0,1);
I14_6 = new Inlet("14:6",0,1);
I14_7 = new Inlet("14:7",0,2);
I14_8 = new Inlet("14:8",0,2);
I14_9 = new Inlet("14:9",0,2);
I14_10 = new Inlet("14:10",0,2);
I14_11 = new Inlet("14:11",0,3);
I14_12 = new Inlet("14:12",0,3);
//I14_13 = new Inlet("14:13",0,3);
I15_1 = new Inlet("15:1",0,1);
I15_2 = new Inlet("15:2",0,1);
I15_3 = new Inlet("15:3",0,2);
I15_4 = new Inlet("15:4",0,3);
//I15_5 = new Inlet("15:5",0,1);
I15_16 = new Inlet("15:16",0,1);
I16_1 = new Inlet("16:1",0,3);
I16_2 = new Inlet("16:2",0,2);
I16_3 = new Inlet("16:3",0,2);
I16_4 = new Inlet("16:4",0,1);
I16_5 = new Inlet("16:5",0,1);
I16_6 = new Inlet("16:6",0,3);
I16_7 = new Inlet("16:7",0,3);
I16_8 = new Inlet("16:8",0,2);
I16_9 = new Inlet("16:9",0,2);
I16_10 = new Inlet("16:10",0,1);
I16_11 = new Inlet("16:11",0,1);
I17_1 = new Inlet("17:1",0,3);
I17_2 = new Inlet("17:2",0,2);
I17_3 = new Inlet("17:3",0,1);
I17_4 = new Inlet("17:4",0,1);
I17_5 = new Inlet("17:5",0,1);
I17_6 = new Inlet("17:6",0,1);
//I17_7 = new Inlet("17:7",0,1);
//I17_8 = new Inlet("17:8",0,1);
//I17_9 = new Inlet("17:9",0,1);
I18_1 = new Inlet("18:1",0,3);
I18_2 = new Inlet("18:2",0,2);
I18_3 = new Inlet("18:3",0,2);
I18_4 = new Inlet("18:4",0,1);
I18_5 = new Inlet("18:5",0,1);
I18_6 = new Inlet("18:6",0,3);
I18_7 = new Inlet("18:7",0,2);
I18_8 = new Inlet("18:8",0,1);
I18_9 = new Inlet("18:9",0,1);
//I18_10 = new Inlet("18:10",0,1);
I19_1 = new Inlet("19:1",0,3);
I19_2 = new Inlet("19:2",0,2);
I19_3 = new Inlet("19:3",0,1);
I20_1 = new Inlet("20:1", 0, 3);
I20_2 = new Inlet("20:2", 0, 2);
I20_3 = new Inlet("20:3", 0, 1);
I21_1 = new Inlet("21:1",0,3);
I21_2 = new Inlet("21:2",0,2);
I21_3 = new Inlet("21:3",0,1);
I21_4 = new Inlet("21:4",0,3);
I21_5 = new Inlet("21:5",0,2);
I21_6 = new Inlet("21:6",0,1);
I21_7 = new Inlet("21:7",0,3);
I21_8 = new Inlet("21:8",0,2);
I21_9 = new Inlet("21:9",0,1);
I21_10 = new Inlet("21:10",0,3);
I21_11 = new Inlet("21:11",0,2);
I21_12 = new Inlet("21:12",0,1);
I21_13 = new Inlet("21:13",0,3);
I21_14 = new Inlet("21:14",0,2);
I21_15 = new Inlet("21:15",0,1);
I22_1 = new Inlet("22:1",0,3);
I22_2 = new Inlet("22:2",0,2);
I22_3 = new Inlet("22:3",0,1);
//I23_1 = new Inlet("23:1",0,3);
//I23_2 = new Inlet("23:2",0,2);
//I23_3 = new Inlet("23:3",0,1);
//I23_4 = new Inlet("23:4",0,3);
//I23_5 = new Inlet("23:5",0,2);
//I23_6 = new Inlet("23:6",0,1);
//I23_7 = new Inlet("23:7",0,1);
I24_1 = new Inlet("24:1",0,1);
I24_2 = new Inlet("24:2",0,2);
I24_3 = new Inlet("24:3",0,3);
//I24_4 = new Inlet("24:4",0,1);
I25_1 = new Inlet("25:1",0,3);
I25_2 = new Inlet("25:2",0,2);
I25_3 = new Inlet("25:3",0,1);
}
public void fillMaps(){
List<Inlet> inletList = Arrays.asList(I3_1, I3_2, I3_3, I3_4, I3_5, I3_6, I3_7, I3_8, I3_18, I3_19, I3_20,
I4_1, I4_2, I4_3, I4_4, I5_1, I5_2, I5_3, I5_4, I5_5,
I6_1, I6_2, I6_3, I6_4, I6_5, I6_6, I6_7, I6_8, I6_9, I6_10, I6_11, I6_12, I6_13, I6_14, I6_15,
I6_16, I6_17, I6_18, I7_1, I7_2, I7_3, I7_4, I7_5, I7_6, I7_7, I7_8, I7_9, I7_10, I8_1, I8_2,
I8_3, I8_4, I10_1, I10_2, I10_3, I10_4,I10_5, I11_1, I11_2, I11_3,
I11_4, I11_5, I11_6, I11_7, I11_8, I11_9, I11_10, I12_1, I12_2, I12_3, I13_1, I13_2, I13_3, I14_1,
I14_2, I14_3, I14_4, I14_5, I14_6, I14_7, I14_8, I14_9, I14_10, I14_11, I14_12, I15_1, I15_2, I15_3, I15_4,
I15_16, I16_1, I16_2, I16_3, I16_4, I16_5, I16_6, I16_7, I16_8, I16_9,
I16_10, I16_11, I17_1, I17_2, I17_3, I17_4, I17_5, I17_6, I18_1,
I18_2, I18_3, I18_4, I18_5, I18_6, I18_7, I18_8, I18_9, I19_1, I19_2, I19_3, I20_1, I20_2, I20_3,
I21_1, I21_2, I21_3, I21_4, I21_5, I21_6, I21_7, I21_8, I21_9, I21_10, I21_11, I21_12, I21_13, I21_14,
I21_15, I22_1, I22_2, I22_3, I24_1, I24_2, I24_3, I25_1, I25_2, I25_3);
for (Inlet i : inletList) {
inletsMap.put(i.getId(),i);
}
List<AV> avList = Arrays.asList(AV3, AV4, AV5, AV6, AV7, AV8, AV10, AV11, AV12, AV13, AV14, AV15, AV16, AV17, AV18, AV19, AV20, AV21, AV22, AV24, AV25);
for (AV a: avList) {
avs.put(a.getId(),a);
}
List<InletCluster> inletClusterList = Arrays.asList(inletCluster3_1, inletCluster3_2, inletCluster3_3, inletCluster4, inletCluster5, inletCluster6_1,
inletCluster6_2, inletCluster6_3, inletCluster6_4, inletCluster7_1, inletCluster7_2,
inletCluster8_1, inletCluster10_1, inletCluster10_2, inletCluster11, inletCluster12_1,
inletCluster13, inletCluster14_1, inletCluster15_1, inletCluster15_3, inletCluster16_1, inletCluster16_2,
inletCluster17_1, inletCluster18_1, inletCluster18_2,
inletCluster19, inletCluster20, inletCluster21_1, inletCluster21_2,
inletCluster21_3,inletCluster21_4, inletCluster22,
inletCluster24, inletCluster25);
for (InletCluster ic: inletClusterList) {
inletClusters.put(ic.getId(),ic);
}
List<Junction> junctionList = Arrays.asList(rootNode, J2, J5, J6, J7, J8, J9, J10, J11, J12, J13, J15, J16,
J17, J18, J19, J22, J23, J24, J25, J28, J34,
J35, J37, J39, J40, J43, J44, J46, J49, J51, J52, J53);
for (Junction j: junctionList) {
junctions.put(j.getId(),j);
}
}
public void instantiateAllInletLists() {
inletList3_1 = Arrays.asList(I3_1, I3_2, I3_3, I3_4, I3_5);
inletList3_2 = Arrays.asList(I3_6, I3_7, I3_8);
inletList3_3 = Arrays.asList(I3_18, I3_19, I3_20);
inletList4 = Arrays.asList(I4_1, I4_2, I4_3, I4_4);
inletList5 = Arrays.asList(I5_1, I5_2, I5_3, I5_4, I5_5);
inletList6_1 = Arrays.asList(I6_1, I6_2, I6_3, I6_4, I6_5);
inletList6_2 = Arrays.asList(I6_6, I6_7, I6_8, I6_9, I6_10);
inletList6_3 = Arrays.asList(I6_11, I6_12, I6_13, I6_14, I6_15, I6_16);
inletList6_4 = Arrays.asList(I6_16, I6_17, I6_18);
inletList7_1 = Arrays.asList(I7_1, I7_2, I7_3);
inletList7_2 = Arrays.asList(I7_4, I7_5, I7_6, I7_7, I7_8, I7_8, I7_9, I7_10);
//inletList7_3 = Arrays.asList(I7_11);
//inletList7_4 = Arrays.asList(I7_12);
inletList8_1 = Arrays.asList(I8_1, I8_2, I8_3, I8_4);
//inletList8_2 = Arrays.asList(I8_5);
//inletList8_3 = Arrays.asList(I8_6);
//inletList8_4 = Arrays.asList(I8_7);
//inletList8_5 = Arrays.asList(I8_8);
//inletList8_6 = Arrays.asList(I8_9);
//inletList9 = Arrays.asList(I9_3);
inletList10_1 = Arrays.asList(I10_1, I10_2, I10_3, I10_4);
inletList10_2 = Arrays.asList(I10_5);
//inletList10_3 = Arrays.asList(I10_6);
//inletList10_4 = Arrays.asList(I10_7);
inletList11 = Arrays.asList(I11_1, I11_2, I11_3, I11_4, I11_5, I11_6, I11_7, I11_8, I11_9, I11_10);
inletList12_1 = Arrays.asList(I12_1, I12_2, I12_3);
//inletList12_2 = Arrays.asList(I12_4);
//inletList12_3 = Arrays.asList(I12_5);
inletList13 = Arrays.asList(I13_1, I13_2, I13_3);
inletList14_1 = Arrays.asList(I14_1, I14_2, I14_3, I14_4, I14_5, I14_6, I14_7, I14_8, I14_9, I14_10, I14_11, I14_12);
//inletList14_2 = Arrays.asList(I14_13);
inletList15_1 = Arrays.asList(I15_1, I15_2, I15_3, I15_4);
//inletList15_2 = Arrays.asList(I15_5);
inletList15_3 = Arrays.asList(I15_16);
inletList16_1 = Arrays.asList(I16_1, I16_2, I16_3, I16_4, I16_5);
inletList16_2 = Arrays.asList(I16_6, I16_7, I16_8, I16_9, I16_10, I16_11);
inletList17_1 = Arrays.asList(I17_1,I17_2,I17_3,I17_4,I17_5,I17_6);
//inletList17_2 = Arrays.asList(I17_7);
//inletList17_3 = Arrays.asList(I17_8);
//inletList17_4 = Arrays.asList(I17_9);
inletList18_1 = Arrays.asList(I18_1, I18_2, I18_3, I18_4, I18_5);
inletList18_2 = Arrays.asList(I18_6, I18_7, I18_8, I18_9);
//inletList18_3 = Arrays.asList(I18_10);
inletList19 = Arrays.asList(I19_1, I19_2, I19_3);
inletList20 = Arrays.asList(I20_1, I20_2, I20_3);
inletList21_1 = Arrays.asList(I21_1, I21_2, I21_3, I21_4, I21_5, I21_6);
inletList21_2 = Arrays.asList(I21_7, I21_8, I21_9);
inletList21_3 = Arrays.asList(I21_10, I21_11, I21_12);
inletList21_4 = Arrays.asList(I21_13, I21_14, I21_15);
inletList22 = Arrays.asList(I22_1, I22_2, I22_3);
//inletList23_1 = Arrays.asList(I23_1, I23_2, I23_3);
//inletList23_2 = Arrays.asList(I23_4, I23_5, I23_6, I23_7);
inletList24 = Arrays.asList(I24_1, I24_2, I24_3); //, I24_4);
inletList25 = Arrays.asList(I25_1, I25_2, I25_3);
}
public void instantiateAllInletClusters() {
inletCluster3_1 = new InletCluster(15,42.8/METER_CONVERSION,1.6/METER_CONVERSION, J16, null, inletList3_1);
inletCluster3_2 = new InletCluster(13,38.5/METER_CONVERSION,3.5/METER_CONVERSION, J13, null, inletList3_2);
inletCluster3_3 = new InletCluster(12,34.1/METER_CONVERSION,1.3/METER_CONVERSION, J12, null, inletList3_3);
inletCluster4 = new InletCluster(16,44.1/METER_CONVERSION, 1.8/METER_CONVERSION, J17, null, inletList4);
inletCluster5 = new InletCluster(18,45.9/METER_CONVERSION,1.0/METER_CONVERSION, J19, null, inletList5);
inletCluster6_1 = new InletCluster(22,43.1/METER_CONVERSION,0.3/METER_CONVERSION, J23, null, inletList6_1);
inletCluster6_2 = new InletCluster(23,44.7/METER_CONVERSION,0.2/METER_CONVERSION, J24, null, inletList6_2);
inletCluster6_3 = new InletCluster(24,47.2/METER_CONVERSION,0.1/METER_CONVERSION, J25, null, inletList6_3);
inletCluster6_4 = new InletCluster(25,48.7/METER_CONVERSION,1.6/METER_CONVERSION, J25, null, inletList6_4);
inletCluster7_1 = new InletCluster(19,45.8/METER_CONVERSION,0.9/METER_CONVERSION, J19, null, inletList7_1);
inletCluster7_2 = new InletCluster(17, 43.2/METER_CONVERSION,0.7/METER_CONVERSION, J18, null, inletList7_2);
inletCluster8_1 = new InletCluster(27,50.1/METER_CONVERSION,2.4/METER_CONVERSION, J28, null, inletList8_1);
inletCluster10_1 = new InletCluster(38,56/METER_CONVERSION,1.2/METER_CONVERSION, J39, null, inletList10_1);
inletCluster10_2 = new InletCluster(31,51.8/METER_CONVERSION,0.8/METER_CONVERSION, J34, null, inletList10_2);
inletCluster11 = new InletCluster(50,61.9/METER_CONVERSION,1.5/METER_CONVERSION, J46, null, inletList11);
inletCluster12_1 = new InletCluster(52,61.4/METER_CONVERSION,1/METER_CONVERSION, J46, null, inletList12_1);
inletCluster13 = new InletCluster(54, 62.0/METER_CONVERSION, 3.1/METER_CONVERSION, J44, null, inletList13);
inletCluster14_1 = new InletCluster(43,62.1/METER_CONVERSION,0.6/METER_CONVERSION, J49, null, inletList14_1);
inletCluster15_1 = new InletCluster(46,64.8/METER_CONVERSION,0.3/METER_CONVERSION, J52, null, inletList15_1);
inletCluster15_3 = new InletCluster(45,67.0/METER_CONVERSION,2.9/METER_CONVERSION, J51, null, inletList15_3);
inletCluster16_1 = new InletCluster(48,65.1/METER_CONVERSION, 0.0/METER_CONVERSION, J53, null, inletList16_1);
inletCluster16_2 = new InletCluster(47,65.6/METER_CONVERSION,0.5/METER_CONVERSION, J53, null, inletList16_2);
inletCluster17_1 = new InletCluster(40,56.9/METER_CONVERSION,1.8/METER_CONVERSION, J40, null, inletList17_1);
inletCluster18_1 = new InletCluster(35,53.9/METER_CONVERSION,0.4/METER_CONVERSION, J37, null, inletList18_1);
inletCluster18_2 = new InletCluster(36,57.8/METER_CONVERSION,4.3/METER_CONVERSION, J37, null, inletList18_2);
inletCluster19 = new InletCluster(6,27.4/METER_CONVERSION,0.2/METER_CONVERSION, J6, null, inletList19);
inletCluster20 = new InletCluster(1, 25.1/METER_CONVERSION, 1.3/METER_CONVERSION, J2, null, inletList20);
inletCluster21_1 = new InletCluster(7,31.4/METER_CONVERSION,0/METER_CONVERSION, J8, null, inletList21_1);
inletCluster21_2 = new InletCluster(8,34.9/METER_CONVERSION,0.8/METER_CONVERSION, J10, null, inletList21_2);
inletCluster21_3 = new InletCluster(10,36.2/METER_CONVERSION,1.5/METER_CONVERSION, J11, null, inletList21_3);
inletCluster21_4 = new InletCluster(11,35/METER_CONVERSION,0.3/METER_CONVERSION, J11, null, inletList21_4);
inletCluster22 = new InletCluster(9,37.1/METER_CONVERSION,3.0/METER_CONVERSION, J10, null, inletList22);
inletCluster24 = new InletCluster(5,27.3/METER_CONVERSION,1.5/METER_CONVERSION, J6, null, inletList24);
inletCluster25 = new InletCluster(3,28.3/METER_CONVERSION,4.5/METER_CONVERSION, J2, null, inletList25);
}
public void instantiateAllJunctions() {
rootNode = new Junction(0, 0,0, null, J2, J5, 1, 1);
J2 = new Junction(2,23.8/METER_CONVERSION,23.8/METER_CONVERSION, rootNode, inletCluster20, inletCluster25,1,1);
J5 = new Junction(5,25.8/METER_CONVERSION,25.8/METER_CONVERSION, rootNode, inletCluster24, J6, 1, 1);
J6 = new Junction(6,27.2/METER_CONVERSION,1.4/METER_CONVERSION, J5, J7, inletCluster19,1,1);
J7 = new Junction(7,27.7/METER_CONVERSION,0.5/METER_CONVERSION, J6, J8, J12,1,1);
J8 = new Junction(8,31.4/METER_CONVERSION,3.7/METER_CONVERSION, J7, inletCluster21_1, J9,1,1);
J9 = new Junction(9,33.4/METER_CONVERSION,2.0/METER_CONVERSION, J8, J10, J11,1,1);
J10 = new Junction(10,34.1/METER_CONVERSION,0.7/METER_CONVERSION, J9, inletCluster21_2, inletCluster22,1,1);
J11 = new Junction(11,34.7/METER_CONVERSION,1.3/METER_CONVERSION, J9, inletCluster21_3, inletCluster21_4,1,1);
J12 = new Junction(12,32.8/METER_CONVERSION,5.1/METER_CONVERSION, J7, J13, inletCluster3_3, 1, 1);
J13 = new Junction(13,35.0/METER_CONVERSION,2.2/METER_CONVERSION, J12, inletCluster3_2, J15, 1, 1);
J15 = new Junction(15,40.7/METER_CONVERSION,5.7/METER_CONVERSION, J13, J16, J22, 1, 1);
J16 = new Junction(16,41.2/METER_CONVERSION,0.5/METER_CONVERSION, J15, inletCluster3_1, J17, 1, 1);
J17 = new Junction(17,42.3/METER_CONVERSION,1.1/METER_CONVERSION, J16, inletCluster4, J18, 1,1);
J18 = new Junction(18,42.5/METER_CONVERSION,0.2/METER_CONVERSION, J17, J19, inletCluster7_2,1,1);
J19 = new Junction(19,44.9/METER_CONVERSION,2.4/METER_CONVERSION, J18, inletCluster5, inletCluster7_1,1,1);
J22 = new Junction(22,41.5/METER_CONVERSION,0.8/METER_CONVERSION, J15, J28, J23,1,1);
J23 = new Junction(23,42.8/METER_CONVERSION,1.3/METER_CONVERSION, J22, J24, inletCluster6_1,1,1);
J24 = new Junction(24,44.5/METER_CONVERSION,1.7/METER_CONVERSION, J23, J25, inletCluster6_2, 1,1);
J25 = new Junction(25,47.1/METER_CONVERSION,2.6/METER_CONVERSION, J24, inletCluster6_3, inletCluster6_4,1,1);
J28 = new Junction(28,47.7/METER_CONVERSION,6.2/METER_CONVERSION, J22, inletCluster8_1, J34, 1,1);
J34 = new Junction(34,51.0/METER_CONVERSION,3.3/METER_CONVERSION, J28, inletCluster10_2, J35,1,1);
J35 = new Junction(35,52.0/METER_CONVERSION,4.7/METER_CONVERSION, J34, J39, J37, 1,1);
J37 = new Junction(37,53.5/METER_CONVERSION,1.5/METER_CONVERSION, J35, inletCluster18_1, inletCluster18_2,1,1);
J39 = new Junction(39,54.8/METER_CONVERSION,2.8/METER_CONVERSION, J35, inletCluster10_1, J40, 1,1);
J40 = new Junction(40,55.1/METER_CONVERSION,0.3/METER_CONVERSION, J39, J43, inletCluster17_1, 1,1);
J43 = new Junction(43,56.6/METER_CONVERSION,1.5/METER_CONVERSION, J40, J44, J49,1,1);
J44 = new Junction(44,58.9/METER_CONVERSION,2.3/METER_CONVERSION, J43, J46, inletCluster13, 1,1);
J46 = new Junction(46,60.4/METER_CONVERSION,1.5/METER_CONVERSION, J44, inletCluster11, inletCluster12_1,1,1);
J49 = new Junction(49,61.5/METER_CONVERSION,4.9/METER_CONVERSION, J43, inletCluster14_1, J51,1,1);
J51 = new Junction(51,64.1/METER_CONVERSION,2.6/METER_CONVERSION, J49, J52, inletCluster15_3,1,1);
J52 = new Junction(52,64.5/METER_CONVERSION,0.4/METER_CONVERSION, J51, J53, inletCluster15_1,1,1);
J53 = new Junction(53,65.1/METER_CONVERSION,0.6/METER_CONVERSION, J52, inletCluster16_1, inletCluster16_2, 1,1);
}
public void setParents(){
//J1.setParent(rootNode);
J2.setParent(rootNode);
inletCluster20.setParent(J2);
//J3.setParent(J2);
//inletCluster23_1.setParent(J3);
//J4.setParent(J3);
inletCluster25.setParent(J2);
//inletCluster23_2.setParent(J4);
J5.setParent(rootNode);
inletCluster24.setParent(J5);
J6.setParent(J5);
inletCluster19.setParent(J5);
J7.setParent(J6);
J8.setParent(J7);
inletCluster21_1.setParent(J8);
J9.setParent(J8);
J10.setParent(J9);
inletCluster21_2.setParent(J10);
inletCluster22.setParent(J10);
J11.setParent(J9);
inletCluster21_3.setParent(J11);
inletCluster21_4.setParent(J11);
J12.setParent(J7);
inletCluster3_3.setParent(J12);
J13.setParent(J12);
inletCluster3_2.setParent(J13);
//J14.setParent(J13);
//inletCluster9.setParent(J14);
J15.setParent(J13);
J16.setParent(J15);
inletCluster3_1.setParent(J16);
J17.setParent(J16);
inletCluster4.setParent(J17);
J18.setParent(J17);
inletCluster7_2.setParent(J18);
J19.setParent(J18);
inletCluster5.setParent(J19);
//J20.setParent(J19);
inletCluster7_1.setParent(J19);
//J21.setParent(J19);
//inletCluster7_3.setParent(J21);
//inletCluster7_4.setParent(J21);
J22.setParent(J15);
J23.setParent(J22);
inletCluster6_1.setParent(J23);
J24.setParent(J23);
inletCluster6_2.setParent(J24);
J25.setParent(J24);
inletCluster6_3.setParent(J25);
inletCluster6_4.setParent(J25);
//J26.setParent(J22);
//inletCluster8_2.setParent(J26);
//J27.setParent(J26);
//inletCluster8_3.setParent(J27);
J28.setParent(J22);
//J29.setParent(J22);
inletCluster8_1.setParent(J28);
//inletCluster8_6.setParent(J29);
// J30.setParent(J28);
// inletCluster8_4.setParent(J30);
//
//J31.setParent(J30);
//inletCluster8_5.setParent(J31);
//J32.setParent(J31);
//J33.setParent(J32);
//inletCluster10_3.setParent(J33);
//inletCluster10_4.setParent(J33);
J34.setParent(J28);
inletCluster10_2.setParent(J34);
J35.setParent(J34);
//J36.setParent(J35);
//inletCluster17_4.setParent(J36);
J37.setParent(J35);
inletCluster18_1.setParent(J37);
//J38.setParent(J37);
inletCluster18_2.setParent(J37);
//inletCluster18_3.setParent(J38);
J39.setParent(J35);
inletCluster10_1.setParent(J39);
J40.setParent(J39);
//J41.setParent(J40);
//inletCluster17_3.setParent(J41);
inletCluster17_1.setParent(J40);
//J42.setParent(J40);
//inletCluster17_2.setParent(J42);
J43.setParent(J40);
J44.setParent(J43);
inletCluster13.setParent(J44);
//J45.setParent(J44);
//inletCluster12_2.setParent(J45);
J46.setParent(J44);
inletCluster11.setParent(J46);
//J47.setParent(J46);
//inletCluster12_3.setParent(J47);
inletCluster12_1.setParent(J46);
// J48.setParent(J43);
// inletCluster14_2.setParent(J48);
J49.setParent(J43);
inletCluster14_1.setParent(J49);
//J50.setParent(J49);
//inletCluster15_2.setParent(J50);
J51.setParent(J49);
inletCluster15_3.setParent(J51);
J52.setParent(J51);
inletCluster15_1.setParent(J52);
J53.setParent(J52);
inletCluster16_1.setParent(J53);
inletCluster16_2.setParent(J53);
}
public void setChildren() {
rootNode.setLeftChild(J2);
rootNode.setRightChild(J5);
//J1.setLeftChild(J2);
//J1.setRightChild(J5);
J2.setLeftChild(inletCluster20);
J2.setRightChild(inletCluster25);
// J3.setLeftChild(J4);
// J3.setRightChild(inletCluster23_1);
//J4.setLeftChild(inletCluster25);
//J4.setRightChild(inletCluster23_2);
J5.setLeftChild(inletCluster24);
J5.setRightChild(J6);
J6.setLeftChild(J7);
J6.setRightChild(inletCluster19);
J7.setLeftChild(J8);
J7.setRightChild(J12);
J8.setLeftChild(inletCluster21_1);
J8.setRightChild(J9);
J9.setLeftChild(J10);
J9.setRightChild(J11);
J10.setLeftChild(inletCluster21_2);
J10.setRightChild(inletCluster22);
J11.setLeftChild(inletCluster21_3);
J11.setRightChild(inletCluster21_4);
J12.setLeftChild(J13);
J12.setRightChild(inletCluster3_3);
J13.setLeftChild(inletCluster3_2);
J13.setRightChild(J15);
// J14.setLeftChild(J15);
// J14.setRightChild(inletCluster9);
J15.setLeftChild(J16);
J15.setRightChild(J22);
J16.setLeftChild(inletCluster3_1);
J16.setRightChild(J17);
J17.setLeftChild(inletCluster4);
J17.setRightChild(J18);
J18.setLeftChild(J19);
J18.setRightChild(inletCluster7_2);
J19.setLeftChild(inletCluster5);
J19.setRightChild(inletCluster7_1);
//J20.setLeftChild(J21);
//J20.setRightChild(inletCluster7_1);
//J21.setLeftChild(inletCluster7_3);
//J21.setRightChild(inletCluster7_4);
J22.setLeftChild(J28);
J22.setRightChild(J23);
J23.setLeftChild(J24);
J23.setRightChild(inletCluster6_1);
J24.setLeftChild(J25);
J24.setRightChild(inletCluster6_2);
J25.setLeftChild(inletCluster6_3);
J25.setRightChild(inletCluster6_4);
//J26.setLeftChild(inletCluster8_2);
//J26.setRightChild(J27);
//J27.setLeftChild(J28);
//J27.setRightChild(inletCluster8_3);
J28.setLeftChild(inletCluster8_1);
J28.setRightChild(J34);
//J29.setLeftChild(inletCluster8_1);
//J29.setRightChild(J34);
//J30.setLeftChild(J31);
//J30.setRightChild(inletCluster8_4);
//J31.setLeftChild(inletCluster8_5);
//J31.setRightChild(J32);
//J32.setLeftChild(J34);
//J32.setRightChild(J33);
//J33.setLeftChild(inletCluster10_3);
//J33.setRightChild(inletCluster10_4);
J34.setLeftChild(inletCluster10_2);
J34.setRightChild(J35);
J35.setLeftChild(J39);
J35.setRightChild(J37);
//J36.setLeftChild(J37);
//J36.setRightChild(inletCluster17_4);
J37.setLeftChild(inletCluster18_1);
J37.setRightChild(inletCluster18_2);
//J38.setLeftChild(inletCluster18_2);
//J38.setRightChild(inletCluster18_3);
J39.setLeftChild(inletCluster10_1);
J39.setRightChild(J40);
J40.setLeftChild(J43);
J40.setRightChild(inletCluster17_1);
//J41.setLeftChild(inletCluster17_3);
//J41.setRightChild(inletCluster17_1);
//J42.setLeftChild(J43);
//J42.setRightChild(inletCluster17_2);
J43.setLeftChild(J44);
J43.setRightChild(J49);
J44.setLeftChild(J46);
J44.setRightChild(inletCluster13);
//J45.setLeftChild(J46);
//J45.setRightChild(inletCluster12_2);
J46.setLeftChild(inletCluster11);
J46.setRightChild(inletCluster12_1);
//J47.setLeftChild(inletCluster12_3);
//J47.setRightChild(inletCluster12_1);
//J48.setLeftChild(J49);
//J48.setRightChild(inletCluster14_2);
J49.setLeftChild(inletCluster14_1);
J49.setRightChild(J51);
//J50.setLeftChild(J51);
//J50.setRightChild(inletCluster15_2);
J51.setLeftChild(J52);
J51.setRightChild(inletCluster15_3);
J52.setLeftChild(J53);
J52.setRightChild(inletCluster15_1);
J53.setLeftChild(inletCluster16_2);
J53.setRightChild(inletCluster16_1);
}
public void instantiateAllAv() {
AV3 = new AV(3,inletCluster3_1.getLengthToRoot(),Arrays.asList(inletCluster3_3,inletCluster3_2,inletCluster3_1));
inletCluster3_1.setAV(AV3);
inletCluster3_2.setAV(AV3);
inletCluster3_3.setAV(AV3);
AV4 = new AV(4,inletCluster4.getLengthToRoot(),Arrays.asList(inletCluster4));
inletCluster4.setAV(AV4);
AV5 = new AV(5,inletCluster5.getLengthToRoot(),Arrays.asList(inletCluster5));
inletCluster5.setAV(AV5);
AV6 = new AV(6,inletCluster6_4.getLengthToRoot(),Arrays.asList(inletCluster6_1,inletCluster6_2,inletCluster6_3,inletCluster6_4));
inletCluster6_1.setAV(AV6);
inletCluster6_2.setAV(AV6);
inletCluster6_3.setAV(AV6);
inletCluster6_4.setAV(AV6);
AV7 = new AV(7,inletCluster7_1.getLengthToRoot(),Arrays.asList(inletCluster7_2,inletCluster7_1));//,inletCluster7_3,inletCluster7_4));
inletCluster7_1.setAV(AV7);
inletCluster7_2.setAV(AV7);
//inletCluster7_3.setAV(AV7);
//inletCluster7_4.setAV(AV7);
AV8 = new AV(8,inletCluster8_1.getLengthToRoot(),Arrays.asList(inletCluster8_1));//,inletCluster8_3,inletCluster8_5,inletCluster8_4,inletCluster8_1,inletCluster8_6));
inletCluster8_1.setAV(AV8);
//inletCluster8_2.setAV(AV8);
//inletCluster8_3.setAV(AV8);
//inletCluster8_4.setAV(AV8);
//inletCluster8_5.setAV(AV8);
//inletCluster8_6.setAV(AV8);
//AV9 = new AV(9,inletCluster9.getLengthToRoot(),Arrays.asList(inletCluster9));
//inletCluster9.setAV(AV9);
AV10 = new AV(10,inletCluster10_1.getLengthToRoot(),Arrays.asList(inletCluster10_2,inletCluster10_1));//,inletCluster10_1,inletCluster10_4));
inletCluster10_1.setAV(AV10);
inletCluster10_2.setAV(AV10);
//inletCluster10_3.setAV(AV10);
//inletCluster10_4.setAV(AV10);
AV11 = new AV(11,inletCluster11.getLengthToRoot(),Arrays.asList(inletCluster11));
inletCluster11.setAV(AV11);
AV12 = new AV(12,inletCluster12_1.getLengthToRoot(),Arrays.asList(inletCluster12_1));//,inletCluster12_1,inletCluster12_3));
inletCluster12_1.setAV(AV12);
//inletCluster12_2.setAV(AV12);
//inletCluster12_3.setAV(AV12);
AV13 = new AV(13,inletCluster13.getLengthToRoot(),Arrays.asList(inletCluster13));
inletCluster13.setAV(AV13);
AV14 = new AV(14,inletCluster14_1.getLengthToRoot(),Arrays.asList(inletCluster14_1)); //inletCluster14_2
inletCluster14_1.setAV(AV14);
//inletCluster14_2.setAV(AV14);
AV15 = new AV(15,inletCluster15_1.getLengthToRoot(),Arrays.asList(inletCluster15_1,inletCluster15_3));//inletCluster15_2,
inletCluster15_1.setAV(AV15);
//inletCluster15_2.setAV(AV15);
inletCluster15_3.setAV(AV15);
AV16 = new AV(16,inletCluster16_2.getLengthToRoot(),Arrays.asList(inletCluster16_1,inletCluster16_2));
inletCluster16_1.setAV(AV16);
inletCluster16_2.setAV(AV16);
AV17 = new AV(17,inletCluster17_1.getLengthToRoot(),Arrays.asList(inletCluster17_1));//inletCluster17_2,inletCluster17_4,,inletCluster17_3));
inletCluster17_1.setAV(AV17);
//inletCluster17_2.setAV(AV17);
//inletCluster17_3.setAV(AV17);
//inletCluster17_4.setAV(AV17);
AV18 = new AV(18,inletCluster18_1.getLengthToRoot(),Arrays.asList(inletCluster18_1,inletCluster18_2));//,inletCluster18_3));
inletCluster18_1.setAV(AV18);
inletCluster18_2.setAV(AV18);
//inletCluster18_3.setAV(AV18);
AV19 = new AV(19,inletCluster19.getLengthToRoot(),Arrays.asList(inletCluster19));
inletCluster19.setAV(AV19);
AV20 = new AV(20,inletCluster20.getLengthToRoot(),Arrays.asList(inletCluster20));
inletCluster20.setAV(AV20);
AV21 = new AV(21,inletCluster21_3.getLengthToRoot(),Arrays.asList(inletCluster21_1,inletCluster21_4,inletCluster21_2,inletCluster21_3));
inletCluster21_1.setAV(AV21);
inletCluster21_2.setAV(AV21);
inletCluster21_3.setAV(AV21);
inletCluster21_4.setAV(AV21);
AV22 = new AV(22,inletCluster22.getLengthToRoot(),Arrays.asList(inletCluster22));
inletCluster22.setAV(AV22);
//AV23 = new AV(23,inletCluster23_2.getLengthToRoot(),Arrays.asList(inletCluster23_1,inletCluster23_2));
//inletCluster23_1.setAV(AV23);
//inletCluster23_2.setAV(AV23);
AV24 = new AV(24,inletCluster24.getLengthToRoot(),Arrays.asList(inletCluster24));
inletCluster24.setAV(AV24);
AV25 = new AV(25,inletCluster25.getLengthToRoot(),Arrays.asList(inletCluster25));
inletCluster25.setAV(AV25);
}
public static void setJunctionDepth(Vertex v) {
Tuple<Double,Double> newDepth = findJunctionDepth(junctions.get(v.getId()), junctions.get(v.getId()));
junctions.get(v.getId()).setLeftDepth(newDepth.x);
junctions.get(v.getId()).setRightDepth(newDepth.y);
}
public static Tuple<Double,Double> findJunctionDepth(Junction start, Vertex v) {
if (v instanceof InletCluster) {
return new Tuple(inletClusters.get(v.getId()).getLengthToParent(), inletClusters.get(v.getId()).getLengthToParent());
} else {
Tuple<Double,Double> dLeft = findJunctionDepth(start, junctions.get(v.getId()).getLeftChild());
Tuple<Double,Double> dRight = findJunctionDepth(start, junctions.get(v.getId()).getRightChild());
double left = dLeft.x > dLeft.y ? dLeft.x : dLeft.y;
double right = dRight.x > dRight.y ? dRight.x : dRight.y;
if (v.getId() != start.getId()) {
return new Tuple(junctions.get(v.getId()).getLengthToParent() + left,junctions.get(v.getId()).getLengthToParent() + right);
} else {
return new Tuple<>(left, right);
}
}
}
public static double setAllJunctionDepths(Vertex v) {
if (v instanceof InletCluster) {
return inletClusters.get(v.getId()).getLengthToParent();
} else {
double dLeft = setAllJunctionDepths(junctions.get(v.getId()).getLeftChild());
double dRight = setAllJunctionDepths(junctions.get(v.getId()).getRightChild());
junctions.get(v.getId()).setLeftDepth(dLeft);
junctions.get(v.getId()).setRightDepth(dRight);
double deepest = dRight >= dLeft ? dRight : dLeft;
return junctions.get(v.getId()).getLengthToParent() + deepest;
}
}
public static void setPathList(int avID, int endNodeID) {
List<Junction> pathList = new ArrayList<>();
List<InletCluster> clusters = avs.get(avID).getInlets();
InletCluster cluster = clusters.get(clusters.size()-1);
Junction nextNode = (Junction) inletClusters.get(cluster.getId()).getParent();
while (!nextNode.equals(junctions.get(endNodeID))) {
nextNode = junctions.get(nextNode.getParent().getId());
pathList.add(nextNode);
}
avs.get(avID).setPathToRoot(pathList);
}
}
|
Markdown
|
UTF-8
| 961 | 2.65625 | 3 |
[] |
no_license
|
# Bike-sharing_Multi-linear_Regression
• This project aims to classify the bikes rides based on the different attributes from the given data.
• The algorithms used for this regression dataset is Multi-Linear Regression which is implemented using R programming and it's libraries.
• The code is present in Bike-Sharing_Dataset.R file. The file Bike-Sharing_Dataset.R contains main function, which invokes functions to train the model from scratch and then use the trained model to identify types on the given input data.
• A model trained using train and test function is saved and the final class analysis of the machine learning models are also stored. This file is used to restore the model state when new data is given as input to the model for classification.
• The details of Multi-Linear Regression architecture including are given in the project report file. This model achieved an F1 score of 0.94 (94%) when evaluated using test dataset.
|
JavaScript
|
UTF-8
| 1,652 | 2.84375 | 3 |
[] |
no_license
|
$(document).ready(function() {
// MENU
function toggleNav() {
var mainNav = $('.main-nav');
var content = $('.content');
var navLinks = $('.main-nav ul li span');
var logoWord = $('.word');
mainNav.mouseover(function() {
$(this).addClass("nav-toggle");
navLinks.addClass("hide");
logoWord.addClass("hide");
content.addClass("content-toggle");
});
mainNav.mouseleave(function() {
$(this).removeClass("nav-toggle");
navLinks.removeClass("hide");
logoWord.removeClass("hide");
content.removeClass("content-toggle");
});
}
toggleNav();
// CARD SWITCH
function cardSwitch() {
var card1 = $('#card1');
var card2 = $('#card2');
var card3 = $('#card3');
var card4 = $('#card4');
var cardBtn1 = $('#cardBtn1');
var cardBtn2 = $('#cardBtn2');
var cardBtn3 = $('#cardBtn3');
var cardBtn4 = $('#cardBtn4');
var allCards = $('.card-base');
var allCardsBtn = $('.card-select li');
cardBtn1.click(function() {
allCards.addClass("hidden");
card1.removeClass("hidden");
allCardsBtn.removeClass("current");
cardBtn1.addClass("current");
});
cardBtn2.click(function() {
allCards.addClass("hidden");
card2.removeClass("hidden");
allCardsBtn.removeClass("current");
cardBtn2.addClass("current");
});
cardBtn3.click(function() {
allCards.addClass("hidden");
card3.removeClass("hidden");
allCardsBtn.removeClass("current");
cardBtn3.addClass("current");
});
cardBtn4.click(function() {
allCards.addClass("hidden");
card4.removeClass("hidden");
allCardsBtn.removeClass("current");
cardBtn4.addClass("current");
});
}
cardSwitch();
});
|
Java
|
UTF-8
| 2,451 | 2.5625 | 3 |
[] |
no_license
|
package edu.ou.spacewar.objects;
import edu.ou.mlfw.gui.Shadow2D;
import edu.ou.spacewar.objects.shadows.BulletShadow;
import edu.ou.spacewar.simulator.Object2D;
import edu.ou.utils.Vector2D;
public class Bullet extends Object2D {
public static final float BULLET_RADIUS = 2;
public static final float BULLET_MASS = 1000;
public static final int BULLET_LIFETIME = 2;
public static final float BULLET_VELOCITY = 225f;
private final Ship ship;
private float lifetime;
public Bullet(final Ship ship) {
super(ship.getSpace(), BULLET_RADIUS, BULLET_MASS);
this.ship = ship;
alive = false;
}
public final float getLifetime() {
return lifetime;
}
public final Ship getShip() {
return ship;
}
@Override
public Shadow2D getShadow() {
return new BulletShadow(this);
}
protected final void setLifetime(final float lifetime) {
this.lifetime = lifetime;
}
@Override
protected final void advanceTime(final float timestep) {
if (lifetime <= 0) {
ship.reload(this);
}
lifetime -= timestep;
}
@Override
public void reset() {
ship.reload(this);
}
@Override
public void resetStats() {
//do nothing
}
@Override
public void collide(final Vector2D normal, final Base base) {
getShip().reload(this);
}
@Override
public void collide(final Vector2D normal, final Beacon beacon) {
getShip().reload(this);
beacon.collect();
}
@Override
public void collide(final Vector2D normal, final Bullet bullet) {
getShip().reload(this);
bullet.getShip().reload(bullet);
}
@Override
public void collide(final Vector2D normal, final Flag flag) {
flag.collide(normal, this);
}
@Override
public void collide(Vector2D normal, EMP laser) {
laser.collide(normal, this);
}
@Override
public void collide(final Vector2D normal, final Mine mine) {
mine.collide(normal, this);
}
@Override
public void collide(final Vector2D normal, final Obstacle obstacle) {
obstacle.collide(normal, this);
}
@Override
public void collide(final Vector2D normal, final Ship ship) {
ship.collide(normal, this);
}
@Override
public void dispatch(final Vector2D normal, final Object2D other) {
other.collide(normal, this);
}
}
|
Shell
|
UTF-8
| 3,432 | 3.28125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
# Copyright 2018 Ryohei Kamiya <ryohei.kamiya@lab2biz.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.
DATASET='points';
rm_if_exist () {
if [ -f "$1" ]; then
rm -rf "$1";
fi
}
label_num=$((0));
for dname in `ls "./${DATASET}"`; do
if [ -d "./${DATASET}/$dname" ]; then
tmp="grd-${DATASET}-${dname}.tmp";
rm_if_exist "$tmp"
for fname in `ls "./${DATASET}/${dname}"`; do
echo "./${DATASET}/${dname}/${fname},${label_num}" >> "$tmp";
done
ofile="grd-${DATASET}-${dname}.csv";
shuf "$tmp" > "$ofile";
label_num=$((label_num+1));
fi
done
estmp="grd-${DATASET}-test-s.tmp";
vstmp="grd-${DATASET}-validation-s.tmp";
tstmp="grd-${DATASET}-training-s.tmp";
emtmp="grd-${DATASET}-test-m.tmp";
vmtmp="grd-${DATASET}-validation-m.tmp";
tmtmp="grd-${DATASET}-training-m.tmp";
eltmp="grd-${DATASET}-test-l.tmp";
vltmp="grd-${DATASET}-validation-l.tmp";
tltmp="grd-${DATASET}-training-l.tmp";
rm_if_exist "$estmp";
rm_if_exist "$vstmp";
rm_if_exist "$tstmp";
rm_if_exist "$emtmp";
rm_if_exist "$vmtmp";
rm_if_exist "$tmtmp";
rm_if_exist "$eltmp";
rm_if_exist "$vltmp";
rm_if_exist "$tltmp";
total_labels=${label_num};
for fname in `ls grd-${DATASET}-*.csv`; do
total_patterns=`wc -l $fname | cut -f1 -d' '`;
eldata_size=$((total_patterns / 10))
vldata_size=$((total_patterns * 2 / 10))
tldata_size=$((total_patterns - eldata_size - vldata_size))
head -n $eldata_size "$fname" >> "$eltmp";
head -n $((eldata_size + vldata_size)) "$fname" | tail -n $vldata_size >> "$vltmp";
tail -n $tldata_size "$fname" >> "$tltmp";
emdata_size=$((eldata_size / 2))
vmdata_size=$((vldata_size / 2))
tmdata_size=$((tldata_size / 2))
head -n $emdata_size "$fname" >> "$emtmp";
head -n $((emdata_size + vmdata_size)) "$fname" | tail -n $vmdata_size >> "$vmtmp";
tail -n $tmdata_size "$fname" >> "$tmtmp";
esdata_size=$((eldata_size / 4))
vsdata_size=$((vldata_size / 4))
tsdata_size=$((tldata_size / 4))
head -n $esdata_size "$fname" >> "$estmp";
head -n $((esdata_size + vsdata_size)) "$fname" | tail -n $vsdata_size >> "$vstmp";
tail -n $tsdata_size "$fname" >> "$tstmp";
done
esdata="grd-${DATASET}-test-s.csv";
vsdata="grd-${DATASET}-validation-s.csv";
tsdata="grd-${DATASET}-training-s.csv";
emdata="grd-${DATASET}-test-m.csv";
vmdata="grd-${DATASET}-validation-m.csv";
tmdata="grd-${DATASET}-training-m.csv";
eldata="grd-${DATASET}-test-l.csv";
vldata="grd-${DATASET}-validation-l.csv";
tldata="grd-${DATASET}-training-l.csv";
shuf "$estmp" > "$esdata"; sed -i "1i x,y" "$esdata";
shuf "$vstmp" > "$vsdata"; sed -i "1i x,y" "$vsdata";
shuf "$tstmp" > "$tsdata"; sed -i "1i x,y" "$tsdata";
shuf "$emtmp" > "$emdata"; sed -i "1i x,y" "$emdata";
shuf "$vmtmp" > "$vmdata"; sed -i "1i x,y" "$vmdata";
shuf "$tmtmp" > "$tmdata"; sed -i "1i x,y" "$tmdata";
shuf "$eltmp" > "$eldata"; sed -i "1i x,y" "$eldata";
shuf "$vltmp" > "$vldata"; sed -i "1i x,y" "$vldata";
shuf "$tltmp" > "$tldata"; sed -i "1i x,y" "$tldata";
rm -f *.tmp
|
Java
|
UTF-8
| 422 | 1.96875 | 2 |
[] |
no_license
|
package com.course.mvc.service;
import java.util.Map;
/**
* Created by Admin on 10.06.2017.
*/
public interface WebSocketService {
void saveBroadcastMessage(String broadcastMessage, String senderLogin);
Map<String,String> getMessagesByLogin(String receiverLogin);
Map<String,String> getBroadcastMessages();
void savePrivateMessage(String receiverLogin, String senderLogin, String messageToForward);
}
|
PHP
|
UTF-8
| 2,525 | 2.6875 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../css/foundation.css" />
<script type="text/javascript">
<!--
function ValidateCreate() {
var today1 = new Date().getDate(),
today2 = new Date().getMonth(),
today3 = new Date().getFullYear(),
idate1 = new Date(document.CreatePost.Tanggal.value).getDate(),
idate2 = new Date(document.CreatePost.Tanggal.value).getMonth(),
idate3 = new Date(document.CreatePost.Tanggal.value).getFullYear();
if (today3 > idate3) {
alert("Tanggal harus lebih besar atau sama dengan tanggal hari ini");
return false;
} else if ((today3 == idate3) && (today2 > idate2)) {
alert("Tanggal harus lebih besar atau sama dengan tanggal hari ini");
return false;
} else if ((today2 == idate2) && (today1 > idate1)) {
alert("Tanggal harus lebih besar atau sama dengan tanggal hari ini");
return false;
}
}
-->
</script>
</head>
<body>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="CRUD"; // Database name
$tbl_name="blogpost"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$id=$_GET['id'];
$sql="SELECT * FROM $tbl_name WHERE IDBlogPost='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<div class="row">
<div class="large-12 columns">
<h3>Update Post </h3>
<hr>
<br>
</div>
</div>
<form name="CreatePost" action="updatepost.php" onsubmit="return ValidateCreate()" method="post">
<div class="row">
<div class="large-12 columns">
<label>Judul</label>
<input type="text" name="Judul" value="<?php echo $rows['Judul']; ?>"/>
<br>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Tanggal</label>
<input type="date" name="Tanggal" value="<?php echo $rows['Tanggal']; ?>"></textarea>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Konten</label>
<textarea name="Konten" rows="30"><?php echo $rows['Konten']; ?></textarea>
<input name="id" type="hidden" value="<?php echo $rows['IDBlogPost']; ?>">
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" class="small button">
</div>
</div>
</body>
</html>
|
JavaScript
|
UTF-8
| 366 | 3.09375 | 3 |
[] |
no_license
|
//function statement named zeroFuel with parameters
//distanceToPump, mpg, fuelLeft
const zeroFuel = (distanceToPump, mpg, fuelLeft)=> {
//if mpg times fuelLeft greaterequal distanceToPump
if (mpg * fuelLeft >= distanceToPump){
//return true
return true
//else
}else{
//return false
return false
}
};
|
C#
|
UTF-8
| 2,534 | 2.5625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace Repository
{
public class MongoProvider : IMongoProvider
{
private readonly IMongoDatabase _database;
private string _collectionName;
public MongoProvider()
{
var mongoHost = "mongodb://localhost";
_database = new MongoClient(mongoHost).GetDatabase("teamTemperature");
}
public IMongoProvider ForCollection(string collectionName)
{
_collectionName = collectionName;
return this;
}
public bool Insert<T>(T model)
{
var database = _database.GetCollection<T>(_collectionName);
try
{
database.InsertOneAsync(model).GetAwaiter().GetResult();
}
catch (MongoWriteException mwx)
{
//maybe add some logging?
// mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
return false;
}
return true;
}
public bool Update<T>(T model)
{
var database = _database.GetCollection<T>(_collectionName);
var t = model.GetType();
var prop = t.GetProperty("Id").GetValue(model);
var filter = Builders<T>.Filter.Eq("_id", prop);
try
{
database.ReplaceOneAsync(filter, model).GetAwaiter().GetResult();
}
catch (MongoWriteException)
{
return false;
}
return true;
}
public bool Delete<T>(T model)
{
var database = _database.GetCollection<T>(_collectionName);
var t = model.GetType();
var prop = t.GetProperty("Id").GetValue(model);
var filter = Builders<T>.Filter.Eq("_id", prop);
var setDeleteFlag = Builders<T>.Update.Set("Deleted", true);
try
{
database.UpdateOneAsync(filter, setDeleteFlag).GetAwaiter().GetResult();
}
catch (MongoWriteException)
{
return false;
}
return true;
}
public List<T> Find<T>()
{
var database = _database.GetCollection<T>(_collectionName);
return database.Find(new BsonDocument()).ToList();
}
}
}
|
C++
|
UTF-8
| 1,782 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
/*
Acknowledgment of code on HTTP POSTing:
Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
Everything else @mrpjevans
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
// Settings
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const char* serverName = "http://<YOUR_INFLUXDB_IP_ADDRESS>:8086/write?db=plantbot";
// Set up
int sensorPin = A0;
int sensorValue = 0;
int delayTime = 30000;
void connectToWiFi() {
// Connect to WiFi
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void sendToInflux(int moisture) {
HTTPClient http;
http.begin(serverName);
String httpRequestData = "succ1 moisture=" + String(moisture);
Serial.println("Sending notification");
int httpResponseCode = http.POST(httpRequestData);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
void setup() {
Serial.begin(115200);
Serial.println("Plantbot!");
connectToWiFi();
}
void loop() {
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
//Check WiFi connection status
if (WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
sendToInflux(sensorValue);
delay(delayTime);
}
|
Python
|
UTF-8
| 3,044 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
from contextlib import contextmanager
from bentoml.exceptions import LockUnavailable
import logging
import random
import time
from bentoml.yatai.db.stores.lock import LockStore, LOCK_STATUS
logger = logging.getLogger(__name__)
# enum of read or write lock
class LockType:
READ = LOCK_STATUS.read_lock
WRITE = LOCK_STATUS.write_lock
@contextmanager
def lock(
db,
locks,
timeout_seconds=10,
timeout_jitter_seconds=1,
max_retry_count=5,
ttl_min=3,
):
"""
Context manager to acquire operation-level locks on all
resources defined in the locks parameter
:param db: instance of bentoml.yatai.db.DB
:param locks: [
(lock_identifier: string,
lock_type: bentoml.yatai.locking.lock.LockType)
]
:param timeout_seconds: amount of time to wait between lock acquisitions
:param timeout_jitter_seconds: amount of random jitter to add to timeout
:param max_retry_count: times to retry lock acquisition before failing
:param ttl_min: amount of time before lock expires
:return: (sess, lock_objs)
:exception: LockUnavailable when lock cannot be acquired
Example Usage:
```
with lock(
db, [(deployment_id, LockType.WRITE), (bento_id, LockType.READ)]
) as (sess, lock_objs):
# begin critical section
```
"""
if len(locks) < 1:
raise ValueError("At least one lock needs to be acquired")
# try to acquire lock
for i in range(max_retry_count):
try:
# create session
with db.create_session() as sess:
lock_objs = []
# acquire all locks in lock list
for (lock_identifier, lock_type) in locks:
lock_obj = LockStore.acquire(
sess, lock_type, lock_identifier, ttl_min
)
lock_objs.append(lock_obj)
# try to commit all locks to db
sess.commit()
logger.debug("Session acquired")
for lck in locks:
op = 'READ' if lck[1] == LOCK_STATUS.read_lock else 'WRITE'
logger.debug(f"\t{op} on {lck[0]}")
start = time.time()
# return locked session to user
yield sess, lock_objs
# release all locks
for lock_obj in lock_objs:
lock_obj.release(sess)
sess.commit()
end = time.time()
logger.debug(f"Session released after {end - start}s")
return
except LockUnavailable as e:
# wait before retrying
sleep_seconds = timeout_seconds + random.random() * timeout_jitter_seconds
time.sleep(sleep_seconds)
logger.warning(
f"Failed to acquire lock: {e}. "
f"Retrying {max_retry_count - i - 1} more times..."
)
raise LockUnavailable(f"Failed to acquire lock after {max_retry_count} attempts")
|
C
|
GB18030
| 2,987 | 2.53125 | 3 |
[] |
no_license
|
/*
* inf.c
*
* Created on: 2018119
* Author: Jack
*/
#include"inf.h"
extern unsigned char RECV_FLAG;
extern unsigned char ircode[4];
extern unsigned char data[33];
extern unsigned char VALUE;
/*
* ƣinfrared_decode()
* ܣ
*
* ֵ
*/
void infrared_decode()
{
if(RECV_FLAG == 1) //ɹյһݣ33½ش
{
unsigned char k=1, i, j,value; //kΪ1ΪһλΪ룬
for(j=0; j<4; j++) //4飬ÿ8λν
{
for(i=0; i<8; i++)
{
value = value>>1;
if(data[k]>6) //λݳcount>6,Ϊ1룬Ϊ0
{
value = value|0x80;
}
k++;
}
ircode[j]=value; //ircodeδ洢û롢һ롢һ뷴롢
}
RECV_FLAG=0; //ձ־λ
P6DIR = 0xff; //38 39ãڹ۲ÿӦݲͬ
P6OUT = ircode[2]; //ircode[2]Ϊ
write_cmd_1602(0x01); //lcd1602
write_cmd_1602(0x80); //ڵһʾ
dis_num(ircode[2]); //ʾircode[2]
}
}
/*
* ƣset_value()
* ܣݲ֮ͬӦļֵ
* ÿӦIJͬ
* ֵ
*/
void set_value(unsigned char argu)
{
switch(argu) //ֻңеİֵɸҪ
{
case 7: VALUE = 'S'; break; case 21: VALUE = 'A'; break; case 9: VALUE = 'E'; break;
case 22: VALUE = 0; break;
case 12: VALUE = 1; break; case 24: VALUE = 2; break; case 94: VALUE = 3; break;
case 8: VALUE = 4; break; case 28: VALUE = 5; break; case 90: VALUE = 6; break;
case 66: VALUE = 7; break; case 82: VALUE = 8; break; case 74: VALUE = 9; break;
default: break;
}
}
/*
* ƣinit_port1()
* ܣP1.0˿ڵж
*
* ֵ
*/
void init_port1()
{
P1DIR &= ~BIT0; //Ϊ뷽
P1IES |= BIT0; //ѡ½ش
P1IE |= BIT0; //ж
P1IFG = ~BIT0; //P1IESлʹP1IFGλ
}
/*
* ƣinit_devi()
* ܣTIMERA
*
* ֵ
*/
void init_device()
{
TACCTL0 = CCIE; //CCR0жʹ
TACCR0 = 33; //յ
TACTL = TASSEL_2 + MC_1; //TIMER_AѡtimerʱMCLKģʽ
BCSCTL2 |= SELS;
_EINT(); //ж
}
|
Java
|
UTF-8
| 2,099 | 2.4375 | 2 |
[] |
no_license
|
package com.ubb.gymapp;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.contains;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.ubb.gymapp.model.Room;
import com.ubb.gymapp.repository.RoomRepository;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RoomTest {
@Autowired
private RoomRepository roomRepo;
@Test
public void testAdd() {
Room room = new Room(0L,"TestRoom");
room = roomRepo.save(room);
assertNotNull(roomRepo.findOne(room.getRoomId()));
roomRepo.delete(room);
}
@Test
public void testFindOne(){
Room room = new Room(0L,"TestRoom");
room = roomRepo.save(room);
Room newRoom = roomRepo.findOne(room.getRoomId());
assertEquals(room, newRoom);
roomRepo.delete(room);
}
@Test
public void testDelete(){
Room room = new Room(0L,"TestRoom");
room = roomRepo.save(room);
roomRepo.delete(room);
assertNull(roomRepo.findOne(room.getRoomId()));
}
@Test
public void testFindAll(){
Room room1 = new Room(0L,"TestRoom1");
Room room2 = new Room(0L,"TestRoom2");
Room room3 = new Room(0L,"TestRoom3");
room1 = roomRepo.save(room1);
room2 = roomRepo.save(room2);
room3 = roomRepo.save(room3);
List<Room> dbRooms = roomRepo.findAll();
assertThat(dbRooms,hasItems(room1,room2,room3));
roomRepo.delete(room1);
roomRepo.delete(room2);
roomRepo.delete(room3);
}
@Test
public void testUpdate(){
Room room = new Room(0L,"TestRoom");
room = roomRepo.save(room);
room.setRoomName("newName");
roomRepo.save(room);
Room newRoom = roomRepo.findOne(room.getRoomId());
assertEquals(newRoom.getRoomName(), "newName");
roomRepo.delete(room);
}
}
|
Ruby
|
UTF-8
| 1,206 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
module PCBR
class Error < RuntimeError
# def initialize body
# super "#{Module.nesting[1]} error: #{body}"
# end
end
def self.new &block
Storage.new &block
end
class Storage
attr_reader :table
attr_reader :set
@@default_lambda = lambda do |a_, b_|
raise Error.new "comparison vectors are of the different length" unless a_.size == b_.size
tt = [0, 0, 0]
[*a_].zip([*b_]) do |a, b|
t = a <=> b and tt[t] = t
end
tt[0] + tt[1] + tt[2]
end
def initialize &block
require "set"
@set = ::Set.new
@table = []
@callback = block || @@default_lambda
end
def store key, vector = nil
raise Error.new "duplicating key" if @set.include? key
vector = Array key if vector.nil?
score = 0
@table.each do |item|
point = @callback.call vector, item[1]
item[2] -= point
score += point
end
@set.add key
@table.push [key, vector, score]
end
def score key
@table.assoc(key)[2]
end
def sorted
# from the best to the worst
@table.sort_by.with_index{ |item, i| [-item[2], i] }.map(&:first)
end
end
end
|
C++
|
UTF-8
| 1,988 | 3.65625 | 4 |
[] |
no_license
|
//bysouffle
/**
实验2.4队列的链式表示和实现
编写一个程序实现链队列的各种基本运算,并在此基础上设计一个主程序,完成如下功能:
(1)初始化并建立链队列。
(2)入链队列。
(3)出链队列。
(4)遍历链队列。
**/
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef struct QNode
{
int data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
int InitQueue(LinkQueue &Q) //初始化
{
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front)
exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
int EnQueue(LinkQueue &Q, int e) //入队
{
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if (!p)
exit(OVERFLOW);
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
int DeQueue(LinkQueue &Q, int &e) //出队
{
if (Q.front == Q.rear)
return ERROR;
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
free(p);
return OK;
}
int visit(int e)
{
printf("%d", e);
return OK;
}
int QueueTraverse(LinkQueue Q)
{
QueuePtr q;
if (Q.front == NULL)
exit(OVERFLOW);
q = Q.front->next;
while (q)
{
visit(q->data);
q = q->next;
}
return OK;
}
int main()
{
int i = 0;
int e;
LinkQueue Q;
printf("初始化链队列...\n");
InitQueue(Q);
printf("%d 初始化成功\n", InitQueue(Q));
printf("入链队列\n"); //入队
for (i = 0; i <= 7; i++)
{
EnQueue(Q, i);
}
printf("操作成功");
printf("打印队列元素:");
QueueTraverse(Q);
printf("\n");
printf("出链队列\n"); //出队
DeQueue(Q, e);
printf("操作成功");
printf("打印队列元素:");
QueueTraverse(Q);
printf("\n出队元素为:%d", e);
printf("\n");
printf("遍历链队列\n"); //遍历
QueueTraverse(Q);
system("pause");
}
|
Java
|
UTF-8
| 255 | 1.507813 | 2 |
[] |
no_license
|
package operator.services.api;
import operator.entities.AccessLevel;
/**
* Created by Artyom Karnov on 8/27/16.
* artyom-karnov@yandex.ru
**/
/**
* Interface for AccessLevelService
*/
public interface AccessLevelService extends GenericService<AccessLevel, Integer> {
}
|
JavaScript
|
UTF-8
| 289 | 2.515625 | 3 |
[] |
no_license
|
import { ERROR, CLEAR_ERROR} from '../constants/actionTypes';
const errorReducer = (state = null, action) => {
switch(action.type) {
case ERROR:
return action.error;
case CLEAR_ERROR:
return null;
default: return state;
}
};
export default errorReducer;
|
SQL
|
UTF-8
| 776 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
USE employee_tracker;
INSERT INTO department(name)
VALUES
('Management')
, ('Sales')
, ('Engineering')
, ('Finance')
, ('legal');
INSERT INTO role(title, salary, department_id)
VALUES
('Legal Team Lead', 200000, 1)
, ('Lawyer', 150000, 2)
, ('Lead Engineer', 125000, 3)
, ('Accountant', 120000, 4)
, ('Softwear Engineer', 85000, 5)
, ('Salesperson', 60000, 6);
INSERT INTO employee(first_name, last_name, role_id)
VALUES
('parth', 'Patel', 1)
, ('krish', 'Gamit', 6)
, ('krishna', 'yadav', 4)
, ('Ravan', 'Lankesh', 5)
, ('Ram', 'Darbar', 3)
, ('Mark', 'Thomas', 2);
UPDATE `employee_tracker`.`employee` SET `manager_id` = '1' WHERE (`id` > '1');
SELECT * FROM employee;
SELECT * FROM role;
SELECT * FROM department
|
Markdown
|
UTF-8
| 4,899 | 3.640625 | 4 |
[] |
no_license
|
## IIFE와 비동기적 코드
[6장](../CHAPTER_6/preview.md)에서 <b>IIFE(즉시 호출하는 함수 표현식)</b>에 대해 알아봤습니다. IIFE를 이용해서 클로저를 만들 수 있다는 것도 알았습니다. 이제 IIFE로 비동기적 코드를 처리하는 중요한 예제를 하나 살펴봅시다. 이 예제는 14장에서 다시 살펴보게 될 겁니다.
IIFE를 사용하는 사례 중 하나는 비동기적 코드가 정확히 동작할 수 있도록 새 변수를 새 스코프에 만드는 겁니다. 5초에서 시작하고 카운트다운이 끝나면 "go"를 표시하는 고전적 타이머 예제를 만들어 봅시다. 이 코드는 자바스크립트의 내장 함수 setTimeout을 사용합니다. setTimeout은 첫 번째 매개변수인 함수를 두 번째 매개변수인 밀리초만큼 기다렸다가 실행합니다. 예를 들어 1.5초 뒤에 hello를 출력한다면 다음과 같이 합니다.
```javascript
setTimeout(function() {
console.log('hello');
}, 1500);
```
필요한 것은 다 알았으니 카운트다운 함수를 만들어 봅시다.
```javascript
var i;
for (i=5; i>=0; i--) {
setTimeout(function() {
console.log(i===0? "go!":i);
}, (5-i)*1000);
}
/*
-1
-1
-1
-1
-1
-1
*/
```
여기서 let 대신 var를 쓴 이유는 IIFE가 중요하던 시점으로 돌아가서 왜 중요했는지 이해하기 위해서입니다. 5, 4, 3, 2, 1, go!가 출력될 거라 예상했다면, 아쉽지만 틀렸습니다. -1이 여섯번 출력될 뿐입니다. 어떻게 된 걸까요? setTimeout에 전달된 함수가 루프 안에서 실행되지 않고 루프가 종료된 뒤에 실행됐기 때문입니다. 따라서 루프의 i는 5에서 시작해 -1로 끝납니다. 그리고 -1이 되기 전에는 콜백 함수는 전혀 호출되지 않습니다(루프가 끝나기 전까지). 따라서 콜백 함수가 호출되는 시점에서 i의 값은 -1입니다.
let을 사용해 블록 수준 스코르를 만들면 이 문제는 해결되지만, 비동기적 프로그래밍에 익숙하지 않다면 아 되는구나, 하고 넘어가지 말고 이 예제를 정확히 이해해야 합니다. 좀 어려울수도 있지만, [14장](../CHAPTER_14/preview.md)의 주제인 비동기적 실행을 이해하기 위해 꼭 필요합니다.
블록 스코프 변수가 도입되지 전에는 이런 문제를 해결하기 위해 함수를 하나 더 썼습니다. 함수를 하나 더 쓰면 스코프가 새로 만들어지고 각 단계에서 i의 값이 클로저에 캡쳐됩니다. 이름 붙은 함수를 쓰는 예제를 먼저 봅시다.
```javascript
function loopBody(i) {
setTimeout(function() {
console.log(i===0? "go!":i);
}, (5-i)*1000);
}
var i;
for (i=5; i>=0; i--) {
loopBody(i);
}
```
루프의 각 단계에서 loopBody 함수가 호출됩니다. 자바스크립트는 매개변수를 값으로 넘깁니다. 따라서 루프의 각 단계에서 함수에 전달되는 것은 변수 i가 아니라 i의 값입니다. 즉 처음에는 5가, 두 번째에는 4가 전달됩니다. 같은 변수 이름 i를 썼지만, 이게 중요한 건 아닙니다. 중요한 것은 스코프 일곱 개가 만들어졌고 변수도 일곱 개 만들어졌다는 겁니다(하나는 외부 스코프, 나머지 여섯 개는 loopBody를 호출할 때마다).
하지만 루프에 한 번 쓰고 말 함수에 일일이 이름을 붙이는 건 성가신 일입니다. 익명 함수를 만들어 즉시 호출하는 IIFE를 사용하는게 더 낫습니다. 이전 예제를 IIFE를 써서 고쳐 쓰면 다음과 같습니다.
```javascript
var i;
for (i=5; i>=0; i--) {
(function(i) {
setTimeout(function() {
console.log(i===0? "go!":i);
}, (5-i)*1000);
})(i);
}
```
이 코드를 살펴보면, 매개변수 하나를 받는 함수를 만들어서 루프의 각 단계에서 호출한 것과 완전히 똑같음을 알 수 있습니다.
블록 스코프 변수를 사용하면 스코프 하나 때문에 함수를 새로 만드는 번거로운 일을 하지 않아도 됩니다. 블록 스코프 변수를 사용하면 이 예제를 극도로 단순화 할 수 있습니다.
```javascript
for(let i=5; i>=0; i--) {
setTimeout(function() {
console.log(i===0? "go!":i);
}, (5-i)*1000);
}
```
이번에는 for 루프 안에 let 키워드를 썼습니다. let 키워드를 for 루프 바깥에 썼다면 똑같은 문제가 발생했을 겁니다. let 키워드를 이런 식으로 사용하면 자바스크립트는 루프의 단계마다 변수 i의 복사본을 새로 만듭니다. 따라서 setTimeout에 전달한 함수가 실행될 때는 독립 스코프에서 변수를 받습니다.
***
[이전 : 함수도 객체다](13.4.1.md) <br/>
[다음 : 변수로서의 함수](13.6.md) <br/>
[목차](../progressCheck.md)
|
C#
|
UTF-8
| 4,461 | 3.34375 | 3 |
[] |
no_license
|
using System;
namespace Sampan.Common.Extension
{
public static class DateTimeExtension
{
/// <summary>
/// 一年的第一天
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static DateTime FirstDayOfYear(this DateTime date)
{
return new DateTime(date.Year, 1, 1).Date;
}
/// <summary>
/// 当前日期所在月份的第一天
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static DateTime FirstDayOfMonth(this DateTime date)
{
return date.AddDays(-(date.Day) + 1).Date;
}
/// <summary>
/// 取得某月的最后一天
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static DateTime LastDayOfMonth(this DateTime date)
{
return date.AddDays(1 - date.Day).AddMonths(1).AddDays(-1).Date;
}
/// <summary>
/// 与指定日期相差几个月
/// </summary>
/// <param name="dt">小的日期</param>
/// <param name="date">大的日期</param>
/// <returns></returns>
public static int IntervalMonths(this DateTime dt, DateTime date)
{
return (date.Year * 12 - (12 - date.Month)) - (dt.Year * 12 - (12 - dt.Month));
}
public static DateTime ObjToDate(this object thisValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
reval = Convert.ToDateTime(thisValue);
}
return reval;
}
public static string ObjToString(this object thisValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return "";
}
public static bool ObjToBool(this object thisValue)
{
bool reval = false;
if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
/// <summary>
/// 获取星期几
/// </summary>
/// <returns></returns>
public static string GetWeek(DateTime dateTime = default)
{
if (dateTime == default) dateTime = DateTime.Now;
string week;
switch (dateTime.DayOfWeek)
{
case DayOfWeek.Monday:
week = "周一";
break;
case DayOfWeek.Tuesday:
week = "周二";
break;
case DayOfWeek.Wednesday:
week = "周三";
break;
case DayOfWeek.Thursday:
week = "周四";
break;
case DayOfWeek.Friday:
week = "周五";
break;
case DayOfWeek.Saturday:
week = "周六";
break;
case DayOfWeek.Sunday:
week = "周日";
break;
default:
week = "N/A";
break;
}
return week;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static long UnixTimestamp(this DateTime dt)
{
var unixStartTime = new DateTime(1970, 1, 1, 8, 0, 0, 0);
long timestamp =
(dt.ToUniversalTime().Ticks - unixStartTime.ToUniversalTime().Ticks) / 10000000; //除10000调整为13位
//long t = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
return timestamp;
}
public static DateTime UnixDateTime(this DateTime dt)
{
return new DateTime(1970, 1, 1);
}
/// <summary>
/// 获取这个日期的最后一秒
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DateTime ToLastDateTime(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, 23, 59, 59);
}
}
}
|
Java
|
UTF-8
| 530 | 2.8125 | 3 |
[] |
no_license
|
package com.two95.cards;
import java.util.List;
public class Suites {
private String cardName;
private String colour;
private List<CardValue> cardValue;
public Suites() {
}
public Suites(String cardName, String colour, List<CardValue> cardValue) {
super();
this.cardName = cardName;
this.colour = colour;
this.cardValue = cardValue;
}
@Override
public String toString() {
return "cardName = " + cardName + ", Card colour = " + colour + ", cardValues = " + cardValue ;
}
}
|
Java
|
UTF-8
| 6,365 | 1.90625 | 2 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
package vn.evolus.castr;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.MediaRouteChooserDialog;
import android.support.v7.media.MediaControlIntent;
import android.support.v7.media.MediaRouteSelector;
import android.support.v7.media.MediaRouter;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaTrack;
import com.google.sample.cast.refplayer.R;
import com.google.sample.cast.refplayer.VideoBrowserActivity;
import com.google.sample.cast.refplayer.browser.VideoProvider;
import com.google.sample.cast.refplayer.mediaplayer.LocalPlayerActivity;
import java.util.ArrayList;
public class MainActivity extends VideoBrowserActivity {
public static final String TAG = "Castr";
private static final String APP_URL = "https://play.evolus.vn/castr/movie-websites.html";
private long lastBackAt = 0;
XWebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupActionBar();
webView = this.getWebView();
webView.loadUrl(APP_URL);
SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.YELLOW);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (webView.canGoBack()) {
webView.reload();
supportInvalidateOptionsMenu();
} else {
gotoHomeRunnable.run();
}
}
});
}
Runnable gotoHomeRunnable = new Runnable() {
@Override
public void run() {
webView.clearHistoryRequested();
supportInvalidateOptionsMenu();
webView.loadUrl(APP_URL);
System.out.println("Go home called");
}
};
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_home) {
gotoHomeRunnable.run();
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_home).setVisible(webView != null && webView.canGoBack());
return super.onPrepareOptionsMenu(menu);
}
private XWebView getWebView() {
return this.findViewById(R.id.webView);
}
@Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed:");
if (webView != null && webView.canGoBack()) {
webView.goBack();
supportInvalidateOptionsMenu();
return;
}
long now = System.currentTimeMillis();
if (lastBackAt > now - 1000) {
super.onBackPressed();
} else {
Toast.makeText(this, "Press back again to quit.", Toast.LENGTH_SHORT).show();
lastBackAt = now;
}
}
public void setPageTitle(String title) {
this.getSupportActionBar().setTitle(title);
}
MediaInfo pendingItem = null;
public void startCasting(String title, String description, String posterURL, String mediaURL) {
Log.d(TAG, "startCasting: " + title + " -> url: " + mediaURL + "poster: " + posterURL);
final MediaInfo item = VideoProvider.buildMediaInfo(title, "", "", 0, mediaURL, "video/mp4", posterURL, posterURL, new ArrayList<MediaTrack>());
this.pendingItem = null;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mCastSession != null && mCastSession.isConnected()) {
pendingItem = null;
LocalPlayerActivity.loadRemoteMedia(MainActivity.this, mCastSession, item, 0, true, gotoHomeRunnable);
} else {
pendingItem = item;
showMediaRouteChooser();
}
}
});
}
private void showMediaRouteChooser() {
final MediaRouteChooserDialog mediaRouteChooserDialog = new MediaRouteChooserDialog(MainActivity.this);
MediaRouteSelector.Builder builder = new MediaRouteSelector.Builder();
builder.addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK);
mediaRouteChooserDialog.setRouteSelector(builder.build());
mediaRouteChooserDialog.show();
mediaRouteChooserDialog.refreshRoutes();
mediaRouteChooserDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
MediaRouter mediaRouter = MediaRouter.getInstance(MainActivity.this);
//No route found
if (mediaRouter.getRoutes() == null || mediaRouter.getRoutes().size() == 0) {
Intent intent = new Intent(MainActivity.this, LocalPlayerActivity.class);
intent.putExtra("media", pendingItem);
intent.putExtra("shouldStart", true);
intent.putExtra("playOnRemote", false);
startActivity(intent);
pendingItem = null;
}
}
});
}
@Override
protected void onApplicationConnected() {
super.onApplicationConnected();
if (pendingItem != null) {
LocalPlayerActivity.loadRemoteMedia(this, mCastSession, pendingItem, 0, true, gotoHomeRunnable);
pendingItem = null;
}
}
public void refreshDone() {
SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setRefreshing(false);
}
}
|
Python
|
UTF-8
| 1,182 | 3.40625 | 3 |
[] |
no_license
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
#recursion method
def maxDepth(self, root: TreeNode) -> int:
if not root :
return 0
else:
return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))
#bfs method
def maxDepth(self, root: TreeNode) -> int:
if not root :
return 0
result =0
q =[]
q.append(root)
# q = Queue.Queue()
# q.put(root)
while len(q) >0 :
result +=1
n = len(q)
for i in range(0,n) :
currNode = q[i]
if currNode.left :
q.append(currNode.left)
if currNode.right :
q.append(currNode.right)
q=q[n:]
return result
if __name__ == '__main__':
t = Solution()
root= TreeNode(3)
node2= TreeNode(9)
node3= TreeNode(20)
node4= TreeNode(15)
node5= TreeNode(7)
root.left =node2
root.right =node3
node3.left =node4
node3.right =node5
result = t.maxDepth(root)
print(result)
|
Python
|
UTF-8
| 788 | 3.203125 | 3 |
[] |
no_license
|
#use libarary
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
import matplotlib.pyplot as plt
import pandas as pd
#read datasets
data=pd.read_csv('diabetes.csv')
#split data
features_col=data.drop('Outcome',axis=1)
target=data['Outcome']
#split data for model
x_train,x_test,y_train,y_test=train_test_split(features_col,target,test_size=0.3,random_state=1)
#creat decisiontreeclassifier
model=DecisionTreeClassifier(criterion='entropy',max_depth=3)
#train model
model=model.fit(x_train,y_train)
#predict model
y_pred=model.predict(x_test)
#accuracy of this model
print('Accuracy is:',metrics.accuracy_score(y_test,y_pred))
|
PHP
|
UTF-8
| 1,378 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace PlanBundle\Schedule\Common\Logger;
use Symfony\Bridge\Monolog\Logger as Monolog;
class SchedulerLogger
{
private $logger;
private $options;
public function __construct(Monolog $monolog, array $options = array())
{
$this->logger = $monolog;
$this->options = $options;
}
public function getLogLevel()
{
return $this->options['logLevel'];
}
public function initLog($logMsg)
{
switch ($this->getLogLevel()) {
case 'emergency': // 600
$this->logger->emergency($logMsg);
break;
case 'alert': //550
$this->logger->alert($logMsg);
break;
case 'critical': //500
$this->logger->critical($logMsg);
break;
case 'error': //400
$this->logger->error($logMsg);
break;
case 'warning': //300
$this->logger->warning($logMsg);
break;
case 'notice': // 250
$this->logger->notice($logMsg);
break;
case 'info': //200
$this->logger->info($logMsg);
break;
case 'debug': //100
default:
$this->logger->debug($logMsg);
break;
}
}
}
|
C#
|
UTF-8
| 1,325 | 3.015625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace SerializeHome
{
class Program
{
static void Main(string[] args)
{
string file = "book.bin";
List<Book> book = new List<Book>
{
new Book(" C# 5.0 and the .NET 4.5 Framework", 5000, "Andrew Troelsen", new DateTime(2013) ),
new Book(" Изучаем с#. Полное Руководство", 6000, "Герберт Шилдт", new DateTime(2010) ),
new Book(" Программирование на С++", 7000, "Бьерн Страуструп", new DateTime(2011) ),
new Book(" Язык программирования С++", 4000, "Стивен Прата", new DateTime(2009) )
};
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(file, FileMode.Create))
{
formatter.Serialize(stream, book.ToArray());
}
List<Book> books;
using (FileStream stream = new FileStream(file, FileMode.OpenOrCreate))
{
books = new List<Book>(formatter.Deserialize(stream) as Book[]);
}
}
}
}
|
Swift
|
UTF-8
| 3,105 | 2.71875 | 3 |
[] |
no_license
|
//
// FlickrAPIController.swift
// SwiftFlickrSearcher3
//
// Created by suraj poudel on 26/07/2016.
// Copyright © 2016 suraj poudel. All rights reserved.
//
import Foundation
import UIKit
public class FlickrAPIController{
public typealias FlickrAPICompletion = (success:Bool,resultsDictionary:[String:AnyObject]?)->()
typealias InternalAPICompletion = (responseDict:[String:AnyObject]?,error:NSError?)->()
func makeAPIRequest(httpMethod:HTTPMethod,params:[String:String],internalAPICompletion:InternalAPICompletion){
var queryItems = [NSURLQueryItem]()
let keys = Array(params.keys)
let values = Array(params.values)
for i in 0..<keys.count{
let queryItem = NSURLQueryItem(name: keys[i], value: values[i])
queryItems.append(queryItem)
}
let components = FlickrAPIComponents()
if let url = components.urlWithParams(queryItems){
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = httpMethod.rawValue
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
if let unwrappedError = error{
NSLog("Error with API request:\(unwrappedError)")
internalAPICompletion(responseDict: nil, error: unwrappedError)
}else{
do{
if let data = data , let dict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]{
internalAPICompletion(responseDict: dict, error: nil)
}
}catch let error as NSError{
print("JSON Error \(error)")
}
}
})
task.resume()
}
}
public func fetchPhotosForTerm(term:String,flickrAPICompletion:FlickrAPICompletion){
let paramsDict = [
FlickrParameterName.Method.rawValue : FlickrMethod.Search.rawValue,
FlickrSearchParameterName.Tags.rawValue : term
]
makeAPIRequest(HTTPMethod.GET, params: paramsDict) { (responseDict, error) in
if let _ = error{
self.fireCompletionOnMainQueueWithSuccess(false,result:nil,flickrAPICompletion:flickrAPICompletion)
}else{
self.fireCompletionOnMainQueueWithSuccess(true, result: responseDict, flickrAPICompletion: flickrAPICompletion)
}
}
}
private func fireCompletionOnMainQueueWithSuccess(success:Bool,result:[String:AnyObject]?,flickrAPICompletion:FlickrAPICompletion){
if NSThread.currentThread() == NSThread.mainThread(){
flickrAPICompletion(success: success, resultsDictionary: result)
}else{
NSOperationQueue.mainQueue().addOperationWithBlock({
flickrAPICompletion(success: success, resultsDictionary: result)
})
}
}
}
|
Markdown
|
UTF-8
| 688 | 2.578125 | 3 |
[] |
no_license
|
---
id: gen
title: Generate Key
sidebar_label: gen
---
# gen
The `gen` command generates an ed25519 key pair.
## Usage
```bash
kit key gen [options]
```
```bash
Usage:
kit key gen [flags]
Flags:
-h, --help help for gen
-s, --seed int Provide a strong seed (not recommended)
```
## Options
* `-s, --seed` - Provide an integer to be used as the seed.
* `-h, --help` - Prints out a help message.
## Example
{% tabs %}
{% tab title="Bash" %}
```bash
kit key gen
```
{% endtab %}
{% tab title="Output" %}
```bash
Private Key: wZRxNmWoDvpvv5abPqXDHL...6ggmSLVrVqa7sWg6rqTCahvogmYugYpLGNDffAct
Public Key: 48YD57pjLkpx5pBaF87jvrHUg9adPkvpCM4nJxmw9W94wEUft6K
Account Address: os132k9z96cryeq9dp4jva380rp6xeskdrdpup3l5
Push Address: pk132k9z96cryeq9dp4jva380rp6xeskdrdp2fuea
```
{% endtab %}
{% endtabs %}
|
Java
|
ISO-8859-1
| 954 | 3.75 | 4 |
[] |
no_license
|
package controle;
import java.util.Scanner;
public class DesafioSemana {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Digite o dia da semana: ");
String dia = entrada.next();
if(dia.equalsIgnoreCase("Domingo")) {
System.out.println("1");
} else if(dia.equalsIgnoreCase("Segunda-feira")) {
System.out.println("2");
} else if(dia.equalsIgnoreCase("Tera-feira")
|| (dia.equalsIgnoreCase("Terca-feira"))) {
System.out.println("3");
} else if(dia.equalsIgnoreCase("Quarta-feira")) {
System.out.println("4");
} else if(dia.equalsIgnoreCase("Quinta-feira")) {
System.out.println("5");
} else if(dia.equalsIgnoreCase("Sexta-feira")) {
System.out.println("6");
} else if("Sbado".equalsIgnoreCase(dia)
|| ("Sabado".equalsIgnoreCase(dia))) {
System.out.println("7");
}
entrada.close();
}
}
|
Java
|
UTF-8
| 523 | 1.867188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.uaa.ponzi.dto;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
@Data
public class SysPermissionNewDto {
@NotEmpty(message = "请填写权限名称")
private String permissionName;
@NotEmpty(message = "请填写权限代码")
private String permissionCode;
@Min(value = -1, message = "请选择权限类型")
private Integer permissionType;
@NotEmpty(message = "请选择所属菜单")
private String sysMenuId;
}
|
Java
|
UTF-8
| 1,475 | 2.421875 | 2 |
[
"MIT"
] |
permissive
|
package me.coderleo.chitchat.client.packethandlers;
import javafx.application.Platform;
import me.coderleo.chitchat.client.packethandlers.auth.PacketLoginResponseHandler;
import me.coderleo.chitchat.client.packethandlers.auth.PacketRegisterResponseHandler;
import me.coderleo.chitchat.common.api.Packet;
import java.util.ArrayList;
public class PacketHandlerManager
{
private static final PacketHandlerManager instance = new PacketHandlerManager();
public static PacketHandlerManager getInstance()
{
return instance;
}
private final ArrayList<PacketHandler<?>> handlers = new ArrayList<>();
private PacketHandlerManager()
{
handlers.add(new PacketLoginResponseHandler());
handlers.add(new PacketRegisterResponseHandler());
handlers.add(new LogoutHandler());
handlers.add(new PacketMessageHandler());
handlers.add(new PacketUserListHandler());
handlers.add(new PacketConversationListHandler());
handlers.add(new PacketUserJoinHandler());
handlers.add(new PacketUserLeaveHandler());
}
@SuppressWarnings({"unchecked", "rawtypes"})
public <T extends Packet> void handle(T packet)
{
for (PacketHandler handler : handlers)
{
if (handler.getPacketClass().equals(packet.getClass()))
{
// javafx thread fix?
Platform.runLater(() -> handler.handle(packet));
}
}
}
}
|
Java
|
UTF-8
| 92 | 1.953125 | 2 |
[] |
no_license
|
package composite.pattern.demo;
public interface ITeacher {
public String getDetails();
}
|
C
|
UTF-8
| 789 | 3.03125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
void handle(int sig)
{
if (SIGINT == sig)
{
sigset_t set;
sigset_t old;
sigemptyset(&set);
sigaddset(&set, SIGTSTP);
sigaddset(&set, SIGQUIT);
//sigprocmask(SIG_BLOCK, &set, NULL);
sigprocmask(SIG_BLOCK, &set, &old);
printf("$$$$$$$$$$$$$$$$$$\n");
int i = 20;
while (i)
{
printf("ctrl + c pressed...%d\n",i--);
sleep(1);
if (10 == i)
{
//sigprocmask(SIG_UNBLOCK, &set, NULL);
sigprocmask(SIG_SETMASK, &old, NULL);
}
}
}
else if (SIGTSTP == sig)
{
printf("ctrl + z pressed...\n");
}
}
int main(void)
{
signal(SIGINT, handle);
signal(SIGTSTP, handle);
while (1)
{
printf("waitting signal...\n");
pause();
}
return 0;
}
|
C
|
UTF-8
| 443 | 3.21875 | 3 |
[] |
no_license
|
#include "hash_tables.h"
/**
* hash_table_create - that function create a new node
* @size: length of the table
* Return: a new node
*/
hash_table_t *hash_table_create(unsigned long int size)
{
hash_table_t *new;
new = malloc(sizeof(hash_table_t));
if (new == NULL)
{
return (NULL);
}
new->array = calloc(size, sizeof(hash_node_t *));
if (new == NULL)
{
free(new);
return (NULL);
}
new->size = size;
return (new);
}
|
TypeScript
|
UTF-8
| 6,568 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
import { ValidationTrigger } from "../src/constants/validationTrigger";
import { field } from "../src/fields/FieldCreatorInstance";
import { FormConfig } from "../src/form-config/FormConfig";
import { FormConfigHelper } from "../src/form-config/FormConfigHelper";
import { setTrigger } from "./test-utils/setTrigger";
const { AfterTouchOnChange, OnChange, OnSubmitOnly } = ValidationTrigger;
describe("FormConfigHelper", () => {
describe("getInitialValues", () => {
let formConfig: FormConfig;
let formConfigHelper: FormConfigHelper;
beforeEach(() => {
formConfig = new FormConfig({
username: field.text("user"),
email: field.email(),
age: field.number("30"),
});
formConfigHelper = new FormConfigHelper(formConfig);
});
it("extracts initial values from fields", () => {
const initialValues = formConfigHelper.getInitialValues();
expect(initialValues).toMatchObject({
username: "user",
email: "",
age: "30",
});
});
it("extracts initial values from object first", () => {
formConfig.withInitialValues({
username: "another-user",
email: "user@mail.com",
age: "25",
});
const initialValues = formConfigHelper.getInitialValues();
expect(initialValues).toMatchObject({
username: "another-user",
email: "user@mail.com",
age: "25",
});
});
it("fallbacks to initial values from fields if no value was provided from object", () => {
formConfig.withInitialValues({
age: "25",
});
const initialValues = formConfigHelper.getInitialValues();
expect(initialValues).toMatchObject({
username: "user",
email: "",
age: "25",
});
});
});
describe("getInitialState", () => {
let formConfig: FormConfig;
let formConfigHelper: FormConfigHelper;
beforeEach(() => {
formConfig = new FormConfig({
username: field.text("user"),
email: field.email(),
age: field.number("30"),
});
formConfigHelper = new FormConfigHelper(formConfig);
});
it("sets defaults properly", () => {
const initialState = formConfigHelper.getInitialState();
expect(initialState).toEqual({
values: { username: "user", email: "", age: "30" },
touched: {},
validity: {},
errors: {},
context: {},
submitting: false,
});
});
it("uses initial context from config", () => {
formConfig.withContext({ contextValue: 1 });
const initialState = formConfigHelper.getInitialState();
expect(initialState.context).toEqual({ contextValue: 1 });
});
it("prefers passed initial values", () => {
const initialState = formConfigHelper.getInitialState({
email: "email@test.com",
age: "50",
});
expect(initialState.values).toEqual({
username: "user",
email: "email@test.com",
age: "50",
});
});
});
describe("shouldValidateOnChange", () => {
let formConfig: FormConfig;
let helper: FormConfigHelper<typeof formConfig>;
beforeEach(() => {
formConfig = new FormConfig({
username: field.text(""),
email: field.text(""),
});
helper = new FormConfigHelper(formConfig);
});
it("returns false by default when not touched", () => {
expect(helper.shouldValidateOnChange("username", true)).toBeTruthy();
expect(helper.shouldValidateOnChange("username", false)).toBeFalsy();
expect(helper.shouldValidateOnChange("username", undefined)).toBeFalsy();
});
it("uses global trigger for fields with no trigger", () => {
formConfig._fields.username.validateOnSubmitOnly();
expect(helper.shouldValidateOnChange("username", true)).toBeFalsy();
expect(helper.shouldValidateOnChange("email", true)).toBeTruthy();
});
test.each<
[
ValidationTrigger,
ValidationTrigger | undefined,
boolean | undefined,
boolean
]
>([
[AfterTouchOnChange, OnChange, true, true],
[AfterTouchOnChange, OnChange, false, true],
[AfterTouchOnChange, OnChange, undefined, true],
[OnChange, undefined, false, true],
[OnChange, OnSubmitOnly, true, false],
[OnSubmitOnly, AfterTouchOnChange, true, true],
])(
'with global trigger "%p", field trigger "%p" and touched "%p" it returns "%p"',
(
globalTrigger: ValidationTrigger,
fieldTrigger: ValidationTrigger | undefined,
touched: boolean | undefined,
result: boolean
) => {
setTrigger(formConfig, globalTrigger);
setTrigger(formConfig._fields.username, fieldTrigger);
expect(helper.shouldValidateOnChange("username", touched)).toBe(result);
}
);
});
describe("shouldValidateOnBlur", () => {
let formConfig: FormConfig;
let helper: FormConfigHelper<typeof formConfig>;
beforeEach(() => {
formConfig = new FormConfig({
username: field.text(""),
email: field.text(""),
});
helper = new FormConfigHelper(formConfig);
});
it("returns true by default when touched right now", () => {
expect(helper.shouldValidateOnBlur("username", true)).toBeTruthy();
expect(helper.shouldValidateOnBlur("username", false)).toBeFalsy();
});
it("uses global trigger for fields with no trigger", () => {
formConfig._fields.username.validateOnSubmitOnly();
expect(helper.shouldValidateOnBlur("username", true)).toBeFalsy();
expect(helper.shouldValidateOnBlur("email", true)).toBeTruthy();
});
test.each<
[ValidationTrigger, ValidationTrigger | undefined, boolean, boolean]
>([
[OnChange, AfterTouchOnChange, true, true],
[OnChange, AfterTouchOnChange, false, false],
[AfterTouchOnChange, undefined, true, true],
[AfterTouchOnChange, undefined, false, false],
[AfterTouchOnChange, OnChange, true, false],
[AfterTouchOnChange, OnSubmitOnly, true, false],
])(
'with global trigger "%p", field trigger "%p" and touched "%p" it returns "%p"',
(
globalTrigger: ValidationTrigger,
fieldTrigger: ValidationTrigger | undefined,
touched: boolean,
result: boolean
) => {
setTrigger(formConfig, globalTrigger);
setTrigger(formConfig._fields.username, fieldTrigger);
expect(helper.shouldValidateOnBlur("username", touched)).toBe(result);
}
);
});
});
|
Shell
|
UTF-8
| 101 | 2.546875 | 3 |
[] |
no_license
|
#!/bin/bash
#set -x
#set -e
echo="name is name"
var=5
set -x
echo $var
set +x
test = 10
echo "test"
|
Python
|
UTF-8
| 1,401 | 2.828125 | 3 |
[] |
no_license
|
# with문을 사용하여 close 처리 및 기타 닫는 부분 보정
# 비정상 종료를 없애고 -> try~
# 정상적인 처리 부분의 틀을 완성했다
import pymysql as my
connection = None
try:
connection = my.connect(host='localhost', # 디비 주소
user='root', # 디비 접속 계정
password='12341234', # 디비 접속 비번
db='python_db', # 데이터베이스 이름
# port=3306, # 포트
charset='utf8',
cursorclass=my.cursors.DictCursor) # 커서타입지정
if connection:
print('디비 오픈')
##################################################################
with connection.cursor() as cursor:
sql = "select * from users where uid='m' and upw='1';"
cursor.execute(sql)
row = cursor.fetchone()
# {'id': 1, 'uid': 'm', 'upw': '1', 'name': '멀티', 'regdate': datetime.datetime(2019, 1, 7, 14, 16, 4)}
print(row)
print("%s님 반갑습니다." %row['name'])
# cursor.close()
##################################################################
except Exception as e:
print('->',e)
finally:
if connection:
connection.close()
print('디비 닫기')
|
Python
|
UTF-8
| 112 | 3.3125 | 3 |
[] |
no_license
|
#print.py
#此示例示意print的用法和关键字参数的作用
print()
print(1,2,3,4)
print(1,2,3,4,sep='')
|
Python
|
UTF-8
| 4,395 | 3.3125 | 3 |
[] |
no_license
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import re
from basic.bupt_2017_11_28.type_deco import prt
import joblib
from sklearn import preprocessing
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from basic.bupt_2017_11_28.type_deco import prt
import seaborn as sns
'''
User:waiting
Date:2017-12-22
Time:14:06
'''
# 将可迭代对象同时赋值给多个变量是允许的,唯一的要求就是,变量的个数要与可迭代对象中元素的数量相同
series = [1,'a',2,(3,4)]
a,b,c,d = series
# print(d[0])
# 当变量的个数与可迭代对象中元素数量不相同时,会raise一个ValueError
# a,b,c,d,e = series
# a,b,c = series
#迭代器、生成器、字符串、文件对象也可以直接使用这种语法
it = iter(series)
a,b,c,d = it
a,b,c,d = 'abcd'
# print(d[0])
# *表达式在这种语法中的作用,如果只想取得可迭代对象中的前n个,后n个,或者中间的n个元素,可以使用*表达式
# *表达式一定是以列表的类型返回
a,*b,c = series #中间n-2个
# print(b)
*a,b,c = series #前n-2个
# print(a)
a,b,*c = series #后n-2个
# print(c)
# 保留最后(最近)n个元素,使用collections模块的deque,比如,在一个文件中按指定的模式逐行匹配文本
from collections import deque
def search(lines,pattern,history = 5):
previous_lines = deque(maxlen=history)
for line in lines:
if re.match(pattern,line):
yield line,previous_lines
previous_lines.append(line)
def use():
with open('a.txt') as f:
for matched,previous_lines in search(f,r'\d+'):
print('cur_matched:{}'.format(matched))
print('previous_lines:{}'.format(previous_lines))
print('---------------')
# use()
# 查找集合中最大/最小的 n个元素,使用collections模块的heapq,
import heapq
def nlargest(series,n,key = None):
return heapq.nlargest(n,series,key)
def nsmallest(series,n,key = None):
return heapq.nsmallest(n,series,key)
series = range(10)
previous_3_largest = nlargest(series,3)
# print(previous_3_largest)
previous_3_smallest = nsmallest(series,3)
# print(previous_3_smallest)
# 如果待比较对象是一个复杂对象,希望按指定的属性进行比较,可以通过传入一个匿名函数,其返回值为指定的属性;也可以返回包含多个属性的元组,优先级依次递减
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 100, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
m= nlargest(portfolio,3, lambda x:(x['shares'],x['price']))
m= nlargest(portfolio,3, lambda x:x['shares'])
# print(m)
# 一键映射多个值的字典,使用collections模块的defaultdict可以为每个key生成一个默认的value映射,避免raise ValueError,并且使用起来更加优雅
from collections import defaultdict
d = defaultdict(list) # key的默认映射是空列表,[]
d = defaultdict(int) # key的默认映射是0
# 通过zip函数让字典按值比较,首先翻转dict的键与值的顺序,让形成的元组value在前,key在后
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
m = min(zip(prices.values(),prices.keys()))
# print(m)
# 寻找两个dict的相同点,dict的keys()方法和items方法都可以被当做集合来使用
prices.keys() & prices.keys()
prices.items() & prices.items()
# 消除序列中的重复元素并保持剩下的元素的相对顺序,可以使用生成器和set来解决
def generate_no_dup(series,key = None): # 若不传key,此方法仅仅对于序列元素是hashable的时候,dict不是hashable
seen = set()
for item in series:
if item not in seen:
val = item if key is None else key(item)
seen.add(val)
yield item
prt(list(generate_no_dup([1,2,3,5,2,3])))
# 对于dict类型,对上述代码需要进行一点修改,dict本身不可hashble,但是二元组的list是hashable
a = [(1,2)]
b = [1,2]
s = {a}
print(b in s)
# prt(list(generate_no_dup( [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}])))
|
Ruby
|
UTF-8
| 338 | 3.421875 | 3 |
[] |
no_license
|
class Book
def title=(input)
expect_array=["and","in","the","of","a","an"]
not_first_word=false
input_array=input.split(" ")
input_array.each do |x|
if(!expect_array.include?(x))||(not_first_word==false)
x.capitalize!
not_first_word=true
end
end
@title=input_array.join(" ")
end
def title
@title
end
end
|
C
|
UTF-8
| 4,162 | 3.21875 | 3 |
[] |
no_license
|
#include <mpi.h>
#include <stdio.h>
#include <math.h>
#include<string.h>
/*
mcd (Maximo Comun Divisor)
Descripcion: Funcion que devuelve el maximo comun divisor de 2 numeros.
El intervalo sera de 134217728 a 4294967295 para poder hacer uso de unsigned ints
*/
unsigned long long int mcd(unsigned long long int a, unsigned long long int b)
{
unsigned long long int part, aux;
part = a%b;
while (part != 0) {
aux = b;
b = part;
part = aux%b;
}
return b;
}
int main(int argc,char **argv)
{
int myid, numprocs, i = 0, *sendbuf, *recvbuf, root = 0;
unsigned long long int n =0;
unsigned long long int porcion = 0, resto = 0;
unsigned long long int cantidadPrimos = 0;
int justo = 0; // division exacta de numeros para cada proceso
unsigned int inicio = 134217728; // 2^27
unsigned int final = 4294967295; // 2^32 le quite uno para usar unsigned int que es mas efectivo
unsigned int total = 4160749569; // total de numeros diferentes para repartir
double startwtime, endwtime;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc,&argv); /* Se inicia el trabajo con MPI */
MPI_Comm_size(MPI_COMM_WORLD,&numprocs); /* MPI almacena en numprocs el numero total de procesos que se pusieron a correr */
MPI_Comm_rank(MPI_COMM_WORLD,&myid); /* MPI almacena en myid la identificacion del proceso actual */
MPI_Get_processor_name(processor_name,&namelen); /* MPI almacena en processor_name en la computadora que corre el proceso actual, y en namelen la longitud de este */
fprintf(stdout,"Proceso %d de %d en %s\n", myid, numprocs, processor_name);
/* Cada proceso despliega su identificacion y el nombre de la computadora en la que corre*/
MPI_Barrier(MPI_COMM_WORLD); /* Barrera de sincronizacion.*/
if (myid == root) {
while (!n) {
printf("Digite un numero entre 2 y 18446744073709551615: ");
fflush(stdout);
scanf("%Lu",&n); /* n es el numero al cual se le buscaran los primos relativos */
}
printf("Usted digito: %d\n", n);
startwtime = MPI_Wtime(); /* inicia el tiempo que dure el programa */
}
porcion = total/numprocs;
resto = total%numprocs;
if(resto != 0) {
porcion = numprocs + porcion - resto; // Si sobran elementos recalcular porcion
}
justo = porcion/numprocs; /* el total exacto en el caso de que hubiese resto */
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); /* todos deben conocer el numero digitado por el usuario */
unsigned long long int actual = inicio + myid*porcion; /* El valor actual que vamos a probar segun el proceso */
unsigned long long int limiteSuperior;
if (actual + porcion < final) {
limiteSuperior = actual + porcion; /* calculo del limite superior para cada proceso */
} else {
limiteSuperior = final;
}
unsigned long long int contador = 0; // contador de primos encontrados
/* se crea un archivo de nombre respuesta+ el identificador del proceso actual */
char copyname[50];
sprintf(copyname, "Respuesta%i.txt", myid);
FILE *archivo;
archivo = fopen(copyname,"w");
while (actual < limiteSuperior) {
int result = mcd(actual,n);
if (result == 1) { // si el mcd es 1 son primos relativos
//printf("x Proceso: %d Primo encontrado: %d\n", myid, sendbuf[contador]); /* para corroborar en consola */
fprintf(archivo, "%d\n", actual);
contador += 1;
}
actual += 1;
}
fclose(archivo);
//Cada proceso envia la cantidad de primos que encontro para saber el tamano del array que guarda los primos en el root
MPI_Reduce(&contador, &cantidadPrimos, 1, MPI_UNSIGNED, MPI_SUM, 0, MPI_COMM_WORLD);
if (myid == root) {
printf("Tarea Programada 1 \n Estudiantes: \n Michelle Cersossimo Morales B21684 \nCarlos Sanabria Sandoval A75952");
printf("Proceso %d da la respuesta. Cantidad de primos encontrados: %u \n", myid, cantidadPrimos);
printf("Ver los archivos creados en esta carpeta para saber los primos encontrados. \n");
endwtime = MPI_Wtime();
printf("Tiempo de reloj: %f\n", endwtime-startwtime);
fflush( stdout );
}
MPI_Finalize();
return 0;
}
|
C++
|
UTF-8
| 1,437 | 2.765625 | 3 |
[] |
no_license
|
#include <cmath>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
const int N = 500005;
const int M = N << 1;
using namespace std;
inline int read()
{
int x=0,f=1;char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-')f=-1;ch = getchar();}
while(ch >='0' && ch <='9'){x=(x<<1)+(x<<3)+ch-'0';ch = getchar();}
return x * f;
}
int head[N],in[N],a[N];
const double eps = 1e-9;
inline bool equal(double x,double y)
{
return fabs(x-y) < eps * max(x,y);
}
struct graph
{
int next,to;
graph () {}
graph (int _next,int _to)
:next(_next),to(_to){}
}edge[M];
inline void add(int x,int y)
{
static int cnt = 0;
edge[++cnt] = graph(head[x],y);
head[x] = cnt;
edge[++cnt] = graph(head[y],x);
head[y] = cnt;
}
double s[N];
void DFS(int x,int fa)
{
for(int i=head[x];i;i=edge[i].next)
if(edge[i].to!=fa)
{
s[edge[i].to] = s[x] + log(in[x]);
DFS(edge[i].to,x);
}
}
double V[N];
int tt;
int main()
{
int n = read();
for(int i=1;i<=n;++i)
a[i] = read();
for(int i=1;i<n;++i)
{
int x = read(), y = read();
add(x,y);
in[x] ++ , in[y] ++;
}
// puts("/**********");
for(int i=2;i<=n;++i)
in[i] --;
s[1] = 0;DFS(1,0);
for(int i=1;i<=n;++i)
V[++tt] = s[i] + log(a[i]);
int cnt = 1;
int ans = 0;
sort(V+1,V+tt+1);
V[tt+1] = 122211323;
for(int i=1;i<=n;++i)
{
if(equal(V[i],V[i+1]))
cnt ++;
else ans = max(ans,cnt),cnt = 1;
}
cout << n - ans << endl;
}
|
Java
|
UTF-8
| 34,340 | 1.65625 | 2 |
[] |
no_license
|
package aidc.aigui.box;
/* $Id$
*
* :Title: aigui
*
* :Description: Graphical user interface for Analog Insydes
*
* :Author:
* Adam Pankau
* Dr. Volker Boos <volker.boos@imms.de>
*
* :Copyright:
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import aidc.aigui.box.abstr.AbstractBox;
import aidc.aigui.box.abstr.DefaultNotebookCommandSet;
import aidc.aigui.box.abstr.SamplePointActionListener;
import aidc.aigui.box.abstr.SamplePointContainer;
import aidc.aigui.box.abstr.WindowNotification;
import aidc.aigui.dialogs.DisplayWindow;
import aidc.aigui.dialogs.RootDisplayWindow;
import aidc.aigui.mathlink.MathAnalog;
import aidc.aigui.plot.BodePlotFrame;
import aidc.aigui.plot.FrequencyListener;
import aidc.aigui.plot.PZPlotFrame;
import aidc.aigui.resources.Complex;
import aidc.aigui.resources.ErrSpec;
import aidc.aigui.resources.MathematicaFormat;
import aidc.aigui.resources.SwingWorker;
import com.wolfram.jlink.MathLinkException;
/**
* @author pankau, vboos
*
*/
@SuppressWarnings("rawtypes")
public class ApproximateMatrixEquation extends AbstractBox implements ListSelectionListener, KeyListener, SamplePointActionListener, SamplePointContainer, WindowNotification
{
private JPanel panel;
private JButton jbUseBodePlot, jbAddPoint, jbEditPoint, jbDeletePoint, jbUseRootLocusPlot, jbDisplayEquation;
private JTextField jtfDesignPoint, jtfError;
private JLabel jlbAnalzedSignal;
private JTextField jtfEpsilonA, jtfEpsilonB;
private JList pointsList;
private DefaultListModel data;
private Vector<SamplePointActionListener> samplePointListeners;
private Vector<FrequencyListener> freqListeners;
//private DisplayWindow dw = null;
private BodePlotFrame bpf = null;
private RootDisplayWindow rdw = null;
private DisplayWindow dw;
private PZPlotFrame pzFrame = null;
private String oldDesignPoints = "", oldAnalyzedSignal = "", oldOptionSettings = "";
private final String sNoSelected = "(no signal selected)";
private final String sHintText = "Specify the approximation points and max. errors";
private MathematicaFormat mf;
public ApproximateMatrixEquation()
{
super("ApproximateMatrixEquation");
hmProps.put("MatrixEquations", "approximatedMatrixEqs" + getInstNumber());
}
/**
* Initialization after construction ( implementation of aidc.aigui.box.abstr.AbstractBox#init )
*/
public void init(int boxCount, int positionX, int positionY, AbstractBox ancestor, HashMap<String,String> hm)
{
super.init(boxCount, positionX, positionY, ancestor, hm);
mf = new MathematicaFormat();
samplePointListeners = new Vector<SamplePointActionListener>();
samplePointListeners.add(this);
freqListeners = new Vector<FrequencyListener>();
}
/*
* (non-Javadoc)
*
* @see aidc.aigui.box.abstr.AbstractBox#createPanel()
*/
@SuppressWarnings("unchecked")
protected JPanel createPanel()
{
JPanel panGrid;
jbAddPoint = new JButton("Add");
jbAddPoint.addActionListener(this);
jbEditPoint = new JButton("Change");
jbEditPoint.addActionListener(this);
jbDeletePoint = new JButton("Delete");
jbDeletePoint.setActionCommand("DeletePoint");
jbDeletePoint.addActionListener(this);
//point
jtfDesignPoint = new JTextField(50);
jtfDesignPoint.addKeyListener(this);
//error
jtfError = new JTextField(50);
jtfError.addKeyListener(this);
JLabel slabel = new JLabel("s -> ");
JLabel elabel = new JLabel("Error -> ");
data = new DefaultListModel();
pointsList = new JList(data);
data.addListDataListener(new ListDataListener() {
public void contentsChanged(ListDataEvent arg0) {
setModified(true);
}
public void intervalAdded(ListDataEvent arg0) {
setModified(true);
}
public void intervalRemoved(ListDataEvent arg0) {
setModified(true);
}});
pointsList.addListSelectionListener(this);
pointsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
pointsList.setLayoutOrientation(JList.VERTICAL);
pointsList.setVisibleRowCount(3);
JScrollPane listscroller = new JScrollPane(pointsList);
listscroller.setPreferredSize(new Dimension(200, 80));
JPanel panFlow = new JPanel();
panFlow.setLayout(new FlowLayout());
panFlow.add(listscroller);
panFlow.setPreferredSize(new Dimension(200, 80));
//== Create tabbed pane for option settings
JTabbedPane tabbedPane = new JTabbedPane();
addOptionPanes(tabbedPane);
jbDisplayEquation = new JButton("Display equations");
//chk.setFont(FontManipulation.getAFont(14, "Arial"));
jbDisplayEquation.addActionListener(this);
jbUseBodePlot = new JButton("Use BodePlot");
jbUseBodePlot.addActionListener(this);
jbUseRootLocusPlot = new JButton("Use RootLocusPlot");
jbUseRootLocusPlot.addActionListener(this);
createEvaluateButton();
jlbAnalzedSignal = new JLabel(sNoSelected,JLabel.CENTER);
jlbAnalzedSignal.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
panGrid = new JPanel();
panGrid.setLayout(new GridBagLayout());
panGrid.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
GridBagConstraints c = new GridBagConstraints();
panel = new JPanel();
panel.setPreferredSize(new Dimension(450, 350));
panel.setLayout(new BorderLayout(0, 0));
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 0.0;
c.weighty = 0.0;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_END;
panGrid.add(slabel, c);
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 1.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.BOTH;
panGrid.add(jtfDesignPoint, c);
c.gridx = 2;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 1;
c.weightx = 0.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.BOTH;
panGrid.add(jbAddPoint, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 0.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_END;
panGrid.add(elabel, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 1.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.BOTH;
panGrid.add(jtfError, c);
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 2;
c.gridheight = 1;
c.weightx = 0.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.BOTH;
panGrid.add(jbDeletePoint, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
panGrid.add(new JLabel(" "), c);
c.gridx = 0;
c.gridy = 3;
panGrid.add(new JLabel(" "), c);
c.gridx = 0;
c.gridy = 4;
panGrid.add(new JLabel(" "), c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 6;
c.weightx = 1.0;
c.weighty = 1.0;
c.fill = GridBagConstraints.BOTH;
//c.anchor = GridBagConstraints.LINE_START;
panGrid.add(listscroller, c);
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 2;
c.gridheight = 1;
c.weightx = 0.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.BOTH;
panGrid.add(jbEditPoint, c);
c.gridx = 2;
c.gridy = 3;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
panGrid.add(jbUseBodePlot, c);
c.gridx = 2;
c.gridy = 4;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
panGrid.add(jbUseRootLocusPlot, c);
c.gridy = 5;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
panGrid.add(new JLabel("epsA ->"), c);
c.gridx = 3;
jtfEpsilonA = new JTextField();
jtfEpsilonA.setToolTipText("EpsilonA used for RootLocusPlot");
panGrid.add(jtfEpsilonA, c);
c.gridx = 2;
c.gridy = 6;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
panGrid.add(new JLabel("epsB ->"), c);
c.gridx = 3;
jtfEpsilonB = new JTextField();
jtfEpsilonB.setToolTipText("EpsilonB used for RootLocusPlot");
panGrid.add(jtfEpsilonB, c);
c.gridx = 3;
c.gridx = 2;
c.gridy = 7;
c.gridwidth = 2;
c.gridheight = 1;
c.weightx = 0.0;
c.weighty = 0.0;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.FIRST_LINE_START;
panGrid.add(jlbAnalzedSignal, c);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel.add(Box.createRigidArea(getCloseButton().getPreferredSize()));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(jbDisplayEquation);
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(jbEvaluate);
buttonPanel.add(getCloseButton());
JSplitPane splitPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panGrid, tabbedPane);
splitPanel.setDividerSize(1);
splitPanel.setResizeWeight(0.5);
panel.add( createNorthPanel(), BorderLayout.NORTH);
panel.add(splitPanel, BorderLayout.CENTER);
panel.add(buttonPanel, BorderLayout.SOUTH);
panel.setPreferredSize(new Dimension(530, 400));
setHints( getWarningIcon(), sHintText);
return panel;
}
/*
* (non-Javadoc)
*
* @see aidc.aigui.box.abstr.AbstractBox#saveState()
*/
public void saveState()
{
if (frameForm != null)
{
int i;
int[] sel = pointsList.getSelectedIndices();
hmProps.put("selection", String.valueOf(sel.length));
for (i = 0; i < sel.length; i++) {
hmProps.put("selection" + i, String.valueOf(sel[i]));
}
hmProps.put("edata", String.valueOf(data.getSize()));
hmProps.put("sdata", String.valueOf(data.getSize()));
for (i = 0; i < data.getSize(); i++)
{
ErrSpec errspec = (ErrSpec)data.getElementAt(i);
hmProps.put("edata" + i, mf.formatMath(errspec.err));
hmProps.put("sdata" + i, mf.formatMath(errspec.fc));
}
hmProps.put("jtfDesignPoint", jtfDesignPoint.getText());
hmProps.put("jtfError", jtfError.getText());
saveOptionPanes(hmProps);
}
setModified(false); // the controls are not modified yet
gui.stateDoc.setModified(true); // but the document is modified now
}
/*
* (non-Javadoc)
*
* @see aidc.aigui.box.abstr.AbstractBox#loadState()
*/
public void loadState()
{
int i;
ArrayList<Integer> array = new ArrayList<Integer>();
String ename, sname;
if (hmProps.get("edata") != null)
{
int ne = Integer.parseInt(hmProps.get("edata"));
int ns = Integer.parseInt(hmProps.get("sdata"));
if (ns < ne) ne = ns;
for (i = 0; i < ne; i++)
{
sname = "sdata" + i;
ename = "edata" + i;
data.addElement( new ErrSpec(hmProps.get(sname),hmProps.get(ename)) );
}
}
if (hmProps.get("selection") != null) {
for (i = 0; i < Integer.parseInt(hmProps.get("selection").toString()); i++) {
ename = "selection" + i;
array.add(Integer.valueOf(hmProps.get(ename).toString()));
}
int[] sel = new int[array.size()];
for (i = 0; i < array.size(); i++)
sel[i] = array.get(i);
// System.out.println(sel[i]);
pointsList.setSelectedIndices(sel);
}
if (hmProps.get("jtfError") != null)
jtfError.setText(hmProps.get("jtfError").toString());
if (hmProps.get("jtfDesignPoint") != null)
jtfDesignPoint.setText(hmProps.get("jtfDesignPoint").toString());
loadOptionPanes(hmProps);
String signal = getProperty("analyzedSignal",sNoSelected);
jlbAnalzedSignal.setText(signal);
setModified(false);
}
/*
* (non-Javadoc)
*
* @see aidc.aigui.box.abstr.AbstractBox#action()
*/
public int evaluateNotebookCommands(AbstractBox ab) {
try {
String command, result, designPoints;
showForm(false);
saveState();
int iReturn;
if ((iReturn = ancestor.evaluateNotebookCommands(this)) < 0)
return iReturn;
designPoints = createListOfPoints();
String newAnalyzedSignal = getProperty("analyzedSignal", "");
//== get the new option settings
// TODO: check changes in the option pane
StringBuilder sbOpt = new StringBuilder();
appendOptionSettings(sbOpt);
String newOptionSettings = sbOpt.toString();
boolean bModified = !oldDesignPoints.equals(designPoints) || !oldAnalyzedSignal.equals(newAnalyzedSignal) || !oldOptionSettings.equals(newOptionSettings);
if (!bModified && iReturn == RET_EVAL_NOCHANGES && getEvalState() == STATE_EVAL_OK)
{
return iReturn;
}
//== must do the evaluation ==
oldDesignPoints = designPoints;
oldAnalyzedSignal = newAnalyzedSignal;
oldOptionSettings = newOptionSettings;
invalidateEvalState();
if (designPoints.length() > 0)
{
designPoints = "sp = " + designPoints;
result = MathAnalog.evaluateToOutputForm(designPoints, 0, true);
if (!getProperty("analyzedSignal", "").equals(""))
{
StringBuilder sb = new StringBuilder();
sb.append(hmProps.get("MatrixEquations") );
sb.append( " = ApproximateMatrixEquation[" );
sb.append( getAncestorProperty("MatrixEquations", "equations0") );
sb.append( ", " );
sb.append( getProperty("analyzedSignal", "") );
sb.append( ", sp, AnalysisMode -> AC" );
appendOptionSettings(sb);
sb.append( "]");
command = sb.toString();
result = MathAnalog.evaluateToOutputForm(command, 0, true);
if (checkResult(command,result,this) < 0)
{
setEvalState(STATE_EVAL_ERROR);
return RET_EVAL_ERROR;
}
setEvalState(STATE_EVAL_OK);
return RET_EVAL_DONE;
}
System.out.println("You have to choose analyzed signal first!!");
return RET_EVAL_ERROR;
}
else // no design points
{
command = hmProps.get("MatrixEquations") + " = " + getAncestorProperty("MatrixEquations", "equations0");
result = MathAnalog.evaluateToOutputForm(command, 0, true);
if (checkResult(command,result,this) < 0)
{
setEvalState(STATE_EVAL_ERROR);
return -1;
}
setEvalState(STATE_EVAL_OK);
return RET_EVAL_DONE;
}
} catch (MathLinkException e) {
MathAnalog.notifyUser();
return -1;
}
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
*/
public void valueChanged(ListSelectionEvent e)
{
if (pointsList.getSelectedIndices().length == 1)
{
System.out.println("Selected index = " + pointsList.getSelectedIndex());
int selected = pointsList.getSelectedIndex();
ErrSpec errspec = (ErrSpec)data.getElementAt(selected);
jtfDesignPoint.setText(mf.formatMath(errspec.fc));
jtfError.setText( errspec.getErrorAsString() );
//samplePointSelected(errspec);
//== inform all listeners
Iterator<SamplePointActionListener> itSPL = samplePointListeners.iterator();
while (itSPL.hasNext())
{
SamplePointActionListener spl = itSPL.next();
if (spl != this) spl.samplePointSelected(errspec);
}
} else {
jtfDesignPoint.setText("");
jtfError.setText("");
}
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
public void keyReleased(KeyEvent e) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
*/
public void keyTyped(KeyEvent e) {
}
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e); //execute super class action
if (e.getSource() == jbUseBodePlot) {
if (bpf == null) {
final SwingWorker worker = new SwingWorker() {
public Object construct() {
System.out.println("APPMX-analyzedSignal:" + getProperty("analyzedSignal",""));
if (evaluateNotebookCommands((AbstractBox) ab) >= 0)
{
String strACSweep = getProperty("ACSweep", "");
String strAnalyzedSignal = getProperty("analyzedSignal", "");
if (!strACSweep.isEmpty() && !strAnalyzedSignal.isEmpty() )
{
try {
bpf = new BodePlotFrame();
bpf.setTitle(boxTypeInfo.getBoxName() + " (" + boxNumber + ") - BodePlot");
samplePointListeners.add(bpf);
freqListeners.add(bpf);
bpf.setSamplePointContainer((SamplePointContainer)ab);
StringBuffer sb = new StringBuffer();
sb.append("v =");
sb.append(strAnalyzedSignal);
sb.append("/.");
sb.append(strACSweep);
sb.append("[[1]]");
MathAnalog.evaluate(sb.toString(), false);
String strFuncList = MathAnalog.evaluateToInputForm("nv = InterpolatingFunctionToList[v]", 0, false);
bpf.addInterpolatingFunction(strFuncList, 0, strAnalyzedSignal);
bpf.setSize(bpf.getWidth(), 400);
bpf.setVisible(true);
} catch (Exception e) { //was MathLinkException (hsonntag)
MathAnalog.notifyUser();
}
} else{
System.out.println("Something is missing in previous steps!!");
((AbstractBox)ab).showMessage("There is no ACAnalysis node!");
}
}
return new Object();
}
};
worker.ab = this;
worker.start(); //required for SwingWorker 3
} else
bpf.setVisible(true);
}
if (e.getSource() == jbUseRootLocusPlot)
{
if (rdw == null) {
final SwingWorker worker = new SwingWorker() {
public Object construct() {
if (ancestor.evaluateNotebookCommands((AbstractBox) ab) >= 0)
{
if (false)
{
StringBuffer sb = new StringBuffer();
sb.append( "temppz = PolesAndZerosByQZ[" );
sb.append( getAncestorProperty("MatrixEquations", "") );
sb.append( ", " );
sb.append( getAncestorProperty("analyzedSignal", "") );
String epsA = jtfEpsilonA.getText().trim();
if (!epsA.isEmpty())
{
sb.append(", ");
sb.append("EpsilonA->");
sb.append(epsA);
}
String epsB = jtfEpsilonB.getText().trim();
if (!epsB.isEmpty())
{
sb.append(", ");
sb.append("EpsilonB->");
sb.append(epsB);
}
sb.append( "]" );
String command = sb.toString() ;
try {
/*String result =*/ MathAnalog.evaluateToOutputForm(command, 300, true);
rdw = new RootDisplayWindow(boxTypeInfo.getBoxName() + " (" + boxNumber + ") - RootLocusPlot", "temppzplot", "temppz", command, ApproximateMatrixEquation.this, null, null);
samplePointListeners.add(rdw);
} catch (MathLinkException e) {
MathAnalog.notifyUser();
rdw=null;
}
}
else
{
showRootLocusPlot();
}
}
return new Object();
}
};
worker.ab = this;
worker.start(); //required for SwingWorker 3
} else
rdw.setVisible(true);
}
if (e.getSource() == jbAddPoint)
{
if (!jtfDesignPoint.getText().trim().equals("") && !jtfError.getText().trim().equals(""))
{
try {
Number err = mf.parseMathToNumber(jtfError.getText());
Complex dsp = mf.parseMathToComplex(jtfDesignPoint.getText());
if (dsp == null) {
JOptionPane.showMessageDialog(frameForm, "s must be a complex number", "Error", JOptionPane.OK_OPTION);
return;
}
ErrSpec errspec = addSamplePoint(dsp, err.doubleValue(), this);
selectSamplePoint(errspec, this);
} catch (ParseException e1) {
JOptionPane.showMessageDialog(frameForm, "Error must be a double number", "Error", JOptionPane.OK_OPTION);
}
}
}
if (e.getSource() == jbDeletePoint)
{
int index = 0;
while (index != -1)
{
index = pointsList.getSelectedIndex();
if (index != -1)
{
deleteSamplePoint( index, this );
}
}
}
if (e.getSource() == jbEditPoint)
{
int index = pointsList.getSelectedIndex();
if (index != -1)
{
if (!jtfDesignPoint.getText().trim().equals("") && !jtfError.getText().trim().equals(""))
{
ErrSpec errspec = (ErrSpec)data.getElementAt(index);
Complex newFreq = mf.parseMathToComplex(jtfDesignPoint.getText());
double newErr = mf.parseMath(jtfError.getText());
errspec.fc = newFreq;
errspec.err = newErr;
changeSamplePoint(errspec, this);
data.setElementAt(errspec, index);
}
}
} else if (e.getSource() == jbDisplayEquation) {
final SwingWorker worker = new SwingWorker() {
public Object construct() {
if (evaluateNotebookCommands((AbstractBox) ab) >= 0) {
String command = "";
try {
command = "DisplayForm[" + hmProps.get("MatrixEquations") + "]";
dw = new DisplayWindow(boxTypeInfo.getBoxName() + " (" + boxNumber + ") - equations");
dw.setTypesetCommand( command, 500 );
} catch (MathLinkException e) {
MathAnalog.notifyUser();
}
}
return new Object();
}
};
worker.ab = this;
worker.start(); //required for SwingWorker 3
}
}
/*
* Parse a list of complex numbers from Mathematica format into a collection
*/
private void parseComplexList( String strList, Collection<Complex> coll)
{
final String strDoublePattern = "[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:\\*(?:10)?\\^[+-]?\\d+)?";
final String strComplexPattern2 = "(" + strDoublePattern + ")\\s*(?:([+-])?\\s*(" + strDoublePattern + ")\\*I)?";
Pattern pnPair = Pattern.compile(strComplexPattern2);
Matcher mtPair = pnPair.matcher(strList);
while (mtPair.find())
{
double re = Double.parseDouble(mtPair.group(1).replaceAll("\\Q*^\\E|\\*10\\^", "E"));
double im = 0;
if (mtPair.groupCount()>1 && mtPair.group(3) != null)
{
im = Double.parseDouble(mtPair.group(3).replaceAll("\\Q*^\\E|\\*10\\^", "E"));
if (mtPair.group(2).equals("-")) im = -im;
}
coll.add(new Complex(re,im));
}
}
/*
* Show the root locus plot
*/
protected void showRootLocusPlot()
{
if (pzFrame == null)
{
pzFrame = new PZPlotFrame();
pzFrame.setSize(480,pzFrame.getHeight());
freqListeners.add(pzFrame);
}
else
pzFrame.clear();
StringBuffer sb = new StringBuffer();
sb.append( "temppz = PolesAndZerosByQZ[" );
sb.append( getAncestorProperty("MatrixEquations", "") );
sb.append( ", " );
sb.append( getAncestorProperty("analyzedSignal", "") );
String epsA = jtfEpsilonA.getText().trim();
if (!epsA.isEmpty())
{
sb.append(", ");
sb.append("EpsilonA->");
sb.append(epsA);
}
String epsB = jtfEpsilonB.getText().trim();
if (!epsB.isEmpty())
{
sb.append(", ");
sb.append("EpsilonB->");
sb.append(epsB);
}
sb.append( "]" );
String cmdPZ = sb.toString() ;
try {
/*int ok =*/ MathAnalog.evaluate( cmdPZ,true);
String strPoles = MathAnalog.evaluateToInputForm( "tempp=Last[First[temppz]]", 300, true);
int nPoles = MathAnalog.evaluateToInt( "Length[tempp]", false);
String strZeros = MathAnalog.evaluateToInputForm( "tempz=Last[Last[temppz]]" , 300, true);
int nZeros = MathAnalog.evaluateToInt( "Length[tempz]", false);
Vector<Complex> poles = new Vector<Complex>(nPoles);
parseComplexList(strPoles, poles);
Vector<Complex> zeros = new Vector<Complex>(nZeros);
parseComplexList(strZeros, zeros);
pzFrame.setPolesAndZeroes(poles.toArray(new Complex[poles.size()]), zeros.toArray(new Complex[zeros.size()]));
double fmin = mf.parseMath(getProperty("ACRangeMin", ""));
double fmax = mf.parseMath(getProperty("ACRangeMax", ""));
if (fmin < fmax)
{
pzFrame.setFrequencyRange(fmin, fmax);
}
}
catch (MathLinkException e)
{
e.printStackTrace();
}
pzFrame.setSamplePointContainer(this);
samplePointListeners.add(pzFrame);
pzFrame.setVisible(true);
pzFrame.fit();
}
/*
* ========== implementation of aidc.aigui.box.abstr.SamplePointContainer =========
*/
@Override
public ErrSpec getSamplePointAt(int index)
{
return (ErrSpec)data.elementAt(index);
}
@Override
public int getSamplePointCount()
{
return data.size();
}
public ErrSpec addSamplePoint(Complex point, double error, Object sender)
{
ErrSpec errspec = new ErrSpec(point, error);
data.addElement(errspec);
setModified(true);
//== inform all listeners
Iterator<SamplePointActionListener> itSPL = samplePointListeners.iterator();
while (itSPL.hasNext())
{
SamplePointActionListener spl = itSPL.next();
if (spl != sender) spl.samplePointAdded(errspec);
}
//samplePointSelected(errspec,sender);
return errspec;
}
@Override
public void selectSamplePoint(ErrSpec errspec, Object sender)
{
System.out.println("sel p=" + errspec.fc + " err=" + errspec.err);
samplePointSelected(errspec);
//== inform all listeners
Iterator<SamplePointActionListener> itSPL = samplePointListeners.iterator();
while (itSPL.hasNext())
{
SamplePointActionListener spl = itSPL.next();
if (spl != sender) spl.samplePointSelected(errspec);
}
}
@Override
public void changeSamplePoint(ErrSpec errspec, Object sender)
{
samplePointChanged(errspec);
//== inform all listeners
Iterator<SamplePointActionListener> itSPL = samplePointListeners.iterator();
while (itSPL.hasNext())
{
SamplePointActionListener spl = itSPL.next();
if (spl != sender) spl.samplePointChanged(errspec);
}
setModified(true);
}
@Override
public void deleteSamplePoint(ErrSpec errspec, Object sender)
{
int index = data.indexOf( errspec );
deleteSamplePoint( index, sender);
}
private void deleteSamplePoint( int index, Object sender )
{
ErrSpec errspec = (ErrSpec)data.getElementAt(index);
data.removeElementAt(index);
jtfDesignPoint.setText("");
jtfError.setText("");
//== inform all listeners
Iterator<SamplePointActionListener> itSPL = samplePointListeners.iterator();
while (itSPL.hasNext())
{
SamplePointActionListener spl = itSPL.next();
if (spl != sender) spl.samplePointDeleted(errspec);
}
setModified(true);
}
@Override
public void samplePointChanged(ErrSpec errspec)
{
int index = data.indexOf(errspec);
data.setElementAt(errspec,index);
}
@Override
public void selectAllSamplePoints( Object sender )
{
int selection[] = new int[pointsList.getModel().getSize()];
for (int i = 0; i < pointsList.getModel().getSize(); i++)
selection[i] = i;
pointsList.setSelectedIndices(selection);
}
@Override
public void clearSelection( Object sender)
{
pointsList.setSelectedIndex(-1);
//== inform all listeners
Iterator<SamplePointActionListener> itSPL = samplePointListeners.iterator();
while (itSPL.hasNext())
{
SamplePointActionListener spl = itSPL.next();
if (spl != sender) spl.samplePointsAllSelected(false);
}
}
@Override
public void frequencyChanged(Complex cfreq, boolean valid, Object sender)
{
//== inform all listeners
Iterator<FrequencyListener> itFreq = freqListeners.iterator();
while (itFreq.hasNext())
{
FrequencyListener frql = itFreq.next();
if (frql != sender) frql.freqChanged(cfreq, sender, valid);
}
}
/*
* ============== implementation of aidc.aigui.box.abstr.SamplePointActionListener
*/
@Override
public void samplePointAdded(ErrSpec errspec)
{
// do nothing because it is done in addSamplePoint
}
@Override
public void samplePointDeleted(ErrSpec errspec)
{
// do nothing because it is done in deleteSamplePoint
}
@Override
public void samplePointSelected(ErrSpec errspec)
{
int index = data.indexOf(errspec);
pointsList.setSelectedIndex(index);
pointsList.ensureIndexIsVisible(index);
}
@Override
public void samplePointsAllSelected( boolean bSelected )
{
if (bSelected)
{
}
else
{
pointsList.setSelectedIndex(-1);
}
}
@Override
public SamplePointContainer getSamplePointContainer()
{
return this;
}
public String createListOfPoints()
{
int i = 0;
StringBuffer sbListOfPoints = new StringBuffer();
if (data.size() > 0)
sbListOfPoints.append( "{" );
if (data.size() == 1)
{
sbListOfPoints.append( data.getElementAt(0).toString() );
}
else
{
for (i = 0; i < data.size(); i++)
{
if (i > 0) sbListOfPoints.append(',');
sbListOfPoints.append( "{" );
sbListOfPoints.append( data.getElementAt(i).toString() );
sbListOfPoints.append( "}" );
}
}
if (data.size() > 0)
sbListOfPoints.append( "}" );
return sbListOfPoints.toString();
}
/**
* Get list of points from properties
* @return points in string
*/
private String getListOfPoints()
{
StringBuffer sb = new StringBuffer();
int nData = Integer.parseInt(hmProps.get("edata"));
if (hmProps.get("edata") != null)
{
if (nData > 1) sb.append('{');
for (int i = 0; i < nData; i++)
{
if (i > 0) sb.append(',');
sb.append('{');
sb.append(" s -> ");
sb.append(hmProps.get("sdata" + i));
sb.append(" , MaxError -> ");
sb.append(hmProps.get("edata" + i));
sb.append('}');
}
if (nData > 1) sb.append('}');
}
return sb.toString();
}
/*
* (non-Javadoc)
*
* @see aidc.aigui.box.abstr.FrequencySelection#selectFrequency(double,
* aidc.aigui.box.abstr.FrequencySelection)
*/
/* NO FREQ SEL.
public void selectFrequency(double frequency, FrequencySelection fs) {
if (fs != rdw && rdw != null)
rdw.selectFrequency(frequency, fs);
if (fs != bpf && bpf != null){
bpf.selectFrequency(frequency, fs);
}
}
*/
/*
* (non-Javadoc)
*
* @see aidc.aigui.box.abstr.FrequencySelection#clearFrequency(aidc.aigui.box.abstr.FrequencySelection)
*/
/* NO FREQ SEL.
public void clearFrequency(FrequencySelection fs) {
if (fs != rdw && rdw != null)
rdw.clearFrequency(fs);
if (fs != bpf && bpf != null)
bpf.clearFrequency(fs);
}
*/
/*
* (non-Javadoc)
*
* @see aidc.aigui.box.abstr.WindowNotification#setWindowClosed(java.lang.Object)
*/
public void setWindowClosed(Object object) {
if (object == rdw) {
gui.unregisterWindow(rdw);
rdw = null;
}
if (object == bpf)
gui.unregisterWindow(rdw);
bpf = null;
}
/* (non-Javadoc)
* @see aidc.aigui.box.abstr.AbstractBox#setNewPropertyValue(java.lang.String)
*/
@Override
public void setNewPropertyValue(String key)
{
super.setNewPropertyValue(key);
if (frameForm != null && key.equals("analyzedSignal"))
{
jlbAnalzedSignal.setText(getProperty("analyzedSignal",sNoSelected));
}
}
/* (non-Javadoc)
* @see aidc.aigui.box.abstr.AbstractBox#setModified(boolean)
*/
@Override
public void setModified(boolean modified)
{
super.setModified(modified);
if (frameForm != null)
{
setHints((data.size() > 0) ? getInfoIcon() : getWarningIcon(), sHintText);
}
}
@Override
protected void createNotebookCommands()
{
if (nbCommands==null)
nbCommands = new DefaultNotebookCommandSet();
else
((DefaultNotebookCommandSet)nbCommands).clear();
String listOfPoints = getListOfPoints();
if (listOfPoints.length() > 0)
{
StringBuilder sbLine = new StringBuilder();
sbLine.append("sp = ");
sbLine.append(listOfPoints);
((DefaultNotebookCommandSet)nbCommands).addCommand(sbLine.toString());
sbLine.setLength(0);
sbLine.append(hmProps.get("MatrixEquations"));
sbLine.append(" = ApproximateMatrixEquation[");
sbLine.append(getAncestorProperty("MatrixEquations", "equations0"));
sbLine.append(", ");
sbLine.append(getProperty("analyzedSignal", ""));
sbLine.append(", sp, AnalysisMode -> AC");
appendOptions(sbLine);
sbLine.append("]");
((DefaultNotebookCommandSet)nbCommands).addCommand(sbLine.toString());
((DefaultNotebookCommandSet)nbCommands).setEvalCount(nbCommands.getCommandCount());
sbLine.setLength(0);
sbLine.append("DisplayForm[");
sbLine.append(hmProps.get("MatrixEquations"));
sbLine.append("]");
((DefaultNotebookCommandSet)nbCommands).addCommand(sbLine.toString());
}
else
{
((DefaultNotebookCommandSet)nbCommands).addCommand(
hmProps.get("MatrixEquations") + " =" + getAncestorProperty("MatrixEquations", "equations0"));
((DefaultNotebookCommandSet)nbCommands).addCommand(
"DisplayForm[" +hmProps.get("MatrixEquations") + "]");
((DefaultNotebookCommandSet)nbCommands).setEvalCount(1);
}
((DefaultNotebookCommandSet)nbCommands).setValid(true);
}
}
|
Java
|
UTF-8
| 466 | 2.15625 | 2 |
[] |
no_license
|
package dto;
public class DocumentStatisticsDto {
private int wordsQuantity;
private long indexTime;
public DocumentStatisticsDto() {
}
public void setWordsQuantity(int wordsQuantity) {
this.wordsQuantity = wordsQuantity;
}
public int getWordsQuantity() {
return wordsQuantity;
}
public void setIndexTime(long indexTime) {
this.indexTime = indexTime;
}
public long getIndexTime() {
return indexTime;
}
}
|
C++
|
UTF-8
| 1,785 | 3.171875 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std;
std::mutex m;
std::condition_variable cv;
const int MAX_SIGNALS = 4; //Max signals count
const int MAX_STOP = 10; //Signal program max stop count
int next_signal_id = 0;//To print next signal status
int wakeup_signal_id = -1;//To set wakeup Signal status to be green
int stop_count = 0;
bool SignalExpired = false;//Signal expired condition
void signalFun(int sigId)
{
while (1)
{
unique_lock<mutex> lock(m);
//Wait for signal expiry and next wake up SIGNAL to be Green is the current SIGNAL thread.
cv.wait(lock, [&sigId]{return ((SignalExpired) && (wakeup_signal_id == sigId)); });
//Logic to stop SIGNAL thread after some expiry counts.
if (stop_count >= MAX_STOP)
break;
//Print signal state for each thread after expiry.
cout << "Signal (" << sigId + 1 << ") : " << ((curr_green_signal == sigId) ? "Green" : "Red") << endl;
//Increase wakeup_signal_id in rotating manner to set next wakup signal's turn.
wakeup_signal_id = sigId + 1;
if (wakeup_signal_id == MAX_SIGNALS)
{
wakeup_signal_id = 0;
SignalExpired = false;
cout << "Wait for signal expire...." << endl << endl;
}
//Broadcast to all signals to print next signal state.
cv.notify_all();
lock.unlock();
}
///Signal Thread exit clean up code
wakeup_signal_id = sigId + 1;
if (wakeup_signal_id == MAX_SIGNALS)
{
wakeup_signal_id = 0;
}
SignalExpired = true;
cv.notify_all();
}
|
Markdown
|
UTF-8
| 1,548 | 3.65625 | 4 |
[
"Apache-2.0"
] |
permissive
|
# 方阵中战斗力最弱的 K 行
给你一个大小为 m * n 的方阵 mat,方阵由若干军人和平民组成,分别用 0 和 1 表示。
请你返回方阵中战斗力最弱的 k 行的索引,按从最弱到最强排序。
如果第 i 行的军人数量少于第 j 行,或者两行军人数量相同但 i 小于 j,那么我们认为第 i 行的战斗力比第 j 行弱。
军人 总是 排在一行中的靠前位置,也就是说 1 总是出现在 0 之前。
示例 1:
``` javascript
输入:mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
输出:[2,0,3]
解释:
每行中的军人数目:
行 0 -> 2
行 1 -> 4
行 2 -> 1
行 3 -> 2
行 4 -> 5
从最弱到最强对这些行排序后得到 [2,0,3,1,4]
```
示例 2:
``` javascript
输入:mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
输出:[0,2]
解释:
每行中的军人数目:
行 0 -> 1
行 1 -> 4
行 2 -> 1
行 3 -> 1
从最弱到最强对这些行排序后得到 [0,2,3,1]
```
提示:
- m == mat.length
- n == mat[i].length
- 2 <= n, m <= 100
- 1 <= k <= m
- matrix[i][j] 不是 0 就是 1
解答:
**#**|**编程语言**|**时间(ms / %)**|**内存(MB / %)**|**代码**
--|--|--|--|--
1|javascript|64 / 100|36.1 / 100|[正常解法](./javascript/ac_v1.js)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
Markdown
|
UTF-8
| 1,022 | 3.125 | 3 |
[] |
no_license
|
# Dicee 🎲
## Goal
The objective of this app is to lern the core programming concepts that form the foundation of most of the apps. This app teaches how to make apps with functionality using setState() inside Stateful Flutter widgets.
## What I create
I did a a Las Vegas dice app. You can make the die roll at the press of a button.

## What I learn
- How to use Flutter stateless widgets to design the user interface.
- How to use Flutter stateful widgets to update the user interface.
- How to change the properties of various widgets.
- How to use onPressed listeners to detect when buttons are pressed.
- How to use setState to mark the widget tree as dirty and requiring update on the next render.
- How to use Expanded to make widgets adapt to screen dimensions.
- Understand and use string interpolation.
- Learn about basic dart programming concepts such as data types and functions.
- Code and use gesture controls.
|
Markdown
|
UTF-8
| 1,456 | 2.96875 | 3 |
[] |
no_license
|
---
title: Android 调用PowerManager 实现延时锁屏
---
今天公司项目有一个需求,就是再语音通话过程中保持聊天界面屏幕常亮。于是查阅资料,发现使用Android 的 *WakeLock* 机制可以很轻松的实现。
首先我们要清楚,在手机锁屏的时候,android 系统为了达到省电的和减少CPU的消耗,在锁屏的一段时间后进入休眠的状态,这时候Android 的CPU会保持在一个功耗较低状态。那么如何在Android 休眠的状态执行消息的接收并且点亮屏幕呢?
直接上代码:
```java
WakeLock wakeLock = null;
//获取电源锁,保持该服务在屏幕熄灭时仍然获取CPU时,保持运行
private void acquireWakeLock()
{
if (null == wakeLock)
{
PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, "PostLocationService");
if (null != wakeLock)
{
wakeLock.acquire();
}
}
}
//释放设备电源锁
private void releaseWakeLock()
{
if (null != wakeLock)
{
wakeLock.release();
wakeLock = null;
}
}
}
```
|
Ruby
|
UTF-8
| 482 | 3.703125 | 4 |
[] |
no_license
|
def fibs (n)
if (n == 0)
""
else
first = 0
second = 1
third = second
total = []
n.times do
total.push(first)
first = second
second = third
third = first + second
end
total
end
end
def fibs_rec (ary, n)
if (n == 0)
return ary
end
if (n == 1)
ary << 0
return ary
end
if (n == 2)
ary << 0 << 1
return ary
end
fibs_rec(ary, n-1)
ary << ary[n-2] + ary[n-3]
ary
end
puts fibs_rec([], 8)
|
TypeScript
|
UTF-8
| 5,261 | 2.546875 | 3 |
[] |
no_license
|
import path from "path";
import fs from "fs";
import { getMocks } from "./get_mocks";
export function mockExternalComponents(component: any): void;
export function mockExternalComponents(componentPath: string, testPath?: string): void {
if (!componentPath || !testPath) {
throw new Error("Either babel plugin \"jest-mock-external-components\" is not enabled or you passed non imported identifier to mockExternalComponents()");
}
let componentFullPath: string = "";
const tryExt = [".tsx", ".ts", ".jsx", ".js"];
if (tryExt.find(ext => componentFullPath.endsWith(ext))) {
// import with extension
try {
componentFullPath = require.resolve(componentPath, {
paths: [
path.dirname(testPath),
],
});
} catch {
// ignore
}
} else {
// try each extension
for (const ext of tryExt) {
try {
componentFullPath = require.resolve(`${componentPath}${ext}`, { paths: [path.dirname(testPath)] });
} catch {
// ignore
}
}
}
if (!componentFullPath) {
return;
}
const code = fs.readFileSync(componentFullPath, "utf8");
if (!code) {
return;
}
const mocks = getMocks(code, testPath.endsWith(".ts") || testPath.endsWith(".tsx") ? "typescript" : "flow");
if (!mocks.length) {
return;
}
try {
// flat mocks by module path
const flattenMocks = mocks.reduce((flattened, mock) => {
const mockPath = mock.path;
if (!flattened[mockPath]) {
flattened[mockPath] = [];
}
flattened[mockPath].push({ identifier: mock.identifier, type: mock.type });
return flattened;
}, {} as { [key: string]: Array<{ identifier: string; type: "default" | "name" | "namespace" }> });
for (const mockPath of Object.keys(flattenMocks)) {
// path.dirname("..") and path.dirname("../") will result to "."
// const mainDirPath = modulePath === "../" || modulePath === ".." ? modulePath : path.dirname(modulePath);
const mainDirPath = path.dirname(componentFullPath);
// if mock is relative path then calculate properly path based on test path directory
let newPath = mockPath.startsWith(".") ? path.join(mainDirPath, mockPath) : mockPath;
if (flattenMocks[mockPath] && flattenMocks[mockPath].length) {
// const newPath = path.join(mainDirPath, mock.path);
jest.doMock(newPath, () => {
const actual = jest.requireActual(newPath);
let mockedModule = { ...actual };
Object.defineProperty(mockedModule, "__esModule", { value: true });
const mocks = flattenMocks[mockPath];
for (const mock of mocks) {
const mockIdentifiers = mock.identifier.split(".");
// drop first identifier for namespace
if (mock.type === "namespace") {
mockIdentifiers.shift();
}
// import * as Comp from "./comp"; commonjs module.exports = ReactComp;
if (!mockIdentifiers.length && mock.type === "namespace") {
delete mockedModule["__esModule"];
mockedModule = mock.identifier;
// Bail
break;
}
if (mock.type === "default") {
mockedModule["default"] = mock.identifier;
} else {
const mostRightIdentifier = mockIdentifiers.pop();
if (!mostRightIdentifier) {
continue;
}
if (!mockIdentifiers.length) {
// top-level export
mockedModule[mostRightIdentifier] = mostRightIdentifier;
} else {
// sub-level export, i.e. import * as E; E.A.B; -> E dropped, A is sublevel export and B is identifier name
// import { A }; A.B -> A is sublevel export
let mockedPath = mockedModule;
while (mockIdentifiers.length > 0) {
const subLevel = mockIdentifiers.shift()!;
mockedPath[subLevel] = {
...actual[subLevel]
};
mockedPath = mockedPath[subLevel];
}
mockedPath[mostRightIdentifier] = mostRightIdentifier;
}
}
}
return mockedModule;
});
}
}
} catch { /* ignore */ }
}
export default mockExternalComponents;
|
Python
|
UTF-8
| 1,070 | 2.65625 | 3 |
[] |
no_license
|
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
def detectFunct(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 3)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
smiles = smile_cascade.detectMultiScale(roi_gray)
for (sx,sy,sw,sh) in smiles:
cv2.rectangle(roi_color,(sx,sy),(sx+sw,sy+sh),(0,255,0),2)
img1 = cv2.imread('face.jpg')
img2 = cv2.imread('face1.jpg')
img3 = cv2.imread('face2.jpg')
detectFunct(img1)
detectFunct(img2)
detectFunct(img3)
cv2.imshow('img1',img1)
cv2.imshow('img2',img2)
cv2.imshow('img3',img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
Markdown
|
UTF-8
| 1,819 | 2.671875 | 3 |
[] |
no_license
|
# 科学网—一本书换一所房子 - 李泳的博文
# 一本书换一所房子
已有 3044 次阅读2013-6-8 08:53|个人分类:[札记](http://blog.sciencenet.cn/home.php?mod=space&uid=279992&do=blog&classid=113747&view=me)|系统分类:[人文社科](http://blog.sciencenet.cn/home.php?mod=space&do=blog&view=all&uid=279992&catid=10)
**——旧札新钞(141)**
@ **赵萝蕤**回忆,**陈梦家**1956年“用《**殷墟卜辞综述**》的稿费在钱粮胡同买了一所房子”。(还有人说买了十八间平房,令不少人眼红。)此书中华书局至今还在重印。那么专业的书,如今多半儿是要自己(或课题)掏钱才可能出版了。倒是浅陋如什么什么感悟的,可以卖个好价钱。
@ 清代篆书大兴,超越唐宋,直接三代以上。**沙孟海**先生将清代篆书分为四派,钱玷、洪亮吉、孙星衍是经学派,王澍、邓石如、吴熙载、赵之谦、吴俊卿是书法派,吴大澂、罗振玉为古器物派,章太炎则是古文字学派。
@ 爱因斯坦欣赏**马赫原理**,但马赫不喜欢相对论。1949年,Godel发现旋转宇宙的解,这是与马赫原理冲突的,因为宇宙作为整体的旋转是没有意义的——它相对于什么旋转呢?在这一点上,广义相对论虽然名曰“相对”,其实比**马赫和伯克莱**更具牛顿绝对空间的精神。
转载本文请联系原作者获取授权,同时请注明本文来自李泳科学网博客。
链接地址:[http://blog.sciencenet.cn/blog-279992-697610.html](http://blog.sciencenet.cn/blog-279992-697610.html)
上一篇:[人体不对称的起源](blog-279992-697279.html)
下一篇:[端午过浣花溪](blog-279992-699296.html)
|
JavaScript
|
UTF-8
| 563 | 3.515625 | 4 |
[] |
no_license
|
var arreglo = [0,5,10,1000];
console.log(arreglo);
//push nos va a permitir agregar un valor al final de nuestro arreglo
arreglo.push(9);
console.log(arreglo);
arreglo.push(90);
console.log(arreglo);
console.log("Vamos a retirar valores del arreglo")
//El método pop no va a permitir quitar un elemento del arreglo
arreglo.pop();
console.log(arreglo);
//Paises
var CopaAmerica = ['Bolivia','Perú','Brasil','Venezuela','Argentina','Paraguay','Ecuador','Chile','Uruguay'];
//los invitados
CopaAmerica.push('Japón','Qatar');
console.log(CopaAmerica);
|
JavaScript
|
UTF-8
| 1,093 | 2.765625 | 3 |
[] |
no_license
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Room {
constructor(__capacity, name) {
this.__capacity = __capacity;
this.name = name;
this._capacity = __capacity;
this._name = name;
}
add(socket) {
console.log('capacity : ', this._capacity);
if (this._capacity > 0) {
console.log('In capacity > 0');
socket.join(this._name);
this._capacity--;
return this._name;
}
else {
console.log('Not in capacity > 0');
return undefined;
}
}
remove(socket) {
const roomOfSocket = Object.keys(socket.rooms);
const test = roomOfSocket.filter(e => e === this._name);
if (test !== []) {
socket.leave(this._name);
this._capacity++;
console.log('leave room... ' + this._name);
return true;
}
else {
return false;
}
}
isFree() {
return this._capacity > 0;
}
}
exports.default = Room;
|
Python
|
UTF-8
| 1,050 | 2.828125 | 3 |
[] |
no_license
|
from wpilib.command.command import Command
from wpilib.joystick import Joystick
from subsystems.Grabber import Grabber
class GrabberMoveWithPOV(Command):
GRABBER_SPEED_UP = 0.7
GRABBER_SPEED_DOWN = -0.4
first_stop = False
grabber: Grabber
joystick: Joystick
def __init__(self, grabber: Grabber, joystick: Joystick):
super().__init__("GrabberMoveWithPOV")
self.grabber = grabber
self.joystick = joystick
self.requires(grabber)
self.setInterruptible(True)
def execute(self):
pov = self.joystick.getPOV()
if pov == 0:
self.grabber.set_speed(self.GRABBER_SPEED_UP)
self.first_stop = True
elif pov == 180:
self.grabber.set_speed(self.GRABBER_SPEED_DOWN)
self.first_stop = True
elif self.first_stop:
self.first_stop = False
self.grabber.set_speed(0.1)
self.grabber.go_to_set_point(self.grabber.get_current_position())
def isFinished(self):
return False
|
Java
|
UTF-8
| 319 | 1.640625 | 2 |
[] |
no_license
|
package com.buzz.exception;
public class CommonException extends Exception {
/**
*
*/
private static final long serialVersionUID = -6256717472813064682L;
public CommonException() {
// TODO Auto-generated constructor stub
}
public CommonException(String arg0) {
super(arg0);
}
}
|
Python
|
UTF-8
| 1,341 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
"""Script that uses scikit-bio to convert fasta files to fastq files."""
import argparse
from skbio import io as skbio_io
def main():
"""Main function."""
args = parse_args()
if args.output.endswith('.gz'):
compression = 'gzip'
else:
compression = 'auto'
with skbio_io.open(args.output, mode='w', compression=compression) as file_:
seqs = skbio_io.read(args.fasta, format='fasta', qual=args.qual)
if args.qual is None:
for seq in seqs:
# Missing quality, add default 'dummy' quality scores.
seq.positional_metadata['quality'] = args.default_qual
skbio_io.write(seq, into=file_, format='fastq',
variant=args.variant)
else:
for seq in seqs:
skbio_io.write(seq, into=file_, format='fastq',
variant=args.variant)
def parse_args():
"""Parses arguments from command line."""
parser = argparse.ArgumentParser()
parser.add_argument('fasta')
parser.add_argument('output')
parser.add_argument('--qual', default=None)
parser.add_argument('--default_qual', type=int, default=40)
parser.add_argument('--variant', default='sanger')
return parser.parse_args()
if __name__ == '__main__':
main()
|
C++
|
UTF-8
| 3,794 | 3.71875 | 4 |
[] |
no_license
|
/*
Program: Adventure Map
Author: Jason Custodio
Class: CS202
Date: 04/16/2014
Description: This program simulates a math riddle game
There will be a menu class that acts as an interface
A player roster will be implemented in the future
The info class acts as any kind of simple data
A player is derived from the info class
A player has a score, a name, a location, and inventory
The score is only an int, the name is info, the location
is the index of where it is in the map
Inventory is a DLL that holds items found in the map
An item is an info
Info only has a name and points to the next and previous items
The map is implemented using a graph
Each vertex holds a question, location, object, a visit flag, and
a head pointer to a LLL of edges
Each edge holds an answer, index of where it points to, and a pointer
to the next edge
To win the game, you must get to the end
Whoever gets the highest score at the end wins with multiplayer
*/
//Holds any kind of data
class info
{
public:
info(); //Default constructor
info(char*); //Info constructor
info(const info&); //Copy constructor
~info(); //Destructor
void setInfo(char*); //Sets data
void display() const; //Display data
void copyInfo(const info&); //Copy data from another info
bool compare(const char*) const; //Compare to see if the data is the same
protected:
char * data; //Holds any kind of data (In this case, names, location, etc)
};
//Item that is put into inventory
class item: public info
{
public:
item(); //Default constructor
item(const info&); //Copy constructor
~item(); //Destructor
item*& goNext(); //Return the next node in the DLL
item*& goPrevious(); //Return the previous node in the DLL
void connectNext(item*); //Connect item to next item
void connectPrevious(item*); //Connect item to previous item
private:
item * next; //Item pointer to the next pointer in the inventory
item * previous; //Item pointer to the next pointer in the inventory
};
//Player that plays the game, holds name, score, inventory, and location index of map
class player: public info
{
public:
player(); //Default constructor
~player();//Destructor
int getLocation(); //Return location
void addScore(int); //Add item to the inventory
void addItem(info&); //Add to the score
void displayScore(); //Display player score
void setLocation(int); //Sets player's location
void removeItem(char*); //Remove item wrapper function
void displayLocation(); //Display location
void displayInventory(); //Display Inventory wrapper function
private:
int score; //Player's score, increments by 100
int location; //Player's location index
item * inventory; //Head DLL pointer to list of items
void displayInventory(item*&); //Displays all items in the inventory
void removeItem(item*&,char*); //Removes item
};
|
C++
|
GB18030
| 1,423 | 3.453125 | 3 |
[] |
no_license
|
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//
class Animal
{
public:
int m_Age; //
};
//Animal Ϊ
//virtual ؼ̳֮ΪΪ ̳
//
class Sheep :virtual public Animal {};
//
class Tuo :virtual public Animal {};
//
class SheepTuo :public Sheep, public Tuo {};
void test01()
{
//μ̳еһ⣺游ԣʹʱжԣԽ
//μ̳еڶ⣺ͬģ壬˷ڴ
SheepTuo st;
st.Sheep::m_Age = 100;
st.Tuo::m_Age = 200;
st.m_Age = 300;
cout << st.Sheep::m_Age << endl;
cout << st.Tuo::m_Age << endl;
cout << st.m_Age << endl;
}
void test02()
{
SheepTuo st;
st.m_Age = 100;
//ͨSheepҵƫ
//*(int *)&st ҵvbtable
cout << "Sheepƫ " << *((int*)*(int *)&st + 1) << endl;
//ͨTuoҵƫ
//*((int *)(&st) + 1) ҵ vbtable
cout << "Tuoƫ " << *((int *)*((int *)(&st) + 1) + 1) << endl;
//ͨSheepƫ ȡm_Age
cout << "st.m_Age = " << *((int *)((char *)&st + (*((int*)*(int *)&st + 1)))) << endl;
cout << "st.m_Age = " << ((Animal *)((char *)&st + (*((int*)*(int *)&st + 1))))->m_Age << endl;
}
int main() {
test01();
//test02();
system("pause");
return EXIT_SUCCESS;
}
|
Markdown
|
UTF-8
| 23,616 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
---
layout: post
title: 第十四章 STL算法第一节
category: CPP基础
tags: CPP基础
description: CPP基础
---
## 算法简介
1. 算法概述
1. 算法部分主要由头文件`<algorithm>`,`<numeric>`和`<functional>`组成。
2. `<algorithm>`是所有STL头文件中最大的一个,其中常用到的功能范围涉及到:比较、交换、查找、遍历操作、复制、修改、反转、排序、合并等等
3. `<numeric>`体积很小,只包括几个在序列上面进行简单数学运算的模板函数,包括加法和乘法在序列上的一些操作。
4. `<functional>`中则定义了一些模板类,用以声明**函数对象**。
5. STL提供了大量实现算法的模版函数,只要我们熟悉了STL之后,许多代码可以被大大的化简,只需要通过调用一两个算法模板,就可以完成所需要的功能,从而大大地提升效率。
2. STL中算法分类
1. 按操作对象分类
1. 直接改变容器的内容
2. 将原容器的内容复制一份,修改其副本,然后传回该副本
2. 功能:
1. 非可变序列算法: 指不直接修改其所操作的容器内容的算法
1. 计数算法: count、count_if
2. 搜索算法: search、find、find_if、find_first_of、…
3. 比较算法: equal、mismatch、lexicographical_compare
2. 可变序列算法: 指可以修改它们所操作的容器内容的算法
1. 删除算法: remove、remove_if、remove_copy、…
2. 修改算法: for_each、transform
3. 排序算法: sort、stable_sort、partial_sort、
3. 排序算法: 包括对序列进行排序和合并的算法、搜索算法以及有序序列上的集合操作
4. 数值算法: 对容器内容进行数值计算
## 算法中的函数对象
### 算法中函数对象和谓词
1. 函数对象和谓词定义
1. **函数对象**:(就是前面讲的仿函数)
1. 重载**函数调用操作符**的类(一个类重载了它的函数调用操作符,即"()"操作符),其对象常称为**函数对象**(function object),即它们是行为类似函数的对象
2. 一个类对象,表现出一个函数的特征,就是通过`对象名+(参数列表)`的方式使用一个类对象,如果没有上下文,完全可以把它看作一个函数对待。
2. 这是通过重载类的`operator()`来实现的。
3. **在标准库中,函数对象被广泛地使用以获得弹性**,标准库中的很多算法都可以使用函数对象或者函数来作为自定的回调行为;
2. 谓词:
1. 一元函数对象:函数参数1个;
2. 二元函数对象:函数参数2个;
3. 一元谓词: 函数参数1个,函数返回值是bool类型,可以作为一个判断式
1. 谓词可以使一个仿函数,也可以是一个回调函数。
4. 二元谓词: 函数参数2个,函数返回值是bool类型
3. **容器算法迭代器的设计理念: 分清楚stl算法返回的值是迭代器还是谓词(函数对象)是stl算法入门的重要点**
2. 函数对象
1. 实现:
```
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//函数模板
template<typename T>
void FuncShowElemt(const T &t) {
cout << t << endl;
}
//函数对象:某个类重载了 ()
//类模板
template<typename T>
class ShowElemt {
private:
int n; //用于记录当前成员函数调用的次数
public:
//构造函数
ShowElemt() {
n = 0;
}
//重载函数调用操作符
//加一个const,既可以传常量,也可以传变量,否则只能传常量
void operator()(const T &t) {
n++;
cout << t << endl;
}
//成员函数
void printCount() {
cout << "函数的调用次数:" << n << endl;
}
};
```
1. 函数对象与函数
```
void test1() {
/****对象函数***/
//创建一个对象
ShowElemt<int> showElemt;
//调用对象的成员函数,看起来很像一个函数的调用,因此也叫做仿函数
showElemt(5);
//等价
//showElemt.operator()(5);
/****函数调用***/
FuncShowElemt<int>(8);
FuncShowElemt(8);
}
```
2. 函数对象的优点:可以保持一些状态
```
void test2() {
//数组
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
//for_each:用于遍历容器中的所有元素
//1. 传参为匿名函数对象
//ShowElemt<int>(): 匿名函数对象
for_each(v1.begin(), v1.end(), ShowElemt<int>());
//2. 也可以传函数的地址,回调函数
for_each(v1.begin(), v1.end(), FuncShowElemt<int>);
//3. 查看函数的调用次数
ShowElemt<int> elemt;
//for_each算法:当函数对象做函数参数时,必须接收一下
elemt = for_each(v1.begin(), v1.end(), elemt);
elemt.printCount();
}
```
1. `for_each`算法:当函数对象做函数参数时,函数对象必须接收一下,为什么呢?
1. 如果不接收,会发现`elemt.printCount();`打印为0,为何呢?
2. 查看`for_each`的源码
```
template<class _InIt,class _Fn>
inline _Fn for_each(_InIt _First, _InIt _Last, _Fn _Func)
{
_Adl_verify_range(_First, _Last);
auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
for (; _UFirst != _ULast; ++_UFirst)
{
_Func(*_UFirst);
}
return (_Func);
}
```
1. 参数都是值传递,非引用(指针)传递,因此,内部修改调用与外部无关
2. 因此,当函数对象当做参数传入时,函数内部本质是调用浅拷贝,拷贝一个新的函数对象接收
3. 所以外面的函数对象elemt任然不变
4. 但是该函数的返回值却返回了内部拷贝的那个信函上对象值
5. 因此,只要在外部接收一下该函数的返回值,既可以拿到函数内部的拷贝值
6. 这就是为何外部的函数对象要接收该函数的返回值,然后打印才会有值的原因。
2. 一元谓词案例:
1. 举例:
```
//一元谓词
template<typename T>
class lsdiv {
private:
T divisor;
public:
lsdiv(const T &divtor) {
this->divisor = divtor;
}
//一元谓词
bool operator()(T &t){
return (t%divisor == 0);
}
};
void test3() {
vector<int> v2;
for (int i = 10; i < 33; i++)
{
v2.push_back(i);
}
int a = 4;
lsdiv<int> mydiv(a);
vector<int>::iterator it;
//遍历容器中的所有元素,找到第一个能够被4整除的元素
//find_if:条件遍历,第三个参数是函数指针或者函数对象,返回值是迭代器
it = find_if(v2.begin(), v2.end(), mydiv);
if (it == v2.end()){ //说明没找到
cout << "容器中没有4的倍数的元素" << endl;
}else {//说明找到了
cout << "容器中第一个4的倍数的元素:"<<*it << endl;
}
}
```
1. find_if算法:
1. 条件遍历,第三个参数就是遍历条件,可以是函数指针或者函数对象
2. 返回值是迭代器
3. 源码:
```
template<class _InIt,class _Pr>
_NODISCARD inline _InIt find_if(_InIt _First, const _InIt _Last, _Pr _Pred)
{
_Adl_verify_range(_First, _Last);
auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
for (; _UFirst != _ULast; ++_UFirst)
{
//调用一元谓词
if (_Pred(*_UFirst))
{
break;
}
}
_Seek_wrapped(_First, _UFirst);
//返回迭代器
return (_First);
}
```
3. 二元函数对象
1. 代码举例
```
//二元函数对象
template<typename T>
class SumAdd {
public:
T operator()(T t1, T t2) {
return t1 + t2;
}
private:
};
void test4() {
vector<int> v1, v2;
vector<int> v3;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
//将V3的大小设置为10
v3.resize(10);
//transform:遍历第一个容器中的元素与第二个容器中的相应位置元素按照最后一个函数处理,然后放入到v3容器中
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(),SumAdd<int>());
//打印V3
for (vector<int>::iterator it = v3.begin(); it != v3.end(); it++) {
cout << *it << endl;
}
}
//使用
int main() {
test4();
cout << "hello world !" << endl;
getchar();
return 0;
}
```
2. stl算法:transform源码
```
template<class _InIt1, class _InIt2, class _OutIt, class _Fn>
inline
_OutIt transform(const _InIt1 _First1, const _InIt1 _Last1,
const _InIt2 _First2, _OutIt _Dest, _Fn _Func)
{
//第一个容器
auto _UFirst1 = _Get_unwrapped(_First1);
const auto _ULast1 = _Get_unwrapped(_Last1);
const auto _Count = _Idl_distance<_InIt1>(_UFirst1, _ULast1);
//第二个容器
auto _UFirst2 = _Get_unwrapped_n(_First2, _Count);
auto _UDest = _Get_unwrapped_n(_Dest, _Count);
for (; _UFirst1 != _ULast1; ++_UFirst1, (void)++_UFirst2, ++_UDest)
{
*_UDest = _Func(*_UFirst1, *_UFirst2);
}
_Seek_wrapped(_Dest, _UDest);
return (_Dest);
}
```
4. 二元谓词
```
//二元谓词
bool mycompare(const int &a, const int &b) {
return a < b;//从小到大排序
}
void test5() {
vector<int>v1(10);
for (int i = 0; i < 10; i++)
{
int temp = rand() % 100;
v1[i] = temp;
}
//排序
sort(v1.begin(), v1.end(), mycompare);
//打印V1
for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) {
cout << *it << endl;
}
}
```
5. 二元谓词在set集合中的应用
1. set容器的find函数,查找字符串时,区分大小写,但是可以设计成不区分大小写
```
//先将set容器中的元素全部转化成小写,然后在按照一定顺序排序
struct CompareNoCase
{
//注意一定要有const,否则报错:ERROR C3848:具有类型"const XXX" 的表达式会丢失一些 const-volatile 限定符
bool operator()(const string &str1, const string &str2) const{
string str_;
str_.resize(str1.size());
//字符串全部转为小写
transform(str1.begin(), str1.end(), str_.begin(), tolower);//tolower这个函数对象系统已经写好了---预定义函数对象
string str2_;
str2_.resize(str2.size());
//字符串全部转为小写
transform(str2.begin(), str2.end(), str2_.begin(), tolower);//tolower这个函数对象系统已经写好了
return (str_ < str2_);
}
};
void test6() {
set<string> st1;
st1.insert("bbb");
st1.insert("aaa");
st1.insert("ccc");
//如果换成"aAa",那么find就查找不到了,因为set容器的find成员函数区分大小写
set<string>::iterator it = st1.find("aAa");
if (it != st1.end())
{
cout << "查找到aaa" << endl;
}
else
{
cout << "没有查找到" << endl;
}
//这么一弄,此时st2中的容器全部转成小写,而且从小到大排序
set<string, CompareNoCase> st2;
st2.insert("bbb");
st2.insert("aaa");
st2.insert("ccc");
//只改变了容器的顺序,但是find就不会区分大小写了呢?---以后研究
set<string, CompareNoCase>::iterator it2 = st2.find("aAa");
if (it2 != st2.end())
{
cout << "(不分大小写)查找到aaa" << endl;
}
else
{
cout << "(不分大小写)没有查找到" << endl;
}
}
```
### 预定义函数对象和函数适配器
#### 预定义函数对象
1. 预定义函数对象基本概念:**标准模板库STL提前定义了很多预定义函数对象**
1. `#include <functional> `必须包含。
2. 算术函数对象
1. 预定义的函数对象支持加、减、乘、除、求余和取反。调用的操作符是与type相关联的实例
2. 举例:
```
加法:plus<Types>
plus<string> stringAdd;
sres = stringAdd(sva1,sva2);
减法:minus<Types>
乘法:multiplies<Types>
除法divides<Tpye>
求余:modulus<Tpye>
取反:negate<Type>
negate<int> intNegate;
ires = intNegate(ires);
Ires= UnaryFunc(negate<int>(),Ival1);
```
3. 关系函数对象
1. 举例:
```
等于equal_to<Tpye>
equal_to<string> stringEqual;
sres = stringEqual(sval1,sval2);
不等于not_equal_to<Type>
大于 greater<Type>
大于等于greater_equal<Type>
小于 less<Type>
小于等于less_equal<Type>
```
4. 逻辑函数对象
1. 举例
```
逻辑与 logical_and<Type>
logical_and<int> indAnd;
ires = intAnd(ival1,ival2);
dres=BinaryFunc( logical_and<double>(),dval1,dval2);
逻辑或logical_or<Type>
逻辑非logical_not<Type>
logical_not<int> IntNot;
Ires = IntNot(ival1);
Dres=UnaryFunc( logical_not<double>,dval1);
```
5. 使用举例:
```
void test7(){
plus<int> intAdd;
int x = 10;
int y = 20;
int z = intAdd(x, y); //等价于 x + y
cout << z << endl;
plus<string> stringAdd;
string myc = stringAdd("aaa", "bbb");
cout << myc << endl;
vector<string> v1;
v1.push_back("bbb");
v1.push_back("aaa");
v1.push_back("ccc");
v1.push_back("zzzz");
//通常情况下,sort()用底层元素类型的小于操作符以升序排列容器的元素。
//为了降序,可以传递预定义的类模板greater,它调用底层元素类型的大于操作符:
cout << "sort()函数排序" << endl;;
//greater<string>()匿名函数对象
sort(v1.begin(), v1.end(), greater<string>()); //从大到小
for (vector<string>::iterator it = v1.begin(); it != v1.end(); it++)
{
cout << *it << endl;
}
vector<string> v2;
v2.push_back("bbb");
v2.push_back("aaa");
v2.push_back("ccc");
v2.push_back("zzzz");
v2.push_back("ccc");
string s1 = "ccc";
//求s1出现的次数
//本来貌似应该这么写,但是这么写错误,仅仅有3个参数,而且第三个参数是一个指针,或者函数对象
//int num = count_if(v1.begin(),v1.end(), equal_to<string>(),s1);
//bind2nd函数适配器:将预定义函数对象与参数绑定
//equal_to<string>():有2个参数,左参数来自容器,右参数被绑定为s1,让容器中的每个元素与右参数s1进行比较
int num = count_if(v2.begin(), v2.end(), bind2nd(equal_to<string>(), s1));
cout << num << endl;
}
```
1. 分析:
1. count_if 函数只有3个参数
2. 源码如下:
```
template<class _InIt,class _Pr>
_NODISCARD inline _Iter_diff_t<_InIt> count_if(_InIt _First, _InIt _Last, _Pr _Pred)
{ // count elements satisfying _Pred //计算元素
_Adl_verify_range(_First, _Last);
auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
_Iter_diff_t<_InIt> _Count = 0;
for (; _UFirst != _ULast; ++_UFirst)
{
if (_Pred(*_UFirst)) //函数返回yes,_count+1
{
++_Count;
}
}
return (_Count);
}
```
3. 从上面可以看出,第三个参数是一个函数指针,或者函数对象
4. 而且内部遍历调用时只传容器中的元素
5. 那么问题来了,我们目的是想让元素中的值与一个字符串比较,那么这个函数应该有两个参数
6. 即函数对象`equal_to<string>()`是2个对象,那么怎么办呢?
7. 此时就用到了函数适配器---bind2nd
1. 作用就是可以将一个二元函数的第二个参数设置成一个默认的值,然后在返回这个函数(对象)
2. `bind2nd(equal_to<string>(), s1)`,这么写就相当于`equal_to(x,s1)`;,其中x是变量,s1是常量
#### 函数适配器
1. 理论知识:
1. STL中已经定义了大量的函数对象,但是有时候需要对**函数返回值**进行进一步的简单计算,或者**填上多余的参数,不能直接带入算法**。
2. 函数适配器实现了这一功能:**将一种函数对象转化为另一种符合要求的函数对象。**
3. 函数适配器可以分为4大类:
1. 绑定适配器(bind adaptor)
2. 组合适配器(composite adaptor)
3. 指针函数适配器(pointer function adaptor)
4. 成员函数适配器(member function adaptor)
4. 下图是STL中所有函数适配器

5. 直接构造STL中的函数适配器通常会导致冗长的类型声明。为简化函数适配器的构造,STL还提供了函数适配器辅助函数,借助于**泛型自动推断技术**,无需显式的类型声明便可实现函数适配器的构造。

2. 常用函数函数适配器
1. 标准库提供一组函数适配器,用来特殊化或者扩展一元和二元函数对象。常用适配器是:
1. 绑定器(binder): binder通过把二元函数对象的一个实参绑定到一个特殊的值上,将其转换成一元函数对象。C++标准库提供两种预定义的binder适配器:bind1st和bind2nd,前者把值绑定到二元函数对象的第一个实参上,后者绑定在第二个实参上。
2. 取反器(negator) : negator是一个将函数对象的值翻转的函数适配器。标准库提供两个预定义的ngeator适配器:not1翻转一元预定义函数对象的真值,而not2翻转二元谓词函数的真值。
3. 常用函数适配器列表如下:
```
bind1st(op, value)
bind2nd(op, value)
not1(op)
not2(op)
mem_fun_ref(op)
mem_fun(op)
ptr_fun(op)
```
2. 总结函数适配器bind2nd的作用:
1. 将一个二元函数转化为一元函数
2. 其中一个参数设置为默认参数value,另一个参数为变量
3. 举例使用:
```
//是否大于
class IsGreat
{
public:
IsGreat(int i)
{
m_num = i;
}
//一元谓词
bool operator()(int &num)
{
if (num > m_num)
{
return true;
}
return false;
}
private:
int m_num;
};
void test8()
{
vector<int> v1;
for (int i = 0; i < 5; i++)
{
v1.push_back(i + 1);
}
for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++)
{
cout << *it << " ";
}
//3的个数
int num1 = count(v1.begin(), v1.end(), 3);
cout << "num1:" << num1 << endl;
//通过谓词求大于2的个数
int num2 = count_if(v1.begin(), v1.end(), IsGreat(2));
cout << "num2:" << num2 << endl;
//通过预定义函数对象,求大于2的个数
//greater<int>() 有2个参数 ,通过bind2nd可以转化成一个参数的函数,另外一个参数绑定成2
int num3 = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(), 2));
cout << "num3:" << num3 << endl;
//取模 能被2整除的数 求奇数
int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus <int>(), 2));
cout << "奇数num4:" << num4 << endl;
int num5 = count_if(v1.begin(), v1.end(), not1(bind2nd(modulus <int>(), 2)));
cout << "偶数num5:" << num5 << endl;
return;
}
```
## STL的容器算法迭代器的设计理念

1. STL的容器通过类模板技术,实现数据类型和容器模型的分离
1. 一种容器可以存放不同的数据类型
2. STL的迭代器技术实现了**遍历容器**的统一方法;也为STL的算法提供了统一性奠定了基础
3. STL的算法,通过**函数对象**实现了数据类型和算法的分离;所以说:STL的算法也提供了统一性。
1. 函数对象分为2种:自定义、STL预定义
1. 核心思想:其实函数对象本质就是回调函数,回调函数的思想:就是任务的编写者和任务的调用者有效解耦合。函数指针做函数参数。
4. 具体例子:transform算法的输入,通过迭代器first和last指向的元算作为输入;通过result作为输出;通过函数对象来做自定义数据类型的运算。
|
Java
|
UTF-8
| 588 | 2.46875 | 2 |
[] |
no_license
|
package com.mycompany.serverside.business;
import com.mycompany.serverside.data.Stone;
/**
* The ThreeStonesServerGameDAO defines the rules that any implementation of a
* Three Stones server-side game logic class must follow.
*
* @author Hannah Ly
* @author Werner Castanaza
* @author Peter Bellefleur MacCaul
*/
public interface ThreeStonesServerGameDAO {
public void buildBoard();
public boolean playRoundOfGame(int x, int y);
public int getServerX();
public int getServerY();
public int getClientScore();
public int getServerScore();
public int getClientStones();
}
|
PHP
|
UTF-8
| 2,031 | 2.515625 | 3 |
[] |
no_license
|
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=windows-874″ />
<title>สร้าง Form สำหรับค้นหาข้อมูล</title>
</head>
<body bgcolor=”#999999″>
<form action=”search.php” method=”post” name=”search”>
search :: <input type=”text” size=”20″ name=”search” />
<input type=”submit” value=” search ” />
</form>
<hr />
<?php
//ถ้ามีการส่งค่าข้อมูล
$search = $_POST[search];
if(isset($search) ) {
echo “<font size=’-1′ color=’#FF0000′>ผลลัพธ์ของคำว่า [ $search ] </font><br />”;
?>
<table align=”left” width=”50%” border=”0″>
<tr bgcolor=”#FFFFFF”>
<td>ชื่อจริง</td>
<td>นามสกุล</td>
<td>อายุ</td>
<td>เพศ</td>
<td>แผนก</td>
<td>เงินเดือน</td>
</tr>
<?php
$link = mysql_connect(“localhost”,”root”,”root”);
mysql_select_db(“vdo”,$link);
$result = mysql_query(“SELECT * FROM mytable where fname like ‘%$search%'”);
$num = mysql_num_rows($result);
echo “<font size=’-1′ color=’green’>ค้นพบทั้งหมด :: [ $num ] </font><br />”;
$sql = “select * from mytable where fname like ‘%$search%’ “;
$view = mysql_query($sql);
while ($data = mysql_fetch_array($view) ) {
?>
<tr>
<td><?php echo “$data[fname]”; ?></td>
<td><?php echo “$data[lname]”; ?></td>
<td><?php echo “$data[age]”; ?></td>
<td><?php echo “$data[gender]”; ?></td>
<td><?php echo “$data[department]”; ?></td>
<td><?php echo “$data[salary]”; ?></td>
</tr>
<?php
} //End while loop
} else {
echo “กรุณากรอกคำค้นของคุณ”;
}
?>
</body>
</html>
|
Java
|
UTF-8
| 1,312 | 2.453125 | 2 |
[] |
no_license
|
package com.khalimudin;
import com.khalimudin.resources.HelloResource;
import com.khalimudin.health.TemplateHealthCheck;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
public class HelloDropwizardApplication extends Application<HelloDropwizardConfiguration> {
public static void main(final String[] args) throws Exception {
new HelloDropwizardApplication().run(args);
}
@Override
public String getName() {
return "HelloDropwizard";
}
@Override
public void initialize(final Bootstrap<HelloDropwizardConfiguration> bootstrap) {
// TODO: application initialization
}
@Override
public void run(final HelloDropwizardConfiguration configuration,
final Environment environment) {
// TODO: implement application
final HelloResource resource = new HelloResource(
configuration.getTemplate(),
configuration.getDefaultName()
);
environment.jersey().register(resource);
final TemplateHealthCheck healthCheck =
new TemplateHealthCheck(configuration.getTemplate());
environment.healthChecks().register("template", healthCheck);
environment.jersey().register(resource);
}
}
|
JavaScript
|
UTF-8
| 456 | 3.28125 | 3 |
[] |
no_license
|
pseudoElt = document.getElementById("pseudo");
/*
elmtPseudo.value = "douze";*/
// Affichage d'un message contextuel pour la saisie du pseudo
pseudoElt.addEventListener("focus", function () {
document.getElementById("aidePseudo").textContent = "Entrez votre pseudo";
});
// Suppression du message contextuel pour la saisie du pseudo
pseudoElt.addEventListener("blur", function (e) {
document.getElementById("aidePseudo").textContent = "";
});
|
C#
|
UTF-8
| 7,271 | 3.5 | 4 |
[] |
no_license
|
using System;
namespace laba3
{
class Program
{
static void Main(string[] args)
{
}
static void Task1_2()
{
int fir = 0, last = 0;
int n = Convert.ToInt32(Console.ReadLine());
double[] arr = new double[n];
double sum = 0;
for (int i = 0; i < arr.Length; i++)
{
arr[i] = Convert.ToDouble(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i += 2)
{
sum += arr[i];
}
Console.WriteLine("Сумма элементов с нечётными номерами: " + sum);
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < 0)
{
fir = i;
break;
}
}
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < 0)
{
last = i;
}
}
sum = 0;
for (int i = fir + 1; i < last; i++)
{
sum += arr[i];
}
Console.WriteLine("Сумма элементов между первым отрицательным и последним отрицательным: " + sum);
for(int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
static void Task1_8()
{
// 8 variant
int c, n, ans = 0;
n = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
double[] arr = new Double[n];
string[] s = Console.ReadLine().Split(' ');
for (int i = 0; i < n; i++)
arr[i] = Convert.ToDouble(s[i]);
for (int i = 0; i < n; i++)
if (arr[i] < c)
ans++;
int lastIdx = 0;
int sumArr = 0;
for (int i = 0; i < n; i++)
if (arr[i] < 0) lastIdx = i;
for (int i = lastIdx + 1; i < n; i++)
sumArr += Convert.ToInt32(arr[i]);
Console.WriteLine(ans);
Console.WriteLine(sumArr);
}
static void Task2_2()
{
int m = Convert.ToInt32(Console.ReadLine());
int[,] arra = new int[m, m];
for(int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
arra[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
int mul;
bool meow = true;
for (int i = 0; i < m; i++)
{
mul = arra[i, 0];
for (int j = 1; j < m; j++)
{
if (arra[i, j] > 0)
{
mul *= arra[i, j];
}
else
{
meow = false;
break;
}
}
if (meow)
{
Console.WriteLine(mul);
}
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(arra[i, j] + " ");
}
Console.WriteLine();
}
int t = 0;
for (int i = 0; i < m; i++)
{
t = arra[i, 0];
arra[i, 0] = arra[i, 1];
arra[i, 1] = t;
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(arra[i, j] + " ");
}
Console.WriteLine();
}
}
static void Task2_8()
{
// variant 8
int n;
n = Convert.ToInt32(Console.ReadLine());
int[,] arr = new int[n, n]; // matrix
// read matrix
for (int i = 0; i < n; i++)
{
string[] s = Console.ReadLine().Split(' ');
for (int j = 0; j < n; j++)
arr[i, j] = Convert.ToInt32(s[j]);
}
for (int i = 0; i < n; i++)
{
int sumArr = 0;
bool flag = true;
for (int j = 0; j < n; j++)
{
if (arr[j, i] > 0) sumArr += arr[j, i];
else
{
flag = false; break;
}
}
if (flag) Console.WriteLine($"Sum of + {i} row: {sumArr}");
}
Console.WriteLine();
Console.WriteLine("Matrix: ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(arr[i, j]);
Console.Write(" ");
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Matrix change: ");
for (int i = 0; i < n; i++)
{
int temp = arr[i, n - 2];
arr[i, n - 2] = arr[i, n - 1];
arr[i, n - 1] = temp;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(arr[i, j]);
Console.Write(" ");
}
Console.WriteLine();
}
Console.WriteLine();
}
static void Task3_All()
{
int[][] arr = new int[5][];
arr[0] = new int[5];
arr[1] = new int[3];
arr[2] = new int[8];
arr[3] = new int[4];
arr[4] = new int[6];
for (int i = 0; i < 5; i++)
{
Random rand = new Random(); // class Random
for (int j = 0; j < arr[i].Length; j++)
{
arr[i][j] = rand.Next(-500, 500);
}
}
for (int i = 0; i < 5; i++)
{
int sumArr = 0;
for (int j = 0; j < arr[i].Length; j++)
{
sumArr += arr[i][j];
}
Console.WriteLine($"sum row {i} : {sumArr}");
}
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j]);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}
|
PHP
|
UTF-8
| 471 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace NewsReader\Contracts;
interface NewsReaderInterface
{
/**
* @param $url
* @return mixed
*/
public function setUrl($url);
/**
* @param $queryString
* @return mixed
*/
public function with($queryString);
/**
* @return mixed
*/
public function get();
/**
* @return mixed
*/
public function all();
/**
* @return mixed
*/
public function mix($array);
}
|
JavaScript
|
UTF-8
| 1,931 | 2.921875 | 3 |
[] |
no_license
|
document.addEventListener('DOMContentLoaded', function(){
// Size options
const sizesBtns = document.querySelectorAll('.card__size');
function changeActiveSize(e) {
if(e.target.classList.contains('active')){
return;
}
sizesBtns.forEach(btn => {
if(btn.classList.contains('active')) {
btn.classList.remove('active');
}
});
e.target.classList.add('active');
}
sizesBtns.forEach(function(btn) {
btn.addEventListener('click', changeActiveSize);
});
// Animation
const card = document.querySelector('.card'),
container = document.querySelector('.container'),
title = document.querySelector('.card__title'),
image = document.querySelector('.card__img'),
desc = document.querySelector('.card__desc'),
sizes = document.querySelector('.card__sizes'),
purchase = document.querySelector('.card__purchase');
// Mouse moving event
container.addEventListener('mousemove', (e) => {
let xAxis = (window.innerWidth / 2 - e.pageX) / 20;
let yAxis = (window.innerHeight / 2 - e.pageY) / 20;
card.style.transform = `rotateY(${xAxis}deg) rotateX(${yAxis}deg)`;
});
// Mouse in container
container.addEventListener('mouseenter', (e) => {
setTimeout(() => {
card.style.transition = 'none';
}, 600);
title.style.transform = 'translateZ(100px)';
desc.style.transform = 'translateZ(100px)';
sizes.style.transform = 'translateZ(100px)';
purchase.style.transform = 'translateZ(100px)';
image.style.transform = 'translateZ(140px) rotateZ(45deg)';
});
// Mouse out container
container.addEventListener('mouseleave', (e) => {
card.style.transform = 'rotateY(0deg) rotateX(0deg)';
card.style.transition = "all 0.60s ease";
title.style.transform = "translateZ(0px)";
desc.style.transform = 'translateZ(0px)';
sizes.style.transform = "translateZ(0px)";
purchase.style.transform = "translateZ(0px)";
image.style.transform = 'translateZ(0px) rotateZ(0deg)';
});
});
|
C++
|
UTF-8
| 888 | 3.015625 | 3 |
[] |
no_license
|
///
/// @file Condition.cc
/// @author patrick(730557219@qq.com)
/// @date 2016-03-04 21:26:17
///
#include "Condition.h"
//由于该实现文件是真正要使用MutexLock函数,即跟实现有关系了,故加上头文件
#include "MutexLock.h"
Condition::Condition(MutexLock & lock)//类外实现函数
: _mutex(lock)//由于是引用,必须在初始化列表中进行初始化
{
pthread_cond_init(&_cond, NULL);
}
Condition::~Condition()
{
pthread_cond_destroy(&_cond);
}
void Condition::wait()
{
pthread_cond_wait(&_cond, _mutex.getMutexPtr());
//由于定义中使用的是引用,所以用 .
//这里要获得MutexLock原生的指针,通过引用解决了这个问题
//所以在MutexLock对象中加上一个获取指针的函数
}
void Condition::notify()
{
pthread_cond_signal(&_cond);
}
void Condition::notifyAll()
{
pthread_cond_broadcast(&_cond);
}
|
Java
|
UTF-8
| 2,582 | 2.34375 | 2 |
[] |
no_license
|
package br.com.mvppoa.kafka.retries.config;
import com.hazelcast.config.Config;
import com.hazelcast.config.EvictionPolicy;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MaxSizeConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class HazelcastConfiguration {
@Bean
public HazelcastInstance hazelcastInstance() {
HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("kafka-delay-queue");
if (hazelCastInstance != null) {
log.debug("Hazelcast already initialized");
return hazelCastInstance;
}
Config config = new Config();
config.setInstanceName("dominioapi");
config.setProperty("hazelcast.partition.migration.stale.read.disabled","true");
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().setPortAutoIncrement(true);
config.getMapConfigs().put("default", initializeDefaultMapConfig());
config.getMapConfigs().put("existingUUIDs", initializeUuidMapConfig());
return Hazelcast.newHazelcastInstance(config);
}
private MapConfig initializeDefaultMapConfig() {
MapConfig mapConfig = new MapConfig();
/*
Number of backups. If 1 is set as the backup-count for example,
then all entries of the map will be copied to another JVM for
fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
*/
mapConfig.setBackupCount(0);
/*
Valid values are:
NONE (no eviction),
LRU (Least Recently Used),
LFU (Least Frequently Used).
NONE is the default.
*/
mapConfig.setEvictionPolicy(EvictionPolicy.NONE);
/*
Maximum size of the map. When max size is reached,
map is evicted based on the policy defined.
Any integer between 0 and Integer.MAX_VALUE. 0 means
Integer.MAX_VALUE. Default is 0.
*/
mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
private MapConfig initializeUuidMapConfig() {
MapConfig mapConfig = new MapConfig();
mapConfig.setTimeToLiveSeconds(600);
mapConfig.setBackupCount(3);
mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
}
|
Python
|
UTF-8
| 2,096 | 3.59375 | 4 |
[] |
no_license
|
import utils
# heap
# array A, with A[0] used to store size(A)
def parent(i): return i/2
def left(i): return 2*i
def right(i): return 2*i+1
def check_heap(A,i):
if (i==0 or i>A[0]):
return True
if (i==1):
return check_heap(A,left(i)) and check_heap(A,right(i))
else:
return (A[i]<=A[parent(i)]) and check_heap(A,left(i)) and check_heap(A,right(i))
# (max-)heap property: A[parent(i)]>=A[i]
# heapify: O(log n)
# T(n) <= T(2n/3) + O(1)
def heapify(A,i): # heapify the tree rooted at position i assuming subtrees left(i), right(i) are heaps
n=A[0]
l=left(i)
r=right(i)
#print i,A[i]
# left child is largest
if ((l<=n) and (A[l] > A[r]) and (A[l] > A[i])):
swap(A,l,i)
heapify(A,l)
# right child is largest
elif ((r<=n) and (A[r] > A[l]) and (A[r] > A[i])):
swap(A,r,i)
heapify(A,r)
# build-heap: bottom-up, O(n)
def build_heap(A):# we will overwrite the first element
A[0]=len(A)-1
n=A[0]
for i in range(n/2,0,-1): # n/2...1
heapify(A,i)
# heapsort: O(n log n), worst-case, in-place
# instead of repeatedly extracting max, do the following:
# first, build a heap from A
# with n=A[0], swap A[1] with A[n], decrement A[0] (size)
# heapify(A,1), and repeat until n=2
def heapsort(A):
build_heap(A)
n=A[0]
for i in range(n,0,-1): # n...2
swap(A,1,i)
A[0] = A[0]-1
heapify(A,1)
A[0]=0
# extract-max: O(log n)
# store max=A[1], set A[1]=A[n], reduce A[0] by 1, heapify(A,1)
def extract_max(A):
n=A[0]
if (n==0): return None
x=A[1]
A[1]=A[n]
A[0] = A[0]-1
heapify(A,1)
return x
# insert: O(log n)
# insert at end of array, then percolate up until heap property no longer violated
def heap_insert(A,k):
A[0]=A[0]+1
n=A[0]
# assume we have size in A
A[n]=k
while (n>1 and A[parent(n)]<k):
swap(A,n,parent(n))
n=parent(n)
# increase-key: O(log n)
# can only go up in the heap
# basically the last 3 lines of heap_insert
def heap_increase_key(A,i,k):
A[i]=k
while (i>1 and A[parent(i)]<k):
swap(A,i,parent(i))
i=parent(i)
# decrease-key: O(log n)
# can only go down in the heap
def heap_decrease_key(A,i,k):
A[i]=k
heapify(A,i)
|
Python
|
UTF-8
| 2,003 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
import appdaemon.plugins.hass.hassapi as hass
class LowBattery(hass.Hass):
def initialize(self):
# Init an empty dict in the global_vars, used for storing data
self.global_vars['battery'] = {}
# Iterate over the entity list, setting listeners, etc.
for entity in self.args.get('entities',[]):
# Set the alerting state, used to only fire one notification
self.global_vars['battery'][entity] = {
'alerting': False,
}
# Configure listeners
self.listen_state(
callback = self.low_battery_cb,
entity = entity,
attribute = 'battery_level',
immediate = True
)
def low_battery_cb(self, entity, attribute, old, new, kwargs):
level = self.args.get('level', 10)
alerting = self.global_vars['battery'][entity].get('alerting', False)
if new <= level and not alerting:
# Set the alerting status and send an alert notification
self.global_vars['battery'][entity]['alerting'] = True
self.notify(
title = 'ALERT: Low Battery: {} '.format(self.friendly_name(entity)),
message = '{} reported a battery level of {}%, which is below the notification threshold of {}%'.format(entity, new, level),
name = 'email'
)
self.log('Sent low battery email for {}'.format(entity))
elif new > level and alerting:
# Reset the alerting status and send a reset notification
self.global_vars['battery'][entity]['alerting'] = False
self.notify(
title = 'RESET: Low Battery: {} '.format(self.friendly_name(entity)),
message = 'Low battery level alert has been reset for entity {}. Battery is at {}%.'.format(entity, new),
name = 'email'
)
self.log('Sent alert reset email for {}'.format(entity))
|
Markdown
|
UTF-8
| 288 | 3.375 | 3 |
[] |
no_license
|
---
title: Log in Python
updated: '2021-09-10 08:00:39'
reference: ''
tags:
- python
- programming
---
In python, we should use `math.log10` instead of `math.log` for better float number processing:
```python
math.log(243, 3) #4.9999999999
math.log10(243) / math.log10(3) # 5.0
```
|
Java
|
UTF-8
| 841 | 2.046875 | 2 |
[] |
no_license
|
package ek.zhou.crm.web.interceptor;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import ek.zhou.crm.domain.User;
public class PrivilegeInterceptor extends MethodFilterInterceptor{
@Override
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
User existUser = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
if(null==existUser){
//没有登陆
ActionSupport actionSupport = (ActionSupport) actionInvocation.getAction();
actionSupport.addActionError("您没有登陆,没有访问权限!请先登陆!");
return "fail";
}
return actionInvocation.invoke();
}
}
|
Python
|
UTF-8
| 886 | 3.671875 | 4 |
[] |
no_license
|
try:
print('Proporcione los siguientes datos del libro:')
name = input('Proporciona el nombre: ')
id = int(input('Proprociona el ID: '))
precio = float(input('Proporcione el precio: '))
envio = input('Indica si el envio es gratuito (True/False): ')
if envio == "True":
envio = True
elif envio == "False":
envio = False
else:
envio = False
# envio = 'Valor incorrecto escribir True o False'
print(f'''
Nombre: {name}
Id: {id}
Precio: {precio}
Envio Gratuito?: {envio}
''')
# print(f'Nombre: {name}')
# print(f'Id: {id}')
# print(f'Precio: {precio}')
# print(f'Envio Gratuito?: {envio}')
except Exception as e:
print(f'Handle Exception {e}')
# bool(input()) la clase bool solamente valida si la cadena es disinto de vacio es True en caso contrario Flase
|
C#
|
UTF-8
| 462 | 2.859375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Extensions;
namespace ShiftArray
{
class Program
{
static void Main()
{
var collection = new List<int>().FillOrdered(10);
collection.ShiftRight(3);
collection.Log();
collection.ShiftLeft(3);
collection.Log();
Console.ReadKey();
}
}
}
|
Python
|
UTF-8
| 2,238 | 2.75 | 3 |
[
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
import gensim
import numpy as np
from nltk.corpus import stopwords
from math import sqrt
import _pickle as pickle
stopword = set(stopwords.words('english'))
def cosine_similarity(v1, v2):
dist = np.dot(v1, v2) / sqrt(np.dot(v1, v1) * np.dot(v2, v2))
return dist
def get_vector(sentence, wordvec_model, tfidf_model = None):
vec_size = len(wordvec_model.syn0[0])
sent_vec = np.zeros(vec_size)
totalweight = 0
word_count = 0
if tfidf_model == None:
for word in [ i for i in sentence.lower().split() if i not in stopword]:
if word in wordvec_model:
sent_vec = sent_vec + wordvec_model[word]
word_count += 1
if(word_count == 0):
checkFlag = False
else:
checkFlag = True
sent_vec = sent_vec / word_count
else:
for word in [ i for i in sentence.lower().split() if i not in stopword]:
if word in wordvec_model:
if word in tfidf_model:
sent_vec = sent_vec + wordvec_model[word]*tfidf_model[word]
totalweight += tfidf_model[word]
else:
sent_vec = sent_vec + wordvec_model[word]*0
if(totalweight == 0):
checkFlag = False
else:
checkFlag = True
sent_vec = sent_vec / totalweight
return sent_vec, checkFlag
#def get_weighted_vec(sentence, wordvec_model):
if __name__ == '__main__':
if 'model' not in globals():
model = gensim.models.KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin", binary=True)
tfidffile = "D:/Python project/Plagiarism Project/tfidfmodel.pl"
with open(tfidffile, 'rb') as tfidf_file:
tfidf_model = dict(pickle.load(tfidf_file))
sentence1 = "Subject to agent great hours of operation and availability ."
sentence2 = "Subject to agent many hours of operation and availability ."
s1 = get_vector(sentence1, model, tfidf_model)
s2 = get_vector(sentence2, model, tfidf_model)
print(cosine_similarity(s1, s2))
print("pass")
|
Go
|
UTF-8
| 424 | 2.65625 | 3 |
[] |
no_license
|
package main
import (
"cflog/functions"
"flag"
)
func main() {
var date string
var hour int
flag.StringVar(&date, "d", "", "Date for the log in format: 2019-01-24")
flag.IntVar(&hour, "h", 0, "Starting hour for the log, Only the hour: example: 12, 20, 23, 00, 1, 2 ,3.. etc , If hour is not specified 00:00 is assumed")
flag.Parse()
if date != "" {
functions.Logs(date, hour)
} else {
flag.Usage()
}
}
|
Java
|
UTF-8
| 1,756 | 3.953125 | 4 |
[
"Apache-2.0"
] |
permissive
|
package competitive.programming.timemanagement;
/**
* @author Manwe
*
* Time management class in order to measure elapsed time and avoid time outs
* The Timer class uses the System.nanoTime() method to get the time. It is not executed in a separated thread, you must use the timeCheck method in order to verify the timeout has not been reached during the execution of your computation
*/
public class Timer {
private long startTime = 0;
private long timeout=0;
/**
* @return
* the number of nanoseconds between last time the timer has been started and now
* Will return System.nanoTime() if the timer has never been started
*/
public long currentTimeTakenInNanoSeconds() {
return ((System.nanoTime() - startTime));
}
/**
* Start the timer.
* If the timer is already started, will simply define the timeout as now + duration
* A call to this method is mandatory if you want the timeCheck method to throws timeout exceptions
*
* @param durationInMilliseconds
* The duration in milliseconds from now until which the timeCheck method will throws Timeoutexceptions
*/
public void startTimer(double durationInMilliseconds) {
startTime = System.nanoTime();
timeout = startTime+(long)(durationInMilliseconds*1000000);
}
/**
* Verify if the timeout has been reached. If yes, throws a TimeoutException
* will not throw anything if the timer has never been started.
* @throws TimeoutException
*/
public void timeCheck() throws TimeoutException {
if (startTime > 0 && System.nanoTime() > timeout) {
throw new TimeoutException();
}
}
}
|
Java
|
UTF-8
| 2,040 | 3.40625 | 3 |
[] |
no_license
|
/**
* NinjaBookShelf was created by Phillip Feist
* Using the NetBeans IDE 7.2.1
* For the Zappos TechU Coding Challenge
* Thanks for viewing!
**/
package ninjabookshelf;
import java.util.Arrays;
import javax.swing.JOptionPane;
/**
* @author Phil Feist
*/
public class NinjaBookShelf {
public static void main(String[] args) {
/**
* This program uses an alphabetically sorted array to produce a bookshelf
* effect.
*/
String[] ninjaBooks = { "Deadly Silence", "Ninjutsu For Dummies", "Enter"
+ " the Ninja", "Return of the Ninja", "Hiding in Plain Sight",
"9,999 Ways to Die", "Handbook of the League of Shadows, Volume"
+ " 1"};
/**
* This displays the ninja books, unsorted,
*/
System.out.println("This week's shipment of Ninja books"
+ " includes: " + ninjaBooks[0] + ", " + ninjaBooks[1] + ", \n" +
ninjaBooks[2] + ", " + ninjaBooks[3] + ", " + ninjaBooks[4] +
", " + ninjaBooks[5] + ", and \n" + ninjaBooks[6] + ".");
/**
* Now the books are sorted alphabetically, and the characters of each
* book is printed separately.
**/
Arrays.sort(ninjaBooks);
/**
* For loop prints each letter of each book in turn
*/
for (int i=0; i<43; i++){
char book1 = ninjaBooks[0].charAt(i);
char book2 = ninjaBooks[1].charAt(i);
char book3 = ninjaBooks[2].charAt(i);
char book4 = ninjaBooks[3].charAt(i);
char book5 = ninjaBooks[4].charAt(i);
char book6 = ninjaBooks[5].charAt(i);
char book7 = ninjaBooks[6].charAt(i);
{
System.out.println(book1 + " " + book2 + " " + book3 +
" " + book4 + " " + book5 + " " + book6 + " " + book7);
}
}
}
}
|
Python
|
UTF-8
| 5,632 | 2.765625 | 3 |
[
"BSD-3-Clause",
"BSD-3-Clause-Open-MPI"
] |
permissive
|
#!/usr/bin/env python
## category General
## desc Find and mark PCR duplicates
## experimental
'''
For a BAM file, find and mark all possible PCR duplicates. This is meant to be
used primarily with paired-end reads, since these have better resolution to
verify that we care seeing a legitimate PCR duplicate and not just reads that
happen to start at the same location.
The orientation for paired-end reads is assumed to be "FR" (forward-reverse).
Note: The BAM file must be sorted in order to find duplicates. For paired-end
reads, the the proper-pair (0x4) flag must be set and the isize/tlen
field must be correctly calculated.
'''
import sys
import os
import pysam
from ngsutils.bam import bam_iter
def usage(msg=None):
if msg:
sys.stdout.write('%s\n\n' % msg)
sys.stdout.write(__doc__)
sys.stdout.write('''\
Usage: bamutils pcrdup {options} infile.bam
Options:
-frag The reads are single-end fragments, so mark PCR
duplicated based only on the location of the read
(not-recommended)
-bam filename Output BAM file with PCR duplicates marked
-counts filename Output of the number of reads at each position
Note: this is actually the number of duplicate reads
at each position. If a position has multiple reads
mapped to it, but they are not pcr duplicates, then
there each will be reported separately.
You must set either -bam or -counts (or both).
''')
sys.exit(1)
def __flush_cur_reads(cur_reads, outbam, inbam, countfile=None):
if cur_reads:
for k in cur_reads:
count = 0
for i, (mapq, idx, r) in enumerate(sorted(cur_reads[k])[::-1]):
count += 1
if i > 0:
r.is_duplicate = True
if outbam:
outbam.write(r)
if countfile:
countfile.write('%s\t%s\t%s\t%s\n' % (inbam.references[k[0]], k[1], k[2], count))
def pcrdup_mark(inbam, outbam, fragment=False, countfile=None):
cur_pos = None
cur_reads = {}
total = 0
unique = 0
duplicates = 0
dup_list = set()
def callback(read):
return '%s, %s, %s - %s' % (total, unique, duplicates, read.qname)
for read in bam_iter(bamfile, callback=callback):
if not read.is_paired or read.is_read1:
total += 1
if read.is_unmapped:
__flush_cur_reads(cur_reads, outbam, inbam, countfile)
if outbam:
outbam.write(read)
continue
start_pos = (read.tid, read.pos)
if fragment:
dup_pos = (read.tid, read.pos, '')
else:
# isize is the insert length, which if this is the first read, will
# be the right most part of the second read. If the ends of the reads
# are trimmed for QC reasons, only the 5' pos of the first read and the 3'
# pos of the second read will be accurate.
dup_pos = (read.tid, read.pos, read.isize)
if not cur_pos or start_pos != cur_pos:
__flush_cur_reads(cur_reads, outbam, inbam, countfile)
cur_pos = start_pos
cur_reads = {}
idx = 0
if not fragment and (read.mate_is_unmapped or not read.is_paired or not read.is_proper_pair or read.isize < 0):
# this is a paired file, but the mate isn't paired or proper or mapped
# just write it out, no flags to set.
if read.qname in dup_list:
read.is_duplicate = True
dup_list.remove(read.qname)
if outbam:
outbam.write(read)
elif dup_pos in cur_reads:
duplicates += 1
if not fragment:
dup_list.add(read.qname)
cur_reads[dup_pos].append((read.mapq, -idx, read))
else:
unique += 1
cur_reads[dup_pos] = [(read.mapq, -idx, read), ]
idx += 1
__flush_cur_reads(cur_reads, outbam, inbam, countfile)
sys.stdout.write('Total reads:\t%s\n' % total)
sys.stdout.write('Unique reads:\t%s\n' % unique)
sys.stdout.write('PCR duplicates:\t%s\n' % duplicates)
if __name__ == '__main__':
infile = None
outfile = None
countfname = None
fragment = False
last = None
for arg in sys.argv[1:]:
if arg == '-h':
usage()
elif last == '-counts':
countfname = arg
last = None
elif last == '-bam':
outfile = arg
last = None
elif arg in ['-counts', '-bam']:
last = arg
elif arg == '-frag':
fragment = True
elif not infile:
if os.path.exists(arg):
infile = arg
else:
usage("%s doesn't exist!" % arg)
elif not outfile:
if not os.path.exists(arg):
outfile = arg
else:
usage("%s exists! Not overwriting file." % arg)
if not infile or not (outfile or countfname):
usage()
bamfile = pysam.Samfile(infile, "rb")
bamout = None
if outfile:
bamout = pysam.Samfile(outfile, "wb", template=bamfile)
if countfname:
countfile = open(countfname, 'w')
else:
countfile = None
pcrdup_mark(bamfile, bamout, fragment, countfile)
bamfile.close()
if bamout:
bamout.close()
if countfile:
countfile.close()
|
C++
|
UTF-8
| 3,146 | 2.75 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
#include "themehandler.hpp"
CThemeHandler::CThemeHandler()
{
}
CThemeHandler::~CThemeHandler()
{
}
void CThemeHandler::ReadDir(const char *dir, CLinkedList *list)
{
file_t d;
dirent_t *de(NULL);
char* tmp;
d=fs_open(dir,O_RDONLY|O_DIR);
while((de=fs_readdir(d)))
{
tmp=new char[strlen(dir)+strlen(de->name)+5];
strcpy(tmp,dir);
strcat(tmp,"/");
strcat(tmp,de->name);
if(de->size==-1)
{
ReadDir(tmp,list);
delete[] tmp;
}
else
{
if(!strcmp(&tmp[strlen(tmp)-6],".theme"))
list->AddItem(tmp);
else
delete[] tmp;
}
};
fs_close(d);
}
CLinkedList* CThemeHandler::LoadThemes(const char *folder)
{
CLinkedList themes;
CLinkedList *ll=NULL;
ReadDir(folder,&themes);
CListItem *listItem=themes.GetFirst();
if(listItem!=NULL)
{
ll=new CLinkedList();
do
{
char *fileName=(char*)listItem->GetData();
ll->AddItem(LoadTheme(fileName));
delete[] fileName;
}while((listItem=listItem->GetNext())!=NULL);
}
return(ll);
}
CThemeInfo* CThemeHandler::LoadTheme(const char *fileName)
{
void *buffer(NULL);
int size(0);
m_InBackground=false;
m_CurrentInfo=new CThemeInfo();
size=fs_load(fileName,&buffer);
if(size!=-1)
{
Init();
m_CurrentInfo->SetPath(fileName);
Execute((char*)buffer,size);
Reset();
}
if(buffer!=NULL)
delete (char*)buffer;
return(m_CurrentInfo);
}
void CThemeHandler::StartElement(const char *name, const char **atts)
{
m_Text[0]='\0';
if(!strcmp(name,"background"))
{
m_InBackground=true;
m_CurrentBackground=new CBackground();
m_CurrentBackground->SetNext(NULL);
}
}
void CThemeHandler::EndElement(const char *name)
{
Trim(m_Text);
if(m_InBackground)
{
if(!strcmp(name,"background"))
{
m_CurrentInfo->AddBackground(m_CurrentBackground);
m_InBackground=false;
}
else if(!strcmp(name,"name"))
{
m_CurrentBackground->SetName(m_Text);
}
else if(!strcmp(name,"description"))
{
m_CurrentBackground->SetDescription(m_Text);
}
else if(!strcmp(name,"path"))
{
char buffer[255];
sprintf(buffer,"%s%s",m_CurrentInfo->GetBasePath(),m_Text);
m_CurrentBackground->SetPath(buffer);
}
else if(!strcmp(name,"start-line"))
{
m_CurrentBackground->SetStartLine(m_Text);
}
else if(!strcmp(name,"url"))
{
m_CurrentBackground->SetURL(m_Text);
}
else if(!strcmp(name,"artist"))
{
m_CurrentBackground->SetArtist(m_Text);
}
}
else
{
if(!strcmp(name,"author"))
m_CurrentInfo->SetAuthor(m_Text);
else if(!strcmp(name,"email"))
m_CurrentInfo->SetEmail(m_Text);
else if(!strcmp(name,"url"))
m_CurrentInfo->SetURL(m_Text);
else if(!strcmp(name,"description"))
m_CurrentInfo->SetDescription(m_Text);
else if(!strcmp(name,"name"))
m_CurrentInfo->SetName(m_Text);
}
}
void CThemeHandler::EndData(const char *data, int len)
{
if((strlen(m_Text)+len)<5000)
strncat(m_Text,data,len);
}
char* CThemeHandler::Trim(char *str)
{
int len=strlen(str);
int st=0;
while((st<len)&&(str[st]<=' '))
st++;
while((st<len)&&(str[len-1]<=' '))
len--;
char *tmp=new char[len-st+1];
strncpy(tmp,&str[st],len-st);
tmp[len-st]='\0';
strcpy(str,tmp);
return(str);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.