language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 1,263 | 2.828125 | 3 |
[] |
no_license
|
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
int main() {
std::vector<char> step;
while (true) {
char c;
scanf(" %c", &c);
if (c == 'P') continue;
if (c == 'K') break;
step.push_back(c);
}
if (step.empty()) {
puts("0");
return 0;
}
step.push_back(step[0]);
int x = 0, y = 0;
std::map<int, std::vector<int>> bound;
for (size_t i = 1; i < step.size(); ++i) {
if (step[i - 1] == 'E' && step[i] != 'S') bound[x].push_back(y);
else if (step[i - 1] == 'W' && step[i] != 'N') bound[x].push_back(y);
else if (step[i - 1] == 'S' && step[i] != 'S' && step[i] != 'W') bound[x].push_back(y);
else if (step[i - 1] == 'N' && step[i] != 'N' && step[i] != 'E') bound[x].push_back(y);
if (step[i - 1] == 'W' && step[i] == 'E') bound[x].push_back(y);
if (step[i - 1] == 'E' && step[i] == 'W') bound[x].push_back(y);
if (step[i] == 'N') ++y;
else if (step[i] == 'S') --y;
else if (step[i] == 'E') ++x;
else --x;
}
int ret = 0;
for (auto &e: bound) {
auto &ys = e.second;
std::sort(ys.begin(), ys.end());
for (size_t i = 1; i < ys.size(); i += 2) {
ret += ys[i] - ys[i - 1] + 1;
}
}
printf("%d\n", ret);
return 0;
}
|
Java
|
UTF-8
| 8,921 | 1.773438 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.kzmen.sczxjf.ui.fragment.kzmessage;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.kzmen.sczxjf.R;
import com.kzmen.sczxjf.bean.kzbean.JiFenShopListItemBean;
import com.kzmen.sczxjf.commonadapter.CommonAdapter;
import com.kzmen.sczxjf.commonadapter.ViewHolder;
import com.kzmen.sczxjf.control.CustomProgressDialog;
import com.kzmen.sczxjf.interfaces.OkhttpUtilResult;
import com.kzmen.sczxjf.net.OkhttpUtilManager;
import com.kzmen.sczxjf.ui.activity.menu.ShopDetailActivity;
import com.kzmen.sczxjf.ui.fragment.basic.ListViewFragment;
import com.kzmen.sczxjf.utils.JsonUtils;
import com.vondear.rxtools.RxLogUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* A simple {@link Fragment} subclass.
*/
public class GoodsCollectionFragment extends ListViewFragment implements Serializable {
@InjectView(R.id.shop_list)
PullToRefreshGridView shopList;
@InjectView(R.id.ll_main)
LinearLayout llMain;
private GridView mGridView;
private View inflate;
ImageView bjNullIv;
TextView biTitle;
LinearLayout bjLl;
private String type = "3";
private int page = 1;
private List<JiFenShopListItemBean> list;
private CommonAdapter<JiFenShopListItemBean> adapter;
private CustomProgressDialog dialog;
/**
* 标志位,标志已经初始化完成
*/
public GoodsCollectionFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_collection_goods, container, false);
ButterKnife.inject(this, view);
initView(view);
mGridView = shopList.getRefreshableView();
list = new ArrayList<>();
//adapter = new Kz_ShopAdapter(getActivity(), list);
adapter = new CommonAdapter<JiFenShopListItemBean>(getActivity(), R.layout.kz_shop_item, list) {
@Override
protected void convert(ViewHolder viewHolder, final JiFenShopListItemBean item, int position) {
viewHolder.setText(R.id.tv_title, item.getTitle())
.setText(R.id.tv_price, item.getScore())
.glideImage(R.id.iv_img, item.getImage());
viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ShopDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("id", item.getId());
intent.putExtras(bundle);
getActivity().startActivity(intent);
}
});
viewHolder.getView(R.id.iv_like).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProgressDialog("加载中");
int state = item.getIscollect();
Map<String, String> params = new HashMap<>();
params.put("type", "3");//收藏类型1课程2问题3商品4回答
params.put("aid", item.getId());//id
params.put("state", "" + (state == 1 ? 0 : 1));//1收藏 其他取消
OkhttpUtilManager.postNoCacah(getActivity(), "User/setCollect", params, new OkhttpUtilResult() {
@Override
public void onSuccess(int type, String data) {
RxLogUtils.e("tst", data);
setADD();
dismissProgressDialog();
}
@Override
public void onErrorWrong(int code, String msg) {
RxLogUtils.e("tst", msg);
dismissProgressDialog();
}
});
}
});
}
};
mGridView.setAdapter(adapter);
isPrepared = true;
lazyLoad();
return view;
}
@Override
public void onPullDownToRefresh(PullToRefreshBase refreshView) {
page = 1;
list.clear();
getData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase refreshView) {
page++;
getData();
}
private void refre() {
shopList.onRefreshComplete();
adapter.notifyDataSetChanged();
}
public void setPullToRefreshListView() {
shopList.getRefreshableView().setAdapter(adapter);
shopList.setMode(PullToRefreshBase.Mode.BOTH);
shopList.getLoadingLayoutProxy().setRefreshingLabel("正在获取数据");
shopList.getLoadingLayoutProxy().setPullLabel("数据更新");
shopList.getLoadingLayoutProxy().setReleaseLabel("释放开始加载");
shopList.setOnRefreshListener(this);
final Handler h = new Handler();
ViewTreeObserver vto = shopList.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
System.out.println("tag" + "开始加载");
shopList.getViewTreeObserver().removeGlobalOnLayoutListener(this);
h.postDelayed(new Runnable() {
@Override
public void run() {
shopList.onRefreshComplete();
shopList.setRefreshing(true);
}
}, 500);
}
});
}
private void initView(final View view) {
Bundle bundle = getArguments();
if (bundle != null) {
type = bundle.getString("type");
} else {
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
@Override
protected void lazyLoad() {
if (!isPrepared || !isVisible) {
return;
}
/* inflate = LayoutInflater.from(getActivity()).inflate(R.layout.listview_null_bj, null);
bjLl = (LinearLayout) inflate.findViewById(R.id.bj_ll);
bjNullIv = (ImageView) inflate.findViewById(R.id.bj_null_iv);
biTitle = (TextView) inflate.findViewById(R.id.bi_title);*/
// setEmpty();
setPullToRefreshListView();
}
/* private void setEmpty() {
setNullListView(bjLl, bjNullIv, R.drawable.no_g_start, biTitle, "暂无数据", 0);
}*/
private void getData() {
Map<String, String> params = new HashMap<>();
params.put("type", type);
params.put("page", "" + page);
params.put("limit", "20");
OkhttpUtilManager.postNoCacah(getActivity(), "User/getCollectList", params, new OkhttpUtilResult() {
@Override
public void onSuccess(int type, String data) {
JSONObject object = null;
try {
object = new JSONObject(data);
List<JiFenShopListItemBean> listdata = JsonUtils.getBeanList(object.optJSONArray("data"), JiFenShopListItemBean.class);
if (listdata != null && listdata.size() > 0) {
page++;
list.addAll(listdata);
} else {
//setEmpty();
shopList.setEmptyView(llMain);
}
refre();
} catch (JSONException e) {
e.printStackTrace();
refre();
shopList.setEmptyView(llMain);
}
adapter.notifyDataSetChanged();
}
@Override
public void onErrorWrong(int code, String msg) {
refre();
shopList.setEmptyView(llMain);
adapter.notifyDataSetChanged();
}
});
}
}
|
Python
|
UTF-8
| 517 | 3.65625 | 4 |
[] |
no_license
|
def solucao(frase):
letras = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
count = 0
for i in letras:
if frase.find(i) != -1:
count += 1
if count == 26:
return "frase completa"
elif count >= 13:
return "frase quase completa"
else:
return "frase mal elaborada"
n = int(input())
for i in range(n):
frase = input()
print(solucao(frase))
|
Markdown
|
UTF-8
| 4,812 | 2.578125 | 3 |
[] |
no_license
|
## About
Currently this framework has been developed to run scripts on Chrome Browser and windows Platform
To run the suite on different browser and platform changes in "wdio.conf.js" file will be required.
### Tech Stack
* [Selenium Service] - This is a node based CLI library for launching Selenium with WebDrivers support.
* [WebdriverIO](https://webdriver.io/) - It is the selenium webdriver api bindings for node.js, It has a very simple api which could be used to automate web & browser apps in a fast and scalable way. NB: from 01.04.2021 webdriver upgraded from v4 to v7. The details about upgrade from v4 to v7 available here: https://mdm.atlassian.net/wiki/spaces/MMS/pages/1556348940/Test+cases+update+from+webdriver+v4+to+v7
* [Javascript](https://developer.mozilla.org/bm/docs/Web/JavaScript) - JavaScript (JS) is a lightweight, interpreted or JIT compiled programming language with first-class functions. Most well-known as the scripting language for Web pages, many non-browser environments also use it, such as node.js and Apache CouchDB.
* [Cucumber](https://cucumber.io/) - The popular BDD test framework which helps us write automated tests.
* [Allure] (http://allure.qatools.ru/) - The Allure Reporter creates Allure test reports which is an HTML generated website with all necessary information to debug your test results and take a look on error screenshots.
### Getting Started
### Pre-requisites
1. NodeJS and npm installed globally in the system. (For webdriver v7 node 12.x should be used)
https://nodejs.org/en/download/
2. JAVA(JDK) installed in the system (Java 8).
3. Set **JAVA_HOME** paths correctly in the system.
4. Chrome browser installed.
5. Text Editor/IDE (Optional) installed-->Sublime/Visual Studio Code/Brackets. [VS code used while developing the scripts]
6. Allure on system to generate and open HTML allure reports from allure-results.
```
Windows/macOS: follow link https://docs.qameta.io/allure/
Linux: https://launchpad.net/~qameta/+archive/ubuntu/allure/+files/allure_2.4.1~xenial_all.deb
Or
dpkg -i allure_2.4.1~xenial_all.deb
sudo apt-get install -f
```
## Installation
### Setup Scripts
* Clone the repository into a folder
* Go inside the folder and run following command from terminal/command prompt
```
npm install
```
* All the dependencies from package.json would be installed in node_modules folder.
### Run Tests
```
npm test
```
* Next step if you wish to generate Allure html report then execute below command -
```
npm run generate-report
```
## Writing Tests
Cucumber framework has been integrated with thi project, WebdriverIO's `wdio-cucumber-framework` adapter helps write BDD style tests with Features & Step Definitions.
```
const {Given, When, Then} = require('cucumber');
const {expect} = require('chai);
const loginPageObj require('../pageobjects/login.page');
Given(/^Open the Login Page and verify title is (.*)$/, (title) => {
loginPageObj.open();
browser.getTitle().should.equal(title);
});
```
## Page Objects
This framework is written using page-object design pattern.
```
class LoginPage extends Page {
get usernameInput() { return $('//*[@id="username-input"]'); }
get passwordInput() { return $('//*[@id="password-input"]'); }
open() {
super.open();
utilObj.waitForElementExists(this.usernameInput);
browser.elementClick('//*[@data-testid="input-search-select-language"]')
browser.elementClick('div=English')
}
}
```
## Finding-Elements
Finding elements in browser's could be tricky sometimes.
* Best way to find elements in web browser is by ***debugging with Chrome DevTools***.
## Reports
Currently this project has been integrated with [Allure-Reports](http://allure.qatools.ru/). WebdriverIO's `wdio-allure-reporter` helps us generate detailed reports of our tests.
Once the test execution is finished you would find the **allure-results** folder generated automatically. Then you would have to run the following command to generate **HTML Report**
```
npm run generate-report
```
## Test Execution on Linux Platform
To execute the suite on linux you have to do below changes in configuration file:
un-comment the below code in wdio.conf.js file
```
services: ['selenium-standalone'],
// capabilities: [{
// maxInstances: 2,
// browserName: 'chrome',
// chromeOptions: {
// args: [ '--disable-gpu', '--no-sandbox', '--window-size=1920,1080'],
// binary: '/usr/bin/google-chrome'
// },
// }],
```
Also change the browser metadata information
```
browserName: 'chrome',
metadata: {
browser: {
name: 'Chrome',
version: '89.0.3440.106'
},
platform: {
name: 'Windows', //change this to 'Linux'
version: '10' //change to Platform version
}
},
```
|
Markdown
|
UTF-8
| 878 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
##### How to import from a URL
Any publicly accessible CSV or JSON file can be uploaded via import. An import allows you to load any size file as opposed to the 1MB limit on uploaded files. The import will run in the background via the Nexosis API and should complete within a minute or two depending on file size. Our API will attempt to determine the file type but is most reliable when the MIME type is correct. Watch out for file sharing URLs as they often point to HTML pages rather than directly to file contents.
You can read more about imports in our <a href="http://docs.nexosis.com/guides/importing-data#importing-by-url" target="_blank">Import documentation</a>.
**JSON files must match the format <a href="https://developers.nexosis.com/docs/services/98847a3fbbe64f73aa959d3cededb3af/operations/datasets-add-data" target="_blank">specified by the Nexosis API</a>**
|
Java
|
UTF-8
| 2,812 | 1.585938 | 2 |
[] |
no_license
|
package com.google.android.exoplayer2.text.p135f;
import android.text.TextUtils;
import com.google.android.exoplayer2.p126c.C2175k;
import com.google.android.exoplayer2.text.C2348d;
import com.google.android.exoplayer2.text.C4693b;
import com.google.android.exoplayer2.text.SubtitleDecoderException;
import com.google.android.exoplayer2.text.p135f.C4049e.C2352a;
import java.util.ArrayList;
import java.util.List;
/* renamed from: com.google.android.exoplayer2.text.f.g */
public final class C4825g extends C4693b {
/* renamed from: a */
private final C2355f f21226a = new C2355f();
/* renamed from: b */
private final C2175k f21227b = new C2175k();
/* renamed from: c */
private final C2352a f21228c = new C2352a();
/* renamed from: d */
private final C2349a f21229d = new C2349a();
/* renamed from: e */
private final List<C2350d> f21230e = new ArrayList();
/* renamed from: a */
protected /* synthetic */ C2348d mo4689a(byte[] bArr, int i, boolean z) {
return m28059b(bArr, i, z);
}
public C4825g() {
super("WebvttDecoder");
}
/* renamed from: b */
protected C4050i m28059b(byte[] bArr, int i, boolean z) {
this.f21227b.m7974a(bArr, i);
this.f21228c.m8636a();
this.f21230e.clear();
C2356h.m8662a(this.f21227b);
while (TextUtils.isEmpty(this.f21227b.m8004y()) == null) {
}
bArr = new ArrayList();
while (true) {
boolean a = C4825g.m28056a(this.f21227b);
if (!a) {
return new C4050i(bArr);
}
if (a) {
C4825g.m28057b(this.f21227b);
} else if (a) {
if (bArr.isEmpty() != 0) {
this.f21227b.m8004y();
i = this.f21229d.m8605a(this.f21227b);
if (i != 0) {
this.f21230e.add(i);
}
} else {
throw new SubtitleDecoderException("A style block was found after the first cue.");
}
} else if (a && this.f21226a.m8660a(this.f21227b, this.f21228c, this.f21230e) != 0) {
bArr.add(this.f21228c.m8640b());
this.f21228c.m8636a();
}
}
}
/* renamed from: a */
private static int m28056a(C2175k c2175k) {
int i = -1;
int i2 = 0;
while (i == -1) {
i2 = c2175k.m7980d();
String y = c2175k.m8004y();
i = y == null ? 0 : "STYLE".equals(y) ? 2 : "NOTE".startsWith(y) ? 1 : 3;
}
c2175k.m7979c(i2);
return i;
}
/* renamed from: b */
private static void m28057b(C2175k c2175k) {
while (!TextUtils.isEmpty(c2175k.m8004y())) {
}
}
}
|
JavaScript
|
UTF-8
| 2,032 | 3.25 | 3 |
[] |
no_license
|
var $ = require("jquery");
$("document").ready(function() {
var va1, va2, va3, vb1, vb2, vb3, vc1, vc2, vc3 = '';
function vales() {
va1 = $(".a1").html();
va2 = $(".a2").html();
va3 = $(".a3").html();
vb1 = $(".b1").html();
vb2 = $(".b2").html();
vb3 = $(".b3").html();
vc1 = $(".c1").html();
vc2 = $(".c2").html();
vc3 = $(".c3").html();
}
function combinationarr() {
var arr = [
[va1, va2, va3],
[vb1, vb2, vb3],
[vc1, vc2, vc3],
[va1, vb1, vc1],
[va2, vb2, vc2],
[va3, vb3, vc3],
[va1, vb2, vc3],
[va3, vb2, vc1]
];
// console.log(arr);
// i in interiorul lui arr
for (var i = 0; i < arr.length; i++) {
// z in interiorul arrayurilor
for (var z = 0; z < arr[i].length; z++) {
// console.log('['+i+']['+z+']=' + arr[i][z]);
console.log('['+i+']=' + arr[i]);
// if (arr[i][z] == "X") {
//
// console.log(arr[i][z]);
//
// $("h2").html(" X wins");
// $("h2").addClass("clX");
// }
}
// --------------------------VARIANTA CARE FUNCTIONEAZA DUPA PRIMUL FOR______________________
// var one = arr[i][0];
// var two = arr[i][1];
// var three = arr[i][2];
// if (one == "X" && three == "X" && two == "X") {
// $("h2").html(" X wins").addClass("clX");
// }
// else if (one == "0" && three == "0" && two == "0") {
// $("h2").html(" 0 wins").addClass("clO");
// }
// else {
// $("h2").html(" it's a tie");
//
// }
}
}
var isx = true;
$("td").click(function() {
// vales();
var cval = $(this).html();
if (!(cval == "X" || cval == "0")) {
if (isx) {
$(this).html("X");
isx = false;
} else {
$(this).html("0");
isx = true;
}
}
vales();
console.log(va1, va2);
combinationarr();
});
$("button").click(function() {
$("td").html(" ");
});
});
|
C++
|
UTF-8
| 2,655 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
#include <algorithm>
#include <numeric>
#include <utility>
#include <vector>
#include <glm/glm.hpp>
#include "kaacore/exceptions.h"
#include "kaacore/geometry.h"
namespace kaacore {
int8_t
compare_points(const glm::dvec2 p, const glm::dvec2 q)
{
if (p.x < q.x) {
return -1;
} else if (p.x > q.x) {
return 1;
} else if (p.y < q.y) {
return -1;
} else if (p.y > q.y) {
return 1;
} else {
return 0;
}
}
int8_t
detect_turn(const glm::dvec2 p, const glm::dvec2 q, const glm::dvec2 r)
{
// equivalent to: ((p-q) x (q-r)).z
double norm_z = (p.x - q.x) * (q.y - r.y) - (p.y - q.y) * (q.x - r.x);
if (norm_z < 0) {
return -1; // CW turn
} else if (norm_z > 0) {
return 1; // CCW turn
} else {
return 0; // no turn
}
}
PolygonType
classify_polygon(const std::vector<glm::dvec2>& points)
{
auto points_count = points.size();
int8_t cur_dir = 0;
int8_t angle_sign = 0;
uint8_t dir_changes = 0;
for (size_t idx = 0; idx < points_count; idx++) {
const glm::dvec2& pt_1 = points[idx % points_count];
const glm::dvec2& pt_2 = points[(idx + 1) % points_count];
const glm::dvec2& pt_3 = points[(idx + 2) % points_count];
auto this_dir = compare_points(pt_2, pt_3);
if (this_dir == -cur_dir) {
dir_changes++;
if (dir_changes > 2) {
return PolygonType::not_convex;
}
}
cur_dir = this_dir;
auto this_sign = detect_turn(pt_1, pt_2, pt_3);
if (this_sign) {
if (this_sign == -angle_sign) {
return PolygonType::not_convex;
}
angle_sign = this_sign;
}
}
if (angle_sign > 0) {
return PolygonType::convex_ccw;
} else if (angle_sign < 0) {
return PolygonType::convex_cw;
} else {
return PolygonType::not_convex;
}
}
glm::dvec2
find_points_center(const std::vector<glm::dvec2>& points)
{
auto sum =
std::accumulate(points.begin(), points.end(), glm::dvec2{0., 0.});
return sum * (1. / points.size());
}
std::pair<glm::dvec2, glm::dvec2>
find_points_minmax(const std::vector<glm::dvec2>& points)
{
KAACORE_CHECK(points.size() > 0);
glm::dvec2 min_pt = points[0];
glm::dvec2 max_pt = points[0];
for (const auto& pt : points) {
min_pt.x = glm::min(min_pt.x, pt.x);
max_pt.x = glm::max(max_pt.x, pt.x);
min_pt.y = glm::min(min_pt.y, pt.y);
max_pt.y = glm::max(max_pt.y, pt.y);
}
return std::make_pair(min_pt, max_pt);
}
} // namespace kaacore
|
Java
|
UTF-8
| 322 | 2.4375 | 2 |
[] |
no_license
|
package designPatterns.singleton;
/**
* @author non
* @version 1.0
* @date 2019/9/18 11:21
*/
public class HungrySingleton {
private static HungrySingleton singleton = new HungrySingleton();
private HungrySingleton(){
}
public static HungrySingleton getInstance(){
return singleton;
}
}
|
C
|
UTF-8
| 196 | 2.984375 | 3 |
[] |
no_license
|
#include<stdio.h>
int main()
{
int i=10;
char ch='a';
float f=23.5f;
void *p;
p=&i;
printf("%d\n",*(int *)p);
p=&ch;
printf("%c\n",*(char *)p);
p=&f;
printf("%f\n",*(float *)p);
return 0;
}
|
Java
|
UTF-8
| 473 | 1.882813 | 2 |
[] |
no_license
|
package com.sftc.web.model.vo.swaggerRequest;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
/**
* Created by xf on 2017/10/18.
*/
@ApiModel(value = "更新通知消息已读请求包装类")
public class UpdateIsReadVO {
@Getter @Setter
@ApiModelProperty(name = "message_id",value = "消息id",example = "141",required = true,dataType = "int")
private int message_id;
}
|
PHP
|
UTF-8
| 2,309 | 3.203125 | 3 |
[] |
no_license
|
<?php
namespace App\Domain\Measurement;
use App\Domain\Cycle\Cycle;
use JsonSerializable;
use DateTime;
class Measurement implements JsonSerializable{
private $id;
private $cycle;
private $temperature;
private $humidity;
private $date;
/**
* Measurement constructor.
* @param $id
* @param $cycle
* @param $temperature
* @param $humidity
* @param $date
*/
public function __construct(?int $id,float $temperature,float $humidity,DateTime $date)
{
$this->id = $id;
$this->temperature = $temperature;
$this->humidity = $humidity;
$this->date = $date;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id): void
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getCycle(): Cycle
{
return $this->cycle;
}
/**
* @param mixed $cycle
*/
public function setCycle(Cycle $cycle): void
{
$cycle->addMeasurement($this);
$this->cycle = $cycle;
}
/**
* @return mixed
*/
public function getTemperature():float
{
return $this->temperature;
}
/**
* @param mixed $temperature
*/
public function setTemperature(float $temperature): void
{
$this->temperature = $temperature;
}
/**
* @return mixed
*/
public function getHumidity():float
{
return $this->humidity;
}
/**
* @param mixed $humidity
*/
public function setHumidity(float $humidity): void
{
$this->humidity = $humidity;
}
/**
* @return mixed
*/
public function getDate():DateTime
{
return $this->date;
}
/**
* @param mixed $date
*/
public function setDate(DateTime $date): void
{
$this->date = $date;
}
/**
* @inheritDoc
*/
public function jsonSerialize()
{
return [
'id'=>$this->getId(),
'humidity'=>$this->getHumidity(),
'temperature'=>$this->getTemperature(),
'date'=>$this->getDate(),
'cycle'=>$this->getCycle()
];
}
}
|
Markdown
|
UTF-8
| 3,602 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
title:如何编写高扩展且可维护的 JavaScript
disc:如何编写高扩展且可维护的 JavaScript :模块
type:JavaScript
------------------
##通常的 JavaScript 模块
使用原生 JavaScript 实现模块是相对容易的,但是已经存在很多的模式随便你使用。每种模式可以说是各有利弊。这里会包含这些模式中的几个,但没有顾及那个最适合你的选择。多数时候,会取决于你的偏好以及哪个在你指定的场景下工作的最好。对于哪个模块实现是最好的,网上没有什么明确的意见。所以,如果不确定可以随便去搜索一下。
##我们现在开始。
JavaScript 模块可以像 JavaScript 对象一样的简单,对象的原型就是功能上独立的单元,也就是函数。请注意没有闭包,这个模块实例可能会污染全局命名空间。
##实例:POJO 模块模式
var myModule = {
propertyEx: "This is a property on myModule",
functionEx: function(){
//在这里插入代码
}
};
为了创建闭包,并且确保所有的变量和函数都是这个模块局部的,通常业内会用一个 IIFE(立即执行的函数表达式)包裹这个模块,这与前面提到的对象方法很类似。
##实例:Scoped 模块模式
var myModule = (function () {
var module;
module.varProperty = "This is a property on myModule";
module.funcProperty = function(){
//在这里插入代码
};
return module;
})();
另一种模式是模块模式,连同所谓的暴露模块模式。暴露模块模式只是模块模式的一个特例,实现了一种形式的私有成员,这样仅仅暴漏了一个公共接口。下面是暴露模块模式的的一个实例。
##实例:暴露模块模式
var myRevealingModule = (function () {
var privateVar = "Alex Castrounis",
publicVar = "Hi!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
function publicSetName( strName ) {
privateVar = strName;
}
function publicGetName() {
privateFunction();
}
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
})();
我要说的最后一个普遍的 JavaScript 模式是原型模式。和前面描述的模块模式类似,但是使用了 JavaScript 原型。下面是一个带有私有成员基于原型模式的模块的一个实例。
##实例:原型模式
var myPrototypeModule = (function (){
var privateVar = "Alex Castrounis",
count = 0;
function PrototypeModule(name){
this.name = name;
}
function privateFunction() {
console.log( "Name:" + privateVar );
count++;
}
PrototypeModule.prototype.setName = function(strName){
this.name = strName;
};
PrototypeModule.prototype.getName = function(){
privateFunction();
};
return PrototypeModule;
})();
我们详细讲述了多种原生 JavaScript 的模块实现方式,也主要探索了三个主要的模块格式和规范。当然也包括了即将到来的原生 ECMAScript 模块规范,但只是一个雏形,我强烈建议去选择自己最有感觉的模块模式或者规范。一旦决定了一个模块规范,并且确保在你的项目中的统一性。统一是可维护性的一个关键要素。
转自知乎日报,有删减[http://zhuanlan.zhihu.com/FrontendMagazine/19884662](http://zhuanlan.zhihu.com/FrontendMagazine/19884662)
|
C#
|
UTF-8
| 1,959 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
using SEDC.Exercise.TryBeingFit.Domain;
using SEDC.Exercise.TryBeingFit.Domain.Core.Enums;
using SEDC.Exercise.TryBeingFit.Services.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SEDC.Exercise.TryBeingFit.Services.Services
{
public class UIService
{
public int LogInMenu()
{
List<string> menuItems = new List<string>() { "LogIn", "Register" };
return ChooseMenu(menuItems);
}
public int RoleMenu()
{
List<string> menuItems = Enum.GetNames(typeof(UserRole)).ToList();
return ChooseMenu(menuItems);
}
public int ChooseMenu<T>(List<T> items)
{
while(true)
{
Console.WriteLine("Enter a number to choose one of the following: ");
for (int i = 0; i < items.Count; i++)
{
Console.WriteLine($"({i + 1}) {items[i]}");
}
int choice = ValidationHelper.ValidateNumber(Console.ReadLine(), items.Count);
if(choice == -1)
{
// ("Input incorect. Please try again", color)
// continue;
}
return choice;
}
}
public void Welcome(User user)
{
Console.WriteLine($"Welcome to the fitness application user: {user.Username}");
switch (user.Role)
{
case UserRole.Standard:
Console.WriteLine($"If you enjoy the application, consider our Premium subscription..");
break;
case UserRole.Premium:
Console.WriteLine($"");
break;
case UserRole.Trainer:
Console.WriteLine($"");
break;
}
}
}
}
|
Java
|
UTF-8
| 2,020 | 2.671875 | 3 |
[] |
no_license
|
package com.twparser.processing;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.util.List;
/**
* handles
*/
public class URLManager {
private static String url = "https://www.reddit.com/r/funny/";
private static String startUrl = "https://www.reddit.com";
private static String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36 OPR/53.0.2907.68";
public static void main(String[] args) throws Exception {
CookieHandler.setDefault(new CookieManager());
URL obj = new URL(startUrl);
HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setRequestProperty("user-agent", USER_AGENT);
connection.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
// Then use the same cookies on all subsequent requests.
//connection = (HttpsURLConnection) new URL(url).openConnection();
BufferedReader in =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
System.out.println(response);
}
}
|
Java
|
UTF-8
| 4,442 | 2.140625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.google.inject.spi;
import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.Module;
import junit.framework.TestCase;
/** Tests for {@link ModuleSource}. */
public class ModuleSourceTest extends TestCase {
private static final StackTraceElement BINDER_INSTALL =
new StackTraceElement(
"com.google.inject.spi.Elements$RecordingBinder",
"install",
"Unknown Source",
235 /* line number*/);
public void testOneModule() {
ModuleSource moduleSource = createWithSizeOne();
checkSizeOne(moduleSource);
}
public void testTwoModules() {
ModuleSource moduleSource = createWithSizeTwo();
checkSizeTwo(moduleSource);
moduleSource = moduleSource.getParent();
checkSizeOne(moduleSource);
}
public void testThreeModules() {
ModuleSource moduleSource = createWithSizeThree();
checkSizeThree(moduleSource);
moduleSource = moduleSource.getParent();
checkSizeTwo(moduleSource);
moduleSource = moduleSource.getParent();
checkSizeOne(moduleSource);
}
private void checkSizeOne(ModuleSource moduleSource) {
assertEquals(1, moduleSource.size());
assertEquals(1, moduleSource.getStackTraceSize());
// Check call stack
StackTraceElement[] callStack = moduleSource.getStackTrace();
assertEquals(BINDER_INSTALL, callStack[0]);
}
private void checkSizeTwo(ModuleSource moduleSource) {
assertEquals(2, moduleSource.size());
assertEquals(3, moduleSource.getStackTraceSize());
// Check call stack
StackTraceElement[] callStack = moduleSource.getStackTrace();
assertEquals(BINDER_INSTALL, callStack[0]);
assertEquals(
new StackTraceElement(
"com.google.inject.spi.moduleSourceTest$A", "configure", "Unknown Source", 100),
callStack[1]);
assertEquals(BINDER_INSTALL, callStack[2]);
}
private void checkSizeThree(ModuleSource moduleSource) {
assertEquals(3, moduleSource.size());
assertEquals(7, moduleSource.getStackTraceSize());
// Check call stack
StackTraceElement[] callStack = moduleSource.getStackTrace();
assertEquals(BINDER_INSTALL, callStack[0]);
assertEquals(new StackTraceElement("class1", "method1", "Unknown Source", 1), callStack[1]);
assertEquals(new StackTraceElement("class2", "method2", "Unknown Source", 2), callStack[2]);
assertEquals(
new StackTraceElement(
"com.google.inject.spi.moduleSourceTest$B", "configure", "Unknown Source", 200),
callStack[3]);
assertEquals(BINDER_INSTALL, callStack[4]);
assertEquals(
new StackTraceElement(
"com.google.inject.spi.moduleSourceTest$A", "configure", "Unknown Source", 100),
callStack[5]);
assertEquals(BINDER_INSTALL, callStack[6]);
}
private ModuleSource createWithSizeOne() {
StackTraceElement[] partialCallStack = new StackTraceElement[1];
partialCallStack[0] = BINDER_INSTALL;
return new ModuleSource(A.class, partialCallStack, /* permitMap = */ null);
}
private ModuleSource createWithSizeTwo() {
ModuleSource moduleSource = createWithSizeOne();
StackTraceElement[] partialCallStack = new StackTraceElement[2];
partialCallStack[0] = BINDER_INSTALL;
partialCallStack[1] =
new StackTraceElement(
"com.google.inject.spi.moduleSourceTest$A", "configure", "moduleSourceTest.java", 100);
return moduleSource.createChild(B.class, partialCallStack);
}
private ModuleSource createWithSizeThree() {
ModuleSource moduleSource = createWithSizeTwo();
StackTraceElement[] partialCallStack = new StackTraceElement[4];
partialCallStack[0] = BINDER_INSTALL;
partialCallStack[1] = new StackTraceElement("class1", "method1", "Class1.java", 1);
partialCallStack[2] = new StackTraceElement("class2", "method2", "Class2.java", 2);
partialCallStack[3] =
new StackTraceElement(
"com.google.inject.spi.moduleSourceTest$B", "configure", "moduleSourceTest.java", 200);
return moduleSource.createChild(C.class, partialCallStack);
}
private static class A extends AbstractModule {
@Override
public void configure() {
install(new B());
}
}
private static class B implements Module {
@Override
public void configure(Binder binder) {
binder.install(new C());
}
}
private static class C extends AbstractModule {
}
}
|
Markdown
|
UTF-8
| 671 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
# How can I store and review all my ideas of new business ideas?
An interesting approach for developing new or documenting existing business models on a single page is the Business Model Canvas - Wikipedia, which was developed by Alexander Osterwalder.
You can download a PDF template for it:
https://canvanizer.com/downloads...
Ash Maurya modified it for Lean Startups: 1-Page Business Plan | LEANSTACK
You can get a free PDF for it too:
https://static1.squarespace.com/...
You can fill out these PDF templates and upload them e.g. to Google Docs.
There are as well different options to maintain (upload and download) your canvas online. You can easily find them with a web search.
|
C#
|
UTF-8
| 1,007 | 2.546875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AdviesOpMaatASP.NET.Classes
{
public class Gebruiker
{
public string Gebruikersnaam { get; set; }
public string Wachtwoord { get; set; }
public string Rol { get; set; }
public Gebruiker()
{
}
public Gebruiker(string gebruikersnaam, string wachtwoord)
{
this.Gebruikersnaam = gebruikersnaam;
this.Wachtwoord = wachtwoord;
}
public Gebruiker(string gebruikersnaam, int rol)
{
Gebruikersnaam = gebruikersnaam;
switch (rol)
{
case 1:
Rol = "Admin";
break;
case 2:
Rol = "Medewerker";
break;
default:
Rol = "NotSet";
break;
}
}
}
}
|
Java
|
UTF-8
| 1,375 | 2.265625 | 2 |
[
"MIT"
] |
permissive
|
package net.foreworld.util.verifycode;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.foreworld.util.RandomUtil;
/**
*
* @author huangxin <3203317@qq.com>
*
*/
public class VerifyCodeImage extends HttpServlet implements Servlet {
private static final long serialVersionUID = -7552720670363550231L;
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setHeader("Pragma", "No-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
resp.setContentType("image/jpeg");
// 生成随机字串
String verifyCode = RandomUtil.genRandomCode(4);
// 存入会话session
HttpSession session = getSession(req);
session.setAttribute(VerifyCodeInterceptor.TOKEN,
verifyCode.toLowerCase());
// 生成图片
int w = 200, h = 80;
VerifyCodeUtil.outputImage(w, h, resp.getOutputStream(), verifyCode);
}
/**
*
* @param req
* @return
*/
private HttpSession getSession(HttpServletRequest req) {
HttpSession session = req.getSession(false);
if (null == session)
session = req.getSession(true);
return session;
}
}
|
C
|
GB18030
| 8,698 | 2.75 | 3 |
[] |
no_license
|
//ܣ༭ؼĩβı
//1༭
//2ַָ
//3ӺǷ
BOOL AddTextToEdit(HWND hEdit,char *szTxt,BOOL bNextLine)
{
static char NextLine[]={13,10,0};
SendMessage(hEdit,EM_SETSEL,-2,-1);
SendMessage(hEdit,EM_REPLACESEL,0,(long)szTxt);
if(bNextLine)
SendMessage(hEdit,EM_REPLACESEL,0,(long)NextLine);
return 1;
}
//ܣִCMDܵţִһԵ̣
//1ַָ
//2ָһŻԵ
//ֵԵֽ
int CmdShell(char *command,char *pOutBuf)
{
char szBuf[5*1024];
char str[256];
STARTUPINFO si;
SECURITY_ATTRIBUTES sa;
PROCESS_INFORMATION pi;
HANDLE hRead,hWrite;
DWORD dwRead,Count=0;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
//ܵcmd
if(!CreatePipe(&hRead,&hWrite,&sa,0))
MessageBox(NULL,"ܵʧ","Message",MB_OK);
//ϵͳĿ¼
GetSystemDirectory(szBuf,256);
lstrcat(szBuf,"\\cmd.exe /c ");
lstrcat(szBuf,command);
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
CreateProcess(NULL,szBuf,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi);
//һһҪڶ֮ܵǰڶ֮ǰreadfile᷵
//TMDbug˷һʱ|||
CloseHandle(hWrite);
//ѭӹܵķϢ
szBuf[0]=0;
szBuf[1]=0;
if (!pOutBuf)//pOutBufΪNULLָд
return 0;
while(1)
{
//ReadFile(hRead,rBuffer,1024,&dwRead,NULL)
ReadFile(hRead,str,255,&dwRead,NULL);
if(dwRead)
{
Count+=dwRead;
str[dwRead]=0;
str[dwRead+1]=0; //ַܵ0Լ
lstrcat(szBuf,str);
continue;
}
else
break;
}
lstrcpy(pOutBuf,szBuf);
pOutBuf[Count+1]=0;
pOutBuf[Count+2]=0;
CloseHandle(hRead);
return lstrlen(szBuf);
}
//ֱܵӺSocket
//1IPַַ
//2˿ں
//3ָ̾룬ﷵcmd̵ľ
//ֵ
SOCKET CmdShellS(char *szIPAdrees,int Port,HANDLE *hProcess)
{
char szBuf[5*1024];
STARTUPINFO si;
PROCESS_INFORMATION pi;
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2),&wsaData))
MessageBox(NULL,"ʼʧ","Message",MB_OK);
SOCKET sClient = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,NULL,0,0);
if(sClient == INVALID_SOCKET)
{
MessageBox(NULL,"ֽʧ","Message",MB_OK);
}
// sockaddr_inṹװ˵ַϢ
sockaddr_in servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(Port);
servAddr.sin_addr.S_un.S_addr =inet_addr(szIPAdrees);//ip
//ӷ
connect(sClient,(sockaddr*)&servAddr,sizeof(servAddr));
//ϵͳĿ¼
GetSystemDirectory(szBuf,256);
lstrcat(szBuf,"\\cmd.exe");
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError=(void *)sClient;
si.hStdInput=(void *)sClient;
si.hStdOutput =(void *)sClient;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
CreateProcess(NULL,szBuf,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi);
(*hProcess)=pi.hProcess;
return sClient;
}
//ܣļչļ ַ
//1Դļ
//2ļչĻָ
void GetFileTypeSz(char *pszFile,char *pszExp)
{
char *p;
p=pszFile;
while((*p)!='.')
{
p++;
if(*p==0)
return;
}
p++;
lstrcpy(pszExp,p);
GetFileTypeSz(p,pszExp);//ݹãҳһչ
}
//ΪбͼؼһĿ/Ŀ
//1бͼؼ
//2ӵĿţУ
//3ӵĿţУ
//4Ŀı
BOOL AddListVeiwItem(HWND hList,int ItemIndex,int SubItemIndex,char *pszText)
{
char str[MAX_PATH]={0};
LVITEM lvi;
ZeroMemory(&lvi,sizeof(lvi));
lvi.mask=LVIF_TEXT;
lvi.iItem=ItemIndex;
lvi.cchTextMax=MAX_PATH;
lvi.pszText=pszText;
lvi.iSubItem=SubItemIndex;
return SendMessage(hList,LVM_INSERTITEM,0,(long)&lvi);
}
//༭бͼؼһĿ/Ŀ
//ͬAddListVeiwItem
BOOL SetListVeiwItem(HWND hList,int ItemIndex,int SubItemIndex,char *pszText)
{
char str[MAX_PATH]={0};
LVITEM lvi;
ZeroMemory(&lvi,sizeof(lvi));
lvi.mask=LVIF_TEXT;
lvi.iItem=ItemIndex;
lvi.cchTextMax=MAX_PATH;
lvi.pszText=pszText;
lvi.iSubItem=SubItemIndex;
return SendMessage(hList,LVM_SETITEM,0,(long)&lvi);
}
//ͼؼһĿĿ
void AddChildItem(HWND hTree,HTREEITEM hParent,char *pszText)
{
TVINSERTSTRUCT ti;
ZeroMemory(&ti,sizeof(ti));
ti.item.mask=TVIF_TEXT|TVIF_HANDLE;
ti.hParent=hParent;
ti.hInsertAfter =TVI_LAST;
ti.item.pszText=pszText;
SendMessage(hTree,TVM_INSERTITEM,0,(long)&ti);
}
//õͼؼһĿı
int GetTreeItemText(HWND hTree,HTREEITEM hItem,char *pszText)
{
TVITEMEX tvi;
tvi.mask=TVIF_TEXT|TVIF_HANDLE;
tvi.hItem=hItem;
tvi.pszText=pszText;
tvi.cchTextMax=MAX_PATH;
int b;
b=TreeView_GetItem(hTree,&tvi);
//SendMessage(hTree,TVM_GETITEM,0,(long)&tvi);
return lstrlen(pszText);
}
//ͼؼijһĿĿ
void CleanTreeItem(HWND hTree,HTREEITEM hPItem)
{
HTREEITEM hItem;
a: hItem=(HTREEITEM)SendMessage(hTree,TVM_GETNEXTITEM,TVGN_CHILD,(long)hPItem);
if(hItem)
{
SendMessage(hTree,TVM_DELETEITEM,0,(long)hItem);
goto a;
}
}
//бͼؼĿ
void CleanListItem(HWND hList)
{
SendMessage(hList,LVM_DELETEALLITEMS,0,0);
}
//бͼؼĸĿıá/ӳ·ʽ
int GetWholePath(HWND hTree,HTREEITEM hCurSel,char *pszPath)
{
int nPathLen=0;
char szBuf[MAX_PATH]={0};
HTREEITEM hParent;
//ĿļĿı
nPathLen+=GetTreeItemText(hTree,hCurSel,szBuf);
lstrcat(szBuf,"\\");
lstrcat(szBuf,pszPath);
lstrcpy(pszPath,szBuf);
hParent=(HTREEITEM)SendMessage(hTree,TVM_GETNEXTITEM,TVGN_PARENT,(long)hCurSel);
if(hParent)
{
//ݹ
nPathLen+=GetWholePath(hTree,hParent,pszPath);
}
return nPathLen+1;
}
//"ļ"Ի
//1
//2ļִ
//3ļȫ·
BOOL OpenFileDlg(HWND hWnd,char *szFilter,char *pszFile)
{
OPENFILENAME of;
ZeroMemory(&of,sizeof(of));
ZeroMemory(pszFile,MAX_PATH);
of.lStructSize=sizeof(of);
of.hwndOwner=hWnd;
of.lpstrFilter=szFilter;
of.lpstrFile=pszFile;
of.nMaxFile=MAX_PATH;
of.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST;
return GetOpenFileName(&of);
}
//ط
//1
//2ִļλ
//3ͬʱǷ
bool InstallService(char *szDriver,char *szFile,bool bStart)
{
SC_HANDLE sh=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if(!sh)return false;
SC_HANDLE rh=CreateService(sh,szDriver,szDriver,SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
szFile,NULL,NULL,NULL,
NULL,NULL);
if(!rh)
{
if(GetLastError()==ERROR_SERVICE_EXISTS)
{
//Ѱװ
rh=OpenService(sh,szDriver,SERVICE_ALL_ACCESS);
if(!rh)
{
CloseServiceHandle(sh);
return false;
}
}
else
{
CloseServiceHandle(sh);
return false;
}
}
if(bStart) //ǷҪ
StartService(rh,0,NULL);
CloseServiceHandle(sh);
CloseServiceHandle(rh);
return true;
}
//жط
//
bool UnInstall(char *szService)
{
SC_HANDLE sh=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if(!sh)return false;
SC_HANDLE rh=OpenService(sh,szService,SERVICE_ALL_ACCESS);
if(DeleteService(rh))return true;
return false;
}
|
Swift
|
UTF-8
| 1,075 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
//
// MedicineTimings.swift
// MedTracker
//
// Created by Shakti Prakash Srichandan on 23/06/21.
//
import Foundation
import UIKit
enum MedicineTimings: String, CaseIterable {
case morning = "Morning"
case afternoon = "AfterNoon"
case night = "Night"
func getReminderMessageAndTime() -> (String , Int) {
switch self {
case .morning :
return ("morning_reminder".localized , MedicineDoses.morningTime)
case .afternoon:
return ("afternoon_reminder".localized , MedicineDoses.afternoonTime)
case .night:
return ("night_reminder".localized , MedicineDoses.nightTime)
}
}
}
enum MedicineDoses {
static let morningTime: Int = 11
static let morningStartTime: Int = 8
static let morningEndTime: Int = 12
static let afternoonTime: Int = 14
static let afternoonEndTime: Int = 19
static let nightTime: Int = 20
static let nightEndTime: Int = 22
}
enum MedicineScore {
static let morningafternoonScore: Int = 30
static let nightScore: Int = 40
}
|
C++
|
UTF-8
| 1,469 | 3.140625 | 3 |
[] |
no_license
|
////////////////////////////////////////////////////////////////////////////////
// Filename: inputclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "inputclass.h"
InputClass::InputClass()
{
}
InputClass::InputClass(const InputClass& other)
{
}
InputClass::~InputClass()
{
}
void InputClass::Initialize()
{
int i;
// Initialize all the keys to being released and not pressed.
for(i=0; i<256; i++)
{
m_keys[i] = false;
}
m_lmbStatus = false;
m_mouseX = 0;
m_mouseY = 0;
m_mouseXClicked = 0;
m_mouseYClicked = 0;
m_mouseXReleased = 0;
m_mouseYReleased = 0;
return;
}
void InputClass::KeyDown(unsigned int input)
{
// If a key is pressed then save that state in the key array.
m_keys[input] = true;
return;
}
void InputClass::KeyUp(unsigned int input)
{
// If a key is released then clear that state in the key array.
m_keys[input] = false;
return;
}
void InputClass::LMBClicked(int mouseX, int mouseY)
{
m_lmbStatus = true;
m_mouseXClicked = mouseX;
m_mouseYClicked = mouseY;
}
void InputClass::LMBReleased(int mouseX, int mouseY)
{
m_lmbStatus = false;
m_mouseXReleased = mouseX;
m_mouseYReleased = mouseY;
}
void InputClass::UpdateMouseX(int mouseX)
{
m_mouseX = mouseX;
}
void InputClass::UpdateMouseY(int mouseY)
{
m_mouseY = mouseY;
}
bool InputClass::IsKeyDown(unsigned int key)
{
// Return what state the key is in (pressed/not pressed).
return m_keys[key];
}
|
Java
|
UTF-8
| 534 | 2.546875 | 3 |
[] |
no_license
|
package escudos;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Escudo_Madera extends Escudo{
public static final String TIPOBBDD = "Escudo de madera";
public Escudo_Madera() {
}
@Override
public String nombre() {
return "Escudo de madera";
}
@Override
public int bonusDef() {
return 2;
}
@Override
public Icon icon() {
return new ImageIcon(Escudo_Madera.class.getResource("/imagenes/equipo/escudo madera.png"));
}
@Override
public String getTipoEscudoBBDD() {
return TIPOBBDD;
}
}
|
C#
|
UTF-8
| 692 | 2.546875 | 3 |
[] |
no_license
|
using System;
using JetBrains.Annotations;
namespace Gamefication.PeriodicTasks
{
public static class PeriodicTaskRunnerExtensions
{
public static void Register([NotNull] this IPeriodicTaskRunner periodicTaskRunner, [NotNull] string taskId,
TimeSpan period, [NotNull] Action taskAction)
{
periodicTaskRunner.Register(new ActionPeriodicTask(taskId, taskAction), period);
}
public static void Unregister([NotNull] this IPeriodicTaskRunner periodicTaskRunner, [NotNull] string taskId,
TimeSpan timeout)
{
periodicTaskRunner.Unregister(taskId, (int) timeout.TotalMilliseconds);
}
}
}
|
JavaScript
|
UTF-8
| 2,259 | 3.703125 | 4 |
[] |
no_license
|
let x=10;
const y=20;
console.log(x);
x="Hello world";
console.log(x);
x=[1,2,3,4,5,6,7];
console.log(x);
console.log(x.length);
console.log(x[2]);
console.log("This i sa string");
console.log('A');
console.table(x)
console.error("error message");
console.debug("Debug Message")
console.time("myForLoop");
for(let i=0;i<100000;i++){
}
console.timeEnd("myForLoop");
function display(){
console.log("Hello, welcome to JS. The best programing language")
}
display();
function add(a,b){
return a+b;
}
console.log(add(2,4));
function multiply(a,b){
return a*b;
}
console.log(multiply(2,4));
function subtract(a,b){
return a-b;
}
console.log(subtract(2,4));
let addition = (a,b)=> a+b;
console.log("The Sum= "+add(12,44))
function netSal(sal,demoFunction) {
console.log("Your salary is "+ demoFunction(sal));
}
sal=10000;
if (sal <= 10000)
netSal(sal,sal => sal*0.9);
else
netSal(sal, sal => sal*0.85);
function compare(a){
if (a>=18)
return true;
else
return false;
}
/*
let ages=[22,13,14,19,30,50,33,22];
let qualified=[];
for (let i=0;i<ages.length;i++){
if(ages[i]>=18){
qualified.push(ages[i]);
}
}*/
ages=[66,99,22,13,14,19,[4,5,6],[30,50,33],22];
console.log(ages);
console.log(ages.flat(Infinity));
ages1=[66,99,22,13,14];
ages2=[19,4,5,6,30,50,33,22];
let combiend=[...ages,...ages2];
console.log(combiend);
/*let qualified2= ages.filter(value => value>=18);*/
/*console.table(qualified2)*/
for (let age of ages){
console.log(age);
}
ages.forEach(x=>console.log(x));
let total= ages.reduce((accumlator,current)=>accumlator+current);
console.log("Total sum: "+total);
let oldest= ages.reduce((accumlator,current)=>accumlator>current ? accumlator : current);
console.log("The oldest: "+oldest);
let dataPoints = [2,4,18,28,9,5,6,7,8,9];
let avg = dataPoints.reduce((accumalator,current)=>accumalator+current) / dataPoints.length;
let sorted = dataPoints.sort((a,b)=>a-b);
console.log(sorted);
let matrix = [ [2, 3], [34, 89], [55, 101, 34], [34, 89, 34, 99]];
console.log("Original array");
console.log(matrix);
console.log("Flattened array: ");
console.log(matrix.flat(Infinity));
console.log("Max value: ");
console.log(matrix.reduce((a,b)=>a>b?a:b));
|
Ruby
|
UTF-8
| 952 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
# Caption class that contains all the variables needed to render a caption
class Caption
def initialize(label, figure)
if figure.key?("custom")
@label = label
@custom = figure["custom"]
@img = figure["img"]
else
@label = label
@artist = figure["artist"]
@title = figure["title"]
@date = figure["date"]
@medium = figure["medium"]
@dimensions = figure["dimensions"]
@collection = figure["collection"]
@location = figure["location"]
@source = figure["source"]
@img = figure["img"]
end
end
# Render a caption in a mix of Markdown and LaTeX for processing by Pandoc
def render
if @custom.nil?
return ""
else
return ""
end
end
end
|
JavaScript
|
UTF-8
| 1,025 | 2.96875 | 3 |
[] |
no_license
|
let elems = document.querySelectorAll('input, textarea');
window.onload = () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js', { scope: './' })
.then((reg) => {
reg.update().catch(err => console.warn(err));
}).catch((error) => {
console.warn('Registration failed with ' + error);
});
}
let hover = document.getElementById('hover-change');
hover.addEventListener('mouseover', () => {
hover.innerText = "site";
});
hover.addEventListener('mouseout', () => {
hover.innerText = "produto";
});
elems.forEach(checkEmpty)
};
function checkEmpty(elem) {
if (elem.value) {
if (elem.value.length > 0) {
if (!elem.classList.contains('not-empty-input'))
elem.classList.add('not-empty-input');
return
}
}
if (elem.classList.contains('not-empty-input'))
elem.classList.remove('not-empty-input');
}
elems.forEach((elem) => {
elem.addEventListener('keyup', (ev) => checkEmpty(ev.target))
});
|
Python
|
UTF-8
| 872 | 3 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
import numpy as np
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
def real_func(x):
return np.sin(2 * np.pi * x)
def fit_func(p, x):
f = np.poly1d(p)
return f(x)
def residuals_func(p, x, y):
ret = fit_func(p, x) - y
return ret
x_points = np.linspace(0, 1, 1000)
x = np.linspace(0, 1, 10)
y = [real_func(_x) + np.random.normal(0, 0.1) for _x in x]
def fitting(M=0):
plt.clf()
p_init = np.random.rand(M + 1)
p_lsq = leastsq(residuals_func, p_init, args=(x, y))
plt.plot(x_points, real_func(x_points), label='real')
plt.plot(x_points, fit_func(p_lsq[0], x_points), label='fitted curve')
plt.plot(x, y, 'bo', label='noise')
plt.legend()
plt.savefig('1_%d.png' % M)
return p_lsq
p_lsq_0 = fitting(M=0)
p_lsq_1 = fitting(M=1)
p_lsq_3 = fitting(M=3)
p_lsq_9 = fitting(M=9)
|
Python
|
UTF-8
| 578 | 2.984375 | 3 |
[] |
no_license
|
#
# @lc app=leetcode.cn id=322 lang=python3
#
# [322] 零钱兑换
#
# @lc code=start
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# 记录表中amount+1等价于无穷大
table = [(amount + 1) for _ in range(amount + 1)]
table[0] = 0
for i in range(1, amount + 1):
for coin in coins:
if i - coin < 0:
continue
table[i] = min(table[i], 1 + table[i - coin])
return -1 if table[amount] == (amount + 1) else table[amount]
# @lc code=end
|
Markdown
|
UTF-8
| 5,061 | 3.890625 | 4 |
[
"MIT"
] |
permissive
|
# JavaScript 展開與其餘

這兩個分別稱為 展開運算子(`spread operator`) 及 其餘運算子 (`rest operator`,也可稱為其餘參數),這兩個運算符有個兩個特點,就是都與陣列有關係,除此之外他都是 `...`;第一次看到這樣的符號出現在 JavaScript 中,我還認為這是哪個預處理器的語法,不過在此他真的是 ES6 語法,以下內容一樣可以貼到 Chrome 運行。
> 預處理器:像是 CSS 的 Sass,在編譯前無法直接被讀取,需要透過編譯為 `.css` 或 `.js` 才能被瀏覽器使用,常見的 JavaScript 預處理器有 `CoffeeScript`、`TypeScript`。
## 展開
展開非常的好用,我們先來看一個簡單的範例,這裡有兩組的陣列,我們想把他合併到同一個變數上,那麼我們可以直接用以下方法接起來。
```js
let groupA = ['小明', '杰倫', '阿姨'];
let groupB = ['老媽', '老爸'];
const groupAll = [...groupA, ...groupB];
// ['小明', '杰倫', '阿姨', '老媽', '老爸'];
```
誒...,看到這裡是不是有似懂非懂的感覺,看似那麼容易卻不太容易理解,`...` 到底做了什麼事情!? 它其實一次又一次的 return 陣列中的值。
```js
console.log(...groupA);
// 小明
// 杰倫
// 阿姨
```
順帶一提,以上的概念如果用傳統的寫法會像是這樣。
```js
let groupA = ['小明', '杰倫', '阿姨'];
let groupB = ['老媽', '老爸'];
const groupAll = groupA.concat(groupB);
// ['小明', '杰倫', '阿姨', '老媽', '老爸'];
```
### 淺層複製
另外陣列與物件相同都有著傳參考的特性,所以當把陣列賦予到另一個值上時,修改其中一個另一個也會跟著變動。
```js
// 由於傳參考的關係,所以將一個陣列傳到另一個上時
// 兩個的值其實是一樣的
let groupA = ['小明', '杰倫', '阿姨'];
let groupB = groupA;
groupB.push('阿明');
console.log(groupA); // ['小明', '杰倫', '阿姨', '阿明'];
```
由於 展開運算子 它是一個一個將值寫入,所以他也有淺層的複製(`shallow copy`) 。
```js
// 這個屬於淺拷貝,所以不會影響到另一個物件
let groupA = ['小明', '杰倫', '阿姨'];
let groupB = [...groupA];
groupB.push('阿明');
console.log(groupA); // ['小明', '杰倫', '阿姨'];
```
### 類陣列轉成純陣列
JavaScript 中有許多類陣列,這類陣列有著陣列的外皮,但卻不能使用陣列的方法,相信先前有參考過原型章節的文章有發現這點,這類陣列由於原型不同,所以 "不能" 使用許多的陣列方法,如: `map()`, `concat()` 等等。
其中一種很常見的就是 DOM 陣列,這也可以透過展開運算子轉為純陣列。
```js
// 可以將類陣列轉成陣列
let doms = document.querySelectorAll('p');
console.log(doms);
let spreadDom = [...doms];
console.log(spreadDom);
```
在先前小明儲值的故事中,悠遊卡的儲值是使用 `for...in`,原因也在於他不是真正的陣列,不過當他如果轉成真正的陣列後,就多了很多方法可以用了 (嘿嘿嘿)。
```js
// 同樣道理,arguments 不是真正的陣列,也可以透過 ... 來轉成純陣列
var originCash = 1000;
function updateEasyCard() {
let arg = [...arguments]
let sum = arg.reduce(function (accumulator, currentValue) {
// 分別為前一個回傳值, 當前值
return accumulator + currentValue; // 與前一個值相加
}, 0);
// 如果使用 arguments 則會出現 `arguments.reduce is not a function`
console.log('我有 ' + sum + ' 元');
}
updateEasyCard(0); // 我有 1000 元
// arguments = [];
updateEasyCard(10, 50, 100, 50, 5, 1, 1, 1, 500); // 我有 718 元
// arguments = [10, 50, 100, 50, 5, 1, 1, 1, 500];
```
## 其餘參數
其餘參數,顧名思義就是傳入的參數,用途類似 `arguments`,但不同的是:
- `arguments` 不是真的陣列,其餘參數則是
- `arguments` 不能混用自訂傳入的參數
以下就是使用其餘參數改寫以上範例。
```js
let mingCard = {
name: '小明',
value: 0
};
function updateEasyCard(mingCard, ...money) {
console.log(money); // 其餘參數的陣列
mingCard.value = money.reduce(function (accumulator, currentValue) {
// 分別為前一個回傳值, 當前值
return accumulator + currentValue; // 與前一個值相加
}, mingCard.value);
console.log(`${mingCard.name} 的卡現在有 ${mingCard.value}`);
}
let money = [10, 50, 100, 50, 5, 1, 1, 1, 500]
updateEasyCard(mingCard, ...money); // 718
updateEasyCard(mingCard, 50, 100, 50, 70, 200); // 小明 的卡現在有 1188
```
透過其餘參數,我們還能混用其他的變數像是 `mingCard`,讓這個儲值函式彈性更高,而不受 `arguments` 依序傳入的限制。
看到目前為止,你會跟我一樣覺得 ES6 的程式碼看起來不像 JavaScript 嗎?
|
Java
|
UTF-8
| 1,250 | 2.71875 | 3 |
[] |
no_license
|
//@author A0114463M
package logic;
import java.util.ArrayList;
import application.Task;
/**
* All handlers that performs changes to memory (such as add, delete or edit)
* shall extend this class. UndoHandlers and RedoHandlers shall also extend this
* class to access the changes and be able to revoke them.
* UndoRedoManager is provided in this class such that the changes made to memory
* by handlers are recorded, which is allowed to undo or redo these actions for
* UndoHandler and RedoHandler
*
*/
abstract class UndoableCommandHandler extends CommandHandler {
UndoRedoManager undoRedoManager = UndoRedoManager.getInstance();
/**
* reset the handler for recording new changes
*/
abstract void reset();
@Override
abstract ArrayList<String> getAliases();
@Override
abstract String execute(String command, String parameter, ArrayList<Task> taskList) throws Exception;
@Override
abstract public String getHelp(String command);
/**
* Record the changes made to memory and generate a UndoRedoRecorder
* for recording purpose. TaskList in LogicController is then updated
* @param taskList
*/
abstract void recordChanges(ArrayList<Task> taskList);
}
|
C++
|
UTF-8
| 516 | 2.875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int ones(int arr[], int n){
if(arr[0] == 0){
return 0;
}
int low = 0;
int high = n-1;
while(low<=high){
int mid = (low+high)/2;
if(arr[mid]==1){
if(arr[mid+1]==0){
return mid+1;
}else{
low = mid+1;
}
}
else{
high = mid-1;
}
}return -1;
}
int main(){
int arr[] = {1,1,1,1,1,1,1,1,0,0,0};
cout << ones(arr,11);
}
|
Python
|
UTF-8
| 3,134 | 2.78125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[58]:
def ratingdrv(data):
import pandas as pd
import numpy as np
data = pd.read_csv("/home/ramanan/Documents/Work/26dec/Day26trips/date26trip4.csv")
data = data[~(data['speed'] <= 5)]
speed = data['speed']
speed = speed.dropna()
maxspeed = max(speed)
harsh = speed.diff()
harsh = harsh.dropna()
harshaccleration = max(harsh)
harshbrake = min(harsh)
Averagespeed = speed.mean()
gyroy = data[['speed','gyroscope-y']]
gyroy = gyroy.dropna()
newy = gyroy[['gyroscope-y']].diff(periods=1)
newy = newy.rename(columns={'gyroscope-y': 'gyroscope-y-diff'})
gyroy['gyroscope-y-diff'] = newy
gyroy = gyroy.drop(['gyroscope-y'], axis=1)
harshturn = gyroy[(gyroy > 50).any(1)]
turnspeed = harshturn['speed']
if len(turnspeed.index) == 0 :
harshturnspeed = 0
Avgturnspeed = 0
else:
harshturnspeed = round(max(turnspeed))
Avgturnspeed = round(turnspeed.mean())
current = data[['sensor current']]
current[current < 0] = 0
currentapplied = (current != 0).any(axis=1)
new_currentapplied = current.loc[currentapplied]
maximumcurrent = int(new_currentapplied.max())
avgcurrent = int(new_currentapplied.mean())
conditions = [
(maximumcurrent <= 99),
(maximumcurrent > 100) & (maximumcurrent <= 149),
(maximumcurrent > 150) & (maximumcurrent <= 200),
(maximumcurrent > 200)
]
ranges = ['good', 'average', 'belowavg', 'poor']
fixrange = np.select(conditions, ranges)
if (fixrange == 'good'):
currentproduced = 1
elif (fixrange == 'average'):
currentproduced = 0.75
elif (fixrange == 'belowavg'):
currentproduced = 0.50
else :
currentproduced = -1
if (avgcurrent > 100):
currentproduced = currentproduced - 0.25
else:
currentproduced = currentproduced + 0.25
if (harshaccleration > 15):
scoreharshaccleration = 0.50
else:
scoreharshaccleration = 0.25
if (harshbrake > -18):
scoreharshbrake = 1.5
else:
scoreharshbrake = 0.75
if (Averagespeed > 24):
scoreAveragespeed = 1.5
else:
scoreAveragespeed = 0.75
if (maxspeed > 37):
scoremaxspeed = -3
else:
scoremaxspeed = 2
if (harshturnspeed > 27):
scoreharshturnspeed = 0.75
else:
scoreharshturnspeed = 1.5
if (Avgturnspeed > 21):
scoreAvgturnspeed = 0.75
else:
scoreAvgturnspeed = 1.5
print(maxspeed)
print(Averagespeed)
print(harshaccleration)
print(harshbrake)
print(harshturnspeed)
print(Avgturnspeed)
print(currentproduced)
print(maximumcurrent)
print(avgcurrent)
ratings = scoreharshaccleration + scoreharshbrake + scoreAveragespeed + scoremaxspeed + scoreharshturnspeed + scoreAvgturnspeed + currentproduced
ratings = ratings/2
ratings = round(ratings, 2)
if (ratings < 0.49):
ratings = 0.5
return ratings
# In[59]:
ratingdrv(data)
# In[11]:
|
C#
|
UTF-8
| 1,397 | 2.734375 | 3 |
[] |
no_license
|
using TouchForFood.Models;
using System.Linq;
using System;
using TouchForFood.Exceptions;
using System.Data;
using System.Collections.Generic;
using TouchForFood.Mappers.Abstract;
namespace TouchForFood.Mappers
{
public class WaiterOM : GenericOM
{
public WaiterOM() :base(){}
public WaiterOM(touch_for_foodEntities db):base(db){}
/// <summary>
/// Writes a waiter object to the database
/// </summary>
/// <param name="waiter">The waiter object to write</param>
/// <returns>True if successful, false otherwise</returns>
public bool Create(waiter waiter)
{
db.waiters.Add(waiter);
return (db.SaveChanges() == 1);
}
public override int delete(int id)
{
waiter waiter = db.waiters.Find(id);
int result = 0;
clearOrder(waiter.orders);
db.waiters.Remove(waiter);
result = db.SaveChanges();
return result;
}
private void clearOrder(ICollection<order> orders)
{
for (int i = 0; i < orders.Count;i++ )
{
orders.ElementAt(i).waiter_id = null;
orders.ElementAt(i).version = orders.ElementAt(i).version + 1;
db.Entry(orders.ElementAt(i)).State = EntityState.Modified;
}
}
}
}
|
PHP
|
UTF-8
| 1,242 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
<?php declare(strict_types=1);
namespace PhpImplementations\Cli;
use Auryn\Injector;
use League\CLImate\CLImate;
use League\CLImate\TerminalObject\Dynamic\Progress;
use PhpImplementations\Url\Parser\MathiasBynens as MathiasBynensParser;
use PhpImplementations\Url\Retriever\MathiasBynens as MathiasBynensRetriever;
require_once __DIR__ . '/../bootstrap.php';
$climate = new CLImate();
$dataSources = [
'MathiasBynens' => [
'retriever' => MathiasBynensRetriever::class,
'parser' => MathiasBynensParser::class,
],
];
$progress = $climate->progress()->total(count($dataSources) * 2);
$progressCounter = 0;
foreach ($dataSources as $key => $dataSource) {
/** @var Injector $auryn */
$retriever = $auryn->make($dataSource['retriever']);
$parser = $auryn->make($dataSource['parser']);
/** @var Progress $progress */
$progress->current(++$progressCounter, sprintf('Retrieving %s test data', $key));
$sourceData = $retriever->retrieve();
$progress->current(++$progressCounter, sprintf('Parsing %s test data', $key));
file_put_contents(
__DIR__ . '/../data/input/' . $key . '.php',
'<?php return ' . var_export($parser->parse($sourceData), true) . ';'
);
}
|
C#
|
UTF-8
| 3,228 | 2.671875 | 3 |
[
"Zlib",
"MIT"
] |
permissive
|
using System;
using System.IO;
using Gibbed.Helpers;
namespace Gibbed.Illusion.FileFormats
{
public class SdsConfigFile
{
public void Deserialize(Stream input)
{
if (input.ReadValueU32() != 0x73647370)
{
throw new FormatException("not an SDS config file");
}
if (input.ReadValueU32() != 2)
{
throw new FormatException("unsupported SDS config version");
}
uint stringTableSize = input.ReadValueU32();
byte[] stringTable = new byte[stringTableSize];
input.Read(stringTable, 0, stringTable.Length);
// "encryption"
for (int i = 0; i < stringTable.Length; i++)
{
stringTable[i] = (byte)(~stringTable[i]);
}
using (var output = File.Create("sdsconfig.strings"))
{
output.Write(stringTable, 0, stringTable.Length);
}
// fucking nested much? jeezus christ
var unk0 = input.ReadValueU16();
for (ushort i = 0; i < unk0; i++)
{
var unk1 = input.ReadValueU16();
//var name1 = stringTable.ToStringUTF8Z(unk1);
var unk2 = input.ReadValueU16();
for (ushort j = 0; j < unk2; j++)
{
var unk3 = input.ReadValueU16();
//var name2 = stringTable.ToStringUTF8Z(unk3);
//Console.WriteLine(name2);
var unk4 = input.ReadValueU16();
var unk5 = input.ReadValueU16();
var unk6 = input.ReadValueU16();
var unk7 = input.ReadValueU32();
var unk8 = input.ReadValueU32();
}
var unk9 = input.ReadValueU16();
for (ushort k = 0; k < unk9; k++)
{
var unk10 = input.ReadValueU16();
//var name3 = stringTable.ToStringUTF8Z(unk10);
var unk11 = input.ReadValueU32();
var unk12 = input.ReadValueU32();
var unk13 = input.ReadValueU16();
for (ushort l = 0; l < unk13; l++)
{
var unk14 = input.ReadValueU16();
//var name4 = stringTable.ToStringUTF8Z(unk14);
var unk15 = input.ReadValueU32();
var unk16 = input.ReadValueU32();
var unk17 = input.ReadValueU8();
var unk18 = input.ReadValueU16();
for (ushort m = 0; m < unk18; m++)
{
var unk19 = input.ReadValueU16();
var unk20 = input.ReadValueU16();
var unk21 = input.ReadValueU16();
var unk22 = input.ReadValueU16();
var unk23 = input.ReadValueU32();
var unk24 = input.ReadValueU32();
}
}
}
}
}
}
}
|
JavaScript
|
UTF-8
| 473 | 3.0625 | 3 |
[] |
no_license
|
// Emulate the code academy environment so that laser cats can run in jsc
// Defines a 'console' like class that has a log function that utilizes jsc's 'debug'
// funtion to print strings to the terminal
var console = {
log: function(output) {
debug(output)
}
};
// Defines a new prompt function based on jsc's 'readline' functionality,
// and the console class defined above.
var prompt = function(prompt) {
console.log(prompt);
return readline();
}
|
Swift
|
UTF-8
| 3,459 | 2.578125 | 3 |
[] |
no_license
|
//
// MapViewController.swift
// BillMates
//
// Created by Lucas Rocali on 6/8/15.
// Copyright (c) 2015 Lucas Rocali. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class MapViewController: UIViewController, CLLocationManagerDelegate {
var model = Model.sharedInstance
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
var locValue : CLLocationCoordinate2D?
func saveLocation(sender: UIBarButtonItem) {
if locValue != nil {
model.setLocation(locValue!)
}
print("pop")
self.navigationController?.popViewControllerAnimated(true)
//self.navigationController?.popToViewController(AddBillViewController(), animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Authorisation from the User.
print("Request user")
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
print("Location enabled")
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
let rightButton = UIBarButtonItem(title: "Save Location", style: UIBarButtonItemStyle.Plain, target: self, action: "saveLocation:")
navigationItem.rightBarButtonItem = rightButton
//let initialLocation = CLLocation(latitude: -37.8140000 , longitude: 144.9633200)
// Do any additional setup after loading the view.
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
locValue = manager.location!.coordinate
if locValue != nil {
let newlLocation = CLLocation(latitude: locValue!.latitude , longitude: locValue!.longitude)
print("locations = \(locValue!.latitude) \(locValue!.longitude)")
/*//var pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(your latitude, your longitude)
var objectAnnotation = MKPointAnnotation()
objectAnnotation.coordinate = locValue
objectAnnotation.title = "Your Location"
self.mapView.addAnnotation(objectAnnotation)*/
self.mapView.showsUserLocation = true
centerMapOnLocation(newlLocation)
}
}
let regionRadius: CLLocationDistance = 100
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
JavaScript
|
UTF-8
| 178 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
var overlays = document.querySelectorAll('.meter_overlay');
for(var i = 0; i < overlays.length; i++) {
var overlay = overlays[i];
overlay.parentNode.removeChild(overlay);
}
|
C
|
UTF-8
| 405 | 2.921875 | 3 |
[] |
no_license
|
#include <stdint.h>
#include "Compatibility.h"
/* XXX I don't like the name of this file */
typedef enum {
NUM_DIGITS = 5,
} NumDigits;
inline void GetDigits(uint16_t n, uint8_t *digits)
{
uint8_t i = NUM_DIGITS - 1;
while (1)
{
uint16_t newN = n / 10;
digits[i] = n - newN * 10;
n = newN;
if (i == 0)
break;
--i;
}
}
|
Python
|
UTF-8
| 1,764 | 3.625 | 4 |
[] |
no_license
|
#!/usr/bin/python3
"""unit_test.py: Testing to make sure that the unweighted undirected graph class
functions are working
"""
import unittest
from node import Node
from graph import Graph
class UnitTest(unittest.TestCase):
"""UnitTest"""
def test_add_node(self):
"""test_add_node: Testing adding a new node to the graph
"""
node_1 = Node(2, [1, 3])
graph = Graph([])
self.assertEqual(graph.vertices, set({}))
self.assertEqual(graph.edges, {})
graph.add_node(node_1)
self.assertEqual(graph.vertices, set({1, 2, 3}))
self.assertEqual(graph.edges, {1: set({2}), 2: set({1, 3}), 3: set({2})})
def test_remove_node(self):
"""test_remove_node: Testing removing of an old node
"""
node_1 = Node(1, [3])
graph = Graph([node_1])
graph.remove_node(node_1)
self.assertEqual(graph.vertices, set({3}))
self.assertEqual(graph.edges, {3: set({})})
def test_is_connected_false(self):
"""test_is_connected_false: Test that is_connected works to find out if a
graph is not connected
"""
node_1 = Node(1, [2])
node_2 = Node(2, [1])
node_3 = Node(3, [4])
node_4 = Node(4, [3])
graph = Graph([node_1, node_2, node_3, node_4])
self.assertFalse(graph.is_connected())
def test_is_connected_true(self):
"""test_is_connected_true: Test that is_connected works to find out if a
graph is connected
"""
node_1 = Node(1, [2, 4])
node_2 = Node(2, [4])
node_3 = Node(3, [2, 1])
graph = Graph([node_1, node_2, node_3])
self.assertTrue(graph.is_connected())
if __name__ == '__main__':
unittest.main()
|
Java
|
UTF-8
| 866 | 2.46875 | 2 |
[] |
no_license
|
package com.wellsfargo.fsd.jw.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username=req.getParameter("unm");
if(username==null) {
username="Somebody";
}
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
out.println("<html><head><title>Servlet Content</title></heda>");
out.println("<body><h1>Hello !<strong>"+ username+ "</strong></h1></body>");
out.println("</html>");
}
}
|
Java
|
UTF-8
| 1,612 | 2.921875 | 3 |
[] |
no_license
|
package Pontos;
/**
*
* @author a15023
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import Dados.Dados;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class Printar extends Frame {
public Printar(){
super("Pontos na Tela");
prepareGUI();
}
public void iniciaPrint(){
Printar awtGraphicsDemo = new Printar();
awtGraphicsDemo.setVisible(true);
}
private void prepareGUI(){
setSize(900,900);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
@Override
public void paint(Graphics g) {
Ellipse2D shape = new Ellipse2D.Float();
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i < 100; i++) {
shape.setFrame(Dados.entrada[i][0]+50, Dados.entrada[i][1]+50, 5, 5);
g2.draw (shape);
}
g2.drawLine((int)Dados.entrada[Dados.vetor.get(99)][0], (int)Dados.entrada[Dados.vetor.get(0)][0], (int)Dados.entrada[Dados.vetor.get(99)][1], (int)Dados.entrada[Dados.vetor.get(0)][1]);
for (int i = 0; i < 99; i++) {
g2.drawLine((int)Dados.entrada[Dados.vetor.get(i)][0], (int)Dados.entrada[Dados.vetor.get(i+1)][0], (int)Dados.entrada[Dados.vetor.get(i)][1], (int)Dados.entrada[Dados.vetor.get(i+1)][1]);
}
}
}
|
JavaScript
|
UTF-8
| 2,635 | 2.953125 | 3 |
[] |
no_license
|
import challenges from "../assets/challenges.json";
let countdownTimeout;
export const state = () => ({
//challenges
level: 1,
currentExperience: 0,
challengesCompleted: 0,
activeChallenge: null,
experienceToNextLevel: 64,
isLevelUpModalOpen: false,
//countdown
time: 25 * 60,
isActive: false,
hasFinished: false
});
export const mutations = {
//challenges
startNewChallenge(state) {
const randomChallengeIndex = Math.floor(Math.random() * challenges.length);
const challenge = challenges[randomChallengeIndex];
state.activeChallenge = challenge;
new Audio("/notification.mp3").play();
if (Notification.permission === "granted") {
new Notification("Novo desafio 🎉", {
body: `Valendo ${challenge.amount}xp`
});
}
},
resetChallenge(state) {
state.activeChallenge = null;
},
completeChallenge(state) {
if (!state.activeChallenge) {
return;
}
const { amount } = state.activeChallenge;
let finalExperience = state.currentExperience + amount;
if (finalExperience >= state.experienceToNextLevel) {
finalExperience = finalExperience - state.experienceToNextLevel;
state.level++;
state.isLevelUpModalOpen = true;
}
state.currentExperience = finalExperience;
state.activeChallenge = null;
state.challengesCompleted++;
state.experienceToNextLevel = Math.pow((state.level + 1) * 4, 2);
},
closeLevelUpModal(state) {
state.isLevelUpModalOpen = false;
},
//countdown
setIsActive(state, value) {
state.isActive = value;
},
setTime(state, value) {
state.time = value;
},
setHasFinished(state, value) {
state.hasFinished = value;
},
resetCountdown(state) {
clearTimeout(countdownTimeout);
state.isActive = false;
state.hasFinished = false;
state.time = 25 * 60;
},
// cookies
getCookies(state, values) {
state.level = parseInt(values.level);
state.currentExperience = parseInt(values.currentExperience);
state.challengesCompleted = parseInt(values.challengesCompleted);
state.experienceToNextLevel = Math.pow((parseInt(values.level) + 1) * 4, 2);
}
};
export const actions = {
//countdown
countdownWatch(context) {
if (context.state.isActive && context.state.time > 0) {
countdownTimeout = setTimeout(() => {
context.commit("setTime", context.state.time - 1);
}, 1000);
} else if (context.state.isActive && context.state.time == 0) {
context.commit("setHasFinished", true);
context.commit("setIsActive", false);
context.commit("startNewChallenge");
}
}
};
|
SQL
|
UTF-8
| 7,436 | 4.375 | 4 |
[] |
no_license
|
------------------- QUESTION 1 -----------------------------------------------------------
-- 1. Show the total sales (quantity sold and dollar value) for each customer.
--
-- This is a strange query...why would I want to track the quantity and not track the product.
-- Quantity of what? Let's see highest sales..
------------------- ANSWER 1 -------------------------------------------------------------
SELECT c.customer_id, c.customer_name, sum(quantity) as total_qty, sum(price) as total_paid
FROM sale s JOIN customer c ON s.customer_id = c.customer_id
GROUP BY c.customer_id, c.customer_name
ORDER BY total_paid DESC
---------------------------------------------------------------------------------------------
------------------- QUESTION 2 ------------------------------------------------------------
-- 2. Show the total sales for each state.
------------------- ANSWER 2 -------------------------------------------------------------
SELECT st.state_name, sum(quantity) as total_qty, sum(price) as total_paid
FROM sale s JOIN Customer c ON s.customer_id = c.customer_id
JOIN state st ON st.state_id = c.state_id
GROUP BY st.state_name
ORDER BY st.state_name
---------------------------------------------------------------------------------------------
------------------- QUESTION 3 ------------------------------------------------------------
-- 3. Show the total sales for each product, for a given customer. Only products
-- that were actually bought by the given customer. Order by dollar value.
------------------- ANSWER 3 -------------------------------------------------------------
SELECT c.customer_id, c.customer_name, p.product_name, sum(price) as total_paid
FROM sale s JOIN customer c ON s.customer_id = c.customer_id
JOIN product p ON p.product_id = s.product_id
WHERE c.customer_id = 1 -- this needs to be the given customer
GROUP BY c.customer_id, c.customer_name, p.product_name
ORDER by total_paid DESC
---------------------------------------------------------------------------------------------
------------------- QUESTION 4 ------------------------------------------------------------
-- 4. Show the total sales for each product and customer. Order by dollar value.
------------------- ANSWER 4 -------------------------------------------------------------
SELECT c.customer_id, c.customer_name, p.product_name, sum(price) as total_paid
FROM sale s JOIN customer c ON s.customer_id = c.customer_id
JOIN product p ON p.product_id = s.product_id
GROUP BY c.customer_id, c.customer_name, p.product_name
ORDER by total_paid DESC
---------------------------------------------------------------------------------------------
------------------- QUESTION 5 ------------------------------------------------------------
-- 5. Show the total sales for each product category and state.
------------------- ANSWER 5 -------------------------------------------------------------
SELECT st.state_name, cat.category_name, sum(price) as total_paid
FROM sale s JOIN customer c ON s.customer_id = c.customer_id
JOIN product p ON p.product_id = s.product_id
JOIN state st ON st.state_id = c.state_id
JOIN category cat ON cat.category_id = p.category_id
GROUP BY cat.category_name, st.state_name
ORDER by cat.category_name, st.state_name, total_paid DESC
---------------------------------------------------------------------------------------------
------------------- QUESTION 6 ------------------------------------------------------------
-- 6. For each one of the top 20 product categories and top 20 customers, it returns a tuple (top
-- product, top customer, quantity sold, dollar value)
-- SCRATCH PAD -- Get the top product categories
SELECT cat.category_id, sum(s.price) as total_paid
FROM sale s JOIN product p ON s.product_id = p.product_id
JOIN category cat ON cat.category_id = p.category_id
GROUP BY cat.category_id
ORDER BY total_paid DESC
LIMIT 20
-- SCRATCH PAD --Get the top customers.
SELECT c.customer_id, sum(s.price) as total_paid
FROM sale s JOIN customer c ON s.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY total_paid DESC
LIMIT 20
-- SCRATCH PAD -- Each combination of top 20 categories and top 20 customers
SELECT cat1.category_id, c.customer_id
FROM category cat1, customer c
WHERE cat1.category_id IN (SELECT cat.category_id
FROM sale s JOIN product p ON s.product_id = p.product_id
JOIN category cat ON cat.category_id = p.category_id
GROUP BY cat.category_id
ORDER BY sum(s.price) DESC
LIMIT 20)
AND c.customer_id IN (SELECT c.customer_id
FROM sale s JOIN customer c ON s.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY sum(s.price) DESC
LIMIT 20)
-- SCRATCH PAD --
-- And the semi-final query and resulting tuple, although this one doesn't quite get ALL top customer and ALL top products
-- even if the sum of the total paid is 0. This gets all values where the total paid is > 0
SELECT cat.category_name, c.customer_name, sum(quantity) as total_qty, sum(price) as total_paid
FROM sale s JOIN product p ON s.product_id = p.product_id
JOIN customer c ON s.customer_id = c.customer_id
JOIN (SELECT cat1.category_id, c.customer_id
FROM category cat1, customer c
WHERE cat1.category_id IN (SELECT cat.category_id
FROM sale s
JOIN product p ON s.product_id = p.product_id
JOIN category cat ON cat.category_id = p.category_id
GROUP BY cat.category_id
ORDER BY sum(s.price) DESC
LIMIT 20)
AND c.customer_id IN (SELECT c.customer_id
FROM sale s JOIN customer c ON s.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY sum(s.price) DESC
LIMIT 20)) a
ON p.category_id = a.category_id
AND c.customer_id = a.customer_id
JOIN category cat ON cat.category_id = a.category_id
GROUP BY category_name, c.customer_name
ORDER BY c.customer_name
-- This query shows the top 20 customers and the top 20 product categories along side their total sales and total qty
-- and includes ALL 20 customers in ALL 20 product categories regardless if their total sales in one of the top
-- categories is $0.
------------------- ANSWER 6 -------------------------------------------------------------
SELECT cat.category_name, top.category_id, c.customer_name, top.customer_id,
COALESCE(price,0) total_price, COALESCE(quantity,0) total_qty
FROM (SELECT category_id, customer_id
FROM (SELECT cat.category_id
FROM category cat, product p, sale s
WHERE s.product_id = p.product_id
AND cat.category_id = p.category_id
GROUP BY cat.category_id
ORDER BY sum(s.price) DESC
LIMIT 20) cat1,
(SELECT customer_id
FROM sale s
GROUP BY customer_id
ORDER BY sum(s.price) DESC
LIMIT 20
) c1
) top LEFT OUTER JOIN
(SELECT sum(s.price) price, sum(s.quantity) quantity, p.category_id, s.customer_id
FROM sale s, product p
WHERE s.product_id = p.product_id
GROUP BY p.category_id, s.customer_id
) merge
ON top.customer_id = merge.customer_id
AND top.category_id = merge.category_id
JOIN customer c ON top.customer_id = c.customer_id
JOIN category cat ON top.category_id = cat.category_id
JOIN product p ON p.category_id = cat.category_id
GROUP BY cat.category_name, top.category_id, c.customer_name, top.customer_id, price, quantity
ORDER BY cat.category_name, c.customer_name
---------------------------------------------------------------------------------------------
|
Python
|
UTF-8
| 3,639 | 2.859375 | 3 |
[] |
no_license
|
# coding=UTF-8
import vk
from vk_parsing.parser import send_message
# Several tokens for 1 user don't work. Need to buy more vk pages.
_user_tokens = ['put your user token here',
'like this'
]
_service_tokens = [
'put your service tokens here',
'as much as possible']
# Split tokens by groups and pass each group to collect_user_data() thread
def groups(s_tokens_n=6, service_tokens= None, user_tokens=None): # tokens_n is number of service tokens in each group
"""
:param s_tokens_n: number of service tokens in each group
:param service_tokens: a list of vk service tokens
:param user_tokens: a list of vk user tokens
:return: groups of service and user tokens
"""
if service_tokens is None:
service_tokens = _service_tokens
if user_tokens is None:
user_tokens = _user_tokens
service_groups = []
users_groups = []
groups_n = len(service_tokens) // s_tokens_n
u_tokens_n = len(user_tokens) // groups_n
if u_tokens_n < 1 or groups_n < 1:
print('Minimum {} user tokens and service tokens are required. Exiting'.format(groups_n))
send_message('Add more user tokens. Exiting')
exit()
while len(service_tokens) > 0:
for group in range(groups_n):
if len(service_groups) < groups_n:
service_groups.append([service_tokens.pop()])
else:
service_groups[group].append(service_tokens.pop())
if len(service_tokens) == 0: break
while len(user_tokens) > 0:
for group in range(groups_n):
if len(users_groups) < groups_n:
users_groups.append([user_tokens.pop()])
else:
users_groups[group].append(user_tokens.pop())
if len(user_tokens) == 0: break
return service_groups, users_groups
class Session:
def __init__(self, service_tokens=None, user_tokens=None):
if service_tokens is None:
self._service_tokens = _service_tokens
else: self._service_tokens = service_tokens
if user_tokens is None:
self._user_tokens = _user_tokens
else: self._user_tokens = user_tokens
self._i = 0
self._y = 0
self._service_vk = None
self._user_vk = None
def update_public_key(self):
service_session = vk.Session(access_token=self._service_tokens[self._i])
self._service_vk = vk.API(service_session)
if self._i is len(self._service_tokens) - 1:
self._i = 0
else:
self._i += 1
print('The service key has been changed:\n')
return self._service_vk
def update_user_key(self):
user_session = vk.Session(access_token=self._user_tokens[self._y])
self._user_vk = vk.API(user_session)
if self._y is len(self._user_tokens) - 1:
self._y = 0
else:
self._y += 1
print('The user key has been changed\n')
return self._user_vk
def get_user_vk(self):
if self._user_vk is not None:
return self._user_vk
else: return self.update_user_key()
def get_service_vk(self):
if self._service_vk is not None:
return self._service_vk
else: return self.update_public_key()
def get_service_tokens_n(self):
return len(self._service_tokens)
def get_user_tokens_n(self):
return len(self._user_tokens)
def get_user_token(self):
return self._user_tokens[self._y][:5]
def get_service_token(self):
return self._service_tokens[self._i][:5]
|
TypeScript
|
UTF-8
| 2,698 | 3.171875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import { Guard } from "./guard";
const message: string = "Unhandled exception";
describe("Shared", () => {
describe("Guard", () => {
describe("throwIfObjectUndefined", () => {
it("should throw for undefined object", () => {
expect(() => Guard.throwIfObjectUndefined(undefined, message)).toThrowError(message);
});
it("should throw for empty object", () => {
expect(() => Guard.throwIfObjectUndefined({}, message)).toThrowError(message);
});
it("should throw for null object", () => {
expect(() => Guard.throwIfObjectUndefined(null, message)).toThrowError(message);
});
it("should not throw for valid object", () => {
expect(() => Guard.throwIfObjectUndefined({ name: "George" }, message)).not.toThrowError(message);
});
it("should not throw for valid object with undefined values", () => {
expect(() => Guard.throwIfObjectUndefined({ name: undefined }, message)).not.toThrowError(message);
});
it("should not throw for valid object with empty values", () => {
expect(() => Guard.throwIfObjectUndefined({ name: '' }, message)).not.toThrowError(message);
});
});
describe("throwIfStringNotDefinedOrEmpty", () => {
it("should throw for undefined string", () => {
expect(() => Guard.throwIfStringNotDefinedOrEmpty(undefined, message)).toThrowError(message);
});
it("should throw for whitespace string", () => {
expect(() => Guard.throwIfStringNotDefinedOrEmpty(" ", message)).toThrowError(message);
});
it("should throw for empty string", () => {
expect(() => Guard.throwIfStringNotDefinedOrEmpty("", message)).toThrowError(message);
});
it("should throw for null string", () => {
expect(() => Guard.throwIfStringNotDefinedOrEmpty(null, message)).toThrowError(message);
});
it("should not throw for valid string", () => {
expect(() => Guard.throwIfStringNotDefinedOrEmpty("George", message)).not.toThrowError(message);
});
});
describe("validate", () => {
it("should throw for truthy condition", () => {
expect(() => Guard.validate(true, message)).toThrowError(message);
});
it("should not throw for falsy condition", () => {
expect(() => Guard.validate(false, message)).not.toThrowError(message);
});
});
});
});
|
Java
|
UTF-8
| 7,645 | 1.945313 | 2 |
[
"Apache-2.0"
] |
permissive
|
package yhao.micro.service.surety.business.apilist.model;
import io.swagger.annotations.ApiModelProperty;
import yhao.infra.common.model.Entity;
import yhao.micro.service.surety.business.apilist.form.guarantee.LoanDetailsSaveForm;
import yhao.micro.service.surety.business.apilist.form.guarantee.LoanGeneralSaveForm;
import java.util.Date;
import java.util.List;
/**
* @Description 打折申请详情查看model
*
* @Author leice
* @Date 2018/12/10 10:56
* @Version 1.0
*/
public class DiscountApplicationInfoModel extends Entity<String> {
@ApiModelProperty("业务编号")
private String businessNumber;
@ApiModelProperty("客户经理")
private String accountManager;
@ApiModelProperty("客户经理id")
private String accountManagerId;
@ApiModelProperty("客户经理所属部门")
private String accountManagerOrg;
@ApiModelProperty("公正日期")
private String fairDate;
@ApiModelProperty("卖方")
private List<OwnerModel> sellers;
@ApiModelProperty("买方")
private List<BuyModel> buyers;
@ApiModelProperty("物业")
private List<PropertyModel> propertys;
@ApiModelProperty("业务类型")
private String businessType;
@ApiModelProperty("担保金额")
private Double guaranteeMoney;
@ApiModelProperty("赎楼金额")
private Double redemptionMoney;
@ApiModelProperty("担保天数")
private Integer guaranteeDays;
@ApiModelProperty("手续费")
private Double handlingFee;
@ApiModelProperty("对外费率")
private Double externalRate;
@ApiModelProperty("应收担保费")
private Double securityFeeReceivable;
@ApiModelProperty("应收合计")
private Double totalReceivable;
@ApiModelProperty("实收费率")
private Double actualRate;
@ApiModelProperty("实收担保费")
private Double paidGuaranteeFee;
@ApiModelProperty("实收合计")
private Double totalHarvest;
@ApiModelProperty("返佣")
private Double rebate;
@ApiModelProperty("折扣")
private String discount;
@ApiModelProperty("打折记录id")
private String discountId;
@ApiModelProperty("打折原因")
private String discountReason;
@ApiModelProperty("最低实收费率")
private Double lowestActualRate;
@ApiModelProperty("业务类型 额度=AMOUNT,现金=CASH")
private String types;
@ApiModelProperty(value = "借款概况信息")
private LoanGeneralSaveForm loanGeneralSaveForm;
@ApiModelProperty(value = "借款明细信息")
private List<LoanDetailsInfoModel> LoanDetailsInfoList;
public String getAccountManagerId() {
return accountManagerId;
}
public void setAccountManagerId(String accountManagerId) {
this.accountManagerId = accountManagerId;
}
public String getAccountManagerOrg() {
return accountManagerOrg;
}
public void setAccountManagerOrg(String accountManagerOrg) {
this.accountManagerOrg = accountManagerOrg;
}
public Double getRedemptionMoney() {
return redemptionMoney;
}
public void setRedemptionMoney(Double redemptionMoney) {
this.redemptionMoney = redemptionMoney;
}
public String getBusinessNumber() {
return businessNumber;
}
public void setBusinessNumber(String businessNumber) {
this.businessNumber = businessNumber;
}
public String getAccountManager() {
return accountManager;
}
public void setAccountManager(String accountManager) {
this.accountManager = accountManager;
}
public String getFairDate() {
return fairDate;
}
public void setFairDate(String fairDate) {
this.fairDate = fairDate;
}
public List<OwnerModel> getSellers() {
return sellers;
}
public void setSellers(List<OwnerModel> sellers) {
this.sellers = sellers;
}
public List<BuyModel> getBuyers() {
return buyers;
}
public void setBuyers(List<BuyModel> buyers) {
this.buyers = buyers;
}
public List<PropertyModel> getPropertys() {
return propertys;
}
public void setPropertys(List<PropertyModel> propertys) {
this.propertys = propertys;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public Double getGuaranteeMoney() {
return guaranteeMoney;
}
public void setGuaranteeMoney(Double guaranteeMoney) {
this.guaranteeMoney = guaranteeMoney;
}
public Integer getGuaranteeDays() {
return guaranteeDays;
}
public void setGuaranteeDays(Integer guaranteeDays) {
this.guaranteeDays = guaranteeDays;
}
public Double getHandlingFee() {
return handlingFee;
}
public void setHandlingFee(Double handlingFee) {
this.handlingFee = handlingFee;
}
public Double getExternalRate() {
return externalRate;
}
public void setExternalRate(Double externalRate) {
this.externalRate = externalRate;
}
public Double getSecurityFeeReceivable() {
return securityFeeReceivable;
}
public void setSecurityFeeReceivable(Double securityFeeReceivable) {
this.securityFeeReceivable = securityFeeReceivable;
}
public Double getTotalReceivable() {
return totalReceivable;
}
public void setTotalReceivable(Double totalReceivable) {
this.totalReceivable = totalReceivable;
}
public Double getActualRate() {
return actualRate;
}
public void setActualRate(Double actualRate) {
this.actualRate = actualRate;
}
public Double getPaidGuaranteeFee() {
return paidGuaranteeFee;
}
public void setPaidGuaranteeFee(Double paidGuaranteeFee) {
this.paidGuaranteeFee = paidGuaranteeFee;
}
public Double getTotalHarvest() {
return totalHarvest;
}
public void setTotalHarvest(Double totalHarvest) {
this.totalHarvest = totalHarvest;
}
public Double getRebate() {
return rebate;
}
public void setRebate(Double rebate) {
this.rebate = rebate;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getDiscountId() {
return discountId;
}
public void setDiscountId(String discountId) {
this.discountId = discountId;
}
public String getDiscountReason() {
return discountReason;
}
public void setDiscountReason(String discountReason) {
this.discountReason = discountReason;
}
public Double getLowestActualRate() {
return lowestActualRate;
}
public void setLowestActualRate(Double lowestActualRate) {
this.lowestActualRate = lowestActualRate;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public LoanGeneralSaveForm getLoanGeneralSaveForm() {
return loanGeneralSaveForm;
}
public void setLoanGeneralSaveForm(LoanGeneralSaveForm loanGeneralSaveForm) {
this.loanGeneralSaveForm = loanGeneralSaveForm;
}
public List<LoanDetailsInfoModel> getLoanDetailsInfoList() {
return LoanDetailsInfoList;
}
public void setLoanDetailsInfoList(List<LoanDetailsInfoModel> loanDetailsInfoList) {
LoanDetailsInfoList = loanDetailsInfoList;
}
}
|
Java
|
UTF-8
| 132 | 1.914063 | 2 |
[
"MIT"
] |
permissive
|
package com.javasummerschool.multiple_interfaces;
public interface IStudent extends IWork, IIntership {
void bagToTeacher();
}
|
Markdown
|
UTF-8
| 1,322 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
# Laravel 5.1 benchmarks
Quick-and-dirty Laravel 5.1 Benchmarks for Cache, DB, Session, etc.
To see exactly what this benchmark is doing, look at [`resources/views/benchmark.php`](resources/views/benchmark.php) -- it is a standalone file running on stock Laravel 5.1.
Sample run on Linode with xdebug disabled:

## Installation on Homestead (YMMV)
* `composer install`
* `cp .env-example .env`
* `mysqladmin -v create -f homestead -u homestead --password=secret`
* `sudo apt-get install php5-redis;service php5-fpm restart`
## Usage
Visit the site in a browser, the benchmarks should appear.
## Tips and tricks
* xdebug makes a large difference -- try it with and without.
* Try redis over a socket -- put this in your config/database.php redis settings
* 'path' => env('REDIS_PATH', '/tmp/redis.sock'),
* 'scheme' => env('REDIS_SCHEME', 'unix'),
* You'll also have to tell Redis to listen on a socket -- add this to /etc/redis/redis.php
* unixsocket /tmp/redis.sock
* unixsocketperm 777
* Mysql already connects over a socket by default for a host of `localhost` -- change the host to `127.0.0.1` to compare (may have to enable mysql to listen first).
## Disclaimer
This is useful to me. I hope it's useful to you. It is what it is. PRs welcome.
|
C#
|
UTF-8
| 1,521 | 2.921875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestPerson
{
class Program
{
static void Main(string[] args)
{
Person person1 = new Player("Florin", "Nicorici", "chaos28");
System.Console.WriteLine(person1.GetFullName());
System.Console.WriteLine(((Student)person1).GetFullName());
System.Console.WriteLine(((Player)person1).GetFullName());
System.Console.WriteLine(person1.GenerateCode());
System.Console.WriteLine(((Player)person1).GenerateCode());
System.Console.WriteLine(((Student)person1).GenerateCode());
person1.PrintDateTime();
((Student)person1).PrintDateTime();
((Player)person1).PrintDateTime();
Student person2 = new Player("Cristian", "Nicorici", "gemini30");
System.Console.WriteLine(person2.GetFullName());
System.Console.WriteLine(((Person)person2).GetFullName());
System.Console.WriteLine(((Player)person2).GetFullName());
System.Console.WriteLine(person2.GenerateCode());
System.Console.WriteLine(((Player)person2).GenerateCode());
System.Console.WriteLine(((Student)person2).GenerateCode());
person2.PrintDateTime();
((Student)person2).PrintDateTime();
((Player)person2).PrintDateTime();
System.Console.ReadLine();
}
}
}
|
PHP
|
UTF-8
| 11,676 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<?php defined('SYSPATH') OR die('No direct script access.');
use Omnipay\Common\GatewayInterface;
/**
* @package Openbuildings\Purchases
* @author Ivan Kerin <ikerin@gmail.com>
* @copyright (c) 2013 OpenBuildings Ltd.
* @license http://spdx.org/licenses/BSD-3-Clause
*/
class Kohana_Model_Payment extends Jam_Model {
const PAID = 'paid';
const PENDING = 'pending';
/**
* @codeCoverageIgnore
*/
public static function initialize(Jam_Meta $meta)
{
$meta
->table('payments')
->behaviors(array(
'paranoid' => Jam::behavior('paranoid'),
'payment_refundable' => Jam::behavior('payment_refundable'),
))
->associations(array(
'purchase' => Jam::association('belongsto', array('inverse_of' => 'payment')),
))
->fields(array(
'id' => Jam::field('primary'),
'method' => Jam::field('string'),
'payment_id' => Jam::field('string'),
'raw_response' => Jam::field('serialized', array('method' => 'json')),
'status' => Jam::field('string'),
'created_at' => Jam::field('timestamp', array('auto_now_create' => TRUE, 'format' => 'Y-m-d H:i:s')),
'updated_at' => Jam::field('timestamp', array('auto_now_update' => TRUE, 'format' => 'Y-m-d H:i:s')),
))
->validator('purchase', 'method', array('present' => TRUE));
}
/**
* Calculate a transaction fee, based on the price provided. By default returns NULL
* @param Jam_Price $price
* @return Jam_Price
*/
public function transaction_fee(Jam_Price $price)
{
return NULL;
}
/**
* Executes the purchase and handles events before and after the execution
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function purchase(GatewayInterface $gateway, array $params = array())
{
$this->meta()->events()->trigger('model.before_purchase', $this, array($params));
$response = $this->execute_purchase($gateway, $params);
$this->purchase->payment = $this;
$this->purchase->save();
$this->meta()->events()->trigger('model.after_purchase', $this, array($params));
if ($this->status === Model_Payment::PAID)
{
$this->meta()->events()->trigger('model.pay', $this, array($params));
}
return $response;
}
/**
* Executes the purchase with the provided payment gateway
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function execute_purchase(GatewayInterface $gateway, array $params = array())
{
$include_card = (isset($params['card']) && isset($params['card']['number']));
$params = Arr::merge($params, $this->convert_purchase($include_card));
$response = $gateway->purchase($params)->send();
$this->payment_id = $response->getTransactionReference();
$this->raw_response = $response->getData();
if ($response->isRedirect())
{
$this->status = Model_Payment::PENDING;
}
else if ($response->isSuccessful())
{
$this->status = Model_Payment::PAID;
}
return $response;
}
/**
* Completes an off site purchase and handles events before and after the completion
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function complete_purchase(GatewayInterface $gateway, array $params = array())
{
if ($this->status !== Model_Payment::PENDING)
{
throw new Exception_Payment('You must initiate a purchase before completing it');
}
$this->meta()->events()->trigger('model.before_complete_purchase', $this, array($params));
$response = $this->execute_complete_purchase($gateway, $params);
$this->purchase->payment = $this;
$this->purchase->save();
$this->meta()->events()->trigger('model.after_complete_purchase', $this, array($params));
if ($this->status === Model_Payment::PAID)
{
$this->meta()->events()->trigger('model.pay', $this, array($params));
}
return $response;
}
/**
* Completes an off site purchase with the provided payment gateway
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function execute_complete_purchase(GatewayInterface $gateway, array $params = array())
{
$include_card = (isset($params['card']) && isset($params['card']['number']));
$params = Arr::merge($params, $this->convert_purchase($include_card));
$response = $gateway->completePurchase($params)->send();
$this->payment_id = $response->getTransactionReference();
$this->raw_response = $response->getData();
if ($response->isSuccessful())
{
$this->status = Model_Payment::PAID;
}
return $response;
}
/**
* Convert a Model_Purchase object to an array of parameteres, suited for Omnipay
*
* @return array
*/
public function convert_purchase($include_card = FALSE)
{
$currency = $this->purchase->display_currency() ?: $this->purchase->currency();
$params = array(
'transactionReference' => $this->payment_id ?: $this->purchase->number,
'currency' => $currency,
'clientIp' => Request::$client_ip
);
if ($include_card)
{
$params['card'] = array();
if ($this->purchase->creator)
{
$params['card']['email'] = $this->purchase->creator->email;
}
if (($billing = $this->purchase->billing_address))
{
$params['card'] = array_merge($params['card'], array_filter(array(
'firstName' => $billing->first_name,
'lastName' => $billing->last_name,
'address1' => $billing->line1,
'address2' => $billing->line2,
'city' => $billing->city ? $billing->city->name() : NULL,
'country' => $billing->country ? $billing->country->short_name : NULL,
'postcode' => $billing->zip,
'email' => $billing->email,
'phone' => $billing->phone,
)));
}
}
$params['items'] = array_map(function ($item) use ($currency) {
$name = str_pad($item->reference ? URL::title($item->reference->name(), ' ', TRUE) : $item->type(), 5, '.');
return array(
"name" => $item->id(),
"description" => $name,
"quantity" => $item->quantity,
"price" => $item->price()->as_string($currency),
);
}, $this->purchase->items(array('is_payable' => TRUE)));
$params['amount'] = $this->purchase->total_price(array('is_payable' => TRUE))->as_string($currency);
return $params;
}
/**
* Executes the refund and handles events before and after the execution
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param Model_Brand_Refund $refund
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function refund(GatewayInterface $gateway, Model_Brand_Refund $refund, array $params = array())
{
$this->meta()->events()->trigger('model.before_refund', $this, array($refund, $params));
$response = $this->execute_refund($gateway, $refund, $params);
$refund->save();
$this->meta()->events()->trigger('model.after_refund', $this, array($refund, $params));
return $response;
}
/**
* Executes the refund with the provided payment gateway
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param Model_Brand_Refund $refund
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function execute_refund(GatewayInterface $gateway, Model_Brand_Refund $refund, array $params = array())
{
$params = Arr::merge($this->convert_refund($refund), $params);
$response = $gateway->refund($params)->send();
$refund->raw_response = $response->getData();
$refund->transaction_status = ($response->isSuccessful()) ? Model_Brand_Refund::TRANSACTION_REFUNDED : NULL;
return $response;
}
/**
* Convert a Model_Brand_Refund object to an array of parameteres, suited for Omnipay
* @param Model_Brand_Refund $refund
* @return array
*/
public function convert_refund(Model_Brand_Refund $refund)
{
$payment = $refund->payment_insist();
$currency = $refund->display_currency() ?: $refund->currency();
$params = array(
'transactionReference' => $payment->payment_id,
'currency' => $currency,
);
$is_full_refund = $refund->amount()->is(Jam_Price::EQUAL_TO,
$refund->purchase_insist()->total_price(array('is_payable' => TRUE)));
if (count($refund->items) AND ! $is_full_refund)
{
$params['items'] = array_map(function ($item) use ($currency) {
return array(
"name" => $item->purchase_item->id(),
"price" => $item->amount()->as_string($currency),
);
}, $refund->items->as_array());
}
$params['amount'] = $refund->amount()->as_string($currency);
return $params;
}
/**
* Executes multiple refunds and handles events before and after the execution
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param Model_Brand_Refund[] $refunds
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function full_refund(GatewayInterface $gateway, array $refunds, array $params = array())
{
$this->meta()->events()->trigger('model.before_full_refund', $this, array($refunds, $params));
$response = $this->execute_multiple_refunds($gateway, $refunds, $params);
foreach ($refunds as $refund)
{
$refund->save();
}
$this->meta()->events()->trigger('model.after_full_refund', $this, array($refunds, $params));
return $response;
}
/**
* Executes multiple refunds with the provided payment gateway
* @param \Omnipay\Common\GatewayInterface $gateway Omnipay payment gateway
* @param Model_Brand_Refund[] $refunds
* @param array $params pass this to the gateway
* @return \Omnipay\Common\Message\ResponseInterface $response payment gateway response
*/
public function execute_multiple_refunds(GatewayInterface $gateway, array $refunds, array $params = array())
{
$params = Arr::merge($this->convert_multiple_refunds($refunds), $params);
$response = $gateway->refund($params)->send();
$raw_response = $response->getData();
$status = ($response->isSuccessful()) ? Model_Brand_Refund::TRANSACTION_REFUNDED : NULL;
foreach ($refunds as $refund)
{
$refund->raw_response = $raw_response;
$refund->transaction_status = $status;
}
return $response;
}
/**
* Convert multiple Model_Brand_Refund objects to an array of parameteres, suited for Omnipay
* @param array $refunds
* @return array
*/
public static function convert_multiple_refunds(array $refunds)
{
$payment = $refunds[0]->payment_insist();
$currency = $refunds[0]->display_currency() ?: $refund->currency();
$amounts = array();
$params = array(
'transactionReference' => $payment->payment_id,
'currency' => $currency,
);
foreach ($refunds as $refund)
{
if (count($refund->items))
{
throw new Exception_Payment('Multiple refunds do not support refund items');
}
else
{
$amounts[] = $refund->amount();
}
}
$params['amount'] = Jam_Price::sum($amounts, $currency)->as_string($currency);
return $params;
}
}
|
TypeScript
|
UTF-8
| 203 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
export default interface ILogger {
fatal: (message: any) => void;
error: (message: any) => void;
warning: (message: any) => void;
info: (message: any) => void;
debug: (message: any) => void;
}
|
Java
|
UTF-8
| 1,103 | 2.1875 | 2 |
[] |
no_license
|
package com.muzihok.web.entity;
import java.util.Date;
public class BoardView extends Board {
private int commentCount;
public BoardView() {
super();
}
public BoardView(int commentCount) {
super();
this.commentCount = commentCount;
}
public BoardView(int id, String title, String writerId, String content, Date regdate, int hit, int recommend,
String categoryId, int commentCount) {
super(id, title, writerId, content, regdate, hit, recommend, categoryId);
this.commentCount = commentCount;
}
public BoardView(int id, String title, String writerId, String content, Date regdate, int hit, int recommend,
String categoryId, String dcId, int commentCount) {
super(id, title, writerId, content, regdate, hit, recommend, categoryId, dcId);
this.commentCount = commentCount;
}
public int getCommentCount() {
return commentCount;
}
public void setCommentCount(int commentCount) {
this.commentCount = commentCount;
}
@Override
public String toString() {
return "BoardView [commentCount=" + commentCount + "]";
}
}
|
Java
|
UTF-8
| 1,538 | 2.359375 | 2 |
[] |
no_license
|
package com.nationwide.individualproject.data;
import javax.persistence.*;
@Entity
@Table(name="`lead`")
public class Lead {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String grade;
private String height;
private String dateNum;
private String location;
private String climber;
private String partner;
public Lead(String G, String H, String D, String L, String C, String P){
grade = G;
height = H;
dateNum = D;
location = L;
climber = C;
partner = P;
}
public Lead(){}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getDateNum() {
return dateNum;
}
public void setDateNum(String dateNum) {
this.dateNum = dateNum;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getClimber() {
return climber;
}
public void setClimber(String climber) {
this.climber = climber;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getPartner() {
return partner;
}
public void setPartner(String partner) {
this.partner = partner;
}
public long getId() {
return id;
}
}
|
C++
|
UTF-8
| 1,125 | 3.453125 | 3 |
[] |
no_license
|
#include<iostream>
#include<chrono>
struct Timer {
std::chrono::steady_clock::time_point start, end;
std::chrono::duration<float> duration;
const char* name;
Timer(const char* name) :name(name) {
start = std::chrono::high_resolution_clock::now();
}
~Timer() {
end = std::chrono::high_resolution_clock::now();
duration = end - start;
float ms = duration.count() * 1000.0f;
std::cout << name << " timer took " << ms << " ms\n";
}
};
int** a2d = new int* [25];
void singleDArray() {
Timer timer("1d");
int* a1d = new int[5 * 5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
a1d[j + i * 5] = 2;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
std::cout << a1d[j + i * 5] << "\n";
}
}
}
void multiDArray() {
Timer timer("2d");
int** a2d = new int* [5];
for (int i = 0; i < 5; i++) {
a2d[i] = new int[5];
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
a2d[i][j] = 2;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
std::cout << a2d[i][j] << "\n";
}
}
}
int main() {
singleDArray();
multiDArray();
}
|
Java
|
WINDOWS-1252
| 2,593 | 2.078125 | 2 |
[] |
no_license
|
package spring.myapp.shoppingmall.service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import spring.myapp.shoppingmall.controller.MallController;
import spring.myapp.shoppingmall.dao.MallDao;
@Service
public class InsertVbank {
@Autowired
private MallDao Malldao;
@Autowired
TransactionTemplate transactionTemplate2;
@Autowired
TransactionTemplate transactionTemplate3;
public void InsertVbank(String merchant_id,String vbanknum,String vbankname,String vbankdate,String vbankholder,String vbankperson,String vbankcode)
{
Malldao.insertvbank(merchant_id,vbanknum,vbankname,vbankdate,vbankholder,vbankperson,vbankcode);
}
public void InsertVbankAndUpdateStatus(String merchant_uid, String vbanknum, String vbankname, String vbankdate,
String vbankholder, String buyer_name, String vbank_code, String status, String imp_uid, String paymethod,
String merchant_id, String[] list, Integer[] integerilist, String price)
{
transactionTemplate2.execute(new TransactionCallbackWithoutResult(){
public void doInTransactionWithoutResult(TransactionStatus transstatus) {
try {
//Malldao.insertgoods(merchant_id,list,integerilist);
Malldao.insertVbankgoods(merchant_id, list, integerilist);
Malldao.insertPrice(Integer.valueOf(price),merchant_uid);
Malldao.insertvbank(merchant_uid, vbanknum, vbankname, vbankdate, vbankholder, buyer_name, vbank_code);
Malldao.statusupdate(status,merchant_uid,imp_uid,paymethod);
} catch(Exception e) {
System.out.println("merchant_id in Rollback : " + merchant_id);
transstatus.setRollbackOnly();
}
}
});
/*
transactionTemplate3.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transstatus) {
if(Malldao.getMerchantid(merchant_id).getStatus().equals("not paid")) {
Malldao.statusupdate("vbank error",merchant_uid,imp_uid,paymethod);
System.out.println("rollback :" + merchant_id);
}
}
});
*/
}
}
|
C++
|
UTF-8
| 275 | 2.75 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
cout<<"segmento codigo: "<<(void *) main<<"\r\n";
cout<<"segmento heap : "<<(void *) malloc(1)<<"\r\n";
int x = 3;
cout<<"segmento stack: "<<(void *) &x<<"\r\n";
sleep(6000);
return 0;
}
|
Java
|
UTF-8
| 3,276 | 2.578125 | 3 |
[] |
no_license
|
package be.kdg.se3.transportss.adapters.in;
import be.kdg.se3.proxy.ConveyorServiceProxy;
import be.kdg.se3.transportss.adapters.in.entity.Conveyor;
import be.kdg.se3.transportss.routing.entity.ConveyorTimes;
import be.kdg.se3.transportss.routing.service.ConveyorService;
import be.kdg.se3.transportss.simulator.service.CommunicationException;
import be.kdg.se3.transportss.utility.JSONSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
/**
* ConveyorServiceProxy adapter
*
* Created by Joren Van de Vondel on 11/3/2016.
*/
public class ConveyorServiceREST implements ConveyorService{
private final Map<Integer, Conveyor> conveyorMap = new HashMap<>();
private final Map<Integer, Long> timeMap = new HashMap<>();
private final LocalDateTime startUp = LocalDateTime.now();
private final ConveyorServiceProxy conveyorServiceProxy = new ConveyorServiceProxy();
private final String url;
private final long timeOut;
private final Logger logger = LoggerFactory.getLogger(ConveyorServiceREST.class);
public ConveyorServiceREST(String url, long timeOut) {
this.url = url;
this.timeOut = timeOut;
}
/**
* @param currentConveyorID ID of the current conveyor
* @param sensorID ID of the previous conveyor/ sensor on which the luggage entered the conveyor
* @param nextConveyorID ID of the conveyor we wish to reach
* @return ConveyorTimes object used by simulator to calculate arrival on next conveyor
* @throws CommunicationException
*/
@Override
public ConveyorTimes getTimeToTravel(int currentConveyorID,int sensorID, int nextConveyorID) throws CommunicationException{
logger.info("Retrieving time to travel information");
logger.debug("Retrieving time to travel information for conveyorID:"+currentConveyorID);
Conveyor conveyor;
if(timeMap.containsKey(currentConveyorID) && timeMap.get(currentConveyorID)<=startUp.until(LocalDateTime.now(), ChronoUnit.MILLIS)){
conveyor = conveyorMap.get(currentConveyorID);
}else{
conveyor = getConveyorObject(currentConveyorID);
timeMap.put(currentConveyorID, startUp.until(LocalDateTime.now(), ChronoUnit.MILLIS));
conveyorMap.put(currentConveyorID, conveyor);
}
return new ConveyorTimes(
conveyor.getTimeToConnector(sensorID, nextConveyorID),
conveyor.getTimeOverConnector(nextConveyorID),
conveyor.getRoundTripTime());
}
private Conveyor getConveyorObject(int currentConveyorID) throws CommunicationException{
try {
logger.debug("Conveyor object not cached, retrieving...");
Conveyor conveyor = JSONSerializer.ObjectFromString(conveyorServiceProxy.get(url+currentConveyorID), Conveyor.class);
logger.debug("Got conveyor object from proxy");
return conveyor;
} catch (IOException e) {
throw new CommunicationException("ConveyorServiceProxy return IO Exception", e);
} catch (CommunicationException e){
throw e;
}
}
}
|
Shell
|
UTF-8
| 683 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
<% if link('routing_api_db').p('release_level_backup') %>
set -ex
JOB_PATH="/var/vcap/jobs/bbr-routingdb"
SDK_PATH="/var/vcap/jobs/database-backup-restorer"
# Anything placed in the BBR_ARTIFACT_DIRECTORY by the backup script will be available to the restore script at restore time.
# The BBR CLI is responsible for setting the BBR_ARTIFACT_DIRECTORY
BBR_ARTIFACT_FILE_PATH="${BBR_ARTIFACT_DIRECTORY}/routing-api-db-backup"
CONFIG_PATH="${JOB_PATH}/config/config.json"
"${SDK_PATH}/bin/backup" --config "${CONFIG_PATH}" --artifact-file "${BBR_ARTIFACT_FILE_PATH}"
<% else %>
echo "script deactivated due to release_level_backup being set to FALSE\n"
<% end %>
|
Java
|
UTF-8
| 520 | 1.859375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.kloia.evented;
import com.datastax.driver.core.querybuilder.Clause;
import java.util.List;
import java.util.UUID;
/**
* Created by zeldalozdemir on 23/02/2017.
*/
public interface Query<T extends Entity> {
T queryEntity(String entityId) throws EventStoreException;
List<T> queryByOpId(UUID opId) throws EventStoreException;
List<T> queryByField(List<Clause> clauses) throws EventStoreException;
List<T> multipleQueryByField(List<List<Clause>> clauses) throws EventStoreException;
}
|
JavaScript
|
UTF-8
| 5,383 | 3.359375 | 3 |
[] |
no_license
|
import {Matrix} from "../Math/Matrix";
import {Vector2f} from "../Math/Vector2f";
export class AutoTile {
/**
* GroupedTile constructor.
*
* @param name
* @param tiles
*/
constructor(name, tiles) {
this.name = name;
this.tiles = new Matrix(new Vector2f(3, 4));
if (tiles) {
this.setTiles(tiles);
}
}
/**
* Creates a new auto tile instance.
*
* @param name
* @param tiles
* @returns {AutoTile}
*/
static create(name, tiles) {
return new AutoTile(name, tiles);
}
/**
* Automatically generates the auto tile map from a specific index.
*
* @param index The root frame index.
* @param area The area of the tile map in tiles.
* @returns this
*/
getFromIndex(index, area) {
for (let y = -2; y <= 1; y++) {
for (let x = -1; x <= 1; x++) {
this.setTile(new Vector2f(x + 1, y + 2), index + (y * area.getX()) + x);
}
}
return this;
}
/**
* Assigns the name.
*
* @param name
* @returns {AutoTile}
*/
setName(name) {
this.name = name;
return this;
}
/**
* Returns the name.
*
* @returns {*}
*/
getName() {
return this.name;
}
/**
* Assigns the tiles matrix.
*
* @param tiles
* @returns {AutoTile}
*/
setTiles(tiles) {
if (!tiles instanceof Matrix) {
return this;
}
this.tiles = tiles;
return this;
}
/**
* Returns the tiles matrix.
*
* @returns {Matrix}
*/
getTiles() {
return this.tiles;
}
/**
* Returns a tile index at the specified position.
*
* @param position
* @returns {number}
*/
getTile(position) {
return this.getTiles().getValue(position);
}
/**
* Assigns a tile index to the position.
*
* @param position
* @param tile
* @returns {AutoTile}
*/
setTile(position, tile) {
this.getTiles().setValue(position, tile);
return this;
}
/**
* Returns whether or not the bitmasking value is valid based on this auto tile map.
*
* @param value
* @returns {boolean}
*/
static isBitmaskValid(value) {
return ![1, 2, 4, 8, 6, 9].includes(value);
}
/**
* Indicates whether or not the bitmasking value indicates a floor tile (bottom row).
*
* @param value
* @returns {boolean}
*/
static isBitmaskFloor(value) {
return [3, 5, 7].includes(value);
}
/**
* Indicates whether or not the bitmasking value indicates a ceiling tile (second row).
*
* @param value
* @returns {boolean}
*/
static isBitmaskCeiling(value) {
return [10, 12, 14].includes(value);
}
/**
* Returns the root tile index.
*
* @returns {number}
*/
getRootTile() {
return this.getTile(new Vector2f(1, 2));
}
/**
* Indicates whether or not a tile exists.
*
* @param index
* @returns {boolean}
*/
hasTile(index) {
for (let i = 0; i < this.getTiles().getData().length; i++) {
for (let j = 0; j < this.getTiles().getData()[i].length; j++) {
if (this.getTiles().getData()[i][j] === index) {
return true;
}
}
}
return false;
}
/**
* Casts the tile series to an array.
*
* @returns {Array}
*/
toArray(){
let tiles = [];
for (let i = 0; i < this.getTiles().getData().length; i++) {
for (let j = 0; j < this.getTiles().getData()[i].length; j++) {
tiles.push(this.getTiles().getData()[i][j]);
}
}
return tiles;
}
/**
* Returns the appropriate tile from a bitmasking value.
*
* @param value
* @see https://gamedevelopment.tutsplus.com/tutorials/how-to-use-tile-bitmasking-to-auto-tile-your-level-layouts--cms-25673
*/
getFromBitmask(value) {
if (!AutoTile.isBitmaskValid(value)) {
return this.getRootTile();
}
switch (value) {
// No neighbors.
case 0:
return this.getTile(new Vector2f(0, 0));
// Bottom right.
case 3:
return this.getTile(new Vector2f(2, 3));
// Bottom left.
case 5:
return this.getTile(new Vector2f(0, 3));
// Bottom.
case 7:
return this.getTile(new Vector2f(1, 3));
// Top right.
case 10:
return this.getTile(new Vector2f(2, 1));
// Right.
case 11:
return this.getTile(new Vector2f(2, 2));
// Top left.
case 12:
return this.getTile(new Vector2f(0, 1));
// Left.
case 13:
return this.getTile(new Vector2f(0, 2));
// Top.
case 14:
return this.getTile(new Vector2f(1, 1));
// All neighbors.
case 15:
return this.getRootTile();
}
}
}
|
C#
|
UTF-8
| 691 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
using System;
class DecimalToBinary
{
static void Main()
{
Console.Write("Please enter the decimal number you want to convert: ");
int number = int.Parse(Console.ReadLine());
int devided = number;
int remainder = 0;
string reversedBinNum = string.Empty;
while (devided > 0)
{
remainder = devided % 2;
reversedBinNum += remainder;
devided /= 2;
}
char[] arr = reversedBinNum.ToCharArray();
Array.Reverse(arr);
string binNum = string.Join("", arr);
Console.WriteLine("The binary representation of decimal number {0} is {1}", number, binNum);
}
}
|
Markdown
|
UTF-8
| 3,104 | 3 | 3 |
[] |
no_license
|
---
title: "Adding Last-Modified response header to Haskell Servant API"
tags: ['code', 'haskell', 'servant']
date: 2018-09-30
layout: 'post'
---
Given the following [Servant API](https://haskell-servant.github.io/)
(boilerplate redacted for brevity):
``` haskell
type MyAPI = "some-api" :> Get '[JSON] NoContent
someApi = return NoContent
```
How do you add a `Last-Modified` header? As a first attempt, we can use the
`Header` type with [`addHeader`](http://hackage.haskell.org/package/servant-0.14.1/docs/Servant-API-ResponseHeaders.html#v:addHeader) and a `UTCTime`:
``` haskell
import Data.Time.Clock (UTCTime, getCurrentTime)
type LastModifiedHeader = Header "Last-Modified" UTCTime
type MyAPI = "some-api" :> Get '[JSON] (Headers '[LastModifiedHeader] NoContent)
someApi = do
now <- getCurrentTime
addHeader now
return NoContent
```
Unfortunately, this returns the time in the wrong format!
```
> curl -I localhost/some-api | grep Last-Modified
Last-Modified: 2018-09-30T19:56:39Z
```
It [should be RFC
1123](https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1). We can
fix this with a `newtype` that wraps the
formatting functions available in `Data.Time.Format`:
``` haskell
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Data.ByteString (pack)
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Format (formatTime, defaultTimeLocale, rfc1123DateFormat)
newtype RFC1123Time = RFC1123Time UTCTime
deriving (Show, FormatTime)
instance ToHttpApiData RFC1123Time where
toUrlPiece = error "Not intended to be used in URLs"
toHeader =
let rfc1123DateFormat = "%a, %_d %b %Y %H:%M:%S GMT" in
pack . formatTime defaultTimeLocale rfc1123DateFormat
type LastModifiedHeader = Header "Last-Modified" RFC1123Time
type MyAPI = "some-api" :> Get '[JSON] (Headers '[LastModifiedHeader] NoContent)
someApi = do
now <- getCurrentTime
addHeader $ RFC1123Time now
return NoContent
```
```
> curl -I localhost/some-api | grep Last-Modified
Last-Modified: Sun, 30 Sep 2018 20:44:16 GMT
```
If anyone knows a simpler way, please let me know!
### Irreverant technical asides
Many implementations reference RFC822 for `Last-Modified` format. What gives?
RFC822 was updated by RFC1123, which only adds a few clauses to tighten up the
definition. Most importantly, it updates the year format from 2 digits to 4!
Note that
[`Date.Time.Format.rfc882DateFormat`](http://hackage.haskell.org/package/time-1.9.2/docs/Data-Time-Format.html#v:rfc822DateFormat)
is technically incorrect here, specifying a four digit year.
[`Data.Time.Format.RFC822`](http://hackage.haskell.org/package/time-http-0.5/docs/Data-Time-Format-RFC822.html)
gets it right.
`rfc822DateFormat` is also technically incorrect in another way: it uses the
`%Z` format specifier for timezone, which produces `UTC` on a `UTCTime`. This
is not an allowed value! However,
[RFC 2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1) says
"for the purposes of HTTP, GMT is exactly equal to UTC" so GMT can safely be
hardcoded here since we know we always have a UTC time.
|
Shell
|
UTF-8
| 857 | 2.953125 | 3 |
[] |
no_license
|
#!/bin/bash
# Run pre-removal scripts on upgrade if defined
if [ $1 = upgrade ] && [ -n $2 ] ; then
: no preremove scripts provided
fi
# Run pre-removal scripts on removal if defined
if [ $1 = remove ] && [ -z $2 ] ; then
: no preremove scripts provided
fi
# switch based on systemd vs systemv
#
if [ "$1" = remove ]; then
systemctl --no-reload disable puppet.service > /dev/null 2>&1 || :
systemctl stop puppet.service > /dev/null 2>&1 || :
fi
# switch based on systemd vs systemv
#
if [ "$1" = remove ]; then
systemctl --no-reload disable mcollective.service > /dev/null 2>&1 || :
systemctl stop mcollective.service > /dev/null 2>&1 || :
fi
# switch based on systemd vs systemv
#
if [ "$1" = remove ]; then
systemctl --no-reload disable pxp-agent.service > /dev/null 2>&1 || :
systemctl stop pxp-agent.service > /dev/null 2>&1 || :
fi
|
C#
|
UTF-8
| 593 | 2.546875 | 3 |
[] |
no_license
|
using AdapterPatternApp.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdapterPatternApp
{
class AdapterPatternDemo
{
static void Main(string[] args)
{
AudioPlayer _audioPlayer = new AudioPlayer();
_audioPlayer.play("mp4", "shabi111.mp4");
_audioPlayer.play("VLC", "shabi222.vlc");
_audioPlayer.play("MP4", "shabi333.mp4");
_audioPlayer.play("mp3", "shabi444.mp3");
Console.ReadKey();
}
}
}
|
Java
|
UTF-8
| 2,087 | 2.40625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.chen.schart.http;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by lichen on 2017/11/29.
*/
public class HttpAPI {
public static HttpService get() {
return get(HttpUrl.getBaseUrl());
}
public static HttpService get(String baseUrl) {
return new HttpAPI().create(baseUrl, HttpService.class);
}
public <T> T create(String baseUrl, Class<T> service) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(getClient())
.build();
return retrofit.create(service);
}
protected OkHttpClient getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", "APPCODE de09d555c76d47bebc49c59d6a936495")
.build();
return chain.proceed(request);
}
})
.addInterceptor(interceptor)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS);
return builder.build();
}
}
|
Markdown
|
UTF-8
| 372 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
# Description
Given an integers array `A`.
Define `B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]`, calculate B **WITHOUT** divide operation.Out put `B`
# Example
## Example 1
```
Input: A = [1, 2, 3]
Output: [6, 3, 2]
Explanation:B[0] = A[1] * A[2] = 6; B[1] = A[0] * A[2] = 3; B[2] = A[0] * A[1] = 2
```
Example 2
```
Input: A = [2, 4, 6]
Output: [24, 12, 8]
```
|
PHP
|
UTF-8
| 1,014 | 2.625 | 3 |
[] |
no_license
|
<?php
namespace WikidataSearch\Console;
use WikibaseDumpProcessor\Services;
use WikidataSearch\Console\Commands\BuildMappingCommand;
use WikidataSearch\Console\Commands\CreateIndexCommand;
use WikidataSearch\Console\Commands\DeleteIndexCommand;
use WikidataSearch\Console\Commands\ProcessDumpCommand;
class CommandRegistry {
private $services;
public function __construct( Services $services ) {
$this->services = $services;
}
public function getCommands() {
$commands = array(
$this->newBuildMappingCommand(),
new CreateIndexCommand(),
new DeleteIndexCommand(),
$this->newProcessDumpCommand()
);
return $commands;
}
private function newBuildMappingCommand() {
$command = new BuildMappingCommand();
$command->setServices(
[ 'ar', 'de', 'en', 'es', 'fr', 'ja' ]
);
return $command;
}
private function newProcessDumpCommand() {
$command = new ProcessDumpCommand();
$command->setServices(
$this->services->newEntityDeserializer()
);
return $command;
}
}
|
JavaScript
|
UTF-8
| 1,258 | 3.203125 | 3 |
[] |
no_license
|
const users = ['Perfil 1','Alguien','Nicolái'];
const memberDiv = document.querySelector('.memberDiv');
const addIcon = document.querySelector('.addIcon');
const userIcons = () => {
users.reverse();
users.map((curElem) => {
memberDiv.insertAdjacentHTML('afterbegin', `
<button class="btn"><span>${curElem}</span></button>
`);
})
// establecemos los ususarios disponibles
};
addIcon.addEventListener('click', () => {
// mostramos un prompt para ingresar el nuevo usuario
let userName = prompt('please enter your name');
// aqui verificamos que el user name no sea nulo y que no exista --- tambien no debe haber mas de 3 usuarios
const btns = document.querySelectorAll('.btn');
if(userName != null && !users.includes(userName) && btns.length < 4){
users.push(userName); // Agregamos el nombre de ususario ingresado
console.log(users); // lo mostramos en consola
memberDiv.insertAdjacentHTML('afterbegin', `
<button class="btn"><span>${userName}</span></button>
`); // agregamos a ladao del que ya teniamos vease en el inspector
}else{
alert('El usuario ya existe, no es valido o ya se tiene suficientes perfiles');
}
})
userIcons();
|
JavaScript
|
UTF-8
| 3,257 | 3.96875 | 4 |
[] |
no_license
|
// List of words to guess
var wordArray = ["ACDC",
"AEROSMITH",
"RADIOHEAD",
"METALLICA",
"NIRVANA",
"PRINCE",
"COLDPLAY",
"TRAIN",
"EMINEM",
"BEYONCE"];
// Word to guess
var word = "";
// guesses remaining
var lives = 10;
// Number of wins
var wins = 0;
// Letters in the chosen word
var letters = [];
// guessed letters
var guessedLetters = [];
// matched letters
var matchedLetters = [];
// Functions
// Set the game up
function setup() {
// Choose a word
var wordIndex = Math.floor(Math.random() * 10);
console.log(wordIndex, "Word Index");
var word = wordArray[wordIndex];
console.log(word, "Word");
//Split word into letters
letters = word.split("");
//Writes the underlines to the screen and updates as the user guesses
wordDisplay();
//Updates the users total guesses
totalGuesses();
}
//Runs when a user guesses
function onGuess(key) {
if (lives === 0) {
restartGame();
} else {
//incorrect guess
incorrectGuess(key);
//matched guess
correctGuess(key);
//Update display
wordDisplay();
//check for winner
if (updateWins() === true) {
restartGame();
}
}
}
function incorrectGuess(key) {
if((guessedLetters.indexOf(key) === -1) && (letters.indexOf(key) === -1)) {
//add to guessed letters array
guessedLetters.push(key);
//decrease lives
lives--;
document.querySelector("#lives").innerHTML = lives;
document.querySelector("#guessed").innerHTML = guessedLetters.join(", ");
}
}
function correctGuess(key) {
for (var i = 0; i < letters.length; i++) {
if ((key === letters[i]) && (matchedLetters.indexOf(key) === -1)) {
matchedLetters.push(key);
}
}
}
function totalGuesses() {
lives = letters.length + 6;
document.querySelector("#lives").innerHTML = lives;
}
function wordDisplay() {
var display = "";
for (var i = 0; i < letters.length; i++) {
if (matchedLetters.indexOf(letters[i]) !== -1) {
display += letters[i];
}
else {
display += " _ ";
}
}
document.querySelector("#myword").innerHTML = display;
}
function restartGame() {
document.querySelector("#guessed").innerHTML = "";
word = null;
letters = [];
matchedLetters = [];
guessedLetters = [];
lives = 0;
key = null;
setup();
onGuess();
}
function updateWins() {
var win;
if (matchedLetters.length === 0) {
win = false;
} else {
win = true;
}
for (var i = 0; i < letters.length; i++) {
if (matchedLetters.indexOf(letters[i]) === -1) {
win = false;
}
}
if (win) {
wins++;
document.querySelector("#wins").innerHTML = wins;
return true;
}
return false;
}
setup();
document.onkeyup = function(event) {
var key = event.key;
letterGuessed = key.toUpperCase();
onGuess(letterGuessed);
};
|
JavaScript
|
UTF-8
| 409 | 3.71875 | 4 |
[
"MIT"
] |
permissive
|
//
// Generate the Fibonacci sequence up to the maximum 32 bits signed integer
//
var x0 = 0, x1 = 1, x;
try {
var i = 1;
while (1) {
// Check whether the next sum will overflow or not
if (0x7fffffff - x1 <= x0) {
throw 1; // overflow
}
x = x1 + x0;
x0 = x1;
x1 = x;
printf("%2d | %10u\n", i, x);
i = i + 1;
}
} catch (err) {
printf(" - overflow error!\n");
}
|
Java
|
UTF-8
| 526 | 2.03125 | 2 |
[] |
no_license
|
package custom.zUtil.io;
import basic.zBasic.ExceptionZZZ;
import basic.zUtil.io.KernelFileExpansionZZZ;
public class FileExpansionZZZ extends KernelFileExpansionZZZ{
public FileExpansionZZZ() throws ExceptionZZZ {
super();
}
public FileExpansionZZZ(char cFilling, int iExpansionLength) {
super(cFilling, iExpansionLength);
}
public FileExpansionZZZ(FileZZZ objFileBase) {
super(objFileBase);
}
public FileExpansionZZZ(FileZZZ objFileBase, int iExpansionLength) {
super(objFileBase, iExpansionLength);
}
}
|
TypeScript
|
UTF-8
| 753 | 2.625 | 3 |
[] |
no_license
|
// const response = await fetch("http://my.json.host/data.json");
// console.log(response.status); // e.g. 200
// console.log(response.statusText); // e.g. "OK"
// const jsonData = await response.json();
// async function downloadData(){
// const response = await fetch("https://api.spacexdata.com/v4/launches",{method: "GET"});
// const launchData = await response.json();
// console.log(launchData);
// }
// await downloadData();
console.log("Hello", Deno.env.get("USER"));
// async function downloadRobinhoodData(){
// const response = await fetch("https://api.robinhood.com/instruments/",{method: "GET"});
// const launchData = await response.json();
// console.log(launchData);
// }
// await downloadRobinhoodData();
|
JavaScript
|
UTF-8
| 1,704 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
import User from '../models/user';
import Helper from '../helper/helper';
const { comparePassword, generateToken, hashPassword } = Helper;
/**
*
*
* @export
* @class UserService
*/
export default class UserService {
/**
*
* Handles the logic to login user
* @static
* @param {Objeect} credential these are the data to login user
* @returns {Object}
* @memberof UserService
*/
static async login(credential) {
const { email, password } = credential;
const user = await User.findOne('email', email);
const isSamePassword = await comparePassword(password, user.password);
if (!user || !isSamePassword) {
return {
code: 401,
error: 'error',
result: 'Provided login credential is incorrect. Check email or password'
};
}
return {
code: 200,
status: 'success',
result: {
token: generateToken(user),
userId: user.id
}
};
}
/**
*
* Handles the logic to create a new user
* @static
* @param {Object} data data of the new user to be created
* @returns {Object}
* @memberof UserService
*/
static async create(data) {
const { firstName, lastName, email, password, gender, jobRole, department, address } = data;
const hashedPassword = await hashPassword(password);
const user = await User.save(
firstName,
lastName,
email,
hashedPassword,
gender,
jobRole,
department,
address
);
return {
code: 201,
status: 'success',
result: {
message: 'User account successfully created',
token: generateToken(user),
userId: user.id
}
};
}
}
|
C++
|
UTF-8
| 2,822 | 2.859375 | 3 |
[] |
no_license
|
#ifndef ADV_HUFFMAN_H
#define ADV_HUFFMAN_H
#include "Node.h"
#include <QString>
#include <iostream>
using namespace std;
class AdvHuffman {
public:
AdvHuffman();
void Decoding(const char* inputFile, QString outPath);
void Encoding(const char* inputFile, const char* outputFile, double *entrpy, double *bps);
void Display(int T);
double Entropy();
private :
int* TabKar;
/* Menyimpan alamat karakter yang ada pada TabNode*/
Node* TabNode;
/* Analogi pohon untuk Adaptive Huffman*/
int* NomorNode;
/* Berisi alamat dari pohon yang terurut dari bawah ke atas menaik serta dari kiri ke kanan*/
int NYT;
/* Menyimpan alamat NYK*/
//METHOD FOR TABKAR
bool searchChar(unsigned char K);
/*Menghasilkan true ketika kar dberada pada pohon*/
int adressChar(unsigned char K);
/*Menghasilkan alamat kar pada pohon. -1 bila tidak ada*/
void setAdrressChar(unsigned char K, int Address);
/*Set array TabKar di indeks K dengann Address*/
//METHOD FOR TABNODE
void insertAfter(unsigned char K);
/* Insert node dengan kar=K dan weight = 1 pada left NYK. Sedangkan right NYK diinsert node NYK baru*/
void switchNode(int A, int B);
/* Menukar 2 buah node pada pohon yang sama */
char codeToChar(string s);
/* convert barisan bit ke char */
string charToCode(char c);
/* convert c ke barisan bit */
string charCodeFromTree(int T, unsigned char kar);
/* menghasilkan barisan bit char dari pohon*/
string NYTcodeFromTree(int T);
/* menghasilkan barisan bit NYT dari pohon*/
bool searchCharTree(int T, unsigned char c);
/* menghasilkan true jika c berada di pohon*/
bool searchNYTTree(int T);
/* menghasilkan true jika NYT berada di pohon*/
//SUPPORTED METHOD
bool isLeaf(int T);
/* mengembalikan true jika T adalah daun */
bool isLeft(int T);
/* mengembalikan true jika T merupakan anak kiri dari parent-nya*/
bool isRight(int T);
/* mengembalikan true jika T merupakan anak kana dari parent-nya*/
//SUPPORTED METHOD FOR ADAPTIVE HUFFMAN
void Update(int T, bool baru);
/* Update pohon saat menginput node baru. T merupakan node baru yang diinput atau frequensi node lama yang ditambah*/
//SUPPORTED METHOD FOR UPDATE()
void UpdateNomorNode();
/* Mengurutkan isi NomorNode */
int MaxNumberNodeInBlock(int P);
/* Mencari nomor node maksimum yang memiliki weight yang sama dengan P */
//SUPPORTED METHOD FOR UPDATE NUMBER
int DeepTree(int T);
/* Menghasilkan nilai dari kedalaman sebuah pohon*/
void setNomorNodeLevel(int T, int N, int *StartNumber);
/* Menginput alamat node ke NomorNode terurut membesar dari kiri ke kana*/
void BarisBin(char* inputFile, char* outputFile);
};
#endif // ADV_HUFFMAN_H
|
C
|
UTF-8
| 2,332 | 3.390625 | 3 |
[] |
no_license
|
//1:
//Which storage classes create variables local to the function containing them?
//automatic, internal linkage, block scope
//2:
//Which storage classes create variables that persist for the duration of the containing program?
//any class that has static duration
//3:
//Which storage class creates variables that can be used across several files? Restricted to just one file?
//file scope, using extern to define them
//4:
//What kind of linkage do block scope variables have?
//internal
//5:
//What is the extern keyword used for?
//to reference a variable that has been declared in another file.
//6:
//Consider this code fragment:
int * p1 = (int *) malloc(100 * sizeof(int));
//In terms of the final outcome, how does the following statement differ?
int * p1 = (int *) calloc(100, sizeof(int));
//malloc and calloc differ because calloc initializes all the memory to 0. much like initializing a string.
//7:
//Which functions know each variable in the following? Are there any errors?
/* file 1 */
int daisy;
int main(void)
{
int lily;
}
int petal()
{
extern int daisy, lily;
}
/* file 2 */
extern int daisy;
static int lily;
int rose;
int stem()
{
int rose;
}
void root()
{
}
//daisy in file #1 has file scope so it is visible to both files and all functions in them.
//however the fucntion petal() has declared its own version of daisy. which actually isn't a valid decleration.
//lily is automatic/block scope in main, so it is not visible to petal()
//
//8:
//What will the following program print?
#include <stdio.h>
char color= 'B';
void first(void);
void second(void);
int main(void)
{
extern char color;
printf("color in main() is %c\n", color);
first();
printf("color in main() is %c\n", color);
second();
printf("color in main() is %c\n", color);
return 0;
}
void first(void)
{
char color;
color = 'R';
printf("color in first() is %c\n", color);
}
void second(void)
{
color = 'G';
printf("color in second() is %c\n", color);
}
//9:
//A file begins with the following declarations:
static int plink;
int value_ct(const int arr[], int value, int n);
//What do these declarations tell you about the programmer's intent?
//Will replacing int value and int n with const int value and const int n enhance the protection of values in the calling program?
|
C++
|
GB18030
| 6,077 | 2.890625 | 3 |
[] |
no_license
|
#include "MathMethod.h"
#include "Math.h"
#include "ObjectManager.h"
#include "PD.h"
#include <algorithm>
bool MathMethod::equal(double a, double b, double speed){
return (fabs(a - b) <= speed / 2);
}
int MathMethod::smaller(int a, int b){
if (a<b)
return a;
else
return b;
}
int MathMethod::bigger(int a, int b){
if (a>b)
return a;
else
return b;
}
bool MathMethod::isInField(double x1, double y1, double x2, double y2, double radio){
return ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) <= radio*radio);
}
double MathMethod::getDistance(double x1, double y1, double x2, double y2){
return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}
double MathMethod::getBevel(double x, double y) {
return sqrt(x*x + y*y);
}
/**
* õ֮Ļ
* @param px1 һX
* @param py1 һY
* @param px2 ڶX
* @param py2 ڶY
* @return
*/
double MathMethod::getRad(double px1, double py1, double px2, double py2) {
//õXľ
double x = px2 - px1;
//õYľ
double y = py2 - py1;
//б߳
double Hypotenuse = (double)sqrt(pow(x, 2) + pow(y, 2));
//õǶȵֵͨǺеĶ ڱ/б=Ƕֵ
double cosAngle = x / Hypotenuse;
//ͨҶȡǶȵĻ
double rad = (double)acos(cosAngle);
//λY<ҡ˵YҪȡֵ-0~-180
if (py2 < py1) {
rad = -rad;
}
return rad;
/*double angle=90-pitoarc(rad);
if(angle>180)
angle-=360;
return angle;*/
}
double MathMethod::getAngle(double px1, double py1, double px2, double py2) {
return rad2Angle(getRad(px1, py1, px2, py2));
}
double MathMethod::getRad(double px1, double py1, double px2, double py2, double bevel) {
//õXľ
double x = px2 - px1;
//õYľ
double y = py2 - py1;
//б߳
//double Hypotenuse = (double) Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
//õǶȵֵͨǺеĶ ڱ/б=Ƕֵ
double cosAngle = x / bevel;
//ͨҶȡǶȵĻ
double rad = (double)acos(cosAngle);
//λY<ҡ˵YҪȡֵ-0~-180
if (py2 < py1) {
rad = -rad;
}
return rad;
}
double MathMethod::getAngle(double px1, double py1, double px2, double py2, double bevel) {
return rad2Angle(getRad(px1, py1, px2, py2, bevel));
}
double MathMethod::angle2Rad(double a){
return a / 180 * M_PI;
}
double MathMethod::rad2Angle(double a){
return a / M_PI * 180;
}
double MathMethod::getWidth(char* bmp, double height){
CCSprite* sprite = CCSprite::create(bmp);
double bmp_width = sprite->getTextureRect().getMaxX();
double bmp_height = sprite->getTextureRect().getMaxY();
return bmp_width / bmp_height*height;
}
double MathMethod::getHeight(char* bmp, double width){
CCSprite* sprite = CCSprite::create(bmp);
double bmp_width = sprite->getTextureRect().getMaxX();
double bmp_height = sprite->getTextureRect().getMaxY();
return bmp_height / bmp_width *width;
}
double MathMethod::getWidth(CCTexture2D* texture, double height){
return texture->getContentSize().width / texture->getContentSize().height * height;
}
double MathMethod::getHeight(CCTexture2D* texture, double width){
return texture->getContentSize().height / texture->getContentSize().width * width;
}
double MathMethod::width_div_height(CCTexture2D* texture){
return texture->getContentSize().width / texture->getContentSize().height;
}
double MathMethod::height_div_width(CCTexture2D* texture){
return texture->getContentSize().height / texture->getContentSize().width;
}
bool MathMethod::pointInRect(CCPoint point, double x, double y, double width, double height){
return (point.x >= x&&point.x <= x + width&&
point.y >= y&&point.y <= y + height);
}
vector<MyPoint>* MathMethod::clonePath(vector<MyPoint>* path){
if (path == NULL)
return NULL;
vector<MyPoint>* new_path = new vector<MyPoint>();
for (int i = 0; i < path->size(); i++){
new_path->push_back(path->at(i));
}
return new_path;
}
void MathMethod::releaseSprite(MySprite* &sprite){
if (sprite != NULL){
PD::gs->removeChild(sprite);
PD::om->sprite->erase(remove(PD::om->sprite->begin(), PD::om->sprite->end(), sprite), PD::om->sprite->end());
delete sprite;
sprite = NULL;
}
}
void MathMethod::releaseRectangle(MyRectangle* &rectangle){
if (rectangle != NULL){
PD::gs->removeChild(rectangle);
PD::om->rectangle->erase(remove(PD::om->rectangle->begin(), PD::om->rectangle->end(), rectangle), PD::om->rectangle->end());
delete rectangle;
rectangle = NULL;
}
}
void MathMethod::releasePath(vector<MyPoint>* &path){
if (path != NULL){
path->clear();
delete path;
path = NULL;
}
}
bool MathMethod::stringStartWith(char *str1, char *str2){
for (int i = 0; str2[i] != '\0'; i++){
if (str1[i] == '\0' || str1[i] != str2[i])
return false;
}
return true;
}
double MathMethod::amendTowerAngle(double angle){
double new_angle = 90 - angle;
if (new_angle>180)
new_angle -= 360;
return new_angle;
}
double MathMethod::amendBulletAngle(double angle){
double new_angle = 90 + angle;
if (new_angle<0)
new_angle += 360;
return new_angle;
}
int MathMethod::angle2TowerId(double angle){
double new_angle = angle + 90 + 11.25 / 2;
if (new_angle<0)
new_angle += 360;
return (int)(new_angle / 11.25) + 1;
}
int MathMethod::angle2SmokeRocketId(double angle){
double new_angle = 90 - angle + 11.25 / 2;
if (new_angle<0)
new_angle += 360;
return (int)(new_angle / 11.25);
}
int MathMethod::angle2BulletId(double angle){
double new_angle = 90 + angle;
if (new_angle<0)
new_angle += 360;
return (int)(new_angle / 11.25);
}
CCPoint MathMethod::convertTouchPointToTruePoint(CCPoint point){
if (PD::cm->rate == 1)
return ccp(point.x, point.y);
else
return ccp(point.x / PD::cm->rate + PD::cm->scrx
, point.y / PD::cm->rate + PD::cm->scry);
}
|
C
|
UTF-8
| 1,214 | 3.859375 | 4 |
[] |
no_license
|
/* Lab 4a Task 3 */
#include <stdio.h>
int main (void) {
/*Step a):
Try to predict the result of the following do loop: */
//result: 9834, 938, 93, 9
int i = 9384;
do {
printf("%d \n", i);
i /= 10;
} while (i>0);
printf("\n\n\n");
/* Test you prediction by un-commenting the code, compiling and running it */
/* Step b)
Re-write the loop shown in Step a as a for loop.
<write your code below, and test the program> */
for(int i = 9384; i > 0; i /= 10){
printf("%d \n", i);
}
printf("\n\n\n");
/* Step c):
Try to predict the result of the following for loop: */
//result:5,4;4,3;3,2;2,1;1,0
int j;
for (i=5,j=i-1; i>0; --i,j=i-1) {
printf("i = %d, j = %d\n",i, j);
}
printf("\n\n\n");
/* Test you prediction by un-commenting the code, compiling and running it */
/* Step d)
Re-write the loop shown in Step c as a while loop.
<write your code below, and test the program> */
i = 5;
j = i-1;
while (i > 0){
printf("i = %d, j = %d\n",i, j);
i--;
j = i-1;
}
return 0;
}
|
Python
|
UTF-8
| 25,205 | 2.609375 | 3 |
[] |
no_license
|
import pygame as pg
import pygame as pg
from os import path
from rocket import *
from enums import *
from physics import *
from planet import *
from obstacles import *
import sys
class Game:
def __init__(self):
pg.init()
self.WIDTH, self.HEIGHT = 800, 1000
self.screen = pg.display.set_mode((self.WIDTH, self.HEIGHT))
self.clock = pg.time.Clock()
self.playing = False
self.load_data()
self.all_sprites = pg.sprite.Group()
self.asteroids = pg.sprite.Group()
self.player_group = pg.sprite.Group()
self.planet_group = pg.sprite.Group()
self.trees = pg.sprite.Group()
self.game_over = False
self.dt = 0
self.font_name = pg.font.match_font(FONT_NAME)
self.afterMenu = True
self.load_data()
self.background = self.spaceImage
self.background_rect = self.background.get_rect()
self.second_background = self.spaceImage
self.second_background_rect = self.second_background.get_rect()
# Second background start just after first one
self.second_background_rect.y = self.background_rect.bottom
def init_entities(self):
#Rocket should be created first, because later there will be references to it in Game class
self.planetAppeared = False
self.rocket = Rocket(self,x = self.WIDTH/2,
y = POSITION_CONSTANT * self.HEIGHT,
# weight is used to calculate how hard should
missileThrustMultiplier=self.rocketStats[self.selectedRocket]['missle'],
allowed_collisions=self.rocketStats[self.selectedRocket]['allowed_collisions'],
# lateral Acceleration should be given in meters per second
lateralAcceleration=self.rocketStats[self.selectedRocket]['lateral_acc'],
distanceToPlanet=self.planetStats[self.selectedPlanet]['initialHeight'],
initialVelocity= 100,
image=self.availableRocketsArray[self.selectedRocket]
)
self.planet = Planet(game = self,
weight= self.planetStats[self.selectedPlanet]['weight'],
color = self.planetStats[self.selectedPlanet]['color'],
radius = self.planetStats[self.selectedPlanet]['radius'],
image = self.planetArray[self.selectedPlanet]
)
self.planet_group.add(self.planet)
self.rocket.initMaxMissileThrust(self.planet.freeFallAccelaration)
for i in range(self.planetStats[self.selectedPlanet]['numberOfAster']):
if self.planetStats[self.selectedPlanet]['initialHeight'] > ASTEROID_BELT_HEIGHT:
m = Obstacles(self,self.asteroids,random.choice(self.asteroidsArray),
type=ObstacleType.Asteroid)
else:
m = Obstacles(self,self.asteroids,random.choice(self.asteroidsArray),
type=ObstacleType.Satellit)
self.asteroids.add(m)
self.background = self.spaceImage
def load_data(self):
self.explosionAnimationArray = []
self.meteorExplosionAnimation = []
self.availableRocketsArray = []
self.asteroidsArray = []
self.sattelitsArray = []
self.planetArray = []
self.game_folder = path.dirname(__file__)
self.img_folder = path.join(self.game_folder,"images")
self.planetStats = [
{'initialHeight':20000,'radius':6371000*2, 'weight':5.972 * 10 ** 24, 'color': BLUE,'describeWeight':'Very heavy','describeHeight':'Very high', 'describeAsteroids': 'Some big number', 'numberOfAster':10},
{'initialHeight':10000,'radius':6371000, 'weight':10.972 * 10 ** 24, 'color':RED,'describeWeight':'Normal','describeHeight':'Not very high', 'describeAsteroids':'Even bigger number', 'numberOfAster':20},
]
self.rocketStats = [
{'allowed_collisions':20,'lateral_acc':20,'missle': 2, 'describeArmour':'Strong armour','describeManevrity':'Low maneuverability','decribeBrakingAbility':'Perfect'},
{'allowed_collisions':10,'lateral_acc':20,'missle': 4,'describeArmour':'Medium armour','describeManevrity':'Medium maneuverability','decribeBrakingAbility':'Medium'},
{'allowed_collisions':5,'lateral_acc':30,'missle': 7, 'describeArmour':'Poor armour','describeManevrity':'High maneuverability','decribeBrakingAbility':'Poor'}
]
self.selectedPlanet = 0
self.selectedRocket = 0
self.startedAncillary = False
self.fireTraceArray = {
'weakTrace':pg.image.load(path.join(self.img_folder,"spaceEffects_001.png")).convert_alpha(),
'strongTrace':pg.image.load(path.join(self.img_folder,"spaceEffects_002.png")).convert_alpha()
}
for i in [1,2]:
filename = "Planet{}.jpg".format(i)
img = pg.transform.scale(pg.image.load(path.join(self.img_folder,filename)).convert_alpha(),(self.WIDTH,int(0.1 * self.HEIGHT)))
img.set_colorkey((0,0,0))
self.planetArray.append(img)
for i in range(10,16):
filename = "spaceEffects_0{}.png".format(i)
img = pg.image.load(path.join(self.img_folder,filename)).convert_alpha()
img.set_colorkey((0,0,0))
self.meteorExplosionAnimation.append(img)
for i in range(9):
filename = "regularExplosion0{}.png".format(i)
img = pg.image.load(path.join(self.img_folder,filename)).convert_alpha()
img.set_colorkey((0,0,0))
self.explosionAnimationArray.append(img)
for i in [1,2,3]:
filename = "spaceMeteors_00{}.png".format(i)
filename1 = "spaceBuilding_0{}.png".format(i)
filename2 = "spaceRockets_00{}.png".format(i)
img = pg.image.load(path.join(self.img_folder,filename)).convert_alpha()
img1 = pg.image.load(path.join(self.img_folder,filename1)).convert_alpha()
img2 = pg.image.load(path.join(self.img_folder,filename2)).convert_alpha()
img.set_colorkey((0,0,0))
img1.set_colorkey((0,0,0))
img2.set_colorkey((0,0,0))
self.asteroidsArray.append(img)
self.sattelitsArray.append(img1)
self.availableRocketsArray.append(pg.transform.scale(img2,(ROCKET_W,ROCKET_H)))
self.spaceImage = pg.image.load(path.join(self.img_folder,"Stars.jpg")).convert_alpha()
def run(self):
self.playing = True
self.showMenu()
self.init_entities()
while self.playing:
if self.afterMenu == True:
#Number of miliseconds from last farme
self.dt = self.clock.tick(60) / 1000
for event in pg.event.get():
if event.type == pg.QUIT:
self.playing = False
if not self.rocket.landed:
self.rocket.keys = pg.key.get_pressed()
self.screen.fill((0,0,0))
self.update()
self.draw()
if self.rocket.game_over:
self.process_keys_end_game()
def draw_trace(self):
if self.rocket.missileThrust == 0:
return
elif self.rocket.missileThrust <= 0.5:
image = self.fireTraceArray['weakTrace']
else:
image = self.fireTraceArray['strongTrace']
# self.rocket.missileThrust/self.rocket.maxMissileThrust multiplier that shows how big is power of of thrust
trace = pg.transform.scale(image, (ROCKET_W, int(self.rocket.missileThrust/self.rocket.maxMissileThrust *ROCKET_H)))
trace_rect = trace.get_rect()
trace_rect.x = self.rocket.rect.x
trace_rect.y = self.rocket.rect.center[1] + ROCKET_H/2
self.screen.blit(trace,trace_rect)
def move_background(self,menu = False):
if menu:
new_pos = 20 * self.clock.tick(60) / 1000 /METERS_IN_ONE_PIXEL * SMOOTHING_CONSTANT
if self.background_rect.bottom < 0:
self.background_rect.y = self.second_background_rect.bottom
if self.second_background_rect.bottom < 0:
self.second_background_rect.y = self.background_rect.bottom
self.background_rect.y -= int(new_pos)
self.second_background_rect.y -= int(new_pos)
self.screen.blit(self.background,self.background_rect)
self.screen.blit(self.second_background,self.second_background_rect)
return
else:
new_pos = self.rocket.vel.y * self.dt/METERS_IN_ONE_PIXEL * SMOOTHING_CONSTANT
# In such way i prevent black holes, that could appear between two backgrounds ,
# Int cast made because when we make operations on numerical we can get
# a different speed for two different objects even while adding the same number
self.background_rect.y -= int(new_pos)
self.second_background_rect.y -= int(new_pos)
# self.rocket.vel > 0 -- means that object is moving up
if self.background_rect.bottom < 0 and self.rocket.vel.y > 0:
self.background_rect.y = self.second_background_rect.bottom
elif self.background_rect.top > self.HEIGHT and self.rocket.vel.y < 0:
self.background_rect.y = self.second_background_rect.y -self.background_rect.size[1]
if self.second_background_rect.bottom < 0 and (menu or self.rocket.vel.y > 0 ):
self.second_background_rect.y = self.background_rect.bottom
elif self.second_background_rect.top > self.HEIGHT and self.rocket.vel.y < 0:
self.second_background_rect.y = self.background_rect.y -self.background_rect.size[1]
def draw_background(self):
self.screen.blit(self.background,self.background_rect)
self.screen.blit(self.second_background,self.second_background_rect)
# global function to draw everythin that should be drowna
def draw(self):
# self.screen.blit(self.background,(0,0))
self.draw_background()
if not self.planetAppeared and not self.rocket.game_over:
self.move_background()
self.draw_trace()
self.asteroids.draw(self.screen)
if self.rocket.distanceToPlanet <= self.HEIGHT * METERS_IN_ONE_PIXEL * 2:
self.rocket.inStratosphere = True
if self.rocket.distanceToPlanet <= self.HEIGHT * METERS_IN_ONE_PIXEL:
self.planet_group.draw(self.screen)
self.planetAppeared = True
self.rocket.inStratosphere = True
self.player_group.draw(self.screen)
self.draw_data()
pg.display.flip()
# support function to render and draw test on prefined different positions
def draw_text(self, text, size, color, x, y, font):
font = pg.font.Font(font, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.topleft = (x, y)
self.screen.blit(text_surface, text_rect)
def showMenu(self):
running = True
params = {'planet':False,'rocket':False}
current_param = 0
while running:
last_update = pg.time.get_ticks()
stats = self.planetStats[self.selectedPlanet]
self.move_background(menu = True)
self.draw_text("Navigate with right/left arrows",
21,
YELLOW,
0.45 * self.WIDTH,
0.6 * self.HEIGHT,
FONT_NAME)
self.draw_text("Press Enter to submit",
21,
YELLOW,
0.62 * self.WIDTH,
0.65 * self.HEIGHT,
FONT_NAME)
self.draw_text("Press Escape to exit",
21,
YELLOW,
0.62 * self.WIDTH,
0.7 * self.HEIGHT,
FONT_NAME)
if not params['planet']:
self.draw_text("Choose a planet",
35,
YELLOW,
0.2 * self.WIDTH,
0.1 * self.HEIGHT,
FONT_NAME)
self.draw_text("Planet weight:",
30,
YELLOW,
0.1 * self.WIDTH,
0.2 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(self.planetStats[self.selectedPlanet]['describeWeight']),
30,
YELLOW,
0.1 * self.WIDTH,
0.25 * self.HEIGHT,
FONT_NAME)
self.draw_text("Start height:",
30,
YELLOW,
0.1 * self.WIDTH,
0.3 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(self.planetStats[self.selectedPlanet]['describeHeight']),
30,
YELLOW,
0.1 * self.WIDTH,
0.35 * self.HEIGHT,
FONT_NAME)
self.draw_text("Asteroids:",
30,
YELLOW,
0.5 * self.WIDTH,
0.2 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(self.planetStats[self.selectedPlanet]['describeAsteroids']),
30,
YELLOW,
0.5 * self.WIDTH,
0.25 * self.HEIGHT,
FONT_NAME)
self.process_keys_in_menu('planet',params)
elif not params['rocket']:
self.draw_text("Choose a rocket",
35,
YELLOW,
0.2 * self.WIDTH,
0.1 * self.HEIGHT,
FONT_NAME)
self.draw_text("Maneuverability: ",
30,
YELLOW,
0.05 * self.WIDTH,
0.2 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(self.rocketStats[self.selectedRocket]['describeManevrity']),
30,
YELLOW,
0.1 * self.WIDTH,
0.25 * self.HEIGHT,
FONT_NAME)
self.draw_text("Armour: ",
30,
YELLOW,
0.05 * self.WIDTH,
0.3 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(self.rocketStats[self.selectedRocket]['describeArmour']),
30,
YELLOW,
0.1 * self.WIDTH,
0.35 * self.HEIGHT,
FONT_NAME)
running = self.process_keys_in_menu('rocket',params)
planet = self.planetArray[self.selectedPlanet]
rocket = pg.transform.scale(self.availableRocketsArray[self.selectedRocket],(2 * ROCKET_W,2 * ROCKET_H))
self.screen.blit(planet,(0,0.9 * self.HEIGHT))
y = 0.2 * self.HEIGHT if params['planet'] else 0.8 * self.HEIGHT
self.screen.blit(rocket,(0.9 * self.WIDTH,y))
self.afterMenu = True
pg.display.flip()
def process_keys_in_menu(self,parametr,params=[],*args):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
self.quit()
if event.key == pg.K_RIGHT:
if parametr == 'planet':
self.selectedPlanet = (self.selectedPlanet + 1 ) % len(self.planetStats)
return True
elif parametr == 'rocket':
self.selectedRocket = (self.selectedRocket + 1 ) % len(self.availableRocketsArray)
return True
if event.key == pg.K_LEFT:
if parametr == 'planet':
if self.selectedPlanet > 0 : self.selectedPlanet -= 1
else : self.selectedPlanet = len(self.planetStats) - 1
return True
elif parametr == 'rocket':
if self.selectedRocket > 0 : self.selectedRocket -= 1
else : self.selectedRocket = len(self.availableRocketsArray) - 1
return True
if event.key == pg.K_RETURN:
params[parametr] = True
if params['planet'] and params['rocket']:
# Starts game here
self.background = self.spaceImage
return False
return True
def quit(self):
pg.quit()
sys.exit()
# draw stats that rocket have at this moment
def draw_data(self):
if not self.rocket.game_over:
self.draw_text("Score :",
21,
YELLOW,
0.05 * self.WIDTH,
0.1 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(self.rocket.score),
21,
YELLOW,
0.1 * self.WIDTH,
0.15 * self.HEIGHT,
FONT_NAME)
self.draw_text("Armour :",
21,
YELLOW,
0.05 * self.WIDTH,
0.2 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(self.rocket.armour),
21,
YELLOW,
0.1 * self.WIDTH,
0.25 * self.HEIGHT,
FONT_NAME)
if self.rocket.cured:
self.draw_text("Armour Up",
21,
YELLOW,
0.1 * self.WIDTH,
0.3 * self.HEIGHT,
FONT_NAME)
self.draw_text("Distance to Planet :",
21,
YELLOW,
0.6 * self.WIDTH,
0.1 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(int(self.rocket.distanceToPlanet)) +" m" ,21,
YELLOW,
0.65 * self.WIDTH,
0.15 * self.HEIGHT,
FONT_NAME)
self.draw_text("Velocity:",
21,
YELLOW,
0.6 * self.WIDTH,
0.2 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(abs(int(self.rocket.vel.y))) +" m/s" ,21,
YELLOW,
0.65 * self.WIDTH,
0.25 * self.HEIGHT,
FONT_NAME)
self.draw_text("Safe landing:",
21,
YELLOW,
0.65 * self.WIDTH,
0.3 * self.HEIGHT,
FONT_NAME)
self.draw_text(str(abs(int(10 * self.rocket.armour))) +" m/s" ,21,
YELLOW,
0.6 * self.WIDTH,
0.35 * self.HEIGHT,
FONT_NAME)
if self.rocket.vel.y < 0 :
self.draw_text("You are going up" ,30,
(155,155,155),
0.4 * self.WIDTH,
0.8 * self.HEIGHT,
FONT_NAME)
if self.rocket.landed and self.rocket.result == Result.Success:
self.draw_text("A long time ago ",
30,
YELLOW,
0.1 * self.WIDTH,
0.2 * self.HEIGHT,
FONT_NAME)
self.draw_text("in a galaxy far, far away .... ",
30,
YELLOW,
0.1 * self.WIDTH,
0.25 * self.HEIGHT,
FONT_NAME)
self.draw_text("Was borned a great hero, ",
30,
YELLOW,
0.1 * self.WIDTH,
0.3 * self.HEIGHT,
FONT_NAME)
self.draw_text("whose mission was to Save Our Space ! ",
30,
YELLOW,
0.1 * self.WIDTH,
0.35 * self.HEIGHT,
FONT_NAME)
self.draw_text("Enter - again ",
30,
YELLOW,
0.55 * self.WIDTH,
0.4 * self.HEIGHT,
FONT_NAME)
self.draw_text("Escape - close ",
30,
YELLOW,
0.6 * self.WIDTH,
0.45 * self.HEIGHT,
FONT_NAME)
elif (self.rocket.landed and self.rocket.result == Result.Fail) or self.rocket.game_over:
self.draw_text("You failed ",
30,
YELLOW,
0.4 * self.WIDTH,
0.8 * self.HEIGHT,
FONT_NAME)
self.draw_text("Enter - again ",
30,
YELLOW,
0.4 * self.WIDTH,
0.2 * self.HEIGHT,
FONT_NAME)
self.draw_text("Escape - close ",
30,
YELLOW,
0.4 * self.WIDTH,
0.3 * self.HEIGHT,
FONT_NAME)
def process_keys_end_game(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
self.quit()
if event.key == pg.K_RETURN:
self.rocket.game_over = False
self.rocket.landed = False
self.planetAppeared = False
self.inStratosphere = False
self.rocket.kill()
for sprite in self.asteroids:
sprite.kill()
self.showMenu()
self.init_entities()
def update(self):
self.planet_group.update()
self.asteroids.update()
self.rocket.update()
g = Game()
g.run()
|
Python
|
UTF-8
| 2,258 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
from primitives import *
from io import StringIO
import pickle
import csv
import re
class BaseParser:
data = ""
def __init__(self):
self._str_ops = []
self._s2l_ops = []
self._clean_ops = []
def load_data(self, filename):
stream = open(filename)
self.data = stream.read()
def run_clean_ops(self, l):
for op in self._clean_ops:
for n, line in enumerate(l):
l[n] = op(line)
return l
def run_str_ops(self, s):
for op in self._str_ops:
s = op(s)
return s
def run_s2l_ops(self, s):
l = []
curre = re.compile("".join([i[0] for i in self._s2l_ops]).strip())
try:
for match in curre.findall(s):
l.append(list(match))
except KeyboardInterrupt as e:
print(("".join([i[0] for i in self._s2l_ops])))
raise e
return l
def run_all(self):
s = self.run_str_ops(self.data)
self.parsed = self.run_s2l_ops(s)
self.parsed = self.run_clean_ops(self.parsed)
return self.parsed
def csv_dump(self):
tmp = StringIO()
csvwriter = csv.writer(tmp, quoting=csv.QUOTE_ALL, lineterminator="\n")
for i in self.parsed:
csvwriter.writerow(i)
return tmp.getvalue() # .replace('","', '"###,###"')
def criterias(self):
self.crits = {"len": len(self.parsed), "rowdata": self.csv_dump()}
return self.crits
def st(self):
return "filters: %s\nregex: %s\ncleaners: %s\n" % (
", ".join([i.__name__ for i in self._str_ops]),
"".join([i[0] for i in self._s2l_ops]),
", ".join([i.__name__ for i in self._clean_ops]),
)
def dump(self, filename):
stream = open(filename, "wb")
pickle.dump((self._str_ops, self._s2l_ops, self._clean_ops), stream)
stream.close()
def load(self, filename):
stream = open(filename, "rb")
self._str_ops, self._s2l_ops, self._clean_ops = pickle.load(stream)
stream.close()
if __name__ == "__main__":
import sys
bp = BaseParser()
bp.load(sys.argv[1])
bp.load_data(sys.argv[2])
print((bp.run_all()))
|
C#
|
UTF-8
| 10,377 | 2.75 | 3 |
[] |
no_license
|
using System;
using System.ComponentModel;
using System.Windows.Controls;
using Coding4Fun.Phone.Controls;
using Microsoft.Phone.Scheduler; //for the reminders. Pretty sure they shouldn't be in this class? where do they fit in mvvm?
using PAX7.Utilicode; //settings
namespace PAX7.Model
{
public class Event : INotifyPropertyChanged, IComparable
{
// constructor - does nothing, no default values.
public Event() {}
//session title
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
RaisePropertyChanged("Name");
}
}
// potentially long description
private string _details;
public string Details
{
get
{
return _details;
}
set
{
_details = value;
RaisePropertyChanged("Details");
}
}
// user editable notes on the event.
private string _usernotes;
public string UserNotes
{
get
{
return _usernotes;
}
set
{
_usernotes = value;
RaisePropertyChanged("UserNotes");
}
}
//kind of event: panel, speech, omegathon, contest, freeplay, music
private string _kind;
public string Kind
{
get
{
return _kind;
}
set
{
_kind = value;
RaisePropertyChanged("Kind");
}
}
#region time handling
// start time
private DateTime _starttime;
public DateTime StartTime
{
get
{
return _starttime;
}
set
{
_starttime = value;
RaisePropertyChanged("StartTime");
}
}
// convenience method to return the start time and day in a readable string
public string friendlyStartTime
{
get
{
return friendlyDate + " " + time;
}
}
// convenience method to return the start time in a readable string
public string time
{
get
{
return StartTime.ToShortTimeString();
}
}
//convenience method to return the day of week
public string day
{
get
{
return StartTime.DayOfWeek.ToString();
}
}
// convenience method to return the day and date in a readable string
public string friendlyDate
{
get
{
return StartTime.DayOfWeek.ToString() + " " + StartTime.Date.ToString("d");
}
}
// end time
private DateTime _endtime;
public DateTime EndTime
{
get
{
return _endtime;
}
set
{
_endtime = value;
RaisePropertyChanged("EndTime");
}
}
// convenience method to return the duration of the event
public float hoursDuration
{
get
{
TimeSpan timespan = EndTime - StartTime;
return timespan.Hours + (timespan.Minutes / 60);
}/* could ask for this is we enable user-entered events
set
{
int hours = int.Parse(value.ToString());
int minutes = (value - hours) * 100;
EndTime = StartTime + new DateTime((int)value, ;
}
*/
}
#endregion
// location
private string _location;
public string Location
{
get
{
return _location;
}
set
{
_location = value;
RaisePropertyChanged("Location");
}
}
// has the user starred this event/put it in their schedule
private bool _starred;
public bool Star
{
get
{
return _starred;
}
set
{
_starred = value;
if (_starred) SetReminder();
else UnsetReminder();
RaisePropertyChanged("Star");
}
}
#region reminders
// guid for the reminder name used internally in the scheduler
private string _reminderName = null;
/// <summary>
/// Set a reminder for this event 1 hour before the scheduled start
/// if scheduled start is past, do not create a reminder unless testing=true
/// code taken from http://windowsphonegeek.com/articles/getting-started-with-windows-phone-reminders
/// </summary>
/// <param name="testing">for testing, make the reminder actually schedule 10 seconds from now</param>
internal void SetReminder(bool testing=false)
{
if (!IsoStoreSettings.IsAllowedSetReminders())
return;
// event was starred - create reminder
_reminderName = Guid.NewGuid().ToString();
// use guid for reminder name, since reminder names must be unique
Reminder reminder = new Reminder(_reminderName);
int MAX_LENGTH = 62; // max length is 63 characters, per msdn
int titleLength;
DateTime reminderStartTime;
try
{
// NOTE: setting the Title property is supported for reminders
// in contrast to alarms where setting the Title property is not supported
titleLength = this.Name.Length > MAX_LENGTH ? MAX_LENGTH : this.Name.Length;
reminder.Title = this.Name.Substring(0, titleLength);
reminder.Content = "scheduled " + this.Kind + " begins at " + this.friendlyStartTime + " in " + this.Location;
//NOTE: the value of BeginTime must be after the current time
//set the BeginTime time property in order to specify when the reminder should be shown
if (this.StartTime == new DateTime(0))
{
//the event time is set to the start of time, don't want/can't set a reminder for that.
return;
}
reminderStartTime = this.StartTime.Subtract(new TimeSpan(1, 0, 0));//start time minus one hour
if (reminderStartTime < DateTime.Now)
{
if (testing)
reminderStartTime = DateTime.Now + new TimeSpan(0, 0, 30);
else
return; //don't create reminders 'now' for real usage
}
reminder.BeginTime = reminderStartTime;
// NOTE: ExpirationTime must be after BeginTime
reminder.ExpirationTime = reminderStartTime + new TimeSpan(1,0,0);
}
catch (Exception e)
{
// gets called during app initialisation with some weird issues
LittleWatson.ReportException(e, "time exceptions creating reminder for event " + this.Name);
return;
}
// NOTE: another difference from alerts
// you can set a navigation uri that is passed to the application when it is launched from the reminder
//reminder.NavigationUri = new Uri("/View/SchedulePivotView.xaml?PivotOn=Stars");
if (ScheduledActionService.Find(_reminderName) != null)
ScheduledActionService.Remove(_reminderName);
ScheduledActionService.Add(reminder);
}
/// <summary>
/// Remove the scheduled reminder for this event
/// Possible the reminder does not actually exist, if the user has been changing their preferences on adding a reminder
/// </summary>
internal void UnsetReminder()
{
if (_reminderName != null && ScheduledActionService.Find(_reminderName) != null )
ScheduledActionService.Remove(_reminderName);
_reminderName = null;
}
#endregion reminders
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
//Display the details of this event in a message box and expose the option to add/remove from starred group
public void ShowEventDetails()
{
AboutPrompt detailsPopup = new AboutPrompt();
detailsPopup.Title = "";// this.Name; //what to do about long names????
// a side scroller!!!
detailsPopup.VersionNumber = "";
ContentControl detailsBody = new ContentControl();
detailsBody.DataContext = this;
detailsBody.Template = App.Current.Resources["aboutEvent"] as ControlTemplate;
detailsPopup.Body = detailsBody;
detailsPopup.Show();
}
// Create a copy of an event to save to isolated storage
// If your object is databound, this copy is not databound.
public Event GetCopy()
{
Event copy = (Event)this.MemberwiseClone();
return copy;
}
/// <summary>
/// implement IComparable to enable List.Sort
/// </summary>
/// <param name="other">another Event object to compare against</param>
/// <returns></returns>
public int CompareTo(object other)
{
Event otherEvent = (Event)other;
if (this.StartTime == otherEvent.StartTime)
return this.Name.CompareTo(otherEvent.Name);
else
return this.StartTime.CompareTo(otherEvent.StartTime);
}
}
}
|
JavaScript
|
UTF-8
| 373 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
const ingredientsReducerDefaultState = [];
export default (state = ingredientsReducerDefaultState, action) => {
switch (action.type) {
case 'SET_INGREDIENTS':
return action.ingredients;
case 'DELETE_INGREDIENT':
return state.filter((ingredient) => ingredient.id != action.id);
default:
return state;
}
};
|
C#
|
UTF-8
| 1,446 | 2.734375 | 3 |
[] |
no_license
|
using Imposto.Core.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Imposto.Core.Domain
{
public class PedidoItem : IValidator
{
public PedidoItem(string nomeProduto, string codigoProduto, decimal valorItemPedido, bool brinde)
{
NomeProduto = nomeProduto;
CodigoProduto = codigoProduto;
ValorItemPedido = valorItemPedido;
Brinde = brinde;
Validar();
}
public string NomeProduto { get; }
public string CodigoProduto { get; }
public decimal ValorItemPedido { get; }
public bool Brinde { get; }
public bool Valido { get; private set; } = true;
public IEnumerable<string> Erros { get; private set; }
public void Validar()
{
var list = new List<string>();
if (string.IsNullOrEmpty(NomeProduto))
{
Valido = false;
list.Add("Nome inválido!");
}
if (string.IsNullOrEmpty(CodigoProduto))
{
Valido = false;
list.Add("Código inválido!");
}
if (ValorItemPedido < 0)
{
Valido = false;
list.Add("Valor inválido!");
}
Erros = list;
}
}
}
|
Markdown
|
UTF-8
| 7,397 | 2.734375 | 3 |
[] |
no_license
|
第四十三回 毅力虔心十年待知己 盗名欺世一旦现原形(4)
曾静见问不出所以然来,也便罢了。那两名武士要了曾静左右的两间房间,吃过饭后,二更时分,装作同路人来访,进入曾静房间,悄悄说道:“曾老先生,令晚你可得小心点儿!”曾静吓道:“你们两位发现了什么不妥吗?你们可得救救我的性命,我说,不如换了客店吧!”
那两名武士乃是年羹尧的心腹武土,惧有非常武艺,听了曾静之言,淡淡笑道:“替你定房的人不问可知,定是吕留良的遗孽,我们定要等他到来,怎好换店?”曾静不好言语,心中暗暗吃惊。想道:“这两人不知是不是吕四娘的对手?咳,吕四娘杀了他们固然不好,他们杀了吕四娘更不好。吕家兄弟和我到底是生前知交,我怎忍见他家被斩草除根。”曾静这时,满心以为替他定房的必然是吕四娘,谁知却料错了。
这晚,曾静那里还睡得着,他看了一回“春秋”,春秋谴责乱臣贼子,史笔凛然,只看了几页,便不敢再看。听听外面已打三更,客店一点声响都没有,曾静内疚神明,坐卧不安,打开窗子,窗子外一阵冷风吹了进来,夜色冥冥中,隐隐可以见到仙霞岭似黑熊一样蹲伏在原野上。曾静不由得想起沈在宽来,冥冥夜色中,竟似见着沈在宽颈血淋漓,手中提着头颅,头颅上两只白渗渗似死鱼一样的眼珠向他注视。曾静惊叫一声,急忙关上窗子,眼前的幻象立即消失。
曾静叹了口气,心道:“平生不作亏心事,半夜敲门也不惊,这话真真不错。”抹了抹额上的冷汗,漫无目的的在房间内镀起方步,不自觉的念起了吴梅村的绝命词来:“……吾病难将医药治,耿耿胸中热血。……故人慷慨多奇节,为当年沉吟不断,草间谕活。……脱屣妻孥非易事,竟一钱不值何须说!……”一声高一声低,断以续续,恍如秋虫呜咽。吟声一止,忽又自言自语笑道:“我比吴梅村到底还强一些,人人都知吴棺村晚节不终,可是千古之后,有谁知道我曾静干过错事?”
曾静哭一会笑一会,忽听得房门外“笃、笃、笃!……”敲门声响,曾静以为是邻房武士,随口问了一声:“谁?”没待回答,便抽开了门栅,房门一下开了,曾静抬头一望,吓得三魂失了两魂,七魄仅余一魄,叫道:“你,你,你是人还是鬼,不,不,不是我害你的,你,你……”
不仅曾静吃惊,另一人吃惊更甚,这人便是吕四娘。吕四娘三更时分,来到蒲城,蒲城没有几家客店,一查便知。吕四娘轻功绝顶,飞上这家客店的瓦面,真如一叶轻堕,落处无声,连那两名聚精会神一心等待的武士也没有发现。
吕四娘先听得曾静念吴梅村的“绝命词”,心中一动,想道:“原来他还知道自怨自艾。”见他年迈苍苍,不忍下手,后来又见他自言自笑,忍不住怒火燃起,正想下手,忽见尾房房门轻启,走出了一个书生模样的人,青巾蒙面,来到曾静房前,轻轻敲门,随即把青巾除下,这人烧变了灰吕四娘也认得,正是吕四娘以为已死了的沈在宽!刚才他走出房时,吕四娘已是疑心,如今除了青巾,更证实了!
吕四娘这一下真是又惊又喜,想不到沈在宽不但没死,而且面色红润,行动矫捷,比平常人还要健壮得多。吕四娘心情欢悦,杀机又泯,心道:“我且看曾老头儿有什么脸皮见他?”
曾静吓得魂消魄散,问他是人是鬼,还说:“你,你不要向我索命!”
沈在宽微笑道:“我不是鬼!那日在仙霞岭上被鹰犬捕去的是我的堂弟在英。”面色一沉,低声又道:“可怜他第一次上山探我,便遭毒手!唉,还连累了一瓢和尚。在英,你不是也认得的吗?”
曾静一听,沈在宽似乎还未知道是他出卖,定了定神,也低头叹了口气道:“是呀,在英不是很似你吗?大好青年,可惜,可惜!”
沈在宽面色凝重,接口说道:“死者已矣,生者更要小心。曾老伯,你身在绝险之中,赶快随我逃吧!”
曾静刚刚宽心,听了此话,面色又变,只听得沈在宽续道:“邻房的两个武士一路跟你同行,他们认不出你是谁吗?听说朝廷正在大捕我们这一班人,严叔叔也已经遇害了,你是我党中的首脑人物,怎么还随便到处乱走?”
原来那日年羹尧派遣武士上山,捉拿沈在宽时,沈在宽刚好因为身体已经康复,一早到山腰散步,行得高兴,不觉离寺庙十余里远,仙霞岭山路迂回,离寺庙十余里已隔了两个山头,年羹尧武士来时,他连知也不知。到了兴尽回寺,才见一瓢和尚尸横寺中,急急下山逃避,其后又知他的堂弟那日恰巧上山探他,竟然做了替死鬼。沈在宽悲愤莫名,可是吕四娘不在,他一人也不能报仇。只好把一瓢和尚埋了。同时又故意替自己立了一个衣冠之冢,故布疑阵,好让再有清廷的鹰犬上山查探时,可以不必再注意他。
一瓢和尚在蒲城相识颇多,其中也有同道中人,沈在宽便在一家姓叶的人家居住,这叶家又是帮会中人,曾静坐着轿子从浙江来到福建的消息,已有人飞马告诉于他,同时也把两个武士跟在轿前轿辰的情况说了,沈在宽一听,深恐曾静也遭毒手,因此预早布置,将曾静引到长安客店来。
曾静听得沈在宽连声催他速走,真是啼笑皆非。又不便将真情向他吐露,正在支支吾吾,尴尬万分之际,门外一声冷笑,左右两个邻房的武士都冲了出来。那虬髯壮汉横门一站,朗声笑道:“好大胆的贼子,老子等你已久了!”伸臂一抓,向沈在宽的琵琶骨一扣!
这名武士长于鹰爪功夫,见沈在宽一派文弱书生的样子,以为还不是手到擒来。那知沈在宽得了吕四娘传他内功治病之法,近十年来日夜虔心修习,内功火候已到,所以瘫痪之症才能痊愈。这时,他虽然对于技击之道丝毫不懂,可是内功的精纯,已可比得了江湖上的一流好手!
那虬髯双手一抓抓去,触着沈在宽的肩头,沈在宽的肌肉遇着外力,本能一缩,虬髯汉子只觉滑不留手,有如抓着一尾泥鳅一样,顿时又给他滑脱开去,不觉大吃一惊,叫道:“这点子扎手!”横掌一拍,沈在宽出掌相抵,那虬髯汉子竟然给他震退两步,这分际,虬髯汉子的同伴已拔出单刀,一招“铁犁耕地”,斩他双腿,那虬髯汉子也再扑上来,抓他手腕,踢他腰胯。
沈在宽到底是不懂技击之人,被两人一逼,手忙脚乱,忽闻得瓦檐上一声冷笑,挥刀的汉子首先倒地,沈在宽喜道:“四娘。”虬髯汉子回头一望,吕四娘出手如电,一剑横披,一颗头颅顿时飞出屋外。这时里房的孩子哇然哭了起来,曾静吓得面如土色,叫道:“贤侄女,贤侄女!”
|
JavaScript
|
UTF-8
| 3,877 | 2.875 | 3 |
[] |
no_license
|
var mysql = require('mysql');
module.exports = {
init : function(host, user, password){
init(host, user, password);
},
insert_site: function (site, callback) {
insert_site(site, callback);
},
insert_photo: function (photo, callback) {
insert_photo(photo, callback);
},
terminate : function(){
terminate();
},
truncate : function(callback){
truncate(callback);
}
};
var pool;
init_db(
'localhost',
'vuparvous',
'root',
''
);
/**
* init database pool with cusom values.
* @param host
* @param user
* @param password
*/
function init_db(host, database, user, password){
pool = mysql.createPool({
host : host,
database : database,
user : user,
password : password,
charset : 'UTF8'
});
console.log(pool);
return pool;
}
/**
* terminates database pool
*/
function terminate(){
pool.end();
}
/**
* repaces all :xxx par xxx value.
* @param query
* @param values
* @returns
*/
function prepare(query, values) {
if (!values)
return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
/**
* updates or inserts if no rows where updated.
* ATTENTION updateQuery doit inclure la clause WHERE.
* @param updateQuery the update SQL
* @param insertQuery the insert SQL
* @param object the object to be escaped and injected into queries.
* @param cb callback once update or insert is finished.
*/
function update_or_insert(updateQuery, insertQuery, object, cb){
pool.getConnection(function(err, connection) {
// Use the connections
//console.log(updateQuery,insertQuery,object);
//console.log(updateQuery);
connection.query( updateQuery, object, function(err, result) {
if (err) throw err;
if(result.affectedRows>0){
//console.log("object updated :", object);
connection.end();
if (cb)
cb(object);
return;
}
// And done with the connection.
var q = connection.query(insertQuery, object, function(err, result) {
// console.log(err,result);
if (err) throw err;
//onsole.log("object inserted :",object);
// And done with the connection.
connection.end();
if (cb)
cb(object);
});
// console.log(q.sql);
});
});
}
/**
* insert or update a site.
* @param mydoc
* @param callback
*/
function insert_site(row, callback) {
var site = {
site_id : row.site_id,
site_name : row['Raison Sociale'],
description_fr : row['TEXTE FRANÇAIS'],
description_en : row['TEXTE ANGLAIS'],
latitude : row['Latitude'],
longitude : row['Longitude'],
category:row['category']
};
update_or_insert('UPDATE sites set ? where site_id = \''+site.site_id+'\'', 'INSERT INTO sites set ?', site, function(cb_row){
console.log("added",site.site_id);
if(callback)
callback(cb_row);
});
}
/**
* insert or update a photo.
* @param mydoc
* @param callback
* @param tried
*/
function insert_photo(photo, callback) {
// var photo = {
// photo_id : row.photo_id,
// site_id : row.site_id,
// filename : row.filename,
// auteur : row. auteur,
// commentaire: row.commentaire,
// // date : row.date,
// score_qualite: row.score_qualite,
// score_insolite:row.score_insolite
// }
delete photo.date;
delete photo._id;
console.log(photo);
update_or_insert('UPDATE photos set ? where photo_id = \''+photo.photo_id+'\'', 'INSERT INTO photos set ?', photo, function(cb_row){
console.log("added",photo.photo_id);
if(callback)
callback(cb_row);
});
}
function truncate(callback){
pool.getConnection(function(err, connection) {
// Use the connections
connection.query( 'truncate photos', null, function(err, result) {
connection.query( 'truncate sites', null, function(err, result) {
connection.end();
if(callback)
callback();
});
});
});
}
|
C++
|
UTF-8
| 1,148 | 3.015625 | 3 |
[] |
no_license
|
#pragma once
#pragma once
#include "Slot.h"
using namespace std;
class Player ;
#define INTEREST 20//2000%
enum city_group
{City1 = 1, City2, City3, City4 };
class Asset : public Slot
{
city_group city;
const int house_price;
int rent_price;
Player* ownership;
int pawned_years;
public:
Asset(string name_slot, string city, int house_price, int rent_price);//constructor
Asset(const Slot& other)throw(string);
bool operator==(const Slot& other);
Asset& operator=(const Asset& other)throw(string) { throw ERROR_COPY_CONSTRTUCTOR; }
const int get_house_price()const{return house_price; }
Player* get_ownership() const { return ownership; }
void set_ownership(Player& owner) { this->ownership = &owner;}
int get_pawned_years() const { return pawned_years; }
int get_rent_price() const { return rent_price; }
operator int() const { return pawned_years * house_price * INTEREST;}// caasting to Revenue
virtual void print(ostream& out)const;
void remove_ownership() { this->ownership = NULL; pawned_years = 0; }
void set_pawned_year(bool reset = false);
virtual ~Asset(){};
};
|
Java
|
UTF-8
| 1,211 | 2.734375 | 3 |
[] |
no_license
|
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
public class RPCClient {
public static void main(String[] args) {
HelloService helloService = getClient(HelloService.class, "127.0.0.1", 5001);
System.out.println(helloService.sayHello("xhl"));
}
private static <T> T getClient(Class<T> clazz, String server, int port) {
// TODO Auto-generated method stub
return (T)Proxy.newProxyInstance(RPCClient.class.getClassLoader(), new Class<?>[]{clazz}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Socket socket = new Socket(server, port);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeUTF(method.getName());
out.writeObject(method.getParameterTypes());
out.writeObject(args);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
return in.readObject();
//return null;
}
});
//return null;
}
}
|
Java
|
UTF-8
| 5,496 | 2.421875 | 2 |
[] |
no_license
|
package study.spring.goodspring.service.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import study.spring.goodspring.model.AdminInquiry;
import study.spring.goodspring.model.Inquiry;
import study.spring.goodspring.model.Member;
import study.spring.goodspring.service.AdminService;
@Slf4j
@Service
public class AdminServiceImpl implements AdminService{
@Autowired
SqlSession sqlSession;
/**
* 1:1 문의 조회 (관리자)
*/
@Override
public List<Inquiry> getInquiryListAdmin(Inquiry input) throws Exception {
List<Inquiry> result = null;
try {
result = sqlSession.selectList("AdminMapper.selectInquiryListAdmin", input);
if (result == null) {
throw new NullPointerException("result=null");
}
} catch (NullPointerException e) {
log.error(e.getLocalizedMessage());
throw new Exception("조회된 데이터가 없습니다.");
} catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 조회에 실패했습니다.");
}
return result;
}
/**
* 1:1 문의 상세 데이터 조회
* @param Inquiry 조회할 데이터의 일련번호를 담고있는 Beans
* @return 조회된 데이터가 저장된 Beans
* @throws Exception
*/
@Override
public Inquiry getInquiryItemAdmin(Inquiry input) throws Exception {
Inquiry result = null;
try {
result = sqlSession.selectOne("AdminMapper.selectInquiryItemAdmin", input);
if (result == null) {
throw new NullPointerException("result = null");
}
} catch (NullPointerException e) {
log.error(e.getLocalizedMessage());
throw new Exception("조회된 코스 데이터가 없습니다.");
} catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 조회에 실패했습니다.");
}
return result;
}
/**
* 답변 등록
* @param Inquiry 저장할 정보를 담고 있는 Beans
* @return int
* @throws Exception
*/
@Override
public Inquiry addInquiryAdmin(Inquiry input) throws Exception {
Inquiry output=null;
int result = 0;
try {
result = sqlSession.update("AdminMapper.updateInquiryAdmin", input);
output = sqlSession.selectOne("AdminMapper.selectInquiryItemAdmin", input);
if (result == 0) {
throw new NullPointerException("result=0");
}
} catch (NullPointerException e) {
log.error(e.getLocalizedMessage());
throw new Exception("저장된 데이터가 없습니다.");
} catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 등록에 실패했습니다.");
}
return output;
}
/**
* 관리자 1:1 문의 데이터 수 조회
*/
@Override
public int getInquiryListAdminCount(AdminInquiry input) throws Exception {
int result = 0;
try {
result = sqlSession.selectOne("AdminMapper.selectInquiryCountAll", input);
} catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 조회에 실패했습니다.");
}
return result;
}
/**
* 관리자 1:1 문의 목록 조회
*/
@Override
public List<AdminInquiry> getAdminInquiryList(AdminInquiry input) throws Exception {
List<AdminInquiry> result = null;
try {
result = sqlSession.selectList("AdminMapper.selectInquiryBooleanAdmin", input);
if (result == null) {
throw new NullPointerException("result=null");
}
} catch (NullPointerException e) {
log.error(e.getLocalizedMessage());
throw new Exception("조회된 데이터가 없습니다.");
} catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 조회에 실패했습니다.");
}
return result;
}
/**
* 관리자 탈퇴 금지
*/
@Override
public Member getUserinfoadmin(Member input) throws Exception {
Member result = null;
try {
result = sqlSession.selectOne("MemberMapper.selectItem", input);
if(result == null) {
throw new NullPointerException("result=null");
}
}catch (NullPointerException e) {
log.error(e.getLocalizedMessage());
throw new Exception("조회된 데이터가 없습니다.");
}catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 조회에 실패했습니다.");
}
return result;
}
@Override
public void deleteMemberadmin(Member input) throws Exception {
try {
sqlSession.update("MemberMapper.userOut", input);
sqlSession.update("CrewMemberMapper.crewOut", input);
} catch (NullPointerException e) {
log.error(e.getLocalizedMessage());
throw new Exception("삭제된 데이터가 없습니다.");
} catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 삭제에 실패했습니다.");
}
}
/**
* 관리자 회원 관리 데이터 수 조회
*/
@Override
public int getMemberCount(Member input) throws Exception {
int result = 0;
try {
result = sqlSession.selectOne("MemberMapper.selectCountAll", input);
} catch (Exception e) {
log.error(e.getLocalizedMessage());
throw new Exception("데이터 조회에 실패했습니다.");
}
return result;
}
}
|
Java
|
UTF-8
| 4,571 | 1.734375 | 2 |
[] |
no_license
|
/*
* This content is generated from the API File Info.
* (Alt+Shift+Ctrl+I).
*
* @desc
* @file artboard_15
* @date 0
* @title Artboard 15
* @author
* @keywords
* @generator Export Kit v1.2.8.xd
*
*/
package exportkit.xd;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class artboard_15_activity extends Activity {
private View _bg__artboard_15;
private ImageView group_97;
private View rectangle_72;
private ImageView path_138;
private TextView order_history;
private TextView track_orders;
private TextView currency;
private TextView store_locator;
private TextView terms___conditions;
private TextView help;
private TextView got_a_question_;
private TextView logout;
private View ellipse_31;
private View ellipse_32;
private View ellipse_33;
private View ellipse_34;
private View ellipse_35;
private View ellipse_36;
private View ellipse_37;
private View ellipse_38;
private TextView grocery_shopping;
private View bg;
private TextView _12_30;
private ImageView path_139;
private View rectangle_73;
private ImageView path_140;
private ImageView group_99;
private ImageView path_142;
private ImageView path_143;
private ImageView path_144;
private ImageView path_145;
private ImageView path_146;
private ImageView path_147;
private ImageView path_148;
private ImageView path_149;
private ImageView path_150;
private ImageView path_151;
private ImageView path_152;
private ImageView path_153;
private ImageView path_154;
private ImageView path_155;
private ImageView path_156;
private ImageView path_157;
private ImageView path_158;
private ImageView path_159;
private ImageView shape;
private ImageView icon;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.artboard_15);
_bg__artboard_15 = (View) findViewById(R.id._bg__artboard_15);
group_97 = (ImageView) findViewById(R.id.group_97);
rectangle_72 = (View) findViewById(R.id.rectangle_72);
path_138 = (ImageView) findViewById(R.id.path_138);
order_history = (TextView) findViewById(R.id.order_history);
track_orders = (TextView) findViewById(R.id.track_orders);
currency = (TextView) findViewById(R.id.currency);
store_locator = (TextView) findViewById(R.id.store_locator);
terms___conditions = (TextView) findViewById(R.id.terms___conditions);
help = (TextView) findViewById(R.id.help);
got_a_question_ = (TextView) findViewById(R.id.got_a_question_);
logout = (TextView) findViewById(R.id.logout);
ellipse_31 = (View) findViewById(R.id.ellipse_31);
ellipse_32 = (View) findViewById(R.id.ellipse_32);
ellipse_33 = (View) findViewById(R.id.ellipse_33);
ellipse_34 = (View) findViewById(R.id.ellipse_34);
ellipse_35 = (View) findViewById(R.id.ellipse_35);
ellipse_36 = (View) findViewById(R.id.ellipse_36);
ellipse_37 = (View) findViewById(R.id.ellipse_37);
ellipse_38 = (View) findViewById(R.id.ellipse_38);
grocery_shopping = (TextView) findViewById(R.id.grocery_shopping);
bg = (View) findViewById(R.id.bg);
_12_30 = (TextView) findViewById(R.id._12_30);
path_139 = (ImageView) findViewById(R.id.path_139);
rectangle_73 = (View) findViewById(R.id.rectangle_73);
path_140 = (ImageView) findViewById(R.id.path_140);
group_99 = (ImageView) findViewById(R.id.group_99);
path_142 = (ImageView) findViewById(R.id.path_142);
path_143 = (ImageView) findViewById(R.id.path_143);
path_144 = (ImageView) findViewById(R.id.path_144);
path_145 = (ImageView) findViewById(R.id.path_145);
path_146 = (ImageView) findViewById(R.id.path_146);
path_147 = (ImageView) findViewById(R.id.path_147);
path_148 = (ImageView) findViewById(R.id.path_148);
path_149 = (ImageView) findViewById(R.id.path_149);
path_150 = (ImageView) findViewById(R.id.path_150);
path_151 = (ImageView) findViewById(R.id.path_151);
path_152 = (ImageView) findViewById(R.id.path_152);
path_153 = (ImageView) findViewById(R.id.path_153);
path_154 = (ImageView) findViewById(R.id.path_154);
path_155 = (ImageView) findViewById(R.id.path_155);
path_156 = (ImageView) findViewById(R.id.path_156);
path_157 = (ImageView) findViewById(R.id.path_157);
path_158 = (ImageView) findViewById(R.id.path_158);
path_159 = (ImageView) findViewById(R.id.path_159);
shape = (ImageView) findViewById(R.id.shape);
icon = (ImageView) findViewById(R.id.icon);
//custom code goes here
}
}
|
Java
|
UTF-8
| 7,671 | 1.726563 | 2 |
[
"GPL-1.0-or-later",
"GPL-3.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.datamgr;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import javax.swing.SwingUtilities;
import docking.widgets.OptionDialog;
import docking.widgets.tree.GTree;
import docking.widgets.tree.GTreeNode;
import ghidra.app.plugin.core.datamgr.archive.*;
import ghidra.app.plugin.core.datamgr.tree.ArchiveNode;
import ghidra.framework.client.ClientUtil;
import ghidra.framework.client.RepositoryAdapter;
import ghidra.framework.main.AppInfo;
import ghidra.framework.model.DomainFile;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.listing.DataTypeArchive;
import ghidra.util.*;
import ghidra.util.exception.CancelledException;
import ghidra.util.exception.VersionException;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
class OpenDomainFileTask extends Task {
private DomainFile domainFile;
private int version;
private DataTypeManagerPlugin dtmPlugin;
private DataTypeManagerHandler dtmHandler;
private PluginTool tool;
private DataTypeArchive dtArchive = null;
OpenDomainFileTask(DomainFile domainFile, int version, PluginTool tool,
DataTypeManagerPlugin dtmPlugin) {
super("Open Project Data Type Archive", true, true, true);
this.domainFile = domainFile;
this.dtmPlugin = dtmPlugin;
this.dtmHandler = dtmPlugin.getDataTypeManagerHandler();
this.tool = tool;
this.version = version;
}
DataTypeArchive getArchive() {
return dtArchive;
}
/* (non-Javadoc)
* @see ghidra.util.task.Task#run(ghidra.util.task.TaskMonitor)
*/
@Override
public void run(TaskMonitor monitor) {
if (isFileOpen()) {
return;
}
boolean associateWithOriginalDomainFile = true;
if (version != DomainFile.DEFAULT_VERSION) {
openReadOnlyFile(monitor);
associateWithOriginalDomainFile = false;
}
else if (domainFile.isReadOnly()) {
openReadOnlyFile(monitor);
}
else if (domainFile.isVersioned() && !domainFile.isCheckedOut()) {
openReadOnlyFile(monitor);
}
else {
openUnversionedFile(monitor);
}
if (dtArchive != null) {
openFileInTree(associateWithOriginalDomainFile);
dtArchive.release(this);
}
}
private boolean isFileOpen() {
List<Archive> dtArchiveList = dtmHandler.getAllArchives();
for (int i = 0; i < dtArchiveList.size(); i++) {
Archive archive = dtArchiveList.get(i);
if (archive instanceof ProjectArchive) {
ProjectArchive projectArchive = (ProjectArchive) archive;
DomainFile archiveDomainFile = projectArchive.getDomainFile();
if (filesMatch(domainFile, archiveDomainFile)) {
// archive = projectArchive;
// dtmHandler.open // TODO
return true;
}
}
}
return false;
}
private boolean filesMatch(DomainFile file1, DomainFile file2) {
if (!file1.getPathname().equals(file2.getPathname())) {
return false;
}
if (file1.isCheckedOut() != file2.isCheckedOut()) {
return false;
}
if (!SystemUtilities.isEqual(file1.getProjectLocator(), file2.getProjectLocator())) {
return false;
}
int otherVersion = file2.isReadOnly() ? file2.getVersion() : -1;
return version == otherVersion;
}
/**
* Open archive in an immutable fashion. Unlike ProgramDB, we do not want to
* allow upgrade or modification of a read-only archve (e.g., not-checked-out).
* @param monitor task monitor
*/
private void openReadOnlyFile(TaskMonitor monitor) {
String fileDescr =
((version != DomainFile.DEFAULT_VERSION) ? "version " + version + " of " : "") +
domainFile.getName();
String contentType = null;
try {
monitor.setMessage("Opening " + fileDescr);
contentType = domainFile.getContentType();
dtArchive =
(DataTypeArchive) domainFile.getImmutableDomainObject(this, version, monitor);
}
catch (CancelledException e) {
// we don't care, the task has been canceled
}
catch (IOException e) {
if (domainFile.isVersioned() && domainFile.isInWritableProject()) {
ClientUtil.handleException(AppInfo.getActiveProject().getRepository(), e,
"Get Versioned Object", null);
}
else {
Msg.showError(this, null, "Project Archive Open Error",
"Error occurred while opening " + fileDescr, e);
}
}
catch (VersionException e) {
VersionExceptionHandler.showVersionError(tool.getToolFrame(), domainFile.getName(),
contentType, "Open", e);
}
}
private void openUnversionedFile(TaskMonitor monitor) {
monitor.setMessage("Opening " + domainFile.getName());
String contentType = null;
try {
final boolean recoverFile = isRecoveryOK(domainFile);
contentType = domainFile.getContentType();
try {
dtArchive =
(DataTypeArchive) domainFile.getDomainObject(this, false, recoverFile, monitor);
}
catch (VersionException e) {
if (VersionExceptionHandler.isUpgradeOK(null, domainFile, "Open", e)) {
dtArchive = (DataTypeArchive) domainFile.getDomainObject(this, true,
recoverFile, monitor);
}
}
}
catch (VersionException e) {
VersionExceptionHandler.showVersionError(null, domainFile.getName(), contentType,
"Open", e);
}
catch (CancelledException e) {
// we don't care, the task has been canceled
}
catch (Exception e) {
if (domainFile.isInWritableProject() && (e instanceof IOException)) {
RepositoryAdapter repo = domainFile.getParent().getProjectData().getRepository();
ClientUtil.handleException(repo, e, "Open File", null);
}
else {
Msg.showError(this, null, "Error Opening " + domainFile.getName(),
"Opening data type archive failed.\n" + e.getMessage());
}
}
}
private boolean isRecoveryOK(final DomainFile dfile)
throws InterruptedException, InvocationTargetException {
final boolean[] recoverFile = new boolean[] { false };
if (dfile.isInWritableProject() && dfile.canRecover()) {
Runnable r = () -> {
int option = OptionDialog.showYesNoDialog(null, "Crash Recovery Data Found",
"<html>" + HTMLUtilities.escapeHTML(dfile.getName()) + " has crash data.<br>" +
"Would you like to recover unsaved changes?");
recoverFile[0] = (option == OptionDialog.OPTION_ONE);
};
SwingUtilities.invokeAndWait(r);
}
return recoverFile[0];
}
private void openFileInTree(boolean associatedWithOriginalDomainFile) {
DataTypesProvider provider = dtmPlugin.getProvider();
GTree tree = provider.getGTree();
DataTypeManagerHandler manager = dtmPlugin.getDataTypeManagerHandler();
DomainFile df = associatedWithOriginalDomainFile ? domainFile : dtArchive.getDomainFile();
Archive archive = manager.openArchive(dtArchive, df);
GTreeNode node = getNodeForArchive(tree, archive);
if (node != null) {
tree.setSelectedNode(node);
}
}
private GTreeNode getNodeForArchive(GTree tree, Archive archive) {
GTreeNode rootNode = tree.getModelRoot();
for (GTreeNode node : rootNode.getChildren()) {
if (node instanceof ArchiveNode) {
ArchiveNode archiveNode = (ArchiveNode) node;
if (archiveNode.getArchive() == archive) {
return archiveNode;
}
}
}
return null;
}
}
|
Java
|
UTF-8
| 2,390 | 2.8125 | 3 |
[] |
no_license
|
package com.codetest.customerapp.DAO;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.codetest.customerapp.model.Customer;
/**
* The Class CustomerDAOImpl.
*/
@Repository
public class CustomerDAOImpl implements CustomerDAO {
static Logger logger = Logger.getLogger(CustomerDAOImpl.class);
private SessionFactory sessionFactory;
/**
* Sets the session factory.
*
* @param sf
* the new session factory
*/
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
/**
* Add customer to the database
*
* @param {@link
* Customer}
*/
public void addCustomer(Customer customer) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(customer);
logger.info("Customer Id = " + customer.getId() + " is added");
customer = null;
}
/**
* Update the customer in the database
*
* @param {@link
* Customer}
*/
public void updateCustomer(Customer customer) {
Session session = this.sessionFactory.getCurrentSession();
System.out.println("cust DAO" + customer.getId());
session.update(customer);
logger.info("Customer Id = " + customer.getId() + " is edited");
customer = null;
}
/**
* Get all the customers
*
* @return {@link Customer}
*/
@SuppressWarnings("unchecked")
public List<Customer> listCustomers() {
Session session = this.sessionFactory.getCurrentSession();
List<Customer> customers = session.createQuery("from Customer").list();
return customers;
}
/**
* Get the customer by customer id
*
* @param id
* customer id
* @return {@link Customer}
*/
public Customer getCustomerById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Customer customer = (Customer) session.get(Customer.class, new Integer(id));
return customer;
}
/**
* Removes customer from the database
*
* @param id
* customer id
*/
public void removeCustomer(int id) {
Session session = this.sessionFactory.getCurrentSession();
Customer customer = (Customer) session.load(Customer.class, new Integer(id));
if (customer != null) {
session.delete(customer);
}
logger.info("Customer Id = " + customer.getId() + " is deleted");
customer = null;
}
}
|
C#
|
UTF-8
| 584 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections.Generic;
using PEG.Cst;
namespace PEG.SyntaxTree
{
public abstract class Terminal : Expression, ICstTerminalNode
{
Terminal ICstTerminalNode.Terminal
{
get { return this; }
}
public IEnumerable<OutputRecord> AsResult(int position)
{
yield return new OutputRecord(this, position);
}
public abstract string Coalesce();
public override void Accept<T>(IExpressionVisitor<T> visitor, T context)
{
visitor.Visit(this, context);
}
}
}
|
Java
|
UTF-8
| 742 | 2.578125 | 3 |
[] |
no_license
|
package cpscala.TSolver.CpUtil;
import java.lang.*;
public class SingleBitSet {
long value = JConstants.ALLONELONG;
int capacity;
public SingleBitSet(int size) {
capacity = size;
value <<= (JConstants.BITSIZE - capacity);
}
public void clear() {
value = 0L;
}
public boolean empty() {
return value == 0L;
}
public void add(int a) {
value |= JConstants.Mask1[a];
}
public boolean has(int a) {
return (value & JConstants.Mask1[a]) != 0L;
}
public void remove(int a) {
value &= JConstants.Mask0[a];
}
public int size() {
return Long.bitCount(value);
}
public long mask() {
return value;
}
}
|
PHP
|
UTF-8
| 6,054 | 2.8125 | 3 |
[] |
no_license
|
<?php
include("funciones/func_mysql.php");
conectar();
//mysql_query("SET NAMES 'utf8'");
//--------------------------------------------------------------------------------
function redim($ruta1,$ruta2,$ancho,$alto)
{
# se obtene la dimension y tipo de imagen
$datos=getimagesize ($ruta1);
$ancho_orig = $datos[0]; # Anchura de la imagen original
$alto_orig = $datos[1]; # Altura de la imagen original
$tipo = $datos[2];
if ($tipo==1){ # GIF
if (function_exists("imagecreatefromgif"))
$img = imagecreatefromgif($ruta1);
else
return false;
}
else if ($tipo==2){ # JPG
if (function_exists("imagecreatefromjpeg"))
$img = imagecreatefromjpeg($ruta1);
else
return false;
}
else if ($tipo==3){ # PNG
if (function_exists("imagecreatefrompng"))
$img = imagecreatefrompng($ruta1);
else
return false;
}
# Se calculan las nuevas dimensiones de la imagen
if ($ancho_orig>$alto_orig)
{
$ancho_dest=$ancho;
$alto_dest=($ancho_dest/$ancho_orig)*$alto_orig;
}
else
{
$alto_dest=$alto;
$ancho_dest=($alto_dest/$alto_orig)*$ancho_orig;
}
// imagecreatetruecolor, solo estan en G.D. 2.0.1 con PHP 4.0.6+
$img2=@imagecreatetruecolor($ancho_dest,$alto_dest) or $img2=imagecreate($ancho_dest,$alto_dest);
// Redimensionar
// imagecopyresampled, solo estan en G.D. 2.0.1 con PHP 4.0.6+
@imagecopyresampled($img2,$img,0,0,0,0,$ancho_dest,$alto_dest,$ancho_orig,$alto_orig) or imagecopyresized($img2,$img,0,0,0,0,$ancho_dest,$alto_dest,$ancho_orig,$alto_orig);
// Crear fichero nuevo, según extensión.
if ($tipo==1) // GIF
if (function_exists("imagegif"))
imagegif($img2, $ruta2);
else
return false;
if ($tipo==2) // JPG
if (function_exists("imagejpeg"))
imagejpeg($img2, $ruta2);
else
return false;
if ($tipo==3) // PNG
if (function_exists("imagepng"))
imagepng($img2, $ruta2);
else
return false;
return true;
}
//-----------------------------------------------------------------------------------------
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
$uploads_dir = 'imagenes/';
$id_evento=$_POST["id_evento"];
if ($_FILES['images']) {
$file_ary = reArrayFiles($_FILES['images']);
$leyenda="";
foreach ($file_ary as $file) {
// print 'Nombre: ' . $file['name'];
$tipo=$file['type'];
$size=$file['size'];
if ($tipo != 'image/JPEG' && $tipo != 'image/JPG' && $tipo != 'image/jpg' && $tipo != 'image/jpeg' && $tipo != 'image/png' && $tipo != 'image/PNG' && $tipo != 'image/gif')
{
$leyenda .=" El archivo '".$file['name']."' no es un archivo valido o Supera el tamaño <br>";
}
else
if ($size > 5500*5500) //1024
{
$leyenda .=" El archivo '".$file['name']."' supera el tamaño de 2mb <br>";
}else{
$rs = mysql_query("SELECT MAX(id_img) AS id FROM imagenes");
if ($row = mysql_fetch_row($rs)) {
$nro_imagen=trim($row[0])+1;
}else{
$nro_imagen=1;
}
$SQL="INSERT INTO imagenes (id_evento, url) VALUES (".$id_evento.", '".$uploads_dir.$nro_imagen."_".$file['name']."')";
mysqli_query($con, $SQL);
move_uploaded_file($file['tmp_name'], $uploads_dir.$nro_imagen."_".$file['name']);
# ruta de la imagen a redimensionar
$imagen=$uploads_dir.$nro_imagen."_".$file['name'];
# ruta de la imagen final, si se pone el mismo nombre que la imagen, esta se sobreescribe
$imagen_final=$uploads_dir.$nro_imagen."_".$file['name'];
$ancho_nuevo=800;
$alto_nuevo=600;
//redim($imagen,$imagen_final,$ancho_nuevo,$alto_nuevo);
}
}
$SQL="SELECT * FROM imagenes WHERE id_evento=".$id_evento;
$imagenes=mysqli_query($con, $SQL);
$nro_imagen=0;
while ($img=mysqli_fetch_array($imagenes)) {
$nro_imagen=$nro_imagen+1;?>
<div class="ed-item web-1-6 div_img" id="<?php echo "img_".$nro_imagen; ?>">
<a href="" class="imagen_pro" data-url ="<?php echo $img["url"]; ?>" data-nro="<?php echo $nro_imagen;?>" id="<?php echo $img["id_img"] ?>">X</a>
<img src="<?php echo $img["url"]; ?>" alt="foto_evento">
</div>
<?php } ?>
<div class="ed-item error_carga">
<?php echo $leyenda; ?>
</div>
<script>
$(".imagen_pro").click(function(event){
event.preventDefault();
nro_imagen=$(this).attr("data-nro");
id=$(this).attr("id");
if (confirm('Estás seguro que deseas eliminar la imagen?')) {
$(".carga_gif").show();
operacion="Eliminar_imagen";
url=$(this).attr("data-url");
$.ajax({
url:"evento_abm.php",
cache:false,
type:"POST",
data:{operacion:operacion, id_img:id, url:url},
success:function(result){
$(".carga_gif").hide();
$("#img_"+nro_imagen).hide(200);
}
});
};
})
</script>
<?php }
// # ruta de la imagen a redimensionar
// $imagen=$src;
// # ruta de la imagen final, si se pone el mismo nombre que la imagen, esta se sobreescribe
// $imagen_final=$src;
// $ancho_nuevo=800;
// $alto_nuevo=600;
mysqli_close($con);
?>
|
Markdown
|
UTF-8
| 242 | 2.890625 | 3 |
[] |
no_license
|
# Sorting
Sorting musical notes in a specific arrangement
This program sorts a variety of numbers in a given array using sorting methods like selection sort,
and corresponds the given numbers to musical notes to create a crescendo of music.
|
JavaScript
|
UTF-8
| 7,733 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
import Piedra from "./piedra.js";
import Coin from "./coins.js";
const stepLimit = 200;
export default class Enemy extends Phaser.GameObjects.Sprite {
constructor(scene, x, y, mapa, tipo) {
super(scene, x, y, tipo);
this.scene.add.existing(this);
this.scene.physics.add.existing(this);
this.body.setCollideWorldBounds(true);
this.life = 3;
this.speed = 15;
this.firstInstance = true;
this.atacado = false;
this.puedeAtacar = true;
this.tiempoEntreAtaques = 100;
this.tiempo = 100;
this.piedra = false;
this.mapa = mapa;
this.maxLife = 3;
this.bonus = 0;
this.tipo = tipo;
this.lastPosition = null;
this.body.setVelocityX(this.speed);
const anims = this.scene.anims;
if (this.tipo.localeCompare("ciclope") === 0) {
//Muere
anims.create({
key: "muerec",
frames: anims.generateFrameNumbers('ciclope', { start: 241, end: 248 }),
frameRate: 8,
repeat: -1
});
//Mueve derecha
anims.create({
key: "movderc",
frames: anims.generateFrameNumbers('ciclope', { start: 15, end: 26 }),
frameRate: 12,
repeat: -1
});
//Mueve izquierda
anims.create({
key: "movizqc",
frames: anims.generateFrameNumbers('ciclope', { start: 165, end: 176 }),
frameRate: 12,
repeat: -1
});
//Ataca derecha
anims.create({
key: "atcderc",
frames: anims.generateFrameNumbers('ciclope', { start: 46, end: 57 }),
frameRate: 12,
repeat: 0
});
//Ataca izquierda
anims.create({
key: "atcizqc",
frames: anims.generateFrameNumbers('ciclope', { start: 196, end: 207 }),
frameRate: 12,
repeat: 0
});
anims.create({
key: "standc",
frames: anims.generateFrameNumbers('ciclope', { start: 150, end: 150 }),
frameRate: 1,
repeat: 0
});
}
this.body.setSize(32, 43).setOffset(20, 21);
this.stepCount = Phaser.Math.Between(0, stepLimit);
if (this.mapa.localeCompare("verde") === 0)
this.body.setGravity(0, 200);
}
freeze() {
this.body.moves = false;
}
preUpdate(d, t) {
super.preUpdate(d, t);
if (this.life > 0) {
if (this.firstInstance) {
this.body.velocity.x = this.speed;
this.anims.play("movizqc", true);
this.lastPosition = "movizqc";
this.firstInstance = false;
}
let p = this.body.x - this.scene.player.body.x;
if (Math.sign(p) === -1) {
p = -p;
}
if (this.scene.player.body.bottom == this.body.bottom && p < 200) {
// if player to left of enemy AND enemy moving to right
if (this.scene.player.body.x < this.body.x && this.body.velocity.x > 0) {
// move enemy to left
this.body.velocity.x *= -1; // reverse direction
cambiaSprite(this);
}
// if player to right of enemy AND enemy moving to left
else if (this.scene.player.body.x > this.body.x && this.body.velocity.x < 0) {
// move enemy to right
this.body.velocity.x *= -1; // reverse direction
cambiaSprite(this);
}
}
else {
//increase enemy's step counter
this.stepCount++;
//check if enemy's step counter has reach limit
if (this.stepCount > stepLimit) {
// reverse enemy direction
this.body.velocity.x *= -1;
// reset enemy's step counter
this.stepCount = 0;
cambiaSprite(this);
}
if (this.body.blocked.right || this.body.touching.right) {
this.body.velocity.x = -this.speed;
cambiaSprite(this);
}
else if (this.body.blocked.left || this.body.touching.left) {
this.body.setVelocityX(this.speed);
cambiaSprite(this);
}
}
if (this.puedeAtacar && p < 200) {
//Variable con el signo de la velocidad de la piedra: true es positiva false negativa
let lastSpeed;
this.body.setVelocityX(0);
if (this.lastPosition.localeCompare("movizqc") === 0) {
this.anims.play("atcizqc", true);
lastSpeed = false;
}
else {
this.anims.play("atcderc", true);
lastSpeed = true;
}
if (this.anims.currentFrame.index == 2 && !this.piedra) {
let audio_ataque = this.scene.sound.add("atacaciclope", {
volume: 0.1,
});
audio_ataque.play();
}
//Cuando llega al ultimo frame del ataque aparece la piedra
else if (this.anims.currentFrame.index == 11 && !this.piedra) {
let piedra = new Piedra(this.scene, this.body.x, this.body.y, this, lastSpeed);
this.piedra = true;
}
else if (this.anims.currentFrame.index == 12) {
this.puedeAtacar = false;
this.play(this.lastPosition, true);
if (this.lastPosition.localeCompare("movizqc") === 0)
this.body.setVelocityX(-this.speed);
else this.body.setVelocityX(this.speed);
}
this.tiempo = 0;
}
else {
this.play(this.lastPosition, true);
if (this.lastPosition.localeCompare("movizqc") === 0)
this.body.setVelocityX(-this.speed);
else this.body.setVelocityX(this.speed);
}
if (this.tiempo >= this.tiempoEntreAtaques) {
this.puedeAtacar = true;
this.piedra = false;
}
else this.tiempo++;
}
else {
this.anims.play("muerec", true);
this.body.enable = false;
this.scene.time.addEvent({
delay: 1000, callback: function () {
this.scene.ciclopsGroup.killAndHide(this);
while (this.bonus < 5) {
let coin = new Coin(this.scene, this.x, this.y);
coin.body.bounce.x = 1;
this.scene.coinsGroup.add(coin);
this.bonus++;
}
}, callbackScope: this
});
}
}
}
function cambiaSprite(enemy) {
if (Math.sign(enemy.body.velocity.x) === 1) {
enemy.anims.play("movderc", true);
enemy.lastPosition = "movderc";
}
//else if enemy moving to left and has started to move over left edge of platform
else if (Math.sign(enemy.body.velocity.x) === -1) {
enemy.anims.play("movizqc", true);
enemy.lastPosition = "movizqc";
}
}
|
Python
|
UTF-8
| 7,814 | 2.609375 | 3 |
[] |
no_license
|
# Released under cc licence: https://creativecommons.org/
# Made by @hedgehog125 on github.com and scratch.mit.edu
# On Github: https://github.com/hedgehog125/AutoUpdate_v2/tree/master
import urllib.request, os, shutil, ast, math
from time import sleep
database = "unknown"
changeAmount = 0
done = False
def parse(string):
return ast.literal_eval(string)
def getWebInfo(Address, decode=True):
url = Address
response = urllib.request.urlopen(url)
data = response.read() # a `bytes` object
if not decode:
return data
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary
return text
def checkPath(path):
if path[0] == "/":
raise ValueError("Security risk: File path starts with a slash, may be trying to modify your files.")
else:
if ".." in path:
raise ValueError('Security risk: File path contains "..", may be trying to modify your files.')
# If it makes it this far it's all good. ;)
def openFile(File,Write = False,Text = ""):
if Write:
f = open(File,'w')
checkPath(File)
f.write(Text)
else:
f = open(File)
text = f.readlines()
f.close()
return text
f.close()
# Mostly from https://stackoverflow.com/questions/15323574/how-to-connect-a-progress-bar-to-a-function
import tkinter as tk
from tkinter import ttk
import threading
import queue
import time
import urllib, webbrowser, os
status = "Checking for updates..."
newVersions = []
changeProgress = 0
def changeLog():
webbrowser.open('file://' + os.path.realpath("Changelogs/Latest.html"))
class App(tk.Tk):
''' Creates the window and starts the thread(s).'''
def __init__(self):
tk.Tk.__init__(self)
self.title("Checking for updates...")
self.attributes("-topmost", True)
self.queue = queue.Queue()
self.listbox = tk.Listbox(self, width=20, height=5)
self.progressbar = ttk.Progressbar(self, orient='horizontal',
length=300, mode='determinate')
self.button = tk.Button(self, text="View Changelog", command=changeLog)
self.spawnthread()
self.progressbar.pack(padx=10, pady=10)
self.button.pack(padx=10, pady=10)
def spawnthread(self):
self.button.config(state="disabled")
self.thread = ThreadedClient(self.queue)
self.thread.start()
self.periodiccall()
def periodiccall(self):
self.checkqueue()
self.button.config(state="active")
self.title(status)
if self.thread.is_alive():
self.after(100, self.periodiccall)
else:
if len(newVersions) == 0:
self.button.config(state="disabled")
self.after(5000, self.destroy)
def checkqueue(self):
global changeProgress
while self.queue.qsize():
try:
msg = self.queue.get(0)
self.listbox.insert('end', msg)
progressToChange = changeProgress
if progressToChange >= 100:
self.progressbar.step(99.9999)
else:
self.progressbar.step(progressToChange)
changeProgress = changeProgress - progressToChange
except Queue.Empty:
pass
class ThreadedClient(threading.Thread):
''' Calls install function.'''
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while database == "unknown":
time.sleep(0.1)
self.install()
def install(self): # Now my code...
global status
global newVersions
global amount
global changeProgress
global done
avalibleVersions = parse(getWebInfo(database + "Versions.txt"))
installedVersions = parse(" \n".join(openFile("Installed.txt")))
newVersions = list(avalibleVersions)
for i in range(len(installedVersions)):
del newVersions[0]
if len(newVersions) == 0: # No updates.
changeProgress = 100
done = True
self.queue.put("")
status = "No updates found."
else:
if len(newVersions) == 1:
status = str(len(newVersions)) + " update found!"
else:
status = str(len(newVersions)) + " updates found!"
time.sleep(1)
status = "Fetching filelist..."
fileList = parse(getWebInfo(database + "Files.txt"))
changeLogs = parse(getWebInfo(database + "ChangeLogs.txt"))
links = ""
keys = list(changeLogs.keys())
default = '''
<center><b><u><font size='10'>
AutoUpdate v2: Latest updates: ChangeLogs
</font></b></u></center><br>
'''
back = "<center><a href='../Latest.html'>Back</a></center><br>"
for i in range(len(changeLogs)):
c = keys[i]
if not c in installedVersions:
openFile("Changelogs/Changelogs/" + c + ".html", True, default + back + " \n".join(changeLogs[c]))
links = links + "<a href='Changelogs/" + c + ".html'>" + c + "</a>" + "<br> \n"
openFile("Changelogs/Latest.html", True, default + links)
time.sleep(1)
status = "Downloading files... 0%"
progress = 0
add = 0
for i in fileList:
writtenFile = False
if i[0].lower() == "file":
checkPath("Assets/" + i[1])
g = urllib.request.urlopen(database + "Assets/" + i[1])
read = False
try:
currentContents = open("Assets/" + i[1], 'b').read()
read = True
except:
read = False
write = False
if not read:
write = True
else:
if currentContents != g.read():
write = True
if write:
writtenFile = True
with open("Assets/" + i[1], 'b+w') as f:
f.write(g.read())
else:
add = add + (100 / len(fileList))
else:
checkPath("Assets/" + i[1])
writtenFile = True
try:
os.makedirs("Assets/" + i[1])
except:
time.sleep(0)
if writtenFile or i == len(fileList):
time.sleep(0.15)
changeProgress = 100 / len(fileList) + add
add = 0
progress = progress + (100 / len(fileList))
status = "Downloading files... " + str(math.floor(progress)) + "%"
self.queue.put("")
time.sleep(0.25)
changeProgress = 100
self.queue.put("")
status = "Downloading files... 100%"
time.sleep(1)
status = "Updating save file..."
openFile("Installed.txt", True, str(avalibleVersions))
time.sleep(1)
status = "All done."
time.sleep(1)
status = "Successfully updated your program."
done = True
def init():
app = App()
app.mainloop()
while not done:
time.sleep(0.1)
|
Markdown
|
UTF-8
| 9,905 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Google Exposure Notification Server
## Functional requirements
This documents the functional requirements for building a decentralized exposure
notification system. For deployment strategies, see [Server Deployment Options](server_deployment_options.md).
### System Components
The Exposure Notification Server's architecture has been split into components.
The following diagram shows the relationship between the different components:

The server components are responsible for the following functions:
* Accepting the temporary exposure keys of positively diagnosed users from
mobile devices, validating those keys via device attestation APIs, and
storing those keys in a database.
* Periodically generating incremental files for download by client
devices for performing the key matching algorithm that is run on the mobile
device. The incremental files **must be digitally signed with a private key**.
The corresponding public key is pushed to mobile device separately.
* Recommended: You should use a content delivery network (CDN) to serve these
files.
* Required: A database for storage of published diagnosis keys.
* Required: A key/secret management system for storage of API keys, other
authorization credentials (CDN for example), and private keys for signing
device download content.
* Recommended: Periodically deleting old temporary exposure keys. After 14
days (or configured time period) the keys can no longer be matched to devices.
* Recommended: Using a CDN to distribute the temporary exposure keys of affected
users to mobile devices.
### Publishing temporary exposure keys
When a user reports a diagnosis, it is reported using the publish API server.
In the reference server implementation, the data is encoded in JSON and sent
over HTTPS, however you can use any encoding and protocol.
A given mobile application and server pair could agree upon additional
information to be shared. The information described in this section is the
minimum required set in order to validate the uploads and to generate the
necessary client batches for ingestion into the device for key matching.
Minimum required fields, followed by a JSON example:
* `temporaryExposureKeys`
* **Type**: Array of `ExposureKey` JSON objects (below)
* **REQUIRED**: contain 1-14 `ExposureKey` object (an individual app/server
could keep longer history)
* **Description**: The verified temporary exposure keys
* `ExposureKey` object properties
* `key` (**REQUIRED**)
* Type: String
* Description: Base64 encoded temporary exposure key from the device
* `rollingStartNumber` (**REQUIRED**)
* Type: integer (uint32)
* Description: Intervals are 10 minute increments since the UTC epoch
* `rollingPeriod` (**OPTIONAL** - this may not be present for some keys)
* Type: integer (uint32)
* Constraints
* Valid values are [1..144]
* If not present, 144 is the default value (1 day of intervals)
* Description: Number of intervals that the key is valid for
* `transmissionRisk` (**REQUIRED**)
* Type: Integer
* **The values and meanings of this enum are not finalized at this time.** //TODO(llatif): check status
* Constraints:
* Valid values range from 0-8
* Description: //TODO(llatif): Add description
* `regions` (**REQUIRED**)
[ISO 3166 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format.
* Type: Array of string
* Description: 2 letter country to identify the region(s) a key is valid for.
* `appPackageName` (**REQUIRED**)
* Type: string
* Constraints:
* For Android device, this must match the device `appPackageName` in the
SafetyNet verification payload
* Description: name of the application bundle that sent the request.
* `platform` (**REQUIRED**)
* Type: string
* Description: Mobile device platform this request originated from.
* `deviceVerificationPayload` (**REQUIRED**)
* Type: String
* Description: Verification payload.
* For Android devices this is a SafetyNet device attestation in JSON Web
Signature (JWS) format.
* For iOS devices, this is a DeviceCheck attestation.
* `verificationPayload`
* Type: String
* Description: some signature / code confirming authorization by the verification authority.
* `padding`
* Type: String
* Constraints:
* Recommend size is random between 1 and 2 kilobytes.
* Description: Random data to obscure the size of the request network packet
sniffers.
The following snippet is an example POST request payload in JSON format.
```json
{
"temporaryExposureKeys": [
{"key": "base64 KEY1", "rollingStartNumber": 12345, "rollingPeriod": 144, "transmissionRisk": 5},
{"key": "base64 KEY2", "rollingStartNumber": 12489, "rollingPeriod": 10, "transmissionRisk": 6},
{"key": "base64 KEYN", "rollingStartNumber": 12499, "rollingPeriod": 100, "transmissionRisk": 7}],
"regions": ["US", "CA", "MX"],
"appPackageName": "com.foo.app",
"platform": "android",
"deviceVerificationPayload": "base64 encoded attestation payload string",
"verificationPayload": "signature /code from of verifying authority",
"padding": "random string data..."
}
```
### Requirements and recommendations
* Required: A whitelist check for `appPackageName` and the regions in
which the app is allowed to report on.
* Required: Android device verification. The SafetyNet device attestation API
can be used to confirm a genuine Android device. For more information on
SafetyNet, see the
[SafetyNet Attestation API](https://developer.android.com/training/safetynet/attestation).
* Having `temporaryTracingKeys` and `regions` be part of the device
attestation will allow only data used to verify the device to be uploaded.
* For verification instructions, see [Verify the SafetyNet attestation response.](https://developer.android.com/training/safetynet/attestation#verify-attestation-response)
* Required: iOS device verification. You can use the `DeviceCheck` API can be
used to confirm a genuine iOS device. For more
information, see the
[DeviceCheck overview](https://developer.apple.com/documentation/devicecheck).
* For verification instructions, see
[Communicate with APNs using authentication tokens](https://help.apple.com/developer-account/#/deva05921840)
* Recommended: The `transaction_id` in the payload should be the SHA256 hash of
the concatenation of:
* `appPackageName`
* Concatenation of the `TrackingKey.Key` values in their base64 encoding,
sorted lexicographically
* Concatenation of regions, uppercased, sorted lexicographically
* Recommended: To discourage abuse, only failures in processing should
return retry-able error codes to clients. For example, invalid device
attestations should return success, with the data only saved for abuse
analysis.
* Appropriate denial of service protection should be put in place.
### Batch creation and publishing
You should schedule a script that generates files for download over the HTTPS
protocol to client devices. The generation of these files are a regular and
frequent operation (at least once a day per device), we recommend that you
generate the files in a single operation rather than on-demand, and distribute
the files using a CDN.
For information on the format of the batch file, see
[Exposure Key Export File Format and Verification](https://www.google.com/covid19/exposurenotifications/pdfs/Exposure-Key-File-Format-and-Verification.pdf).
The batch file generation should be per-region, incremental feeds of new data.
While additional data can be included in the downloads, there is a minimum set
that is required by the exposure notification API, which is relayed from
affected users in an unmodified form.
The device operating system and libraries will use the known public key to verify
an attached data signature before loading the data. To make the data verifiable:
* The data must be signed with the private key of the server.
* The public key for the server will be distributed by Apple and Google to
devices along with a list containing the countries for which the server
can provide data to.
* Export files must be signed using the ECDSA on the P-256 Curve with a
SHA-256 digest.
**Important: The matching algorithm only runs on data that has been verified
with the public key distributed by the device configuration mechanism.**
The app on the device must know which files to download. We recommend that
a consistent index file is used so that a client would download that index file
to discover any new, unprocessed batches.
If you are using a CDN to distribute these files, ensure that the cache
control expiration is set so that the file is refreshed frequently for distribution.
### Managing secrets
The use of a secure secret manager (for example,
[Hashicorp](https://www.hashicorp.com/),
[Key Vault](https://azure.microsoft.com/en-us/services/key-vault/),
[Cloud Secret](https://cloud.google.com/secret-manager)) or a hardened
on-premises equivalent is required to store the following data:
* API keys
* Android SafetyNet API key
* API keys and credentials needed for publication to the CDN
* Private signing key
* The private key for signing the client download files
### Data Deletion
Since devices will only be retaining the temporary exposure keys for a limited
time (a configurable number of days), we recommend:
* Dropping keys from the database on a similar schedule as they would be dropped
from devices.
* Removing obsolete files from the CDN.
* If used, the index file on the CDN should be updated to no longer point to
deleted files.
You should design your database to accommodate bulk deletion due to abuse,
broken apps, human error, or incorrect lab results.
|
PHP
|
UTF-8
| 396 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class Message
* @package App
*/
class Message extends Model
{
/**
* @var string
*/
protected $table = 'message';
/**
* @author Jerry
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function title()
{
return $this->belongsTo(Title::class);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.