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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 2,173
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
# SbConstant
#### 介绍
**SBConstant**,常量抽取工具,主要是为了满足公司编码规范,做的抽取工具,希望大家喜欢。 基于Antlr4开发了,SBConstant。
各种开发规范,都有要求不能在代码里出现魔数,在实际落实的时候会出现不能出现任何字符串的要求,虽说有道理但是依然是一个重复性很高的操作。
所以开发SBConstant,自动对代码进行改造。
目前**SBConstant**可以实现两种命令:
**默认命令**
- mybatis实体,抽取数据库字段
- 普通类,方法内部,魔法数提成常量
##### 实体抽取
使用场景,**mybatis plus**插件,支持**QueryWrapper**字段查询,如下:
```java
queryWrapper.eq("tenant", sysUser.getRelTenantIds());
```
这时候,会引入魔法字符**tenant**,通过程序实现的实体抽取功能可以把,实体数据库的column抽取出常量如:
```java
public class CustomerAppConstant {
//命名空间
public static final String ID = "id"
public static final String CREATE_BY = "create_by"
public static final String CREATE_TIME = "create_time"
public static final String UPDATE_BY = "update_by"
public static final String UPDATE_TIME = "update_time"
}
```
抽取命令
```sh
java -cp SBConstant.jar:./libs com.lame.sbconstant.SBConstant -ai -f CustomerApp.java
```
#### 方法内部变量抽取
会生成一个抽取后的类,所有变量被提前,因为开起了自动识别项目类型,所以可以自动别
```sh
java -cp SBConstant.jar:./libs com.lame.sbconstant.SBConstant -ai -f CustomerApp.java
```
**XTF抽取命令**
增加额外的参数`-command xtf`,可以自动使用实体变量替换
```shell
java -cp SBConstant.jar:./libs com.lame.sbconstant.SBConstant -ai -command xtf -f XController.java
```
#### 软件架构
基于antlr4,的java语法解析器。java文件解析成语法数后,完成常量识别和字段抽取工作
#### 安装教程
1. 安装java
2. gradle release
#### 参与贡献
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
|
SQL
|
UTF-8
| 6,314
| 4.3125
| 4
|
[] |
no_license
|
SELECT * FROM emp;
/*
# BETWEEN 구문
1. 컬럼명 between A and B
동일한 결과 내용으로 컬럼명 >= A and 컬럼명 <=B
**/
-- sal가 1000에서 2000사이 데이터 출력
SELECT * FROM emp
WHERE sal BETWEEN 1000 AND 2000;
-- ex) empno가 7600~7900 사이의 데이터를 출력하세요.
SELECT * FROM emp
WHERE empno BETWEEN 7600 AND 7900;
/*
# null 데이터 처리.
1. 데이터가 할당되지 않는 경우를 의미한다.
'' 공백으로 들어간 데이터와,
숫자형인 경우 0으로 들어간 데이터와 차이가 있다는 것을
반드시 확인하여야 한다.
2. 처리내용
1) 조건문 처리
컬럼명 is null : 해당 컬럼에 데이터가 할당되지 않는 경우
컬럼명 is not null : 해당 컬럼에 데이터 할당된 경우
2) 함수 처리 nvl
nvl(컬럼명, null일때 나올 데이터)
숫자형 nvl(comm, 0)
문자형 nvl(ename,'')
***/
-- comm이 null인 경우에 숫자가 안되기에 연산이 되지 않는다.
-- nvl을 활용하면 해당 내용에 대한 연산이 가능하다.
SELECT nvl(comm,0) comm
FROM emp;
SELECT sal, comm, sal+comm "합산1",
sal + nvl(comm,0)"합산2"
FROM emp;
SELECT mgr, nvl(mgr,0)
FROM emp;
-- 프로그램으로 처리하여 나타날 0과 null을 동일시 하여 처리 조건에도
-- 사용할 수 있다.
SELECT sal, comm
FROM emp
WHERE nvl(comm,0) != 0;
-- ex1) 사원명과 관리자번호(mgr)- null인 경우 0으로 출력하세요.
SELECT ename, nvl(mgr,0) mgr
FROM emp;
-- 직책명과 보너스가 null인경우 0으로 출력하세요.
SELECT job, nvl(comm,0) comm
FROM emp;
SELECT * FROM emp;
-- ex2) 중복되지 않는 관리자번호를 출력하세요 null이 아닌 경우만 (nvl함수 이용)
SELECT DISTINCT deptno
FROM emp
WHERE nvl(mgr,0)!=0;
-- 중복되지 않는 관리자번호(mgr)를 출력하세요. null인 경우
SELECT DISTINCT mgr
FROM emp
WHERE nvl(mgr,0) =0;
-----------
SELECT * FROM emp;
/*
# in 구문
1. 데이터는 or 조건에 관련된 내용은 이거나로
해당 조건 이외에 조건에 대한 내용을 논리적으로
처리해준다.
2. 이 때, 하나의 컬럼을 기준으로 많은 or 조건을 처리할 때,
효과적이고 간편하게 처리하기 위하여 in 구문을 제공한다.
*/
-- deptno 10이거나 20번인 경우
SELECT ename, deptno
FROM emp
WHERE deptno = 10 OR deptno = 20;
-- 컬럼명 in (데이터1, 데이터2 ) : 해당 컬럼에 데이터1이거나 데이터2인경우
SELECT ename, deptno
FROM emp
WHERE deptno IN (10,20);
SELECT empno, ename, deptno
FROM emp
WHERE empno IN(7369,7521,7654);
-- ex) job이 SALESMAN 이거나, MANAGER 인 경우를 IN 구문을 이용해서
-- 출력하세요
SELECT *
FROM emp
WHERE job IN('SALESMAN','MANAGER');
-- subquery : 수행된 결과값을 기준으로 다시 조회 조건을 처리하는 구문
-- 부서번호가 30번인 사원번호를 검색해서, 그 사원번호에 해당하는 사원정보를
-- 처리
SELECT *
FROM emp
WHERE empno in(
SELECT empno
FROM emp
WHERE deptno = 30);
-- 연봉이 최고인 사람의 정보를 출력하세요.
SELECT *
FROM emp
WHERE sal in(
SELECT max(sal)
FROM emp
);
/*
# like 연산자를 이용한 keyword 조건 검색
1. 컬럼에 저장된 문자열 중에서 like 연산자에서 지정한 문자 패턴과 부분적으로
일치하면 참이 되어, 조건문에서 검색되게 하는 것을 말한다.
ex) 사원명에 'A'라는 문자열을 포함하면 조회도게 한다.
1) 위치 상관없이 검색 : 컬럼명 like '%A%'
2) A로 시작하면 검색 : 컬럼명 like 'A%'
3) N로 끝나는 검색 : 컬럼명 like '%N'
4) 자릿수 위치에 맞는 데이터 검색 세번째자리에
A나오는 데이터 검색 : 검색컬럼 like '__A%'
*/
-- ename 안에 문자 A가 들어있는걸 다 검색.
SELECT *
FROM EMP
WHERE ename LIKE '%A%';
-- ename 안에서 문자 A로 시작하는 것 검색
SELECT *
FROM EMP
WHERE ename LIKE 'A%';
-- ename 안에서 문자 N로 끝나는 것 검색
SELECT empno, ename FROM emp WHERE ename LIKE '%N';
-- 세번째 자리에 A나오는 데이터 검색 : 검색컬럼 like '__A%'
SELECT empno, ename FROM emp WHERE ename LIKE '__A%';
--ex1) job 컬럼에 MAN이라는 글자가 포함되어 있으면 출력하세요..
SELECT job
FROM EMP
WHERE job LIKE '%MAN%';
--ex2) ename에서 S로 끝나는 글자와
-- S를 포함하는 글자가 있는 데이터를 구분해서
-- sql을 2개 작성하세요.
SELECT * FROM emp
where ename LIKE '%S';
SELECT *
FROM emp
WHERE ename LIKE '%S%';
--ex3) ename이나 job의 마지막에서 두번째 글자가 E가
-- 들어가는 데이터를 조회하세요.
SELECT *
FROM emp
WHERE ename LIKE '%E_'
OR job LIKE '%E_';
/*
# 정렬처리
1. SQL 명령문에서 검색된 결과는 테이블에 데이터가 입력된 순서대로 출력
2. 데이터의 출력 순서를 특정 컬럼을 기준으로 오름차순/내림차순으로 정렬하는 경우가
발생한다.
3. 여러 개의 컬럼에 대해 정렬 순서를 지정해서 처리해야 할 경우가 발생한다.
- 입사일은 오름차순, 급여 기준으로 내림차순..
4. 기본적인 정렬 방법
- 문자값을 알파벳순으로 출력되고, 한글은 가나다라 순으로 출력된다.
- 숫자 값을 가장 작은 값으로 먼저 출력.
- 날짜 과거의 날짜순으로 출력된다.
5. 기본 형식.
select *
from 테이블
where ..
order by 컬럼명 [ASC/DESC]
asc : default 오름차순 정렬
desc : 역순으로 정렬
*/
-- 사원번호를 역순으로 사원번호와 이름을 조회
SELECT empno, ename
FROM emp
ORDER by empno DESC;
-- ex1) 입사일을 기준으로 역순으로 출력하세요
SELECT hiredate
FROM emp
ORDER BY hiredate DESC;
-- ex2) 연봉을 오름차순으로 출력하세요.
SELECT sal
FROM emp
ORDER BY sal ;
-- ex3) 부서번호 오름차순, 연봉 내림차순으로 동시에 처리 출력하세요. hint (,)
SELECT deptno "부서번호", sal "급여", a.*
FROM emp a -- FROM 테이블명 별칭
ORDER BY deptno, sal DESC;
|
C++
|
GB18030
| 2,947
| 2.609375
| 3
|
[] |
no_license
|
// HexView.cpp : implementation file
//
#include "stdafx.h"
#include "SimpleSniffer.h"
#include "HexView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CHexView
IMPLEMENT_DYNCREATE(CHexView, CEditView)
CHexView::CHexView()
{
// CHexView ʾʮϢ
// ʼ theApp е Hex ָΪ this
theApp.m_editor = dynamic_cast<Hex*>(this);
}
CHexView::~CHexView()
{
}
BEGIN_MESSAGE_MAP(CHexView, CEditView)
//{{AFX_MSG_MAP(CHexView)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CHexView drawing
void CHexView::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
}
/////////////////////////////////////////////////////////////////////////////
// CHexView diagnostics
#ifdef _DEBUG
void CHexView::AssertValid() const
{
CEditView::AssertValid();
}
void CHexView::Dump(CDumpContext& dc) const
{
CEditView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CHexView message handlers
// ʵʮƵʾ, Hex Ĵ麯
void CHexView::ShowHexText(char *data, int len)
{
CString result; // 洢ս
CString temp; // ʱ洢м
int lineHead; // ƫ
for(lineHead = 0; lineHead < len; lineHead += 16)
{
// ӡƫ
temp.Format("%04X: ", lineHead);
result += temp;
CString hex; // һе16ַʽ
CString asc; // һеASCIIʽ
int pos; // ƫ
int lineLength = len - lineHead >= 16 ? 16 : len - lineHead; // Ҫӡֽڸ
for(pos = 0; pos < lineLength; ++pos)
{
unsigned char c = (unsigned char)data[lineHead + pos];
// 16Ƹʽ
if(pos != 8)
temp.Format(" %02X", c);
else
temp.Format("-%02X", c);
hex += temp;
// ASCIIʽ
asc += _istprint(c) ? c : '.';
}
result += hex;
if(pos < 16)
{
CString sPad(' ', 3 * (16 - pos));
result += sPad;
}
result += " ";
result += asc;
result += "\r\n";
}
// ʾ!
this->SetWindowText(result);
}
// ʼ, ñ༭ֻ
void CHexView::OnInitialUpdate()
{
CEditView::OnInitialUpdate();
static BOOL inited = FALSE;
if(inited) return;
inited = TRUE;
// ´ֻ״ε OnInitialUpdate ʱִ
CEdit& control = this->GetEditCtrl();
control.SetReadOnly();// ༭ֻ, ֶ
// Ϊ"" Դﵽ ոĸȿЧ
this->m_Font.CreatePointFont(120, "");
this->SetFont(&this->m_Font, false);
}
|
Python
|
UTF-8
| 712
| 2.546875
| 3
|
[] |
no_license
|
from tkinter import *
from selection import *
root=Tk()
root.title("SECRET_CODE")
def nextpage():
root.destroy()
selections()
L1=Label(root,text="2 WAY SECRET CODE",font=("bold",40,),bg="green",fg="white")
L1.pack()
l0=Label(root)
l0.pack()
l2=Label(root,text="MESSAGING",font=("bold",40,),bg="green",fg="white")
l2.pack()
blk_lab=Label(root)
blk_lab.pack()
#photo
photo = PhotoImage(file = 'Top_secret.png')
photo = photo.subsample(1)
lbl = Label(root,image = photo)
lbl.image = photo
lbl.pack()
blk_lab2=Label(root)
blk_lab2.pack()
but=Button(root,text="**SECRERT**",bg="red",fg="white",font=("bold",14,),padx=10,pady=10,command=nextpage)
but.pack()
root.mainloop()
|
Markdown
|
UTF-8
| 1,871
| 2.859375
| 3
|
[] |
no_license
|
# bin Scripts
This repo contains various bin scripts that I use. Nothing here is explicitly personal, so the repo is public. If you find some use in it let me know. Don't expect things to be well commented or even well written. It's quick. It's dirty. It makes my life easier.
## airdrop
Broadcasts a file over `nc` so that it can be read on a remote system. Handy for sending files quickly around a local network, just like Apple's AirDrop. This defaults to `en1` (default wireless adapter on Apple hardware) but can be configured to use any network interface.
Make `file` available on port `5050` of your machine and copy the corrosponding `curl` string into your clipboard.
airdrop file
Make `file` available on port `5050` of your machine and copy the corrosponding `curl` string into your clipboard. Uses the information from `en0` for this.
airdrop file en0
Make `file` available on the public port `5050` of your remote connection. This requires your router / switch / firewall to accept incomming connections on this port.
airdrop file --public
## bdate
My blog posts use the number of milliseconds since epoch to judge time. This is a quick output to the clipboard (in OSX) of the current seconds since epoch with "000" tacked on to the end without a newline.
## checklb
Pings my domain every second and then parses out the `X-Forward` header I set to see which server is actually responding.
## im
I collect links by day into files. This gives me a quick way of storing them because I always have a terminal open. If run without arguments it will copy all the links to the clipboard (OSX) for easy pasting.
## phrase
I have a list of phrases in various languages I use infrequently when I tire of English. This allows me to easily search and list all matching phrases / words.
## shuf
Shuffles the input lines around using `awk`.
|
Markdown
|
UTF-8
| 753
| 2.578125
| 3
|
[] |
no_license
|
---
title: "Detectors"
---
Multiple flows can be detected by a single detector within a certain facility of a segment area. Additionally, detectors are decoupled from a segment area to allow for detector devices to move multiple times in multiple areas.
Required parameters for _Detectors_ are:
* Jurisdiction
* Description
* Short Name
Optional parameters are:
* Serial Number
* Make
* Model
* Automated
If counts are detected by an automated counter, the Serial Number, Make, and Model should be recorded in the event the automated counter is re-used for a different flow, facility, or segment area; and to monitor the functional status of the counter.
If counts are manually recorded then the Make or Model field should be filled with "Manual".
|
Java
|
UTF-8
| 669
| 3.359375
| 3
|
[] |
no_license
|
import java.util.Scanner;
/**
* @author Branium Academy
* @address https://braniumacademy.net/
*/
public class L21Ex4 {
public static void main(String[] args) {
var input = new Scanner(System.in);
System.out.println("Nhập số nguyên dương n: ");
var n = input.nextInt();
printRevert(n);
}
// phương thức in ra các chữ số của n theo thứ tự đảo ngược
public static void printRevert(int n) {
if (n > 0) { // điều kiện để tiếp tục
System.out.print(n % 10);
printRevert(n / 10); // giảm n đi 10 lần để loại bỏ phần đơn vị
}
}
}
|
Python
|
UTF-8
| 663
| 3.59375
| 4
|
[] |
no_license
|
import math
def is_palindrome(x):
s = str(x)
n = len(s)
for i in range(n):
if s[i] != s[n - i - 1]:
return False
return True
def count(a, b):
res = 0
for x in range(a, b + 1):
sq = int(math.sqrt(x))
if sq * sq == x and is_palindrome(x) and is_palindrome(sq):
res = res + 1
return res
def get_ints(line):
line = line.split(" ")
return [int(item) for item in line]
with open("c.in", "rb") as file:
tn = int(file.readline())
for test in range(tn):
tmp = get_ints(file.readline())
a = tmp[0]
b = tmp[1]
result = count(a, b)
print "Case #{test}: {result}".format(test = test + 1, result = result)
|
C#
|
UTF-8
| 599
| 3.3125
| 3
|
[] |
no_license
|
using System.Linq;
namespace AlternatingSplit
{
internal class Program
{
public static void Main(string[] args)
{
}
}
public class Kata
{
public static string Encrypt(string text, int n)
{
for (var index = 0; index < n; index++)
text = string.Concat(
text.Select((c, i) => new {c, i}).Where(g => g.i % 2 == 0).Select(g => g.c),
text.Select((c, i) => new {c, i}).Where(g => g.i % 2 == 1).Select(g => g.c)
);
return text;
}
}
}
|
C
|
UTF-8
| 6,616
| 4.125
| 4
|
[] |
no_license
|
/*
Number converter
Menu
Convert between integer, binary, octal and hexadecimal
This program should accept numeric values in hexadecimal,
decimal, octal and binary formats as:
Hex 0x0 to 0xFFFFFFFF
Dec 0 to 4294967295
Oct o0 to o37777777777
Bin b0 to b11111111111111111111111111111111
After a value is input the code in main will interpret the
data types above an process the conversion to an unsigned
int. The unsigned int will be used to convert the input to
strings containing hexadecimal, octal and binary strings.
*/
//int input_to_decimal(char *input);
#include <stdio.h>
#include <string.h>
#include <math.h>
unsigned int bin_to_uint(char *input);
unsigned int oct_to_uint(char *input);
unsigned int hex_to_uint(char *input);
unsigned int dec_to_uint(char *input);
void uint_to_hex(unsigned int n, char *output);
void uint_to_oct(unsigned int n, char *output);
void uint_to_bin(unsigned int n, char *output);
int error = 0;
int main(){
char input[50];
unsigned int n = 0;
char output[50];
// Write code here to test your functions
// Uncomment code below when done
printf("Enter a binary, octal, decimal or hexadecimal number\n");
printf("convert > ");
gets(input);
// Detect input data type
// Hexadecimal
if(input[0] == '0' && input[1] == 'x'){
n = hex_to_uint(input);
}
// Decimal
else if(input[0] >= '0' && input[0] <= '9'){
n = dec_to_uint(input);
}
// Octal
else if(input[0] == 'o'){
n = oct_to_uint(input);
}
// Binary
else if(input[0] == 'b'){
n = bin_to_uint(input);
}
// Unknown
else{
printf("ERROR: Unknown data type: %s\n", input);
}
// Print results
printf("The decimal value of %s is %u\n", input, n);
uint_to_hex(n, output);
printf("The hexadecimal value of %s is %s\n", input, output);
uint_to_oct(n, output);
printf("The octal value of %s is %s\n", input, output);
uint_to_bin(n, output);
printf("The binary value of %s is %s\n", input, output);
return 0;
}
// Convert a hexadecimal char array to uint
unsigned int hex_to_uint(char *input){
unsigned int res = 0;
unsigned iterator;
int len=strlen(input);
unsigned mul=0;
for(int i=len-1;i>0;i--){
if('0'<=input[i] && input[i]<='9'){
int c=input[i]-48;
int power=pow(16,mul);
res=res+c*power;}
if('A'<=input[i] && input[i]<='E'){
int c=input[i]-55;
printf("c is %d",c);
int power=pow(16,mul);
res=res+c*power;
}
mul++;
}
return res;
}
unsigned int dec_to_uint(char *input){
unsigned int res = 0;
int len=strlen(input);
unsigned mul=0;
for(int i=len-1;i>=0;i--){
if('0'<=input[i] && input[i]<='9'){
int c=input[i]-48;
int power=pow(10,mul);
res=res+c*power;}
mul++;
}
return res;
}
// Convert a octal char array to uint
unsigned int oct_to_uint(char *input){
unsigned int res = 0;
unsigned iterator;
int len=strlen(input);
unsigned mul=0;
for(int i=len-1;i>0;i--){
if('0'<=input[i] && input[i]<='7'){
int c=input[i]-48;
int power=pow(8,mul);
res=res+c*power;
}
mul++;
}
return res;
}
/*
Copy oct_to_uint() and modify for binary input.
*/
// Convert a binary char array to unsigned int
unsigned int bin_to_uint(char *input){
unsigned int res = 0;
unsigned iterator;
int len=strlen(input);
unsigned mul=0;
for(int i=len-1;i>0;i--){
if('0'==input[i]){
res=res+1;
}
if('1'==input[i]){
int power=pow(2,mul);
res=res+power;
}
mul++;
}
return res;
}
void uint_to_hex(unsigned int n, char *output){
// Declare a uint for remainder
unsigned remain;
// Declare an int for division
int div=1;
int i=0;
// Declare a char array buffer
char res[20];
printf("n is %d\n",n);
while(div>0){
if(0<=n&&n<=15){
if(0<=n&&n<=9){
char c=n+48;
res[i]=c; res[i+1]='\0';i++;break;
}
if(10<=remain&&remain<=15){
char c=n+55;
res[i]=c;res[i+1]='\0';i++;break;
}
}
else{
div=n/16;
remain=n%16;
if(0<=remain&&remain<=9){
char c=remain+48;
res[i]=c;
}
if(10<=remain&&remain<=15){
char c=remain+55;
res[i]=c;
}
i++;
n=div;
}
}
output[0]='0';output[1]='x';
for(int a=0;a<i;a++){
output[a+2]=res[i-1-a];
}
output[i+2]='\0';
printf("hex is %s\n",output);
return;
}
// Convert a unsigned integer char array to octal
void uint_to_oct(unsigned int n, char *output){
unsigned remain;
// Declare an int for division
int div=1;
int i=0;
// Declare a char array buffer
char res[20];
printf("n is %d\n",n);
while(div>0){
if(0<=n&&n<=7){
char c=n+48;
res[i]=c;res[i+1]='\0';i++;break;
}
else{
div=n/8;
remain=n%8;
if(0<=remain&&remain<=7){
char c=remain+48;
res[i]=c;
}
i++;
n=div;
}}
output[0]='o';
for(int a=0;a<i;a++){
output[a+1]=res[i-1-a];
}
output[i+1]='\0';
printf("oct is %s\n",output);
return;
}
/*
Copy uint_to_oct() and modify for binary
*/
// Convert a unsigned integer char array to binary
void uint_to_bin(unsigned int n, char *output){
unsigned remain;
// Declare an int for division
int div=1;
int i=0;
// Declare a char array buffer
char res[20];
printf("n is %d\n",n);
while(div>0){
if(0<=n&&n<=1){
char c=n+48;
res[i]=c;res[i+1]='\0';i++;break;
}
else{
div=n/2;
remain=n%2;
if(0<=remain&&remain<=2){
char c=remain+48;
res[i]=c;
}
i++;
n=div;
}}
output[0]='b';
for(int a=0;a<i;a++){
output[a+1]=res[i-1-a];
}
output[i+1]='\0';
return;
}
|
Java
|
UTF-8
| 758
| 1.875
| 2
|
[] |
no_license
|
package com.appnews.jjs.appnews.base;
import android.app.Application;
import com.appnews.jjs.appnews.utils.okhttp.OkHttpUtils;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
/**
* Created by 15596 on 2016/11/23.
*/
public class AppBaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
// .addInterceptor(new LoggerInterceptor("TAG"))
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.readTimeout(10000L, TimeUnit.MILLISECONDS)
//其他配置
.build();
OkHttpUtils.initClient(okHttpClient);
}
}
|
Shell
|
UTF-8
| 485
| 3.171875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
if [[ "${0}" = /* ]]; then ME="${0}"; else ME="${PWD}/${0}"; fi
while [ -h ${ME} ]; do ME=$(readlink $ME); done
source `dirname ${ME}`/../shell_base.sh
echo "Usage: ${progName} --device=<device_name>"
echo " [--dist=<android-5.1.1_r1|cm-12.0>]: Android distribution."
echo " [--numrows=<n>]: Items to return."
echo " [--pipeline_number=<n>]: Filter by pipeline number."
echo " [--build_number=<n>]: Filter by build number."
echo ""
echo "Not yet implemented"
exit 1
|
Java
|
UTF-8
| 884
| 2.078125
| 2
|
[] |
no_license
|
package com.shencode.ownwebplatform.controller;
import com.shencode.ownwebplatform.model.Message;
import com.shencode.ownwebplatform.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
@RequestMapping("/login")
public class LoginController {
@Resource
private UserService service=null;
@GetMapping("")
public String getlogin()
{
return "login";
}
//登录验证
@PostMapping("/DbLogin")
@ResponseBody
public Message login(String loginName, String password)
{
return service.login(loginName,password);
}
}
|
C++
|
UTF-8
| 987
| 3.453125
| 3
|
[] |
no_license
|
#include "currency.h"
#include <gtest/gtest.h>
using namespace std;
TEST(Currency, EmptyConnstructor)
{
Currency C1;
Currency C2;
Currency C3 = (C1 + C2);
EXPECT_EQ(0, C3.getrupees());
EXPECT_EQ(0, C3.getpaise());
}
TEST(Currency, plus_with_without)
{
Currency C1(7,22);
Currency C2(1,2);
Currency C3 = (C1 + C2);
Currency C5 = (C1 + 5);
EXPECT_EQ(8, C3.getrupees());
EXPECT_EQ(24, C3.getpaise());
EXPECT_EQ(12, C5.getrupees());
EXPECT_EQ(27, C5.getpaise());
}
TEST(Currency, Preincrement)
{
Currency C1(7,22);
Currency& C4 = ++C1;
EXPECT_EQ(8, C4.getrupees());
EXPECT_EQ(23, C4.getpaise());
}
TEST(Currency, postincrement)
{
Currency C1(7,22);
Currency C3 = C1++;
EXPECT_EQ(7, C3.getrupees());
EXPECT_EQ(22, C3.getpaise());
}
TEST(Currency, equals)
{
Currency C1(7,22);
Currency C2(7,22);
EXPECT_EQ(1, (C1 == C2));
}
|
JavaScript
|
UTF-8
| 16,152
| 2.53125
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"CC-BY-4.0",
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"Python-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
/**
* @fileoverview Translation file for Japanese.
*
* @license Copyright 2016 The Coding with Chrome Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author junji.hashimoto@gmail.com (Junji Hashimoto)
*/
window['Locales'] = window['Locales'] || {};
/**
* @final
* @export
*/
/* eslint-disable max-len */
Locales['jpn'] = {
'(0 - 254)': '(0 - 254)',
'* You need to restart the application after enabling or disabling these options.': '* このオプションを変更した後、アプリの再起動が必要です。',
'About Coding with Chrome': 'コーディング ウィズ クロームについて',
'Address: {$address}': 'アドレス: {$address}',
'Advanced Coding': 'アドバンスド コーディング',
'Advanced Mode': 'アドバンスド モード',
'Advanced': 'アドバンスド',
'Automatically reloads the preview after a change on the editor content': 'このエディタの中身を変更後、自動的にプレビューを更新します。',
'Begin a new program to drive a Sphero or an on-screen robot with Blockly': 'ブロックリーを使って、スクリーンでスフィロを動かす新しいプログラムを始めます',
'Begin a new program to drive an EV3 or an on-screen robot with Blockly': 'ブロックリーを使って、スクリーンでEV3を動かす新しいプログラムを始めます',
'Begin to learn coding with visual block programming. Put together the program steps by dragging and dropping coding blocks.': 'ブロックプログラミングでプログラミングを始めましょう。ブロックをドラッグアンドドロップで並べて一緒にプログラムを組み立てます。',
'Beginner': 'ビギナー',
'Blockly file': 'ブロックリー ファイル',
'Blockly': 'ブロックリー',
'Blocks': 'ブロック',
'Build software with text-based programming languages': 'テキストで書かれたプログラムをビルド',
'Build website code': 'ウェブサイトコードをビルド',
'CUSTOM': 'カスタム',
'Cancel': 'キャンセル',
'Check Syntax...': '文法チェック',
'Circle Animation': '丸を書く動画',
'Close Settings': '設定を閉じる',
'Close': '閉じる',
'Coding with Chrome credits': 'コーディング ウィズ クロームの著作権',
'Coding with Chrome is an educational development environment': 'コーディング ウィズ クロームは教育用の開発環境です。',
'Coding with Chrome': 'コーディング ウィズ クローム',
'CoffeeScript file': 'CoffeeScript ファイル',
'CoffeeScript': 'CoffeeScript',
'Collapse Blockly editor.': 'ブロックリーエディタを折りたたむ。',
'Collison Example': '衝突判定の例',
'Color sensor - sound': '色センサー - 音',
'Connect Bluetooth device': 'Bluetooth デバイスにつなぐ',
'Connect {$type} device': '{$type} デバイスにつなぐ',
'Connecting Bluetooth device': 'Bluetooth デバイスに接続中',
'Connecting device {$xxx}...': '{$xxx} デバイスに接続中',
'Control a Sphero with JavaScript': 'JavaScriptでスフィロを動かす',
'Control a real or virtual EV3 by assembling Blockly Blocks': 'ブロックリーを組み立てて本物もしくはスクリーンのEV3を動かす',
'Control a real or virtual Sphero by assembling Blockly Blocks': 'ブロックリーを組み立てて本物もしくはスクリーンのスフィロを動かす',
'Control an EV3 with JavaScript': 'JavaScriptでEV3を動かす',
'Control real or on-screen robots with Blockly': 'ブロックリーで本物もしくはスクリーンのロボットを動かす',
'Control the EV3 or a virtual robot with JavaScript': 'JavaScriptでEV3もしくはスクリーンのロボットを動かす',
'Control the Sphero or a virtual robot with JavaScript': 'JavaScriptでスフィロもしくはスクリーンのロボットを動かす',
'Control real or virtual robots': '本物もしくはスクリーンのロボットを動かす',
'Create applications and websites using HTML, CSS and JavaScript': 'HTMLとCSSとJavaScriptを使ってアプリもしくはウェブサイトを作る',
'Create artworks of color and forms': '色とフォームのデザインを作る',
'Create empty project': '空のプロジェクトを作る。',
'Create new project': '新しいプロジェクトを作る。',
'Create some music': '音楽を作る。',
'Create website code': 'ウェブサイトを作る。',
'Debug mode': 'デバッグ モード',
'Default UI language.': '言語選択',
'Draw Portal Turret': 'ポータル(映画)のタレットを描く',
'Draw a Portal Turret': 'ポータル(映画)のタレットを描く',
'Draw art, play music or create games': '絵を書いて、音楽を再生して、ゲームを作る',
'Draw lines with loops': '繰り返しを使って線を描く',
'Draw points with random colors and loops': 'ランダムカラーと繰り返しを使って点を描く',
'Draw': '描く',
'EDUCATOR': '先生',
'EV3 block file': 'EV3ブロックファイル',
'EV3 file': 'EV3ファイル',
'EV3': 'EV3',
'Educator - Block Grabber': '先生 - ブロックグラバー',
'Educator Robot is grabbing a block': 'ロボッター先生がブロックをつかみます。',
'Empty project': '空のプロジェクト',
'Enable autocomplete': '自動補完の有効化',
'Example Sphero is rolling a rectangle': 'スフィロのサンプルは四角を回します。',
'Example that animates a circle': '丸を動かすサンプル',
'Example that animates a triangle': '三角を動かすサンプル',
'Executes the code and send commands to the connected unit': 'プログラムを実行してコマンドを接続先に送ります。',
'Exit': '終了',
'Expand Blockly editor': 'ブロックリーエディタを開く。',
'First, please {$startBold}select your current coding skill{$endBold}': 'まず、{$startBold}あなたのプログラミングのレベルを選んでください。{$endBold}',
'Form example': 'フォームのサンプル',
'Form': 'フォーム',
'GRYO BOY': 'GRYO BOY',
'General Settings': '一般設定',
'General': '一般',
'Go Blockly': 'ブロックリーモードへ',
'Go Coding ': 'コーディングモードへ',
'Go Robots': 'ロボットモードへ',
'Go Simple': 'シンプルモードへ',
'Go Web': 'ウェブモードへ',
'HTML5 file': 'HTML5 ファイル',
'HTML5 form example': 'HTML5 フォームの例',
'HTML5': 'HTML5',
'Hello %s': 'Hello %s',
'Hello World example': 'ハローワールドの例',
'Hello World': 'ハローワールド',
'Hello, World': 'ハローワールド',
'If enabled, CwC will be launched in fullscreen': '有効にすると自動的にフルスクリーンで起動する。',
'If enabled, a welcome screen will show every time CwC is started with the choice between "beginner mode" and "advanced mode".': '有効にすると起動時の画面でビギナーモードとアドバンスドモードの選択画面がでます。',
'Insert Image...': '画像を挿入',
'JavaScript file': 'JavaScriptファイル',
'JavaScript made easy - JavaScript plus a variety of functions that make your life easier': 'JavaScript簡単モード - JavaScriptといろいろ役立つ関数。',
'JavaScript made easy through easy starter functions': '簡単な入門用の関数を使うJavaScript簡単モード',
'JavaScript': 'JavaScript',
'Launch in fullscreen': 'フルスクリーン表示',
'Lego Mindstorms EV3': 'レゴマインドストームEV3',
'Line loop': 'Line loop',
'Line follower example': 'ライントレースのサンプル',
'Line follower': 'ライントレース',
'Load circle animation': '丸を書く動画を読み込む',
'Load triangle animation': '三角を書く動画を読み込む',
'Load turtle catch': '亀捕まえゲームの読み込み',
'Make some noise': '音をたてて',
'Markup language': 'マークアップ言語',
'Markup': 'マークアップ',
'Misc settings': 'その他の設定',
'Misc': 'その他',
'More options...': 'もっと他のオプション',
'Music': '音楽',
'New file': '新しいファイル',
'New program': '新しいプログラム',
'New project': '新しいプロジェクト',
'New variable...': '新しい変数...',
'No': 'いいえ',
'Ok': 'はい',
'Open Example': 'サンプルを開く',
'Open file': 'ファイルを開く',
'Pencil Code file': '鉛筆コードファイル',
'Pencil Code': '鉛筆コード',
'Plays different tones depending on the detected color.': '色に合わせたいろいろな音を流す。',
'Point loop': '点の繰り返し',
'Program robots with JavaScript': 'JavaScriptでロボットプログラム',
'Programming language': 'プログラム言語',
'Programming': 'プログラム',
'Prompt': 'プロンプト',
'Put together the components of a website- HTML, CSS and JavaScript': 'ウェブのファイル(HTMLとCSSとJavaScript)を一緒に置いてください。',
'ROBOT ARM H25': 'ROBOT ARM H25',
'Rectangle example': '四角の例',
'Redo last change': 'やり直し',
'Reload preview': 'プレビューを更新',
'Rename variable...': '変数の名前を変える',
'Robot: EV3': 'ロボット: EV3',
'Robot: Sphero': 'ロボット: スフィロ',
'Robots': 'ロボット',
'Runs the code and update preview': 'コードを動かして、プレビューを更新する。',
'Save as new file': '新しいファイルとして保存',
'Save the project': 'プロジェクトを保存',
'Select Tutorials': '入門用の紹介を選択',
'Settings': '設定',
'Show screen on startup': '起動時にスクリーンを表示',
'Show welcome screen': 'ウェルカムスクリーンを表示',
'Shows general information...': '通常の設定を見る',
'Simple JS file': 'シンプル JS ファイル',
'Simple game where the goal is to catch a turtle': '亀を捕まえる簡単なゲーム',
'Simple line follower example': '簡単なライントレースロボットのサンプル',
'Simple': 'シンプル',
'Sphero 2.0': 'スフィロ 2.0',
'Sphero block file': 'スフィロ ブロック ファイル',
'Sphero file': 'スフィロ ファイル',
'Sphero': 'スフィロ',
'Start drawing': '描画を始める。',
'Start an empty CoffeeScript project': '空のCoffeeScriptプロジェクトを始める。',
'Start an empty EV3 project': '空のEV3プロジェクトを始める。',
'Start an empty HTML5 project': '空のHTML5プロジェクトを始める。',
'Start an empty JavaScript project': '空のJavaScriptプロジェクトを始める。',
'Start an empty Sphero project': '空のスフィロプロジェクトを始める。',
'Start an empty pencil code project': '空の鉛筆コードプロジェクトを始める。',
'Start building new code': '新しいプログラムを始める。',
'Start learning JavaScript with video tutorials on YouTube': 'YouTubeの紹介用の動画でJavaScriptを使って学びましょう。',
'Stops or terminates the preview': 'プレビューを止めるもしくは終了する。',
'Stops the execution of the code': 'プログラムの実行を止める。',
'Switch to Blockly': 'ブロックリーに切り替える',
'Switch to Editor': 'エディタに切り替える',
'Switch to the Blocky editor mode': 'ブロックリーエディタモードに切り替える。',
'Switch to the raw code editor view': 'コードエディタに切り替える。',
'TRACK3R': 'トラック3R',
'Text loop example': 'テキストの繰り返しのサンプル',
'Text loop': 'テキストの繰り返し',
'Text-based programming languages': 'テキストによるプログラム言語',
'The "advanced mode" will turn off all block-based options': '"アドバンスドモード" はすべてのブロックによる設定を無効化します。',
'The "debug mode" will turn on some additional debug options': '"デバッグモード" は追加のデバッグ設定を有効化します。',
'This screen allows you to change some random settings': 'このスクリーンでランダムな設定の変更ができます。',
'This screen allows you to change the default settings': 'このスクリーンで初期設定の変更ができます。',
'Triangle animation': '三角を動かす動画',
'Try example': 'サンプルを試す',
'Try a Hello World example': 'ハローワールドのサンプルを試す',
'Try a Sphero example - change color on collision': 'スフィロのサンプルを試す - ぶつかると色が変わる。',
'Try a Sphero example - rolling a rectangle': 'スフィロのサンプルを試す - 四角が回転する。',
'Turtle catch': '亀を捕まえる',
'Undo last change': 'やり直し。',
'Unsaved Changes for Basic: Text loop': '保存されてない変更: テキストループ',
'Use Advanced Mode': 'アドバンスド モードを使う',
'Use Beginner Mode': 'ビギナー モードを使う',
'Use Blockly to build code by dragging and dropping code blocks': 'ブロックをドラッグアンドドロップしてプログラムするブロックリーを使う',
'Use CoffeeScript': 'CoffeeScriptを使う',
'Use EV3 Robot': 'EV3ロボットを使う',
'Use HTML5': 'HTML5を使う',
'Use JavaScript to create programs': 'プログラムを作るのにJavaScriptを使う',
'Use JavaScript': 'JavaScriptを使う',
'Use Pencil Code': '鉛筆コードを使う',
'Use Sphero robot': 'スフィロロボットを使う',
'Use a high-level programming language like JavaScript or CoffeeScript to write your code': 'プログラムを書くのにJavaScriptやCoffeeScriptの高級言語を使う。',
'Use the simple CoffeeScript language to create programs': 'プログラムを書くのに簡略化CoffeeScriptを使う。',
'Video tutorials': '入門用の紹介の動画',
'Warning': '注意',
'Welcome to Coding with Chrome!': 'コーディング ウィズ クロームへようこそ!',
'Write code in JavaScript': '簡略化JavaScriptでプログラムを書く',
'Write code in the simplified CoffeeScript language': '簡略化CoffeeScriptでプログラムを書く',
'Write code with Pencil Code': '鉛筆コードでプログラムを書く',
'Write many things on the screen with a repeating program (a loop)': '繰り返し(ループ)を使ってスクリーンにいっぱい書いてください。',
'Yes': 'はい',
'You can change your choice at any time in the settings menu': 'いつでも設定メニューから設定を変更できます。',
'create new program': '新しいプログラムを作る。',
'hello world': 'ハローワールド',
'immediately': 'すぐに',
'new EV3 blocks program': '新しい EV3 ブロックプログラム',
'new Sphero blocks program': '新しい スフィロ ブロックプログラム',
'on collision': 'ぶつかった時',
'set backlight (': '背景を変える (',
'set color (': '色を変える (',
'stop motors(': 'モーターを止める(',
'when finished': '終わったとき',
'{$startSpan}Click here{$endSpan} to see our short introduction to Coding with Chrome.': 'コーディング ウィズ クロームの紹介をみる場合、{$startSpan}ここをクリック{$endSpan}してしてください。',
};
|
C++
|
UTF-8
| 1,707
| 2.6875
| 3
|
[] |
no_license
|
#include "scoremanager.hpp"
SReg ScoreManager::Sreg = SReg(SC_SREG_DATA, SC_SREG_LATCH, SC_SREG_CLOCK);
PlayerScoreIndicator ScoreManager::_indicators[SC_MAX_PLAYERS];
void ScoreManager::Configure() {
ScoreManager::Sreg.Init();
int offset = 0;
for (int i = 0; i < SC_MAX_PLAYERS; i++)
{
ScoreManager::_indicators[i] = PlayerScoreIndicator(offset);
offset += SC_LED_PER_USR;
}
}
void ScoreManager::Reset() {
for (uint32_t i = 0; i < SC_MAX_PLAYERS; i++)
ScoreManager::_indicators[i].Reset();
}
bool ScoreManager::Increment(uint8_t pid) {
if (pid >= SC_MAX_PLAYERS) return false;
else return _indicators[pid].Increment();
}
void ScoreManager::Decrement(uint8_t pid) {
if (pid >= SC_MAX_PLAYERS) return;
_indicators[pid].Decrement();
}
/*--*/
PlayerScoreIndicator::PlayerScoreIndicator() {
}
PlayerScoreIndicator::PlayerScoreIndicator(uint32_t offset) {
this->_offset = offset;
this->_currentScore = 0;
}
void PlayerScoreIndicator::Reset() {
for (uint32_t i = this->_offset; i < SC_LED_PER_USR; i++)
{
ScoreManager::Sreg.DigitalWrite(i, LOW);
this->_currentScore = 0;
}
}
bool PlayerScoreIndicator::Increment() {
ScoreManager::Sreg.DigitalWrite(this->_offset + this->_currentScore, HIGH);
this->_currentScore++;
return this->_currentScore >= SC_LED_PER_USR;
}
void PlayerScoreIndicator::Decrement() {
if (this->_currentScore > 0) {
--this->_currentScore;
ScoreManager::Sreg.DigitalWrite(this->_currentScore, LOW);
}
}
uint32_t PlayerScoreIndicator::GetScore() {
return this->_currentScore;
}
|
C#
|
UTF-8
| 4,568
| 2.609375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Library2
{
public partial class Book : Form
{
public Book()
{
InitializeComponent();
}
DataBase db = new DataBase();
private void Btngroup_Click(object sender, EventArgs e)
{
Type type = new Type();
type.ShowDialog();
this.Hide();
}
private void Btnadd_Click(object sender, EventArgs e)
{
OBook addBook = new OBook();
addBook.Text = "Add";
addBook.ShowDialog();
this.Hide();
}
private void Btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//int id = int.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
//if (db.Exe("delete from tbl_book where id=" + id) == true)
int id;
id = int.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
dt = db.Select("select * from tbl_depository where idbook=" + id);
if (dt.Rows.Count == 0)
{
if (db.Exe("delete from tbl_book where id = " + id) == true)
Book_Load(sender, e);
}
else
MessageBox.Show(".کتاب مورد نظر در امانت است", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Book_Load(object sender, EventArgs e)
{
treeView1.Nodes.Clear();
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
dt = db.Select("select tbl_book.id,tbl_book.name,tbl_book.writer,tbl_type.type from tbl_book inner join tbl_type on tbl_book.type=tbl_type.id");
dataGridView1.DataSource = dt;
//----------------------------
dt2 = db.Select("select *from tbl_type");
for (int i = 0; i < dt2.Rows.Count; i++)
{
treeView1.Nodes.Add(dt2.Rows[i].ItemArray[1].ToString());
}
dt2.Reset();
//dt = db.Select("select *from tbl_book");
//int id = 0;
//for (int i = 0; i < dt.Rows.Count; i++)
//{
// id= (int)dt.Rows[i].ItemArray[3];
// treeView1.Nodes[id].Nodes.Add(dt.Rows[i].ItemArray[0].ToString());
//}
}
private void Btnedit_Click(object sender, EventArgs e)
{
//OBook oBook = new OBook();
//oBook.Text = "Edit";
//oBook.textBox1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
//oBook.textBox2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
//oBook.textBox3.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
//oBook.ShowDialog();
OBook oBook = new OBook();
oBook.Text = "Edit";
oBook.txtid.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
oBook.txtname.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
oBook.txtwriter.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
oBook.ShowDialog();
}
private void Button1_Click(object sender, EventArgs e)
{
Book_Load(sender, e);
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strf="";
if (radioButton1.Checked)
strf = "name";
else if (radioButton2.Checked)
strf = "writer";
//dt= db.Select("select *from tbl_book where "+strf+" like '%' + N'"+txtsearch.Text+"' +'%' ");
dt = db.Select("select tbl_book.id,tbl_book.name,tbl_book.writer,tbl_type.type from tbl_book inner join tbl_type on tbl_book.type = tbl_type.id and " + strf + " like '%' + N'" + txtsearch.Text + "' + '%'");
dataGridView1.DataSource = dt;
}
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Button2_Click(object sender, EventArgs e)
{
Main main = new Main();
main.ShowDialog();
}
}
}
|
JavaScript
|
UTF-8
| 1,542
| 3.0625
| 3
|
[] |
no_license
|
'use strict';
function Article(rawDataObj) {
this.author = rawDataObj.author;
this.authorUrl = rawDataObj.authorUrl;
this.title = rawDataObj.title;
this.category = rawDataObj.category;
this.body = rawDataObj.body;
this.publishedOn = rawDataObj.publishedOn;
}
Article.all = [];
Article.prototype.toHtml = function() {
let template = Handlebars.compile($('#article-template').text());
this.daysAgo = parseInt((new Date() - new Date(this.publishedOn)) / 60 / 60 / 24 / 1000);
this.publishStatus = this.publishedOn ? `published ${this.daysAgo} days ago` : '(draft)';
this.body = marked(this.body);
return template(this);
};
Article.loadAll = function(rawData) {
rawData.sort(function(a, b) {
return (new Date(b.publishedOn)) - (new Date(a.publishedOn));
});
rawData.forEach(function(ele) {
Article.all.push(new Article(ele));
})
}
Article.fetchAll = function() { //.fetchAll() atuomatically parcese data into JS object so data must be stringified.
if (localStorage.rawData) { //if on local storage, get data from local storage
let rawData = (JSON.parse(localStorage.rawData))
Article.loadAll(rawData)
articleView.initIndexPage();
}
else { // else, get data from the .json file
$.getJSON('/data/hackerIpsum.json').then(function(data) {
localStorage.rawData = (JSON.stringify(data)) // because we used .fetchAll on line 30
data.forEach(function(articleObject) {
Article.all.push(new Article(articleObject))
})
articleView.initIndexPage();
})
}
}
|
Python
|
UTF-8
| 323
| 3.3125
| 3
|
[] |
no_license
|
import math
c=50
h=30
numbers = input("Enter numbers separating with comma:")
my_list= numbers.split(",")
my_list = list(my_list)
final_list=[]
for d in my_list:
a = (2*c*int(d))%h
q = math.sqrt(a)
final_list.append(str(q))
print(','.join(final_list))
# with this program not getting required result
|
JavaScript
|
UTF-8
| 2,200
| 3.078125
| 3
|
[] |
no_license
|
/* Created by Palette in 2017/12/04 */
var is_alive = [1, 1, 1, 1, 1, 0];
var turn_num = 0;
window.onload = function(){
$(".button").click(get_random);
$("#button").hover(start_cal, end_cal);
$("#info-bar").click(get_result);
}
function get_random(){
var ID = this.id, btn = $('.button');
var turn = turn_num;
if(!is_alive[ID]) return;
else {
var r_num = $('#t' + ID);
r_num.css('opacity', 1);
r_num.text('...');
all_disable(parseInt(ID), turn);
var pp = $.post('/', {})
.done(
function(data, status){
if(turn!==turn_num) pp.abort();
else r_num.text(data);
select_alive(parseInt(ID), turn);
});
}
}
function get_result(){
if(is_alive[5]===0) return;
else {
var result = 0;
for(var i=0;i<=4;i++){
result += parseInt($('#t'+i).text());
}
$('#t5').text(result);
$('#info-bar').css('background-color', '#989FCF');
is_alive[5] = 0;
}
}
function all_disable(id, turn){
if(turn!==turn_num) return;
for(var i=0;i<is_alive.length;i++){
is_alive[i] = 0;
if(i!==id) {
$("#" + i).css('background-color', '#989FCF');
}
}
}
function select_alive(id, turn){
if(turn!==turn_num) return;
var btn = $(".button"), total = 0;
$("#" + id).css('background-color', '#989FCF');
for(var i=0;i<btn.length;i++){
if($('#t' + i).text()==='') {
is_alive[i] = 1;
if(i!==id) $("#" + i).css('background-color', 'rgba(48, 63, 159, 1)');
}
else total += 1;
}
if(total===5) {
$('#info-bar').css('background-color', '#989FCF');
is_alive[5] = 1;
}
}
function start_cal(){
turn_num++;
console.log('Start calculating....');
}
function end_cal(){
turn_num++;
is_alive = [1, 1, 1, 1, 1, 0];
for(var i=0;i<=4;i++){
$('#t'+i).text('');
$('#t'+i).css('opacity', 0);
$("#"+i).css('background-color', 'rgba(48, 63, 159, 1)');
}
$("#t5").text('');
$('#info-bar').css('background-color', '#7E7E7E');
}
|
Ruby
|
UTF-8
| 488
| 3.46875
| 3
|
[] |
no_license
|
#Loops
i=1
#while : sampai kondisinya benar
while i <= 5
puts "#{i}"
i += 1
end
puts "#################################"
#until sampai kondisinya salah
until i < 1
puts "nilai i : #{i}"
i -= 1
end
#for in
puts "###############angka####################"
for angka in (0..3)
puts "Nilai angka : #{angka}"
end
#contoh array
puts "###############aray####################"
bahasa = ["html", "css", "javascript"]
for b in bahasa
puts "Nilai bahasa : #{b}"
end
|
Markdown
|
UTF-8
| 3,963
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
---
title: "Prediction of Taxi Demand Using Random Forest"
date: 2019-12-14
published: true
tags: [dataviz, hvplot, seaborn, matplotlib, randomForest]
excerpt: "This is the introduction of the prediction model."
hv-loader:
hv-chart-1: "charts/importance.html"
toc: true
toc_sticky: true
---
## Introduction
Random forest regression model is built here to predict the demand of taxi in a certain space unit across the Manhattan. We focus on the demand in each taxi zones, which are roughly based on NYC Department of City Planning’s Neighborhood Tabulation Areas (NTAs). The predcition result provide an overall view of taxi trips made in each taxi zone the next day. Here are some predictors we think that would be related to the number of taxi trips:
- **Number of restaurants** in each taxi zone,
- **Number of stores** in each taxi zone,
- **Number of subway stops** in each taxi zone,
- **Percent of people commuting by taxi** of each taxi zone,
- **Median income** of each taxi zone.
- whether **rain or not** on the day when trip was made
- **Mean temperature** of the day when trip was made
- Is the day when trip was made **weekend**?
## Data Processing
Taxi trips data is downloaded using `pandas.read_parquet`. Taxi zones data is provided by NYC Open Data. There are in total 11842094 records and we only focus on the trips made in 2nd week of 2015.
### Data from Open Street Map
Location data of restaurants, stores, and subway stops could be easily downloaded by using `osm2gpd` package. By using spatial join `sjoin` and `groupby`, the number of the facilities in each taxi zone could be easily calculated and is diplayed in the figure below.

### Census Tract Data
Median income, number of people commuting by taxi and number of commuters are extracted from American Community Survey 5-Year Data.

### Weather data
Weather data is [ASOS-AWOS-METAR Data](https://mesonet.agron.iastate.edu/request/download.phtml). Daily mean temperature and mean precipitation data are included in the regression model to increase accuracy.

## Predcition result
`RandomForestRegressor` is used to build the regression model. Taxi trips made on Monday, Tuesday, Wednesday, Friday and Sunday in the 2nd week of 2015 are set as training data set, and trips made on Thurday and Saturday are set as test data set. The correltion between each two predictors is plotted.

A simple grid search is run to optimize our hyperparameters. `n_estimators` is 200, and `max_depth` is 5 in the model. The test score of the prediction is 0.91, whereas the score is 0.40 when using linear regression model. The top important predictor is the count of stores in each taxi zone.
<div id="hv-chart-1"></div>
For test set data, MAE is 1828.39. The mean value of the taci trips made on these two days is 6593.24. We map the absolute error and more should be done to make the model more generalizable.

The model perform better for weekday demand prediction, which probably because lack of the training data for weekend.

We map the predicted and actual demand and our prediction model detect the general trend of demand across the space. To make our model more accurate, more predictors could be added into the model.

Based on the result, we can conclude that the model is generally good to predict the demand of taxi in NYC. Greater amount of data and more strongly related predictors would make the model better.
|
Java
|
UTF-8
| 15,466
| 2.109375
| 2
|
[] |
no_license
|
package jango;
import android.content.Context;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import root.DateConverter;
public class Django {
public static final String URL = "http://192.168.1.105:8000/api/";
public static List<User> userArrayList = new ArrayList<>();
public static List<Student> studentArrayList =new ArrayList<>();
public static List<Teacher> teacherArrayList =new ArrayList<>() ;
public static List<Major> majorList = new ArrayList<>() ;
public static List<DatetimeRange> dateRangeList = new ArrayList<>() ;
public static List<Term> termList = new ArrayList<>() ;
public static List<MT> MTList = new ArrayList<>() ;
public static List<TMT> TMTList = new ArrayList<>() ;
public static List<GoldRequest> goldReqList = new ArrayList<>() ;
public static final String STUDENT_STRING = "STUDENT";
public static final String TEACHER_STRING = "TEACHER";
public static final String ADMIN_STRING = "ADMIN";
public static String USER_ROLE ;
public static int USER_PK ;
public static int ROLE_PK ;
public static int[] today = new int[3];
public static User appUser ;
public static Student appStudent ;
public static Teacher appTeacher ;
//_______________________________________________________________________
public static void getUserListFromJango(){
Django.userArrayList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<User>> call = jsonPlaceHolderApi.getUsers();
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, retrofit2.Response<List<User>> response) {
List<User> userlist = response.body() ;
Django.userArrayList = userlist ;
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
// Toast.makeText(LoginActivity.this, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
return;
}
public static void getTeachersListFromJango(){
Django.teacherArrayList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Teacher>> call = jsonPlaceHolderApi.getTeachers();
call.enqueue(new Callback<List<Teacher>>() {
@Override
public void onResponse(Call<List<Teacher>> call, Response<List<Teacher>> response) {
List<Teacher> teacherList = response.body();
Django.teacherArrayList = teacherList;
}
@Override
public void onFailure(Call<List<Teacher>> call, Throwable t) {
//Toast.makeText(LoginActivity.this, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
}
public static void getDateRangeTimeList(){
Django.dateRangeList = new ArrayList<>();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<DatetimeRange>> call = jsonPlaceHolderApi.getDateRange();
call.enqueue(new Callback<List<DatetimeRange>>() {
@Override
public void onResponse(Call<List<DatetimeRange>> call, Response<List<DatetimeRange>> response) {
List<DatetimeRange> teacherList = response.body();
Django.dateRangeList = teacherList;
return;
}
@Override
public void onFailure(Call<List<DatetimeRange>> call, Throwable t) {
//Toast.makeText(LoginActivity.this, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
}
public static void getMajorList(){
Django.majorList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Django.URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Major>> call = jsonPlaceHolderApi.getMajor();
call.enqueue(new Callback<List<Major>>() {
@Override
public void onResponse(Call<List<Major>> call, retrofit2.Response<List<Major>> response) {
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
Django.majorList = response.body() ;
}
@Override
public void onFailure(Call<List<Major>> call, Throwable t) {
// Toast.makeText(LoginActivity.this, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
return;
}
public static void getTermList(){
Django.termList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Django.URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Term>> call = jsonPlaceHolderApi.getTermList();
call.enqueue(new Callback<List<Term>>() {
@Override
public void onResponse(Call<List<Term>> call, retrofit2.Response<List<Term>> response) {
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
Django.termList = response.body() ;
}
@Override
public void onFailure(Call<List<Term>> call, Throwable t) {
// Toast.makeText(LoginActivity.this, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
return;
}
public static void getMTList(){
Django.MTList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Django.URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<MT>> call = jsonPlaceHolderApi.getMTList();
call.enqueue(new Callback<List<MT>>() {
@Override
public void onResponse(Call<List<MT>> call, retrofit2.Response<List<MT>> response) {
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
Django.MTList = response.body() ;
}
@Override
public void onFailure(Call<List<MT>> call, Throwable t) {
// Toast.makeText(LoginActivity.this, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
return;
}
public static void getTMTList(){
Django.TMTList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Django.URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<TMT>> call = jsonPlaceHolderApi.getTMTList();
call.enqueue(new Callback<List<TMT>>() {
@Override
public void onResponse(Call<List<TMT>> call, retrofit2.Response<List<TMT>> response) {
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
Django.TMTList = response.body() ;
}
@Override
public void onFailure(Call<List<TMT>> call, Throwable t) {
// Toast.makeText(LoginActivity.this, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
return;
}
public static void getStudentListFromJango(){
Django.studentArrayList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Student>> call = jsonPlaceHolderApi.getStudents();
call.enqueue(new Callback<List<Student>>() {
@Override
public void onResponse(Call<List<Student>> call, retrofit2.Response<List<Student>> response) {
List<Student> studentlist = response.body() ;
Django.studentArrayList = studentlist;
}
@Override
public void onFailure(Call<List<Student>> call, Throwable t) {
//Toast.makeText(context, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
return;
}
public static void getGoldreqListFromJango(){
Django.goldReqList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<GoldRequest>> call = jsonPlaceHolderApi.getGoldReqList();
call.enqueue(new Callback<List<GoldRequest>>() {
@Override
public void onResponse(Call<List<GoldRequest>> call, retrofit2.Response<List<GoldRequest>> response) {
List<GoldRequest> studentlist = response.body() ;
Django.goldReqList = studentlist;
}
@Override
public void onFailure(Call<List<GoldRequest>> call, Throwable t) {
//Toast.makeText(context, "خطا در برقراری ارتباط", Toast.LENGTH_SHORT).show();
}
});
return;
}
public static void updateList(){
getGoldreqListFromJango();
getTMTList();
getMTList();
}
//________________________________________________________________________________________
public static Major getMajor (int pk){
for (int i=0 ; i<Django.majorList.size();i++){
if(Django.majorList.get(i).getMajorPK() == pk){
return Django.majorList.get(i);
}
}
return null;
}
public static Term getTerm (int pk){
for (int i=0 ; i<Django.termList.size();i++){
if(Django.termList.get(i).getTermPK() == pk){
return Django.termList.get(i);
}
}
return null;
}
public static DatetimeRange getDateRange (int pk){
for (int i=0 ; i<Django.dateRangeList.size();i++){
if(Django.dateRangeList.get(i).getDateRangePK() == pk){
return Django.dateRangeList.get(i);
}
}
return null;
}
public static MT getMT (int pk){
for (int i=0 ; i<Django.MTList.size();i++){
if(Django.MTList.get(i).getMtPK() == pk){
return Django.MTList.get(i);
}
}
return null;
}
public static TMT getTMT (int pk){
for (int i=0 ; i<Django.TMTList.size();i++){
if(Django.TMTList.get(i).getTmtPK() == pk){
return Django.TMTList.get(i);
}
}
return null;
}
public static Student getStudent (int pk){
for (int i=0 ; i<Django.studentArrayList.size();i++){
if (Django.studentArrayList.get(i).getStudentPK() == pk){
return Django.studentArrayList.get(i);
}
}
return null;
}
public static Teacher getTeacher (int pk){
for (int i=0 ; i<Django.teacherArrayList.size();i++){
if (Django.teacherArrayList.get(i).getTeacherPK() == pk){
return Django.teacherArrayList.get(i);
}
}
return null;
}
//________________________________________________________________________________________
public static void getToday(){
Date date= new Date(); // your date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Iran"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) +1 ;
int day = cal.get(Calendar.DAY_OF_MONTH);
DateConverter converter = new DateConverter();
converter.gregorianToPersian(year, month, day);
today[0]=converter.getYear();
today[1]=converter.getMonth();
today[2]=converter.getDay();
}
public static String check_user_password (String username , String password){
for(int i=0 ; i < Django.userArrayList.size() ;i++){
if (Django.userArrayList.get(i).getUsername().matches(username) && Django.userArrayList.get(i).getPassword().matches(password)){
Django.appUser = Django.userArrayList.get(i);
Django.USER_PK = Django.userArrayList.get(i).getUserPK();
boolean bool_teacher = isTeacher(Django.userArrayList.get(i).getUserPK());
boolean bool_student = isStudent(Django.userArrayList.get(i).getUserPK());
if(bool_teacher == true){
Django.USER_ROLE = TEACHER_STRING;
return TEACHER_STRING;
}
else if(bool_student == true){
Django.USER_ROLE = STUDENT_STRING;
return STUDENT_STRING;
}
else{
Django.USER_ROLE = ADMIN_STRING ;
return ADMIN_STRING;
}
}
}
return "not exist";
}
public static boolean isStudent(int pk){
for (int i=0 ; i<Django.studentArrayList.size() ; i++){
if(Django.studentArrayList.get(i).getUser_of_student_PK() == pk){
Django.appStudent = Django.studentArrayList.get(i);
Django.ROLE_PK = Django.studentArrayList.get(i).getStudentPK();
return true;
}
}
return false;
}
public static boolean isTeacher(int pk){
for (int i=0 ; i<Django.teacherArrayList.size() ; i++){
if(Django.teacherArrayList.get(i).getTeacherUserPK() == pk){
Django.appTeacher = Django.teacherArrayList.get(i);
Django.ROLE_PK = Django.teacherArrayList.get(i).getTeacherPK();
return true;
}
}
return false;
}
}
|
C#
|
UTF-8
| 6,594
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Data.Entity;
using WestBlueGolfLeagueWeb.Models.Entities;
using WestBlueGolfLeagueWeb.Models.Extensions;
using log4net;
namespace WestBlueGolfLeagueWeb.Models.ScoreEntry.LeaderBoard
{
public class LeaderBoardExecutor
{
private WestBlue db;
private year year;
private LeaderBoardStore lbc;
private static readonly ILog Logger = LogManager.GetLogger(typeof(LeaderBoardExecutor));
public LeaderBoardExecutor(WestBlue wb, year year)
{
this.db = wb;
this.year = year;
this.lbc = new LeaderBoardStore(wb, this.year);
}
public void CalculateAndSaveLeaderBoards()
{
this.year = this.db.years.First(x => x.id == this.year.id);
this.lbc.Initialize();
var allPlayersForYear = this.db.AllPlayersForYear(this.year, includeResults: true);
var playerIds = allPlayersForYear.Select(x => x.id);
PlayerLeaderBoard playerLeaderBoard = null;
player currPlayer = null;
try
{
foreach (var lb in LeaderBoards.PlayerBoards)
{
playerLeaderBoard = lb;
this.CleanUpLeaderBoardDatas<player>(playerIds, lb);
foreach (player p in allPlayersForYear)
{
currPlayer = p;
var results = p.AllResultsForYear(year);
this.CalculateAndSetValue(p.id, lb, results, p);
}
var leaderBoardDatas = this.lbc.GetBoardData(lb.LeaderBoardKey);
this.SortAndRankLeaderBoardData(leaderBoardDatas, lb.Ascending);
}
}
catch (Exception e)
{
var thrown = new Exception("Error calculating player leaderboard: " + playerLeaderBoard.LeaderBoardName + ", " + currPlayer.name, e);
Logger.Error(thrown);
throw thrown;
}
TeamLeaderBoard teamLeaderBoard = null;
team currTeam = null;
try
{
var teams = this.db.TeamsForYear(this.year.value).Where(x => !string.Equals("league subs", x.teamName, StringComparison.OrdinalIgnoreCase));
var teamIds = teams.Select(x => x.id);
foreach (var lb in LeaderBoards.TeamBoards)
{
teamLeaderBoard = lb;
this.CleanUpLeaderBoardDatas<team>(teamIds, lb);
foreach (var t in teams)
{
currTeam = t;
var results = t.AllResultsForYear(year);
this.CalculateAndSetValue(t.id, lb, results, t);
}
var leaderBoardDatas = this.lbc.GetBoardData(lb.LeaderBoardKey);
this.SortAndRankLeaderBoardData(leaderBoardDatas, lb.Ascending);
}
}
catch (Exception e)
{
var thrown = new Exception("Error calculating team board: " + teamLeaderBoard.LeaderBoardName + ", " + currTeam.teamName, e);
Logger.Error(thrown);
throw thrown;
}
// For each multi value board, create it if it doesn't exist
// get leaderboard datas
// execute query/code
this.db.SaveChanges();
}
public double CalculateBoardValueForPlayer(PlayerLeaderBoard plb, player p, year y)
{
var value = plb.DoCalculation(p, y, p.AllResultsForYear(y));
return value.HasValue ? value.Value : 0;
}
public double CalculateBoardValueForTeam(TeamLeaderBoard tlb, team t, year y)
{
var value = tlb.DoCalculation(t, y, t.AllResultsForYear(y));
return value.HasValue ? value.Value : 0.0;
}
public string FormattedBoardValueForPlayer(PlayerLeaderBoard plb, player p, year y)
{
var value = this.CalculateBoardValueForPlayer(plb, p, y);
return plb.Format.FormatValue(value);
}
public string FormattedBoardValueForTeam(TeamLeaderBoard tlb, team t, year y)
{
var value = this.CalculateBoardValueForTeam(tlb, t, y);
return tlb.Format.FormatValue(value);
}
/// <summary>
/// Cleans up board datas
/// </summary>
private void CleanUpLeaderBoardDatas<T>(IEnumerable<int> ids, ILeaderBoard board)
{
if (this.lbc.hasBoardData(board.LeaderBoardKey)) {
var lookup = new HashSet<int>(ids);
var datas = new List<leaderboarddata>(this.lbc.GetBoardData(board.LeaderBoardKey));
foreach (var d in datas)
{
int id = board.IsPlayerBoard ? d.playerId.Value : d.teamId.Value;
if (!lookup.Contains(id))
{
this.lbc.DeleteLeaderBoardData(id, board.LeaderBoardKey);
}
}
}
}
private void CalculateAndSetValue<T>(int id, SingleEntityLeaderBoard<T> lb, IEnumerable<result> results, T t)
{
var value = lb.DoCalculation(t, this.year, results);
if (value.HasValue)
{
var lbd = this.lbc.GetLeaderBoardData(id, lb);
lbd.value = value.Value;
lbd.formattedValue = lb.Format.FormatValue(lbd.value);
}
else
{
this.lbc.DeleteLeaderBoardData(id, lb.LeaderBoardKey);
}
}
private void SortAndRankLeaderBoardData(IEnumerable<leaderboarddata> datas, bool isAsc)
{
if (isAsc)
{
datas = datas.OrderBy(x => x.value).ToList();
}
else
{
datas = datas.OrderByDescending(x => x.value).ToList();
}
int rank = 0, count = 0;
double previousValue = double.MaxValue;
foreach (var lbd in datas)
{
count++;
if (lbd.value != previousValue)
{
rank = count;
}
lbd.rank = rank;
previousValue = lbd.value;
}
}
}
}
|
Python
|
UTF-8
| 845
| 3.421875
| 3
|
[] |
no_license
|
from collections import defaultdict
def solution(tickets):
answer = []
graph = defaultdict(list)
for t in tickets:
graph[t[0]].append(t[1])
for key in graph:
# 이렇게 해야 알파벳 순으로 간다.
graph[key].sort()
print(graph)
def dfs(node, path):
if len(path) == len(tickets) + 1 :
return path
for i, city in enumerate(graph[node]):
graph[node].pop(i)
print(node, path)
print(graph)
newPath = path[:]
newPath.append(city)
result = dfs(city,newPath)
if result : return result
graph[node].insert(i,city)
answer = dfs('ICN',['ICN'])
return answer
print(solution([["ICN", "SFO"], ["ICN", "ATL"], ["SFO", "ATL"], ["ATL", "ICN"], ["ATL","SFO"]]))
|
Java
|
UTF-8
| 637
| 2.25
| 2
|
[] |
no_license
|
package net.nowtryz.mcutils.command.contexts;
import lombok.*;
import lombok.experimental.FieldDefaults;
import lombok.experimental.SuperBuilder;
import net.nowtryz.mcutils.api.Translation;
import org.bukkit.command.CommandSender;
@Getter
@ToString
@SuperBuilder
@EqualsAndHashCode
@FieldDefaults(makeFinal=true, level= AccessLevel.PROTECTED)
public abstract class Context {
CommandSender sender;
String commandLabel;
String[] args;
public void reply(String message) {
this.sender.sendMessage(message);
}
public void reply(@NonNull Translation translation) {
translation.send(sender);
}
}
|
Java
|
UTF-8
| 1,991
| 1.976563
| 2
|
[] |
no_license
|
package com.java.springboot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.java.springboot.utilities.ConfigurationsImpl;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author ${Suresh M Kumar}
*
* Jan 31, 2018
*/
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Autowired
ConfigurationsImpl configurationsImpl;
@Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.java.springboot"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
configurationsImpl.getConfigurations().getProjectTitle(),
configurationsImpl.getConfigurations().getProjectDescription(),
configurationsImpl.getConfigurations().getProjectVersion(),
configurationsImpl.getConfigurations().getProjectTermsOfServiceUrl(),
new Contact(configurationsImpl.getConfigurations().getProjectContactName(),
configurationsImpl.getConfigurations().getProjectContactUrl(),
configurationsImpl.getConfigurations().getProjectContactEmail()),
configurationsImpl.getConfigurations().getProjectLicense(),
configurationsImpl.getConfigurations().getProjectLicenseURL());
return apiInfo;
}
/* @SuppressWarnings("unchecked")
private Predicate<String> postPaths() {
return or(
regex("/token.*"),
regex("/demo.*"),
regex("/secure.*"));
}*/
}
|
Java
|
UTF-8
| 4,591
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
package uk.co.caeldev.builder4test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import uk.co.caeldev.builder4test.impl.Pojo;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static uk.co.caeldev.builder4test.impl.PojoBuilder.creator;
import static uk.co.caeldev.builder4test.impl.PojoBuilder.name;
import static uk.co.caeldev.builder4test.impl.PojoBuilder.value;
import static uk.co.caeldev.builder4test.impl.PojoBuilder.valueCreator;
import static uk.org.fyodor.generators.RDG.string;
class FixedSizeListBuilderTest {
@Test
@DisplayName("Should be able to build distinct instances of FixedSizeListBuilder")
public void shouldReturnUniqueInstances() {
//When
FixedSizeListBuilder<Pojo> builder1 = FixedSizeListBuilder.fixedSizeListBuilder(1, creator);
FixedSizeListBuilder<Pojo> builder2 = FixedSizeListBuilder.fixedSizeListBuilder(1, creator);
//Then
assertThat(builder1).isNotEqualTo(builder2);
}
@Test
@DisplayName("Should be able to build a list using defaults values")
public void shouldBuildAListWithDefaultValuesNoRandoms() {
//When
FixedSizeListBuilder<Pojo> builder = FixedSizeListBuilder.fixedSizeListBuilder(2, creator);
List<Pojo> pojos = builder.get();
//Then
assertThat(pojos).hasSize(2);
assertThat(pojos.get(0).getName()).isEqualTo("defaultName");
assertThat(pojos.get(0).getValue()).isEqualTo("defaultValue");
assertThat(pojos.get(1).getName()).isEqualTo("defaultName");
assertThat(pojos.get(1).getValue()).isEqualTo("defaultValue");
}
@Test
@DisplayName("Should be able to build a list overriding default values")
public void shouldBuildAListWithOverrideConstantValues() {
//When
FixedSizeListBuilder<Pojo> builder = FixedSizeListBuilder.fixedSizeListBuilder(2, creator)
.override(name, "testName").override(value, "testValue");
List<Pojo> pojos = builder.get();
//Then
assertThat(pojos).hasSize(2);
assertThat(pojos.get(0).getName()).isEqualTo("testName");
assertThat(pojos.get(0).getValue()).isEqualTo("testValue");
assertThat(pojos.get(1).getName()).isEqualTo("testName");
assertThat(pojos.get(1).getValue()).isEqualTo("testValue");
}
@Test
@DisplayName("Should be able to build a list overriding default with constant and random values")
public void shouldBuildAListWithOverrideConstantAndRandomValues() {
//When
FixedSizeListBuilder<Pojo> builder = FixedSizeListBuilder.fixedSizeListBuilder(2, creator)
.override(name, "testName").override(value, string());
List<Pojo> pojos = builder.get();
//Then
assertThat(pojos).hasSize(2);
assertThat(pojos.get(0).getName()).isEqualTo("testName");
assertThat(pojos.get(1).getName()).isEqualTo("testName");
assertThat(pojos.get(0).getValue()).isNotEqualTo("defaultValue");
assertThat(pojos.get(1).getValue()).isNotEqualTo("defaultValue");
assertThat(pojos.get(0).getValue()).isNotEqualTo(pojos.get(1).getValue());
}
@Test
@DisplayName("Should be able to build a list overriding default with only random values")
public void shouldBuildAListWithOverrideRandomValues() {
//When
FixedSizeListBuilder<Pojo> builder = FixedSizeListBuilder.fixedSizeListBuilder(2, creator)
.override(name, string()).override(value, string());
List<Pojo> pojos = builder.get();
//Then
assertThat(pojos).hasSize(2);
assertThat(pojos.get(0).getName()).isNotEqualTo(pojos.get(1).getName());
assertThat(pojos.get(0).getValue()).isNotEqualTo(pojos.get(1).getValue());
}
@Test
@DisplayName("Should be able to build a list overriding default with creators")
public void shouldBuildAListWithOverrideCreatorValues() {
//When
FixedSizeListBuilder<Pojo> builder = FixedSizeListBuilder.fixedSizeListBuilder(2, creator)
.override(name, valueCreator).override(value, valueCreator);
List<Pojo> pojos = builder.get();
//Then
assertThat(pojos).hasSize(2);
assertThat(pojos.get(0).getName()).isEqualTo(pojos.get(1).getName());
assertThat(pojos.get(0).getValue()).isEqualTo(pojos.get(1).getValue());
//And
assertThat(pojos.get(0).getName()).isEqualTo("test1");
assertThat(pojos.get(0).getValue()).isEqualTo("test1");
}
}
|
C#
|
UTF-8
| 1,259
| 2.875
| 3
|
[] |
no_license
|
using System;
using System.Net.Mime;
namespace Microservices
{
public static class MessageBodyInfoExtensions
{
/// <summary>
///
/// </summary>
/// <param name="bodyInfo"></param>
/// <returns></returns>
public static ContentType ContentType(this MessageBodyInfo bodyInfo)
{
#region Validate parameters
if (bodyInfo == null)
throw new ArgumentNullException("bodyInfo");
#endregion
return ContentType(bodyInfo.Type, bodyInfo.Name);
}
/// <summary>
/// Содержимое закодировано в Base64.
/// </summary>
/// <returns></returns>
public static bool IsBase64(this MessageBodyInfo bodyInfo)
{
#region Validate parameters
if (bodyInfo == null)
throw new ArgumentNullException("bodyInfo");
#endregion
if (String.IsNullOrWhiteSpace(bodyInfo.Type))
return false;
return bodyInfo.ContentType().IsBase64();
}
private static ContentType ContentType(string contentType, string name)
{
try
{
return new ContentType(contentType);
}
catch
{
string mime = MediaType.GetMimeByFileName(name);
if (String.IsNullOrWhiteSpace(mime))
return new ContentType("text/plain; charset=utf-8");
else
return new ContentType(mime);
}
}
}
}
|
C++
|
UTF-8
| 1,803
| 3.09375
| 3
|
[] |
no_license
|
#include <iostream>
#include "circle.hpp"
#include "rectangle.hpp"
#include "composite-shape.hpp"
using namespace vlasov;
int getRectInfo(Rectangle objrect)
{
std::cout << "Rectangle height: " << objrect.getFrameRect().height << " ";
std::cout << " , Width: " << objrect.getFrameRect().width << " ";
std::cout << " and center(x,y): " << objrect.getFrameRect().pos.x << " ";
std::cout << "," << objrect.getFrameRect().pos.y << std::endl;
std::cout << "Rectangle's area: " << objrect.getArea() << std::endl;
return 0;
};
int getCircInfo(Circle objcircle)
{
std::cout << "Circle limit for height: " << objcircle.getFrameRect().height << " ";
std::cout << " , limit for width: " << objcircle.getFrameRect().width << " ";
std::cout << " and center(x,y)" << objcircle.getFrameRect().pos.x << " ";
std::cout << "," << objcircle.getFrameRect().pos.y << std::endl;
std::cout << "Circle's area: " << objcircle.getArea() << std::endl;
return 0;
}
int main()
{
try
{
vlasov::Rectangle objrect({5, 11, 3, 6});
getRectInfo(objrect);
vlasov::Circle objcircle(3, {1, 1});
getCircInfo(objcircle);
std::shared_ptr<vlasov::Shape> rectPtr = std::make_shared<vlasov::Rectangle>(objrect);
std::shared_ptr<vlasov::Shape> circPtr = std::make_shared<vlasov::Circle>(objcircle);
CompositeShape compShape(rectPtr);
std::cout << compShape.getArea() << "\n";
std::cout << objrect.getArea() << "<-After Rectangle \n";
compShape.addShape(circPtr);
std::cout << compShape.getArea() << "\n";
std::cout << objcircle.getArea() << "<-After Circle \n";
compShape.scale(2);
std::cout << compShape.getArea() << "<-After scale \n";
} catch (std::invalid_argument & error) {
std::cerr << error.what() << std::endl;
return 1;
}
return 0;
}
|
PHP
|
UTF-8
| 1,134
| 2.984375
| 3
|
[] |
no_license
|
<?php
$msg = "";
if(isset($_GET["msg"])){
$msg = $_GET["msg"];
}
require '../dbConnect.php'; //access and run this external file
//prepared statement
try{
$content = "";
$sql = 'SELECT * FROM wdv341_events';
$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch()){
$id = $row["event_id"];
$name = $row["event_name"];
$desc = $row["event_description"];
$presenter = $row["event_presenter"];
$content .= "<tr><td>".$id."</td><td>".$name."</td><td>".$desc."</td><td>".$presenter."</td></tr>";
}
$content = "<table><tr><th>Event ID</th><th>Event Name</th><th>Event Description</th><th>Event Presenter</th></tr>".$content."</table>";
} catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo $content;?>
<form action = "../../Unit 12/deleteEvent.php" method = "get">
<p>Delete row of ID: <input type = "text" name = "id"></p>
<input type = "submit" name = "submit" value = "Delete">
<div><?php echo $msg;?></div>
</form>
</body>
</html>
|
Swift
|
UTF-8
| 10,220
| 2.609375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CapitalOneATMBranchLocator
//
// Created by Rajesh kumar Subbiah on 7/14/16.
// Copyright © 2016 Rajesh kumar Subbiah. All rights reserved.
//
import UIKit
import MapKit
import Contacts
class ViewController: UIViewController {
var currentAnnotation = Annotation()
var atmsListArray:Array = [Annotation]()
let atmReqURL = "http://api.reimaginebanking.com/atms"
var lat:Double = 0.0 //= 38.9283
var lng:Double = 0.0//= -77.1753
var rad = 2
let key = "19234714d799e8aba91c3d387cc7b9d8"
let locationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Map related
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getATMList()
{
//Request URL:
//http://api.reimaginebanking.com/atms?lat=38.9283&lng=-77.1753&rad=1&key=19234714d799e8aba91c3d387cc7b9d8
let reqURL = "\(atmReqURL)?lat=\(lat)&lng=\(lng)&rad=\(rad)&key=\(key)"
print("RequestURL is:\(reqURL)")
//Call the webservices
let requestURL: NSURL = NSURL(string: reqURL)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
//Parse the data and load in to Data Model
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let atmslist = json["data"] as? [[String: AnyObject]] {
if(atmslist.count == 0)
{
let alert = UIAlertController(title: "Oops!", message:"There is no ATM near you", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
else{
for atm in atmslist {
let atmDetails:Annotation = Annotation()
atmDetails._id = (atm["_id"] as? String)!
atmDetails.title = (atm["name"] as? String)!
let GeoCodes = atm["geocode"] as? [String:Double]
var geoCode1:GeoLoc = GeoLoc()
for geocode in GeoCodes!
{
let geokey = geocode.0
if(geokey == "lat")
{
geoCode1.lat = geocode.1
}
else if(geokey == "lng")
{
geoCode1.lng = geocode.1
}
}
atmDetails.geocode = geoCode1
atmDetails.coordinate = CLLocationCoordinate2DMake(geoCode1.lat, geoCode1.lng)
atmDetails.accessibility = (atm["accessibility"] as? Bool)!
let hrs = atm["hours"] as? [String]
for hr in hrs!
{
atmDetails.hours.append(hr)
}
var address1:Address = Address()
let addr = atm["address"] as? [String:String]
for addrs in addr!
{
let addkey = addrs.0
switch addkey
{
case "state":
address1.state = addrs.1
case "zip":
address1.zip = addrs.1
case "city":
address1.city = addrs.1
case "street_name":
address1.street_name = addrs.1
case "street_number":
address1.street_number = addrs.1
default: break
}
}
atmDetails.address = address1
atmDetails.subtitle = "\(address1.street_number) \(address1.street_name) \(address1.city) \(address1.state) \(address1.zip)"
let langs = atm["language_list"] as? [String]
for lang in langs!
{
atmDetails.language_list.append(lang)
}
atmDetails.amount_left = (atm["amount_left"] as? Int)!
print(atmDetails.coordinate)
self.atmsListArray.append(atmDetails)
}
}
}
//Place the pins in the Map
self.mapView.addAnnotations(self.atmsListArray)
self.mapView.delegate = self
}
catch
{
print("Error with Json: \(error)")
}
}
}
task.resume()
}
//Get the driving direction to ATM
func getDirections(){
let addressDict =
[CNPostalAddressStreetKey: "\(currentAnnotation.address.street_number) \(currentAnnotation.address.street_name)",
CNPostalAddressCityKey : currentAnnotation.address.city,
CNPostalAddressStateKey: currentAnnotation.address.state,
CNPostalAddressPostalCodeKey: currentAnnotation.address.zip]
let place = MKPlacemark(coordinate: currentAnnotation.coordinate,
addressDictionary: addressDict)
let mapItem = MKMapItem(placemark: place)
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
mapItem.openInMapsWithLaunchOptions(launchOptions)
}
}
extension ViewController : CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print("location:: \(location.coordinate)")
lat = location.coordinate.latitude
lng = location.coordinate.longitude
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
if(lat != 0.0 && lng != 0.0)
{
getATMList()
}
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("error:: \(error)")
}
}
extension ViewController : MKMapViewDelegate {
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.pinTintColor = UIColor.greenColor()
pinView?.canShowCallout = true
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))
button.setBackgroundImage(UIImage(named: "car"), forState: .Normal)
button.addTarget(self, action: #selector(ViewController.getDirections), forControlEvents: .TouchUpInside)
pinView?.leftCalloutAccessoryView = button
return pinView
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
if(view.annotation != nil)
{
currentAnnotation = (view.annotation as? Annotation)!
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegionMake(currentAnnotation.coordinate, span)
mapView.setRegion(region, animated: true)
}
}
/*func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
print("inside region will change")
}
*/
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
print("inside region did change")
lat = mapView.centerCoordinate.latitude
print("Latitude:\(lat)")
lng = mapView.centerCoordinate.longitude
print("Longitude:\(lng)")
getATMList();
}
}
|
Markdown
|
UTF-8
| 3,074
| 3.59375
| 4
|
[] |
no_license
|
# intrusive_ptr
intrusive_ptr也是一种引用计数型智能指针,摘要如下:
```c++
template<class T>
class intrusive_ptr {
public:
typedef T element_type; // 被代理的对象
intrusive_ptr(); // 构造函数
intrusive_ptr(T *p, bool add_ref = true);
intrusive_ptr(intrusive_ptr const & r);
template<class Y> intrusive_ptr(intrusive_ptr<Y> const & r);
~intrusive_ptr();
intrusive_ptr & operator=(intrusive_ptr const & r);
template<class Y> intrusive_ptr & operator=(intrusive_ptr<Y> const & r);
intrusive_ptr & operator=(T * r);
void reset(); // 重置指针
void reset(T * r);
void reset(T * r, bool add_ref);
T & operator*() const;
T * operator->() const; // 操作符重载
explicit operator bool() const;
T * get() const;
T * detach();
void swap(intrusive_ptr & b);
};
```
intrusive_ptr自己不管理引用计数,而是调用以下两个函数来间接管理引用计数:
```c++
void intrusive_ptr_add_ref(T * p); // 增加引用计数
void intrusive_ptr_release(T * p); // 减少引用计数
```
## 用法
```c++
struct counted_date
{
int m_count = 0;
};
void intrusive_ptr_add_ref(counted_date* p)
{
++p->m_count;
}
void intrusive_ptr_release(counted_date* p)
{
if (--p->m_count == 0)
{
delete p;
}
}
int main()
{
typedef intrusive_ptr<counted_date> counted_ptr; // 类型定义
counted_ptr p(new counted_date); // 创建智能指针
assert(p); // bool转型
assert(p->m_count == 1);
counted_ptr p2(p); // 指针拷贝构造
assert(p->m_count == 2); // 引用计数增加
counted_ptr weak_p(p.get(), false); // 弱引用
assert(weak_p->m_count == 2); // 引用计数不增加
p2.reset(); // 复位指针
assert(!p2); // p2不持有指针
assert(p->m_count == 1); // 引用计数减少
} // 对象被正确析构
```
## 引用计数器
为了进一步简化实现引用计数的工作,intrusive_ptr在头文件<boost/smart_ptr/intrusive_ref_counter.hpp>里定义了一个辅助类intrusive_ref_counter:
```c++
template<typename DerivedT,
typename CounterPolicyT = thread_safe_counter>
class intrusive_ref_counter
{
private:
typedef typename CounterPolicyT::type counter_type;
mutable counter_type m_ref_counter;
public:
intrusive_ref_counter();
unsigned int use_count() const;
protected:
~intrusive_ref_counter() = default;
friend void intrusive_ptr_add_ref(const intrusive_ref_counter* p);
friend void intrusive_ptr_release(const intrusive_ref_counter* p);
};
```
intrusive_ref_counter内部定义了一个计数器变量m_ref_counter,使用模板参数配置策略实现了引用计数的增减,默认的策略是线程安全的thread_safe_counter。
|
Java
|
UTF-8
| 4,852
| 3.421875
| 3
|
[] |
no_license
|
package Algorithms;
import java.util.*;
import Wifi_Data.*;
/**
* This class is responsible for calculating user location, given the wifi scan that the user inputs.
* @author Hodaya_Tamano
* @author Shir_Bentabou
* @version 27.12.2017
*/
public class Algorithm2 {
//these are all variables that are used to calculate the location. set to final.
final static int square = 2;
final static int norm = 10000;
final static double sig_diff = 0.4;
final static int min_diff = 3;
final static int no_signal = -120;
final static int diff_no_sig = 100;
final static int num_of_samples = 4; //to find location we need at least 3 measurements
/**
* This function receives two files - one with missing location and another full csv file, and sends every row
* to the missing_location function to calculate the user's location. (row here is referred as a scan from a user's phone).
* @param missing_location arraylist of rows.
* @param full_csv arraylist of rows.
* @return ArrayList arraylist of rows.
*/
public static ArrayList<Row> locations_csv(ArrayList<Row> missing_location, ArrayList<Row> full_csv){
double [] loc = new double [3]; //to receive answer from search_in_csv
for (int i=0; i<missing_location.size(); i++){
Row current = new Row();
current = missing_location.get(i);
//System.out.println(current);
loc = search_in_csv(current, full_csv); //send row to search_in_csv to calculate location
current.setLat(loc[0]);
current.setLon(loc[1]);
current.setAlt((int)loc[2]);
missing_location.set(i, current); //switch between the original Row to the Row we are holding with location data
}
return missing_location;
}
/**
* This function passes throughout a whole csv file and compares to a row from the missing csv file.
* It creates an arraylist of samples of wifis to calculate user location,
* then sends and receives answer from user_location.
* @param original original Row object.
* @param full_csv arraylist of rows.
* @return array of doubles with location info.
*/
public static double [] search_in_csv(Row original, ArrayList<Row> full_csv){
ArrayList<Wifi_Samples> answer = new ArrayList<Wifi_Samples>();
double [] loc = new double [3];
for (int i=0; i<full_csv.size(); i++){//pass throughout the csv and search for matching samples by mac
Row current = new Row();
current = full_csv.get(i);
for (int j=0; j<original.getWifi().size(); j++){ //passes throughout the original missing loc row with loc info from current row
Wifi original_wifi = original.getWifi().get(j);
Wifi_Samples ws = new Wifi_Samples(current.getLat(), current.getLon(), current.getAlt());
for (int k=0; k<current.getWifi().size(); k++){ //passes throughout the wifi list in row
Wifi current_wifi = current.getWifi().get(k);
if (current_wifi.getMac().equals(original_wifi.getMac())){
ws.addWifi(current_wifi);
}
}
answer.add(ws);
}
}
loc = user_location(answer, original);
return loc;
}
/**
* This function calculates the user's location by an arraylist of samples and a row from the mising loc. info file.
* Returns the location info as an array of 3 doubles.
* @param ws wifi samples.
* @param original original row object.
* @return array of doubles with location info.
*/
public static double [] user_location (ArrayList<Wifi_Samples> ws, Row original){
double [] loc = new double[3]; //to return answer
for (int i=0; i<ws.size(); i++){//throughout the samples
double pi=1;
for (int j=0; j<ws.get(i).getSamples().size(); j++){//throughout the wifi sample arraylist
for (int k=0; k<original.getWifi().size(); k++){//throughout the original wifi arraylist
double diff=0;
if (ws.get(i).getSamples().get(j).getMac().equals(original.getWifi().get(k).getMac())){
diff+=3;
if (ws.get(i).getSamples().get(j).getSignal() == no_signal){
ws.get(i).getSamples().get(j).setSignal(diff_no_sig);
}else{
diff=Math.abs(ws.get(i).getSamples().get(j).getSignal()-original.getWifi().get(k).getSignal());
diff=Math.max(diff,min_diff);
}
pi = pi*norm/Math.pow(diff, sig_diff)*Math.pow(original.getWifi().get(k).getSignal(), square);
}
}
}
ws.get(i).setPi(pi);
Wifi_Samples.sortingByPi(ws); //sort sample list by pi value
//select strongest samples by pi value
try{
for (int n=num_of_samples; n<ws.size(); n++){
ws.remove(n);
}
}catch(IndexOutOfBoundsException e){
System.out.println("Not enough samples. Goodbye.");
break;
}
//calculate location answer using algo1
loc = Algorithm1.user_loc(ws);
}
//return location answers
return loc;
}
}
|
Java
|
UTF-8
| 1,385
| 3.25
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class LargestNumber {
public String largestNumber(int[] nums) {
int length = nums.length;
List<Integer> list = new ArrayList<>();
for(int i = 0;i<length;i++)
list.add(nums[i]);
StringBuilder builder = new StringBuilder();
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer val1, Integer val2) {
int tmpVal1 = val1,tmpVal2 = val2;
int tmp1 = val1,tmp2 = val2;
while(true)
{
tmp2/=10;
tmpVal1=tmpVal1*10;
if(tmp2==0)
break;
}
tmpVal1+=val2;
while(true){
tmpVal2 = tmpVal2*10;
tmp1/=10;
if(tmp1==0)
break;
}
tmpVal2+=val1;
return tmpVal1-tmpVal2;
}
});
if((int)list.get(length-1)==0)
return "0";
for(int i = length-1;i>=0;i--){
builder.append(list.get(i));
}
return builder.toString();
}
public static void main(String[] args) {
}
}
|
Markdown
|
UTF-8
| 539
| 2.890625
| 3
|
[] |
no_license
|
# Lifting Tracker
The goal of this project is to analyse the path of a bar in a video recording of a lifting movement (e.g. deadlift, squat, bench press) with the results then visualised as charts and key values.
## Implementation
The video processing is done using OpenCV in Python and uses colour detection to track the desired objects movement. The current development method is using a tennis ball as the 'known object' as it has a distinct colour to track, and the known size allows for speed and distance calculations to be derived.
|
C++
|
UTF-8
| 937
| 3.234375
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
void exchange(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void exchangeC(char *x,char *y)
{
char temp;
temp=*x;
*x=*y;
*y=temp;
}
int Part(int A[],char B[] , int p, int r)
{
int x=A[r];
int i=p-1;
for(int j = p;j<=r-1;j++)
{
if(A[j]<=x)
{
i++;
exchange(&A[i],&A[j]);
exchangeC(&B[i],&B[j]);
}
}
exchange(&A[i+1],&A[r]);
exchangeC(&B[i+1],&B[r]);
return i+1;
}
void Qs(int A[],char B[],int p, int r)
{
if (p<r)
{
int q;
q=Part(A,B,p,r);
Qs(A,B,p,q-1);
Qs(A,B,q+1,r);
}
}
int main()
{
int A[8]={6,56,3,8,9,3,7,1};
char B[]={'a','b','c','d','e','f','g','h'};
Qs(A,B,0,7);
for (int i=0;i<8;i++) {
cout<< B[i]<<"=" ;
cout<<A[i]<<endl;
}
}
|
Markdown
|
UTF-8
| 4,915
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
## 一 Electron简介
Electron 是一款基于Node.js的跨平台桌面应用开发框架,由Github开发,通过该框架可以利用 HTML、CSS、JavaScript 等web前端技术来开发跨平台桌面应用。
Electron的著名实现案例是VSCode。
Electron内部集成了`Chromium Content Module`与Node.js运行时,前者无法访问本地数据,但是可以创建GUI界面,后者能够访问本地数据,但是不能创建GUI界面。Electron结合二者后,开发者无需关心底层,直接使用原生操作系统的功能,创建桌面应用:
- Chromium Content Module:Chromium的核心组件,包含浏览器核心功能:Blink渲染引擎、JS的V8引擎,以及提供在单独进程渲染Web页面、加速GPU等功能
- Node.js运行时:可以访问本地文件系统、创建服务器、从外部模块加载文件
在使用Electron创建应用时,会把一个指定版本的Chromium和Node.js打包进应用,虽然让开发者可以充分使用二者的功能,但是也造成了软件包体积的庞大(主要因为node_modules问题)。
## 二 Electron安装
```
npm i electron -g
```
全局安装后,electron 才能提供 electron 命令。
## 三 HelloWorld
### 3.1 手动书写一个HelloWorld
初始化一个node.js项目,分别包含:
- main.js:项目入口文件
- /views/index.html:软件打开时默认显示的页面,该文件内容书写一个 `hello world` 即可
- package.json:node项目初始化后默认配置文件
main.js内容:
```js
const { app, BrowserWindow } = require("electron");
// 软件窗口对象
let mainWindow;
function createWindow(){
mainWindow = new BrowserWindow({ width: 800, height: 600 });
// 加载初始界面
mainWindow.loadFile("./views/index.html");
// 打开开发者工具。
mainWindow.webContents.openDevTools();
mainWindow.on("closed", ()=>{
mainWindow = null;
});
}
app.on("ready", createWindow);
// 当全部窗口关闭时退出。
app.on('window-all-closed', () => {
// 在 macOS 上,除非用户用 Cmd + Q 确定地退出,否则绝大部分应用及其菜单栏会保持激活。
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// 在macOS上,当单击dock图标并且没有其他窗口打开时,通常在应用程序中重新创建一个窗口。
if (mainWindow === null) {
createWindow();
}
});
```
运行:
```
electron .
```
### 3.2 使用官方示例
直接使用官网的quick start案例:
```
git clone https://github.com/electron/electron-quick-start
cd electron-quick-start
npm install && npm start
```
## 四 Electron特性
- 支持多视窗,每个视窗都有自己独立的JavaScript上下文
- 通过 shell 和 screen API 整合桌面操作系统特性
- 支持常见的桌面端软件需求,如:菜单、快捷键、托盘
- 支持自动更新、汇报程序崩溃、操作系统通知等
## 五 打包
electron有两种打包方式:electron-packager及electron-builder。electron-builder更加高效方便。这里只介绍该打包方式。
```
yarn add electron-builder --save-dev
"build": {
"appId": "com.xxx.app",
"mac": {
"target": ["dmg","zip"]
},
"win": {
"target": ["nsis","zip"]
}
},
"scripts": {
"dist": "electron-builder --win --x64"
},
```
## 六 主进程和渲染进程
主进程:
- 核心进程:在Electron中运行package.json和app脚本的进程为主进程
- 渲染进程:electron使用Chromium的多进程机制来渲染页面,每个页面拥有一个自己的进程,该进程称为渲染进程。如app.js文件中加载的index.html、index.js
主进程和渲染进行之间通信的常见方式:
- **ipcRenderer用于渲染进程**
- ipcRenderer.on(channel, listener) --> channel为事件频道,字符串.listener为触发回调函数,用于响应webContent.send()
- ipcRenderer.send(channel, data) --> 概念同上,用于向ipcMain发送异步信息
- **ipcMain用于主进程,响应从渲染进程中发送的消息**
- ipcMain.on(channel,listener) --> 响应从ipcRender中相同channel
- **event.sender**:主进程监听到渲染进程发送的消息,在响应事件回调函数中使用event.sender.send()方法可以向渲染进程发送消息
- **webContent**:ipcMain本身是无法直接发送事件的,只能通过响应事件回调的event来发送,那如果我们想先让主进程发送消息就可以使用webcontent.这个webcontent是在BrowserWIndow实例中的方法
- webContent.send(channel,data) --> 主进程向渲染进程发送消息
- 不同渲染进程之间共享数据
- 可以简单的使用HTML5中提供的API来实现,如localStorage和sessionStorage
- 在electron中,我们可以在主进程中将一个对象存储为全局变量,在渲染进程中通过remote模块进行操作
|
Java
|
UTF-8
| 3,215
| 2.1875
| 2
|
[] |
no_license
|
package com.example.admin.bookaholicfam;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import static android.provider.Telephony.Carriers.PASSWORD;
import static java.util.jar.Pack200.Packer.PASS;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Library.db";
// public static final String TABLE_NAME="USERDETAILS";
public static final String TABLE_NAME="user_details";
public static final String COL_1="MBNO";
public static final String COL_2="FNAME";
public static final String COL_3="LNAME";
public static final String COL_4="UNAME";
public static final String COL_5="LOC";
public static final String COL_6="PASS";
//CREATE TABLE IF NOT EXISTS UserDetails(fname VARCHAR(20),lname VARCHAR(20),uname VARCHAR(20),loc TEXT,mb VARCHAR(10) PRIMARY KEY, pass VARCHAR(20)
//SELECT count(*) FROM sqlite_master WHERE type='table' AND name='table_name';
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// SQLiteDatabase db=this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i("inoncreate","ok");
db.execSQL("CREATE TABLE user_details(MBNO TEXT PRIMARY KEY,FNAME TEXT,LNAME TEXT,UNAME TEXT ,LOC TEXT,PASS TEXT);");
Log.i("acreate","ok");
try {
Log.i("beforet","ok");
db.execSQL("SELECT count(*) FROM user_details");
Log.i("table","ok");
}
catch (Exception e)
{
Log.i("error","error");
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//db.execSQL("DROP TABLE IF EXISTS "+"user_details");
//onCreate(db);
db.execSQL("CREATE TABLE user_details(MBNO TEXT PRIMARY KEY,FNAME TEXT,LNAME TEXT,UNAME TEXT ,LOC TEXT,PASS TEXT)");
}
public boolean insertData(String mbno,String fname,String lname,String uname,String loc,String pass)
{
//Boolean result= mydb.insertData(mbs,ed1s,ed2s,ed3s,lcs,p2s);
Log.i("in insert","ok");
SQLiteDatabase db=this.getWritableDatabase();
Log.i("Before content values","ok");
ContentValues contentValues=new ContentValues();
Log.i("Before col1","ok");
contentValues.put(COL_1,mbno);
Log.i("Before col2","ok");
contentValues.put(COL_2,fname);
Log.i("Before col3","ok");
contentValues.put(COL_3,lname);
Log.i("Before col4","ok");
contentValues.put(COL_4,uname);
Log.i("Before col5","ok");
contentValues.put(COL_5,loc);
Log.i("Before col6","ok");
contentValues.put(COL_6,pass);
Log.i("Before database insert22","ok");
long result=db.insert("user_details",null,contentValues);
Log.i("After database insert22","ok");
if(result==-1) {
Log.i("failinsert","ok");
return false;
}
else
Log.i("successinsert","ok");
return true;
}
}
|
C++
|
UTF-8
| 2,242
| 3.171875
| 3
|
[] |
no_license
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <time.h>
#include <map>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
const char* sin = s.c_str();
bool bRet = false;
for(int i=0, j=s.length()-1; i<s.length(); i++,j--) {
if(sin[i] != sin[j])
break;
if(i>=j) {
bRet = true;
break;
}
}
return bRet;
}
string longestPalindrome(string s)
{
map< char, vector<int> > hashMap;
const char *strInput = s.c_str();
int maxlen = 1;
string maxPal = s.substr(0, 1);
for (int i = 0; i < s.length(); i++)
{
for (int j = 0; j < hashMap[strInput[i]].size(); j++)
{
int k = hashMap[strInput[i]][j];
if(i-k+1 > maxlen
&& isPalindrome(s.substr(k, i-k+1))) {
maxlen = i-k+1;
maxPal = s.substr(k, i-k+1);
}
}
hashMap[strInput[i]].push_back(i);
}
return maxPal;
}
#if 0
string longestPalindrome(string s) {
int maxlen = 1;
string maxPal = s.substr(0,1);
for(int i=0; i<s.length(); i++){
for(int j=i+maxlen; j<s.length(); j++) {
if(j-i+1 > maxlen
&& isPalindrome(s.substr(i, j-i+1))) {
maxlen = j-i+1;
maxPal = s.substr(i, j-i+1);
}
}
}
return maxPal;
}
#endif
};
string& getInput()
{
char strinput[100];
scanf("%s", strinput);
string* input = new string(strinput);
return *input;
}
int main()
{
string s = getInput();
clock_t begin = clock();
clock_t end;
double elapsed_secs;
Solution a;
string len = a.longestPalindrome(s);
cout << len << endl;
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "Run time: " << elapsed_secs << "s" << endl;
return 0;
}
|
C++
|
UTF-8
| 794
| 2.640625
| 3
|
[] |
no_license
|
// TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
// 0. You just DO WHAT THE FUCK YOU WANT TO.
#pragma once
#include <string>
#include <vector>
#include "UTF8.h"
class StringParser
{
public:
StringParser(const std::string& toParse, int start = 0);
template<typename Condition>
std::string advanceTo(const Condition& cond);
Codepoint next();
Codepoint skipAhead();
Codepoint peekAhead();
Codepoint peek(int i = 0);
Codepoint last();
std::string advanceToNested(Codepoint start, Codepoint stop);
bool atEnd();
std::string str();
void reset(int to=0);
public:
bool StripWhitespace = true;
bool SkipWhitespace = true;
private:
std::string mStringToParse;
int mCurPosition;
std::string postProcess(const std::string& s);
};
#include "StringParser_Templates.hpp"
|
TypeScript
|
UTF-8
| 387
| 2.71875
| 3
|
[] |
no_license
|
//javascript
export const fetch1 = function (url, params) {
// dosomething
return new Promise((resolve, reject) => {
})
}
//typescript
interface RES {
code: number,
msg: string,
data?: any
}
export const fetch2 = function (url:string, params?:any): Promise<RES> {
// dosomething
return new Promise((resolve, reject) => {
})
}
|
Markdown
|
UTF-8
| 2,633
| 3.703125
| 4
|
[] |
no_license
|
Tennis game scoring system
-------------------------------
## Problem Statement
Implement tennis game scoring system.
The scoring system for tennis works like this.
* A match has one set and a set has many games
* A game is won by the first player to have won at least 4 points in total and at least 2 points more than the opponent.
* The running score of each game is described in a manner peculiar to tennis: scores from zero to three points are described as 0, 15, 30, 40, respectively
* If at least 3 points have been scored by each player, and the scores are equal, the score is "deuce".
* If at least 3 points have been scored by each side and a player has one more point than his opponent, the score of the game is "advantage" for the player in the lead.
* There are many games to a set in tennis
* A player wins a set by winning at least 6 games and at least 2 games more than the opponent.
* If one player has won six games and the opponent five, an additional game is played. If the leading player wins that game, the player wins the set 7–5. If the trailing player wins the game, a tie-break is played.
* A tie-break, played under a separate set of rules, allows one player to win one more game and thus the set, to give a final set score of 7–6. A tie-break is scored one point at a time. The tie-break game continues until one player wins seven points by a margin of two or more points. Instead of being scored from 0, 15, 30, 40 like regular games, the score for a tie breaker goes up incrementally from 0 by 1. i.e a player's score will go from 0 to 1 to 2 to 3 …etc.
* Add a score method that will return the current set score followed by the current game score
* Add a pointWonBy method that indicates who won the point
### Example interfaces(Java)
The interface should look something like this in Java:
```
Match match = new Match("player 1", "player 2");
match.pointWonBy("player 1");
match.pointWonBy("player 2");
// this will return "0-0, 15-15"
match.score();
match.pointWonBy("player 1");
match.pointWonBy("player 1");
// this will return "0-0, 40-15"
match.score();
match.pointWonBy("player 2");
match.pointWonBy("player 2");
// this will return "0-0, Deuce"
match.score();
match.pointWonBy("player 1");
// this will return "0-0, Advantage player 1"
match.score();
match.pointWonBy("player 1");
// this will return "1-0"
match.score();
```
##How to run
```bash
cd ${PROJECT_HOME}
docker build -t tennis-game:latest .
# build task execute all the test.
```
### Run unit test from project home dir.
`mvn test`.
|
Java
|
UTF-8
| 927
| 2.578125
| 3
|
[] |
no_license
|
package com.apvintern.domain.utils;
import com.apvintern.data.entities.UserResponse;
import com.apvintern.domain.entities.User;
import java.util.ArrayList;
import java.util.List;
public final class UserMapper {
public UserMapper() {
}
public User toUser(UserResponse userResponse) {
User user = null;
if (userResponse != null) {
user = new User(userResponse.getName(),
userResponse.getId(),
userResponse.getEmail());
}
return user;
}
public List<User> toUsers(List<UserResponse> userResponses) {
List<User> users = null;
if (userResponses != null && !userResponses.isEmpty()) {
users = new ArrayList<>(userResponses.size());
for (UserResponse userResponse : userResponses) {
users.add(toUser(userResponse));
}
}
return users;
}
}
|
PHP
|
UTF-8
| 1,333
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Created by Reliese Model.
*/
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
/**
* Class Woreda
*
* @property int $id
* @property string $woreda_name
* @property string $population
* @property string $area
* @property string $hh
* @property string $adult
* @property int $subcity_id
* @property string $review
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*
* @property Subcity $subcity
* @property Collection|Data[] $data
* @property Collection|Ketena[] $ketenas
* @property Collection|User[] $users
* @property Collection|WoredaRi[] $woreda_ris
*
* @package App\Models
*/
class Woreda extends Model
{
protected $table = 'woreda';
protected $casts = [
'subcity_id' => 'int'
];
protected $fillable = [
'woreda_name',
'population',
'area',
'hh',
'adult',
'subcity_id',
'review'
];
public function subcity()
{
return $this->belongsTo(Subcity::class);
}
public function data()
{
return $this->hasMany(Data::class);
}
public function ketenas()
{
return $this->hasMany(Ketena::class);
}
public function users()
{
return $this->hasMany(User::class, 'assiged_at');
}
public function woreda_ris()
{
return $this->hasMany(WoredaRi::class);
}
}
|
C#
|
UTF-8
| 2,080
| 2.671875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelpdeskSystem
{
class MyPublic
{
public static SqlConnection conn;
private static string serverName = "DESKTOP-KAGK96M\\SQLEXPRESS";
private static string dbName = "HelpdeskSystem";
private static string userId = "sa";
private static string pass = "1234";
public static string PURVIEW, USERNAME;
public static void ConnectDatabase()
{
string connect = "Data Source="+ serverName + ";Initial Catalog="+ dbName +";User ID="+userId+";Password="+pass;
conn = new SqlConnection(connect);
try
{
conn.Open();
}
catch
{
throw;
}
}
public static void OpenData(string strSelect, DataSet dsDatabase, string strTableName, SqlDataAdapter daDataAdapter)
{
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
daDataAdapter.SelectCommand = new SqlCommand(strSelect, conn);
SqlCommandBuilder cmbCommandBuilder = new SqlCommandBuilder(daDataAdapter);
daDataAdapter.Fill(dsDatabase, strTableName);
conn.Close();
}
catch (Exception)
{
}
}
public static void OpenData(string strSelect, DataSet dsDatabase, string strTableName)
{
SqlDataAdapter daDataAdapter = new SqlDataAdapter();
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
daDataAdapter.SelectCommand = new SqlCommand(strSelect, conn);
daDataAdapter.Fill(dsDatabase, strTableName);
conn.Close();
}
catch (Exception)
{
}
}
}
}
|
TypeScript
|
UTF-8
| 280
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
export class Utils {
public static clamp(val: number, low: number, high: number): number {
return val < low ? low : val > high ? high : val;
}
public static getTime(hour: number, min: number, sec: number): number {
return hour * 3600 + min * 60 + sec;
}
}
|
Java
|
UTF-8
| 326
| 1.820313
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.bstek.bdf2.core.exception;
import org.springframework.security.web.context.HttpRequestResponseHolder;
/**
* @since 2013-1-27
* @author Jacky.gao
*/
public interface IExceptionHandler {
void handle(HttpRequestResponseHolder requestResponseHolder,Throwable exception);
boolean support(Throwable exception);
}
|
Java
|
UTF-8
| 641
| 1.890625
| 2
|
[
"MIT"
] |
permissive
|
//Deobfuscated with https://github.com/SimplyProgrammer/Minecraft-Deobfuscator3000 using mappings "C:\Users\Admin\Desktop\Minecraft-Deobfuscator3000-1.2.2\1.12 stable mappings"!
//Decompiled by Procyon!
package me.shatteredhej.railhack.railhackmod.event.events;
import net.minecraft.network.*;
public class EventNetworkPacketEvent extends MinecraftEvent
{
public Packet m_Packet;
public EventNetworkPacketEvent(final Packet p_Packet) {
this.m_Packet = p_Packet;
}
public Packet GetPacket() {
return this.m_Packet;
}
public Packet getPacket() {
return this.m_Packet;
}
}
|
Markdown
|
UTF-8
| 1,433
| 3.609375
| 4
|
[] |
no_license
|
---
title: 228. Summary Ranges
parent: data_structure
has_children: false
nav_order: 100
permalink: /docs/228
---
# 228. Summary Ranges
[leetcode link](https://leetcode.com/problems/summary-ranges/)
**difficulty(1-5)**
2 easy
**notes**
## Description
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
## Solution
```c++
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if(nums.size() == 0){
return res;
}
int s = nums[0], e = nums[0];
for (int i = 1; i < nums.size(); i++){
if ((e+1) == nums[i]){
e++;
}
else{
res.push_back((s < e) ?
(to_string(s) + "->" + to_string(e)) :
to_string(s));
s = nums[i];
e = nums[i];
}
}
res.push_back((s < e) ?
(to_string(s) + "->" + to_string(e)) :
to_string(s));
return res;
}
};
```
array
{: .label .label-red }
|
Shell
|
UTF-8
| 1,737
| 3.859375
| 4
|
[] |
no_license
|
#!/bin/sh
HOME_DB_FOLDER="$HOME/.cache"
DB_FILE="locate.db"
if [ "$1" = "-h" ]; then
cat <<EOF>&2
Usage: ${0##*/} [FOLDERS]
Update the 'locate' databases for the home folder, external drives and the FOLDERS arguments.
For external drives, databases are only updated if found, they are not
automatically created (unless explicitly specified in the FOLDERS arguments).
- The database for the home folder is store in '$HOME_DB_FOLDER/$DB_FILE'.
- Other databases are stored in '$MEDIA_DB' at the target root.
EOF
exit
fi
update() {
[ $# -ne 2 ] && set -- "$1" "$1/locate.db"
echo >&2 "Updating '$2' database for '$1'..."
## From https://git.archlinux.org/svntogit/packages.git/tree/trunk/updatedb.conf?h=packages/mlocate.
updatedb -l 0 -o "$2" -U "$1" \
--prune-bind-mounts=1 \
--prunefs="9p afs anon_inodefs auto autofs bdev binfmt_misc cgroup cifs coda configfs cpuset cramfs debugfs devpts devtmpfs ecryptfs exofs ftpfs fuse fuse.encfs fuse.sshfs fusectl gfs gfs2 hugetlbfs inotifyfs iso9660 jffs2 lustre mqueue ncpfs nfs nfs4 nfsd pipefs proc ramfs rootfs rpc_pipefs securityfs selinuxfs sfs shfs smbfs sockfs sshfs sysfs tmpfs ubifs udf usbfs vboxsf" \
--prunepaths="/gnu/store /afs /mnt /net /sfs /tmp /udev /var/cache /var/lib/pacman/local /var/lock /var/run /var/spool /var/tmp" \
--prunenames=".git .hg .svn .cache Trash .Trash-$(id -u)"
}
update "/" "$HOME_DB_FOLDER/$DB_FILE"
## Only update external media databases.
for i in "/run/media/$USER"/* "/media/$USER"/*; do
[ -f "$i/$DB_FILE" ] && update "$i"
done
if [ ! -d "/media/$USER" ]; then
for i in "/media"/*; do
[ -f "$i/$DB_FILE" ] && update "$i"
done
fi
## Create database for the specified folders.
for i; do
[ -d "$i" ] && update "$i"
done
|
TypeScript
|
UTF-8
| 1,557
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import { A } from '@ember/array';
import { KeyEvent } from '@ember/test-helpers/dom/trigger-key-event';
import { KeyMacroModifierCallback } from './callback';
export interface MacroOptions {
callback: KeyMacroModifierCallback;
executionKey: string;
modifierKeys?: string[],
keyEvent?: KeyEvent;
element?: HTMLElement;
isDisabledOnInput?: boolean;
priority?: number;
groupName?: string | null;
isDisabled?: boolean;
}
export default class Macro {
keyEvent: KeyEvent = 'keydown';
callback: KeyMacroModifierCallback = () => {};
element: HTMLElement = document.body;
executionKey: string = '';
isDisabledOnInput: boolean = false;
modifierKeys: string[] = [];
priority: number = 0;
groupName: string | null = null;
isDisabled: boolean = false;
constructor(options: MacroOptions) {
if (options.modifierKeys !== undefined) {
this.modifierKeys = A(options.modifierKeys);
}
if (options.element !== undefined) {
this.element = options.element;
}
this.callback = options.callback;
this.executionKey = options.executionKey;
if (options.keyEvent) {
this.keyEvent = options.keyEvent;
}
if (options.isDisabledOnInput !== undefined) {
this.isDisabledOnInput = options.isDisabledOnInput;
}
if (options.priority !== undefined) {
this.priority = options.priority;
}
if (options.groupName !== undefined) {
this.groupName = options.groupName;
}
if (options.isDisabled !== undefined) {
this.isDisabled = options.isDisabled;
}
}
}
|
Markdown
|
UTF-8
| 5,954
| 2.640625
| 3
|
[] |
no_license
|
# css兼容性
1. h5标签兼容
1. 使用document.createElement()创建元素,然后设置样式;
2. 引入成熟的库;
2. 元素浮动之后,能设置宽度的话就给元素加宽度.如果需要宽度是内容撑开,就给它里边的块元素加上浮动;(浮动元素内有块级元素会出现把浮动元素给撑大)-ie6下,为块级元素设置高度后触发;
1. 给里面的块级元素加宽度;
2. 为里面的块级元素添加浮动
3. 第一块元素浮动,第二块元素加margin值等于第一块元素,在IE6下会有间隙问题;
1. 第二块元素也采用浮动
4. IE6下子元素超出父级宽高,会把父级的宽高撑开
1. 不能这么写
5. p/td/h不包含快级元素
6. margin兼容性问题
+ margin-top传递
1. 父级加边框 -ie6不能解决
2. 父级overflow:hide -ie6不能解决
3. 触发BFC和haslayout(ie6:zoom:1)
+ 上下margin重叠
1. 设置单边margin
7. ie6不支持display:inline-block;
1. hack处理:*display:inline;zoom:1;
8. IE6 最小高度19px;
1. overflow:hiden;
9. IE6/7 双边距
+ 触发条件:元素浮动后再设置margin-left后会出现双倍margin-left
1. *display:inline
10. li里元素都浮动 li 在IE6/7 下方会产生4px间隙问题
1. 为li添加 *vertical-align: top;
11. 浮动元素之间有注释和内联元素并且宽度相差3px,导致多复制一个文字问题
1. 避免上述两个条件
12. IE6/7 父级元素的overflow:hidden 是包不住子级的relative
1. 为父级添加:*position:relative;
13. IE6下绝对定位元素父级宽高是奇数,绝对定位元素的right和bottom值会有1px的偏差
1. 避免父级宽高是奇数
14. IE6下绝对定位元素和浮动元素并列并浮动元素占据了全部宽度绝对定位元素消失
1. 不处于同级:嵌套一层
15. IE6 下input的空隙
1. 给input 加:*float:left
16. IE6 下 输入类型表单控件有背景时,输入内容过多会使图片跑出去(输入的值会将背景顶出输入框:加上fixed)
1. background-image:fixed;
17. ie6不支持png24
1. _background-image:none;
_filter :progid:DXImageTransform.Microsoft.AlphaImageLoader(src="XX.png", sizingMethod="crop");
2. JS插件(问题:不能处理body之上png24)
DD_belatedPNG.fix('xxx');
18. hack,注意书写顺序
1. \9 所有的IE10及之前 -写在样式的最后面
2. +/*IE7及ie7以下的ie浏览器认识
3. _IE6及ie6的ie浏览器认识
# js兼容
1. 事件对象
+ 火狐的事件对象是在事件触发时传入事件处理函数中
1. var ev=ev||window.event
+ event.x与event.y问题
> IE下,even对象有x、y属性,但是没有pageX、pageY属性;Firefox下,even对象有pageX、pageY属性,但是没有x、y属性。
解决方法:
```
var myX = ev.x ? ev.x : ev.pageX;
var myY = ev.y ? ev.y:ev.pageY;
```
2. event.srcElement问题
+ IE下,even对象有srcElement属性,但是没有target属性;
+ Firefox下,event对象有target属性,但是没有srcElement属性。
+ 兼容
```
srcObj = ev.srcElement ? ev.srcElement : ev.target;
```
3. children/childNodes
+ children:只获取元素节点
* 全浏览器兼容
+ childNodes:会获取文本节点和元素节点
* IE6/7/8:第一个文本节点不会获取(length=2)
* IE9以上/DOM:获取节点个数三个(length=3)
+ 解决方案一:都用children,但是这个好像不是w3c的标准,不过所有浏览器都兼容
+ 解决方案二:
```
function getChildElem(elem){
var eles=[];
var allElem=elem.childNodes;
for(var i=0,len=allElem.lenght;i<len;i++){
if(allElem[i].nodeType===1){
eles.push(allElem[i]);
}
}
return eles;
}
```
4. 获取非行间样式:currentStyle/getComputedStyle
+ currentStyle: IE专属对象,全版本支持。 注意是对象,不是方法,调用时使用.或者[]而不是();
+ getComputedStyle:方法,返回样式列表。ie9及以上/DOM支持 window.getComputedStyle('elem','伪类')/window.defaultView.getComputedStyle('elem','伪类');
+ 兼容:
```
function getStyle(elem,style){
var getComputedStyle=window.getComputedStyle||window.defaultView.getComputedStyle;
return ele.currentStyle?ele.currentStyle[style]:ele.getComputedStyle(ele,null)[style];
}
```
5. 字符串索引:字符串类似数组,可以使用下标进行访问,但是IE6/7不支持
+ 兼容 使用charAt(i);
6. firstChild/firstElementChild、lastChild/lastElementChild、nextSibling/nextElementSibling、previousSibling/previousElementSibling;
+ IE6/7/8:使用没有Element的获取元素节点
+ IE9以上/DOM使用没有Element或获取文本节点。如果获取元素节点使用带有Element的属性
+ 兼容:
```
function getFirstChild(elem){
return elem.firstElementChild?elem.firstElementChild:elem.firstChild;
}
```
7. 绑定事件函数addEventListener/attachEvent
+ attachEvent:IE6/7/8支持
```
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
//处理传入的是元素集合
if (el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
} else {
el.addEventListener(type, fn, false);
}
};
} else {
return function (el, type, fn) {
if (el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
} else {
el.attachEvent('on' + type, function () {
//attachEvent处理函数的内部this默认是指向windowj需要修复this指向当前触发的元素,并将时间对象event作为事件处理函数的第一个参数参数传入
return fn.call(el, window.event);
});
}
};
}
})();
```
8. 滚动条距离scrollTop
+ IE/Chrome: document.body.scrollTop
+ FF: document.documentElement.scrollTop
+ 兼容
```
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop
```
9. test ssh
|
Java
|
UTF-8
| 393
| 1.734375
| 2
|
[] |
no_license
|
package com.warehouse.inventorymanagement.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import com.productcatalogservice.data.Product;
public interface ProductService {
boolean loadProductsHandler(MultipartFile file, HttpServletRequest request);
boolean updateProducts(List<Product> messages);
}
|
Java
|
UTF-8
| 1,919
| 2.328125
| 2
|
[] |
no_license
|
package com.chshru.music.ui.main.list;
import com.chshru.music.data.model.OnlineList;
import com.chshru.music.data.model.Song;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListData {
public static final int PLAY_LIST = 0;
public static final int PLAY_ONE = 1;
public static final int PLAY_RAND = 2;
public static final int MODE_COUNT = 3;
public static final String P_LOCAL = "0";
public static final String P_HISTORY = "1";
public static final String P_LOVE = "2";
public static final String P_SEARCH = "3";
public static final int P_LOCAL_LIST_END = 3;
private Map<String, List<Song>> mList;
private List<OnlineList> mOnlineList;
private String mPos;
private int mCurMode;
public ListData() {
mCurMode = 0;
mList = new HashMap<>();
mList.put(P_LOCAL, new ArrayList<>());
mList.put(P_HISTORY, new ArrayList<>());
mList.put(P_LOVE, new ArrayList<>());
mOnlineList = new ArrayList<>();
}
public void addOnlineList(String key, List<Song> list) {
if (mList.containsKey(key)) {
mList.remove(key);
}
mList.put(key, list);
}
public void removeOnlineList(String key) {
mList.remove(key);
}
public List<OnlineList> getOnlineList() {
return mOnlineList;
}
public void setCurMode(int curMode) {
mCurMode = curMode;
}
public int getCurMode() {
return mCurMode;
}
public void setPos(String pos) {
mPos = pos;
}
public String getPos() {
return mPos;
}
public void addAll(List<Song> list, String p) {
mList.get(p).addAll(list);
}
public void clear(String p) {
mList.get(p).clear();
}
public List<Song> getList(String pos) {
return mList.get(pos);
}
}
|
Java
|
UTF-8
| 3,660
| 2.234375
| 2
|
[] |
no_license
|
package com.mwdev.sxsmcardpay.database;
import android.content.Context;
import android.content.res.Resources;
import com.mwdev.sxsmcardpay.PosApplication;
import com.mwdev.sxsmcardpay.R;
import com.mwdev.sxsmcardpay.util.PosLog;
import com.ta.TAApplication;
import com.ta.util.db.TASQLiteDatabase;
import com.ta.util.db.TASQLiteDatabasePool;
import java.util.List;
/**
* Created by xiongxin on 16-8-16.
*/
public class PosDataBaseFactory {
private static final String TAG = PosDataBaseFactory.class.getName();
private static PosDataBaseFactory mFactory;
private TASQLiteDatabase mTaSqlDatabase;
private TAApplication mContex;
private Resources r;
private PosDataBaseFactory(){};
public static PosDataBaseFactory getIntance(){
if(mFactory == null)
mFactory = new PosDataBaseFactory();
return mFactory;
}
/**
* 初始化生成数据库
*
*/
public void initiedFactory(TAApplication cx){
mContex = cx;
r = mContex.getResources();
mContex.setSQLiteDatabasePool(createSqliteDatabasePool(r.getString(R.string.db_name),
r.getInteger(R.integer.db_version)));
mTaSqlDatabase = mContex.getSQLiteDatabasePool().getSQLiteDatabase();
String[] tables =r.getStringArray(R.array.db_tables);
try{
for(int i = 0;i<tables.length;i++){
Class c = Class.forName(tables[i]);
if(mTaSqlDatabase!=null){
if(!mTaSqlDatabase.hasTable(c));
mTaSqlDatabase.creatTable(c);
}
}
}catch (ClassNotFoundException ex){
PosLog.w(TAG,ex.getMessage());
}
mContex.getSQLiteDatabasePool().closeSQLiteDatabase();
mTaSqlDatabase=null;
}
/**
*替换TAApplication 中的 TASQLiteDatabasePool实例化对象
*
*/
private TASQLiteDatabasePool createSqliteDatabasePool(String dbName,int dbVersion){
TASQLiteDatabasePool pool = TASQLiteDatabasePool.getInstance(mContex, dbName, dbVersion, false);
pool.createPool();
return pool;
}
/**
*链接数据库对象
*
*/
public void openPosDatabase(){
if(mTaSqlDatabase==null){
mContex.getSQLiteDatabasePool().createPool();
mTaSqlDatabase = mContex.getSQLiteDatabasePool().getSQLiteDatabase();
}
}
/**
*断开链接
*
*/
public void closePosDatabase(){
mContex.getSQLiteDatabasePool().closeSQLiteDatabase();
mTaSqlDatabase=null;
}
/**
*释放数据库,但并不断开链接 ,
* 在多线程访问数据库时用到
*
*/
public void reselsePosDatabase(){
if(mTaSqlDatabase!=null)
mContex.getSQLiteDatabasePool().releaseSQLiteDatabase(mTaSqlDatabase);
}
public void insert(Object entity){
if(mTaSqlDatabase!=null){
boolean r =mTaSqlDatabase.insert(entity);
}
}
public void delete(Object entity){
if(mTaSqlDatabase!=null)
mTaSqlDatabase.delete(entity);
}
public void delete(Class<?> clazz,String where){
if(mTaSqlDatabase!=null)
mTaSqlDatabase.delete(clazz,where);
}
public <T>List<T> query(Class<?> clazz, String where,
String groupBy, String having, String orderBy, String limit){
List<T> list=null;
if(mTaSqlDatabase!=null)
list = mTaSqlDatabase.query(clazz,false,where,groupBy,having,orderBy,limit);
return list;
}
}
|
Java
|
UTF-8
| 390
| 2.453125
| 2
|
[] |
no_license
|
package ua.kiev.home.prog_it.graduate_work.project1;
public class Helper {
public static void main(String[] args) {
StrategyUnit str = new StrategyUnit(StrategyTypes.TotalGoalScored);
System.out.println(str.getStrategyName());
StrategyUnit str1 = new StrategyUnit(StrategyTypes.WinnerOFTheGame);
System.out.println(str1.getStrategyName());
}
}
|
JavaScript
|
UTF-8
| 3,974
| 2.71875
| 3
|
[] |
no_license
|
import {lab} from 'd3-color';
import {scaleLinear} from 'd3-scale';
const power = 2;
const incomeScale = scaleLinear()
.domain([175, 3384])
.range([0, Math.pow(100, power)]);
const supportScale = scaleLinear()
.domain([5, 85])
.range([0, 100]);
export function giveColor(income, support) {
return lab(40 + Math.pow(incomeScale(income), 1 / power) * 0.7 +
supportScale(support) * 0.4, 0, supportScale(support) * -1.6 +
Math.pow(incomeScale(income), 1 / power) * 2);
}
export function giveIncomeColor(income) {
return lab(120 - Math.pow(incomeScale(income), 1 / power) / 3, 0,
Math.pow(incomeScale(income), 1 / power) * 2);
}
export function giveSupportColor(support) {
return lab(120 - supportScale(support), 0, 0 - supportScale(support));
}
export function combinePow(data) {
if (data === undefined) {
return undefined;
}
let currentCount = 0;
let currentLatCount = 0;
let currentLongCount = 0;
let currentVoteCount = 0;
let currentVotersCount = 0;
let currentVotePercCount = 0;
let currentIncomeCount = 0;
const powList = [];
function powIterate(d, i) {
//console.log(currentLatCount);
currentCount = currentCount + 1;
currentLatCount = currentLatCount + Number(d.latitude);
currentLongCount = currentLongCount + Number(d.longitude);
currentVoteCount = currentVoteCount + Number(d['ballots counted']);
currentVotersCount = currentVotersCount + Number(d['registered voters']);
currentVotePercCount = currentVotePercCount + Number(d['% PiS Votes']) * Number(d['ballots counted']);
currentIncomeCount = currentIncomeCount + Number(d['avg income']) * Number(d['registered voters']);
if (i + 1 === data.length || d.powiat !== data[i + 1].powiat) {
powList.push({latitude: currentLatCount / currentCount,
longitude: currentLongCount / currentCount,
'avg income': currentIncomeCount / currentVotersCount,
'% PiS Votes': currentVotePercCount / currentVoteCount,
'registered voters': currentVotersCount});
currentCount = 0;
currentLatCount = 0;
currentLongCount = 0;
currentVoteCount = 0;
currentVotersCount = 0;
currentVotePercCount = 0;
currentIncomeCount = 0;
}
}
data.forEach(powIterate);
return powList;
}
export function combineWoj(data) {
if (data === undefined) {
return undefined;
}
let currentCount = 0;
let currentLatCount = 0;
let currentLongCount = 0;
let currentVoteCount = 0;
let currentVotersCount = 0;
let currentVotePercCount = 0;
let currentIncomeCount = 0;
const wojList = [];
function wojIterate(d, i) {
currentCount = currentCount + 1;
currentLatCount = currentLatCount + Number(d.latitude);
currentLongCount = currentLongCount + Number(d.longitude);
currentVoteCount = currentVoteCount + Number(d['ballots counted']);
currentVotersCount = currentVotersCount + Number(d['registered voters']);
currentVotePercCount = currentVotePercCount + Number(d['% PiS Votes']) * Number(d['ballots counted']);
currentIncomeCount = currentIncomeCount + Number(d['avg income']) * Number(d['registered voters']);
if (i + 1 === data.length || d.wojewodztwo !== data[i + 1].wojewodztwo) {
wojList.push({latitude: currentLatCount / currentCount,
longitude: currentLongCount / currentCount,
'avg income': currentIncomeCount / currentVotersCount,
'% PiS Votes': currentVotePercCount / currentVoteCount,
'registered voters': currentVotersCount});
currentCount = 0;
currentLatCount = 0;
currentLongCount = 0;
currentVoteCount = 0;
currentVotersCount = 0;
currentVotePercCount = 0;
currentIncomeCount = 0;
}
}
data.forEach(wojIterate);
return wojList;
}
|
PHP
|
UTF-8
| 1,623
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
Use App\Models\Computer;
Use Log;
class ComputerController extends Controller
{
//
public function getAll(){
$data = Computer::get();
return response()->json($data, 200);
}
public function create(Request $request){
$data['Manufacturer'] = $request['Manufacturer'];
$data['model'] = $request['model'];
$data['size'] = $request['size'];
$data['Processor'] = $request['Processor'];
$data['Memory'] = $request['Memory'];
Computer::create($data);
return response()->json([
'message' => "Successfully Computer created",
'success' => true
], 200);
}
public function delete($id){
$res = Computer::find($id)->delete();
return response()->json([
'message' => "Successfully deleted",
'success' => true
], 200);
}
public function get($id){
$data = Computer::find($id);
return response()->json($data, 200);
}
public function update(Request $request,$id){
$data['Manufacturer'] = $request['Manufacturer'];
$data['model'] = $request['model'];
$data['size'] = $request['size'];
$data['Processor'] = $request['Processor'];
$data['Memory'] = $request['Memory'];
Computer::find($id)->update($data);
return response()->json([
'message' => "Successfully updated",
'success' => true
], 200);
}
}
|
C
|
UTF-8
| 1,078
| 3.359375
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
void compare(int **pp,int r,int c)
{
int i,j;
int min=pp[0][0];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
min = min<pp[i][j]?min:pp[i][j];
printf("min=%d\n",min);
for(i=0;i<r;i++)
for(j=0;j<c-1;j++)
if(pp[i][j]==min)
{
pp[i][j]=pp[i][j+1];
}
int min_two=pp[0][0];
for(i=0;i<r;i++)
for(j=0;j<c-1;j++)
min_two = min_two<pp[i][j]?min_two:pp[i][j];
printf("min_two=%d\n",min_two);
if(pp!=NULL)
{
free(pp);
pp = NULL;
}
}
void input(int **ptr,int r,int c)
{
int i,j;
printf("Please input arr:\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&ptr[i][j]);
compare(ptr,r,c);
}
void create_memory(int r,int c)
{
int **p;
int i;
p = (int **)malloc(r*sizeof(int *));
if(NULL==p)
{
printf("malloc error");
exit(-1);
}
for(i=0;i<r;i++)
{
*(p+i) = (int *)malloc(c*sizeof(int));
if(NULL==*(p+i))
{
printf("malloc error");
exit(-1);
}
}
input(p,r,c);
}
int main()
{
int **p;
int r,c;
printf("Please input r,c:\n");
scanf("%d,%d",&r,&c);
create_memory(r,c);
return 0;
}
|
Python
|
UTF-8
| 1,816
| 2.859375
| 3
|
[] |
no_license
|
from __future__ import annotations
from typing import TypeVar, Generic, Any
from git import Repo
import os
import stat
from shutil import rmtree
from pickle import dump, load
from uuid import uuid4 as uuid
def delFolder(path: str) -> None:
for root, dirs, files in os.walk(path):
for d in dirs:
os.chmod(os.path.join(root, d), stat.S_IWUSR)
for f in files:
os.chmod(os.path.join(root, f), stat.S_IWUSR)
rmtree(path)
T = TypeVar("T")
class Stack(Generic[T]):
def __init__(self) -> None:
self.__id = uuid()
self.__repoPath = os.path.join(os.getcwd(), str(self.__id))
self.__objPath = os.path.join(self.__repoPath, "object.p")
if os.path.exists(self.__repoPath):
delFolder(self.__repoPath)
os.mkdir(self.__repoPath)
self.repo = Repo.init(self.__repoPath)
with open(self.__objPath, "wb") as f:
dump(None, f)
self.repo.index.add(self.__objPath)
self.repo.index.commit("initial comit")
def __enter__(self) -> Stack[T]:
return self
def __exit__(self, *dumbArgs: Any) -> None:
self.repo.close()
delFolder(self.__repoPath)
def push(self, obj: T) -> None:
with open(self.__objPath, "wb") as f:
dump((obj, uuid()), f)
self.repo.git.stash()
os.remove(self.__objPath)
def pop(self) -> T | None:
try:
self.repo.git.stash("pop")
except:
return None
with open(self.__objPath, "rb") as f:
ret = load(f)
os.remove(self.__objPath)
return ret[0]
with Stack[str]() as a:
a.push("1")
a.push("2")
a.push("3")
print("stack elements are:")
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
|
Python
|
UTF-8
| 113
| 3.125
| 3
|
[] |
no_license
|
def sum_of_multiples(maxnum, numbers=[3,5]):
return sum(sum(range(0, maxnum, n)) for n in numbers if n != 0)
|
Java
|
UTF-8
| 406
| 1.609375
| 2
|
[] |
no_license
|
package pl.mslawin.notes.app.constants;
import android.util.Patterns;
import java.util.regex.Pattern;
/**
* Created by maciej on 10/11/15.
*/
public final class NotesConstants {
public static final String TASKS_LIST_ID_PARAM = "TASKS_LIST_ID_PARAM";
public static final String TASKS_LIST_NAME_PARAM = "TASKS_LIST_NAME_PARAM";
private NotesConstants() {
// constants class
}
}
|
Go
|
UTF-8
| 112
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
package entities
// Entity represents a P4 Entity
type Entity interface {
Type() EntityType
GetID() uint32
}
|
Ruby
|
UTF-8
| 464
| 3.609375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
require 'pry'
def key_for_min_value(name_hash)
if name_hash.size != 0
smallest = 0
name = {}
counter = true
name_hash.collect do |key, value|
if counter == true
smallest = value
name = key
counter = false
else
if smallest > value
smallest = value
name = key
end
end
end
name
else
end
end
|
SQL
|
UTF-8
| 283
| 2.765625
| 3
|
[] |
no_license
|
DROP TABLE IF EXISTS EMPLOYEE;
CREATE TABLE EMPLOYEE(
ID INT NOT NULL AUTO_INCREMENT
, FIRST_NAME VARCHAR(60) NOT NULL
, LAST_NAME VARCHAR(40) NOT NULL
, BIRTH_DATE DATE
, NATIONALITY VARCHAR(30) NOT NULL
, RATING INT
, DESCRIPTION VARCHAR(200)
, PRIMARY KEY (ID)
);
|
Python
|
UTF-8
| 1,572
| 3.515625
| 4
|
[] |
no_license
|
import copy
test = [[1,2,-1],
[3,-1,0],
[2,3,-1]]
def print_mtx(mtx):
for x in mtx:
print(x)
def minors(i, j, matrix):
matrix_copy = copy.deepcopy(matrix)
# removes row with index j and column with index i
for row in range(len(matrix_copy)):
selected_row = matrix_copy[row]
del selected_row[i]
del matrix_copy[j]
return matrix_copy
def izvirzijums(matrix):
if len(matrix) == 1:
return matrix[0][0]
atbilde = 0
for i in range(len(matrix)):
atbilde += matrix[0][i]*(-1)**(0+i)*izvirzijums(minors(i, 0, matrix))
return atbilde
def muli_const(const, matrix):
return [[elem * const for elem in row] for row in matrix]
def transplanacija(matrix):
return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
def adjunktu_matrica(matrix):
matrix_copy = copy.deepcopy(matrix)
matrix_copy_copy = copy.deepcopy(matrix_copy)
for i in range(len(matrix_copy)):
for j in range(len(matrix_copy)):
matrix_copy_copy[i][j] = (-1)**(i+j) * \
izvirzijums(minors(i, j, matrix_copy))
# for some reason I get an inverse of what I want
return matrix_copy_copy
def inverss(matrix):
if izvirzijums(matrix) == 0:
print(
f'matricai {matrix} neeksistē inversa matrica, jo tās determinants ir 0')
return matrix
else:
atbilde = muli_const(
(1/izvirzijums(matrix)), adjunktu_matrica(matrix))
return atbilde
# print_mtx(inverss(test))
print_mtx(inverss(test))
|
TypeScript
|
UTF-8
| 606
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import { from } from 'rxjs';
import { toString } from './to-string';
import { take } from 'rxjs/operators';
describe('toString', () => {
it('should convert a number to a default base 10 string', done => {
from([10])
.pipe(toString(), take(1))
.subscribe({
next: value => expect(value).toBe('10'),
complete: () => done(),
});
});
it('should convert a number to hex radix string', done => {
from([255])
.pipe(toString(16), take(1))
.subscribe({
next: value => expect(value).toBe('ff'),
complete: () => done(),
});
});
});
|
PHP
|
UTF-8
| 691
| 3.15625
| 3
|
[] |
no_license
|
<?php
class User {
public $id;
public $name;
public $email;
public $oauthProvider = 'facebook';
public $oauthId = '';
function __construct($values) {
if (!is_null($values) && !empty($values)) {
$this->id = $values['id'];
$this->email = $values['email'];
$this->name = $values['name'];
}
}
function getHash() {
return md5($this->id . '-'. $this->oauthId . '-' . $this->oauthProvider );
}
static function putUserInSession($user) {
session_destroy();
session_start();
$_SESSION['_lgd_user'] = $user;
}
static function getCurrentUser() {
if (array_key_exists('_lgd_user', $_SESSION)) {
return $_SESSION['_lgd_user'];
}
return FALSE;
}
}
?>
|
Markdown
|
UTF-8
| 6,576
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
Format-Markdown
---------------
### Synopsis
Formats an object as Markdown
---
### Description
Formats an object as Markdown, with many options to work with
---
### Examples
#### EXAMPLE 1
```PowerShell
Format-Markdown -ScriptBlock {
Get-Process
}
```
#### EXAMPLE 2
```PowerShell
1..6 | Format-Markdown -HeadingSize { $_ }
```
---
### Parameters
#### **InputObject**
|Type |Required|Position|PipelineInput |
|------------|--------|--------|------------------------------|
|`[PSObject]`|false |1 |true (ByValue, ByPropertyName)|
#### **MarkdownParagraph**
If set, will treat the -InputObject as a paragraph.
This is the default for strings, booleans, numbers, and other primitive types.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **MarkdownTable**
If set, will generate a markdown table.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **MarkdownTableAlignment**
If provided, will align columnns in a markdown table.
Valid Values:
* Left
* Right
* Center
*
|Type |Required|Position|PipelineInput |
|------------|--------|--------|---------------------|
|`[String[]]`|false |2 |true (ByPropertyName)|
#### **Property**
An array of properties. Providing this implies -MarkdownTable
|Type |Required|Position|PipelineInput |
|--------------|--------|--------|---------------------|
|`[PSObject[]]`|false |3 |true (ByPropertyName)|
#### **Heading**
A heading.
If provided without -HeadingSize, -HeadingSize will default to 2.
If provided with -InputObject, -Heading will take priority.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[String]`|false |4 |true (ByPropertyName)|
#### **HeadingSize**
The heading size (1-6)
If provided without -Heading, the -InputObject will be considered to be a heading.
|Type |Required|Position|PipelineInput |
|---------|--------|--------|---------------------|
|`[Int32]`|false |5 |true (ByPropertyName)|
#### **Link**
If set, will create a link. The -InputObject will be used as the link content
|Type |Required|Position|PipelineInput |Aliases |
|----------|--------|--------|---------------------|------------------|
|`[String]`|false |6 |true (ByPropertyName)|Hyperlink<br/>Href|
#### **ImageLink**
If set, will create an image link. The -Inputobject will be used as the link content.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[String]`|false |7 |true (ByPropertyName)|
#### **BulletPoint**
If set, will generate a bullet point list.
|Type |Required|Position|PipelineInput |Aliases |
|----------|--------|--------|---------------------|---------------|
|`[Switch]`|false |named |true (ByPropertyName)|BulletpointList|
#### **Checkbox**
If set, bullet or numbered list items will have a checkbox.
Each piped -InputObject will be an additional list item.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **Checked**
If set, bullet or numbered list items will be checked.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **NumberedList**
If set, will generate a numbered list.
Each piped -InputObject will be an additional list item.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **BlockQuote**
If set, will generate a block quote.
Each line of the -InputObject will be block quoted.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **BlockQuoteDepth**
If set, will generate a block quote of a particular depth.
Each line of the -InputObject will be block quoted.
|Type |Required|Position|PipelineInput |
|---------|--------|--------|---------------------|
|`[Int32]`|false |8 |true (ByPropertyName)|
#### **Number**
If provided, will create a markdown numbered list with this particular item as the number.
|Type |Required|Position|PipelineInput |
|---------|--------|--------|---------------------|
|`[Int32]`|false |9 |true (ByPropertyName)|
#### **HorizontalRule**
If set, will generate a horizontal rule.
If other parameters are provided, the horiztonal rule will be placed after.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **Code**
If set, will output the -InputObject as a Markdown code block
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[Switch]`|false |named |true (ByPropertyName)|
#### **CodeLanguage**
If set, will output the -InputObject as a Markdown code block, with a given language
If the -InputObject is a ScriptBlock, -CodeLanguage will be set to PowerShell.
|Type |Required|Position|PipelineInput |
|----------|--------|--------|---------------------|
|`[String]`|false |10 |true (ByPropertyName)|
#### **ScriptBlock**
If provided, will output a script block as a Markdown code block.
|Type |Required|Position|PipelineInput |
|---------------|--------|--------|---------------------|
|`[ScriptBlock]`|false |11 |true (ByPropertyName)|
---
### Syntax
```PowerShell
Format-Markdown [[-InputObject] <PSObject>] [-MarkdownParagraph] [-MarkdownTable] [[-MarkdownTableAlignment] <String[]>] [[-Property] <PSObject[]>] [[-Heading] <String>] [[-HeadingSize] <Int32>] [[-Link] <String>] [[-ImageLink] <String>] [-BulletPoint] [-Checkbox] [-Checked] [-NumberedList] [-BlockQuote] [[-BlockQuoteDepth] <Int32>] [[-Number] <Int32>] [-HorizontalRule] [-Code] [[-CodeLanguage] <String>] [[-ScriptBlock] <ScriptBlock>] [<CommonParameters>]
```
|
Java
|
UTF-8
| 614
| 2.59375
| 3
|
[] |
no_license
|
package sync;
/**
* Created by liudap on 2018/1/26.
*/
public class Thread2 implements Runnable{
private SynchronizedTest getS1;
public Thread2(SynchronizedTest s1){
this.getS1 = s1;
}
public void run() {
// SynchronizedTest s = new SynchronizedTest();
// s.method1();
// SynchronizedTest s1 = new SynchronizedTest();
getS1.staticMethod2();
System.out.println("------------");
// SynchronizedTest.staticIn.method1();
// SynchronizedTest.staticMethod1();
// SynchronizedTest.staticMethod2();
}
}
|
Markdown
|
UTF-8
| 557
| 2.71875
| 3
|
[] |
no_license
|
# Elm Text Viewer
## Overview
Uses [Prism.js](https://prismjs.com/) and [Elm](https://elm-lang.org/) to create a basic text viewer application. Can set language and requested URL as flags:
```
<script>
var app = Elm.Main.init({
node: document.getElementById('app'),
flags: {
language: 'text',
url: 'https://elm-lang.org/assets/public-opinion.txt'
}
});
</script>
```
## Initialize Project
1. `npm i --global uglifyjs elm-test`
2. `elm install`
## Build Project
`make`
## Run Web Server
`make serve`
## Run Tests
`make test`
|
PHP
|
UTF-8
| 850
| 2.6875
| 3
|
[] |
no_license
|
<?php
try {
$pdo = new PDO( 'mysql:host=localhost;dbname=centralized;charset=utf8;', 'root', 'admin' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
"select * from item_category");
$stmt->execute();
$option = '';
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ){
$option .= '<option value="' . $row["category_id"] . '">' . $row["category_name"] . '</option>';
}
} catch( PDOException $e ) {
echo $e->getMessage();
}
$pdo = null;
?>
<input id="item_name" type="text" class="form-control" />
<select id="item_cate" class="form-control">
<?php echo $option; ?>
</select>
<hr />
<p>Please input item (<i>item name-item description</i>) Example : <b>highlighter-pink</b></p>
<div id="show_error" style="color: red; text-align: center; font-size: 15px; margin-top: 15px;"></div>
|
Python
|
UTF-8
| 294
| 2.515625
| 3
|
[] |
no_license
|
from django.test import SimpleTestCase
from bank.helper_functions import get_perm_name
class TestPermName(SimpleTestCase):
def test_one_arg(self):
self.assertEqual('bank.a', get_perm_name('a'))
def test_multiple_args(self):
self.assertEqual('bank.a_b', get_perm_name('a', 'b'))
|
Shell
|
UTF-8
| 2,097
| 3.828125
| 4
|
[] |
no_license
|
#!/bin/bash
has_error() {
[ ! -f "$PWD/builder_error.log" ]; touch "$PWD/builder_error.log";
while getopts "m:" opt; do
case $opt in
m) multi+=("$OPTARG");;
*) echo "Error: -m";;
esac
done
shift $((OPTIND -1))
for val in "${multi[@]}"; do
printf "***Error: %s\n" "$val" >> "$PWD/builder_error.log"
done
exit 1
}
DOTENV=".env.example"
if [ -f "$PWD/$DOTENV" ]; then
if [ ! -f "$PWD/apache/apache-cont1/entrypoint-var.env" ]; then
cp "$PWD/$DOTENV" "$PWD/entrypoint-var.env"
mv "$PWD/entrypoint-var.env" "$PWD/apache/apache-cont1/"
sed -i -e 's/^/export /' "$PWD/apache/apache-cont1/entrypoint-var.env"
if [ ! -f "$PWD/.env" ]; then
cp "$PWD/$DOTENV" "$PWD/.env"
rm "$PWD/$DOTENV"
else
has_error -m "$PWD/.env exists"
fi
else
has_error -m "$PWD/apache/apache-cont1/entrypoint-var.env exists"
fi
fi
VOL="$PWD/vol"
if [ ! -d "$VOL" ]; then
MDIRS=("$VOL" "$VOL/logs" "$VOL/mysql" "$VOL/certs")
WDIRS=("$VOL/html/cache/" "$VOL/html/inc/" "$VOL/html/tmp/" "$VOL/html/cache_public/" "$VOL/html/logs/" "$VOL/html/storage/")
XDIRS="$VOL/html/plugins/ffmpeg/ffmpeg.exe"
for i in "${MDIRS[@]}"; do
mkdir -p "$i"
if [ ! -d "$i" ]; then has_error -m "$i does not exist" else printf "Run: mkdir %s\n" "$i"; fi
done
git clone https://github.com/unaio/una.git "$VOL/html"
if [ ! -d "$VOL/html" ]; then
has_error -m "$VOL/html does not exist"
else
for i in "${WDIRS[@]}"; do
if [ -d "$i" ]; then
if chmod +w "$i"; then
printf "Ok: chmod +w %s\n" "$i"
else
has_error "$i does not exist"
fi
else
has_error -m "chmod +w $i"
fi
done
fi
if ! chmod +x "$VOL/html/plugins/ffmpeg/ffmpeg.exe"; then has_error -m "$XDIRS" else echo "Ok: $XDIRS"; fi
else
has_error -m "$VOL already exists"
fi
|
Java
|
UTF-8
| 321
| 2.578125
| 3
|
[] |
no_license
|
package problem;
public class Line {
public Vector2 a;
public Vector2 b;
public double A;
public double B;
public double C;
public Line(Vector2 a, Vector2 b) {
this.a = a;
this.b = b;
}
public Vector2 getIntersection(Line l) {
return new Vector2(0, 0);
}
}
|
Java
|
UTF-8
| 656
| 3.171875
| 3
|
[] |
no_license
|
public class AssignmentEight
{
public static void main(String[] args)
{
A8Utils utils = new A8Utils();
utils.printStars(0);
utils.printStars(5);
int[] numbers = { 41, 0, 74, -1, 8, -17, 79, 5, 22, -17 };
System.out.println("Minumum is " + utils.min(numbers));
String[] patterns = { "al ", "Sta", "eat", "eac" };
for(int ii = 0; ii < patterns.length; ++ii)
{
System.out.println("Is pattern '" + patterns[ii] + "' in 'Cal State Long Beach'? " + utils.isIn(patterns[ii], "Cal State Long Beach"));
}
utils.permutations("1234");
utils.permutations("ios");
utils.countNumberOfPerms("LongBeach");
}
}
|
Shell
|
UTF-8
| 593
| 3.4375
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
load 'lib'
function setup() {
TMPFILE="$(mktemp /tmp/terraform-modules-XXXXXXXXXXX.txt)"
}
function teardown() {
#rm -f $TMPFILE
:
}
@test "check if terraform modules are properly pinned" {
skip_unless_terraform
grep -Eo '^\s*source\s*=\s*"(.*?)"' *.tf | cut -d'"' -f2 | sort -u > $TMPFILE
if [ -s $TMPFILE ]; then
# Verify the modules are pinned to `tags/x.y` or nothing at all (maybe using `version` parameter instead)
sed 's/^.*?ref=//' < $TMPFILE | grep -E '^(tags/[0-9]+\.[0-9]+.*|)$'
else
# If the file is empty, then no modules are being used
true
fi
}
|
JavaScript
|
UTF-8
| 548
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//Credits to: https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-string
/**
* Formats a integer price into a price with decimals with a preceding $ sign
* @parmas {string} - priceWithDecimals representation of price
*/
export const formatPrice = (priceWithDecimals) => {
if(!priceWithDecimals){
return 'Please add a product to cart'
}
const realPrice = parseInt(priceWithDecimals) / 100
return realPrice.toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
})
}
|
Java
|
UTF-8
| 3,867
| 2.15625
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer",
"ANTLR-PD",
"CDDL-1.0",
"bzip2-1.0.6",
"Zlib",
"BSD-3-Clause",
"MIT",
"EPL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-jdbm-1.00",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.image;
import java.util.List;
import java.util.Objects;
public class ImageComponentVersions implements Comparable<ImageComponentVersions> {
private String cm;
private String cmGBN;
private String cdp;
private String cdpGBN;
private String os;
private String osPatchLevel;
private List<ParcelInfoResponse> parcelInfoResponseList;
public ImageComponentVersions() {
}
public ImageComponentVersions(String cm, String cmGBN, String cdp, String cdpGBN, String os,
String osPatchLevel, List<ParcelInfoResponse> parcelInfoResponseList) {
this.cm = cm;
this.cmGBN = cmGBN;
this.cdp = cdp;
this.cdpGBN = cdpGBN;
this.os = os;
this.osPatchLevel = osPatchLevel;
this.parcelInfoResponseList = parcelInfoResponseList;
}
public String getCm() {
return cm;
}
public void setCm(String cm) {
this.cm = cm;
}
public String getCmGBN() {
return cmGBN;
}
public void setCmGBN(String cmGBN) {
this.cmGBN = cmGBN;
}
public String getCdp() {
return cdp;
}
public void setCdp(String cdp) {
this.cdp = cdp;
}
public String getCdpGBN() {
return cdpGBN;
}
public void setCdpGBN(String cdpGBN) {
this.cdpGBN = cdpGBN;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getOsPatchLevel() {
return osPatchLevel;
}
public void setOsPatchLevel(String osPatchLevel) {
this.osPatchLevel = osPatchLevel;
}
public List<ParcelInfoResponse> getParcelInfoResponseList() {
return parcelInfoResponseList;
}
public void setParcelInfoResponseList(List<ParcelInfoResponse> parcelInfoResponseList) {
this.parcelInfoResponseList = parcelInfoResponseList;
}
@Override
public String toString() {
return "ImageComponentVersions{" +
"cm='" + cm + '\'' +
", cmGBN='" + cmGBN + '\'' +
", cdp='" + cdp + '\'' +
", cdpGBN='" + cdpGBN + '\'' +
", os='" + os + '\'' +
", osPatchLevel='" + osPatchLevel + '\'' +
", parcelInfoResponseList=" + parcelInfoResponseList +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ImageComponentVersions that = (ImageComponentVersions) o;
return Objects.equals(cm, that.cm) &&
Objects.equals(cmGBN, that.cmGBN) &&
Objects.equals(cdp, that.cdp) &&
Objects.equals(cdpGBN, that.cdpGBN) &&
Objects.equals(os, that.os) &&
Objects.equals(osPatchLevel, that.osPatchLevel);
}
@Override
public int hashCode() {
return Objects.hash(cm, cmGBN, cdp, cdpGBN, os, osPatchLevel);
}
//CHECKSTYLE:OFF
@Override
public int compareTo(ImageComponentVersions o) {
int ret = 0;
if (cm != null) {
ret = cm.compareTo(o.cm);
}
if (ret == 0 && cdp != null) {
ret = cdp.compareTo(o.cdp);
}
if (ret == 0 && cmGBN != null) {
ret = cmGBN.compareTo(o.cmGBN);
}
if (ret == 0 && cdpGBN != null) {
ret = cdpGBN.compareTo(o.cdpGBN);
}
if (ret == 0 && os != null) {
ret = os.compareTo(o.os);
}
if (ret == 0 && osPatchLevel != null) {
ret = osPatchLevel.compareTo(o.osPatchLevel);
}
return ret;
}
//CHECKSTYLE:ON
}
|
Python
|
UTF-8
| 1,505
| 3.828125
| 4
|
[] |
no_license
|
import nltk
import sys
import os
from nltk.tokenize import TweetTokenizer
class Analyzer():
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
#declare new lists
self.positives = []
self.negatives = []
#iterate over every line of the txt file, adding valid words to the list
with open(positives) as positive:
for line in positive:
if not line.startswith((';', ' ')):
self.positives.extend(line.split())
with open(negatives) as negative:
for line in negative:
if not line.startswith((';',' ')):
self.negatives.extend(line.split())
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
#define tokenizer and create a list that divides the original string into substrings
tokenizer = nltk.tokenize.TweetTokenizer()
tokens = tokenizer.tokenize(text)
score = 0
#iterate over each token, determining if each word is positive,negative or neutral
for token in tokens:
temp = token.lower()
#increase score by 1 if word is positive
if temp in self.positives:
score+=1
#decrease score by 1 if word is negative
elif temp in self.negatives:
score-=1
return score
|
Java
|
UTF-8
| 932
| 3.921875
| 4
|
[] |
no_license
|
给定n个正整数ai,判定每个数是否是质数。
输入格式
第一行包含整数n。
接下来n行,每行包含一个正整数ai。
输出格式
共n行,其中第 i 行输出第 i 个正整数ai是否为质数,是则输出“Yes”,否则输出“No”。
数据范围
1≤n≤100,
1≤ai≤231−1
输入样例:
2
2
6
输出样例:
Yes
No
import java.util.*;
public class Main{
static boolean isPrime(int n){
if(n < 2) return false;
for(int i = 2;i <= n /i;i++){
if(n%i==0) return false;
}
return true;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while(n -- >0){
int a = in.nextInt();
if(isPrime(a))
System.out.println("Yes");
else System.out.println("No");
}
}
}
|
Java
|
UTF-8
| 140
| 1.664063
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
/**
* These are tests relating to how Moo uses MVEL, but essentially they are tests of MVEL, not of Moo.
*/
package com.codiform.moo.mvel;
|
PHP
|
UTF-8
| 1,403
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* CrawlQueueInterface.php
*
* PHP version 7.2
*
* @category Interface
* @package Mjorgens\Crawler\CrawlQueue
* @author Marc Jorgensen <marcjorgensen@gmail.com>
* @license MIT https://opensource.org/licenses/MIT
* @link https://github.com/mjorgens/web-crawler
*/
namespace Mjorgens\Crawler\CrawlQueue;
use Psr\Http\Message\UriInterface;
/**
* Interface CrawlQueueInterface
*
* @category Interface
* @package Mjorgens\Crawler\CrawlQueue
* @author Marc Jorgensen <marcjorgensen@gmail.com>
* @license MIT https://opensource.org/licenses/MIT
* @link https://github.com/mjorgens/web-crawler
*/
interface CrawlQueueInterface
{
/**
* Add an UriInterface to the queue
*
* @param UriInterface $url The url to add
*
* @return void
*/
public function add(UriInterface $url);
/**
* Return the top UriInterface from the queue
*
* @return UriInterface
*/
public function next(): UriInterface;
/**
* Check if the queue is empty
*
* @return bool
*/
public function isEmpty(): bool;
/**
* Return the number of items in the queue
*
* @return int
*/
public function numOfUrls(): int;
/**
* Check if the UriInterface is already in the queue
*
* @param UriInterface $url The url to check
*
* @return bool
*/
public function contains(UriInterface $url): bool;
}
|
JavaScript
|
UTF-8
| 310
| 2.78125
| 3
|
[] |
no_license
|
function show() {
document.getElementById("popup").style.display = "block";
}
function hide() {
document.getElementById("popup").style.display = "none";
document.getElementById("name").value = "";
document.getElementById("age").value = "";
document.getElementById("country").value = "";
}
|
C++
|
UTF-8
| 780
| 3.46875
| 3
|
[] |
no_license
|
// 75. 颜色分类
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
void sortColors(vector<int>& nums) {
int begin = 0, end = nums.size() - 1, cur = 0;
while (cur < end)
{
// 如果当前的数字是0,移动到前边
if (nums[cur] == 0)
{
swap(nums[cur], nums[begin]);
++cur;
++begin;
}
// 如果当前的数字是2,移动到后面
else if (nums[cur] == 2)
{
swap(nums[cur], nums[end]);
--end;
}
else
{
++cur;
}
}
}
};
int main()
{
return 0;
}
|
C#
|
UTF-8
| 3,327
| 2.78125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Auxiliary.MathTools;
using Tao.OpenGl;
namespace GraphicsObjects.Scene_s_Objects
{
public class Box:SceneObject
{
private Vector3D _center;
private Vector3D _sizes;
private bool isVisible;
private Vector3D[] points;
private Vector3D Color;
public Box(Vector3D center, Vector3D size)
{
_center = center;
_sizes = size;
points = new Vector3D[10];
Color = new Vector3D(1.0f,0.0f,0.0f);
CalculatePoints();
isVisible = true;
}
public override void Hide()
{
isVisible = false;
}
public override void Show()
{
isVisible = true;
}
public override void Draw()
{
if (!isVisible) return;
Gl.glPushMatrix();
Gl.glTranslatef(_center[0],_center[1],_center[2]);
Gl.glColor3f(Color[0],Color[1],Color[2]);
Gl.glBegin(Gl.GL_QUAD_STRIP);
for (int i = 0; i < 10; i++)
Gl.glVertex3f(points[i][0], points[i][1], points[i][2]);
Gl.glEnd();
Gl.glBegin(Gl.GL_QUAD_STRIP);
Gl.glVertex3f(points[0][0], points[0][1], points[0][2]);
Gl.glVertex3f(points[6][0], points[6][1], points[6][2]);
Gl.glVertex3f(points[2][0], points[2][1], points[2][2]);
Gl.glVertex3f(points[4][0], points[4][1], points[4][2]);
Gl.glEnd();
Gl.glBegin(Gl.GL_QUAD_STRIP);
Gl.glVertex3f(points[1][0], points[1][1], points[1][2]);
Gl.glVertex3f(points[7][0], points[7][1], points[7][2]);
Gl.glVertex3f(points[3][0], points[3][1], points[3][2]);
Gl.glVertex3f(points[5][0], points[5][1], points[5][2]);
Gl.glEnd();
Gl.glPopMatrix();
}
public void Resize(Vector3D newSize)
{
_sizes.X = newSize.X;
_sizes.Y = newSize.Y;
_sizes.Z = newSize.Z;
CalculatePoints();
}
private void CalculatePoints()
{
points[0]= new Vector3D(-_sizes[0],-_sizes[1],-_sizes[2]);
points[1] = new Vector3D(-_sizes[0], -_sizes[1], _sizes[2]);
points[2] = new Vector3D(_sizes[0], -_sizes[1], -_sizes[2]);
points[3] = new Vector3D(_sizes[0], -_sizes[1], _sizes[2]);
points[4] = new Vector3D(_sizes[0], _sizes[1], -_sizes[2]);
points[5] = new Vector3D(_sizes[0], _sizes[1], _sizes[2]);
points[6] = new Vector3D(-_sizes[0], _sizes[1], -_sizes[2]);
points[7] = new Vector3D(-_sizes[0], _sizes[1], _sizes[2]);
points[8] = new Vector3D(points[0]);
points[9] = new Vector3D(points[1]);
}
public override void MoveTo(Vector3D NewCenter)
{
_center.X = NewCenter.X;
_center.Y = NewCenter.Y;
_center.Z = NewCenter.Z;
}
public override void SetColor(Vector3D color)
{
Color[0] = color[0];
Color[1] = color[1];
Color[2] = color[2];
}
}
}
|
Python
|
UTF-8
| 695
| 2.9375
| 3
|
[] |
no_license
|
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
#consider boundary case:
res =[]
if len(candidates)==0:
return []
self.dfs(candidates,target,0,[],res)
return res
def dfs(self, nums, target, index, path, res):
if target < 0:
return
if target ==0:
path = sorted(path)
if path in res:
return
else:
res.append(path)
return res
for i in range(index,len(nums)):
self.dfs(nums[1:],target-nums[i],i,path+[nums[i]],res)
|
Python
|
UTF-8
| 1,672
| 2.609375
| 3
|
[] |
no_license
|
from keras.models import load_model
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.preprocessing.image import img_to_array, load_img
import numpy as np
import tensorflow as tf
# dimensions of our images.
img_width, img_height = 150, 150
input_shape = (img_width, img_height, 3)
test_model = Sequential()
test_model.add(Conv2D(32, (3, 3), input_shape=input_shape))
test_model.add(Activation('relu'))
test_model.add(MaxPooling2D(pool_size=(2, 2)))
test_model.add(Conv2D(32, (3, 3)))
test_model.add(Activation('relu'))
test_model.add(MaxPooling2D(pool_size=(2, 2)))
test_model.add(Conv2D(64, (3, 3)))
test_model.add(Activation('relu'))
test_model.add(MaxPooling2D(pool_size=(2, 2)))
test_model.add(Flatten())
test_model.add(Dense(64))
test_model.add(Activation('relu'))
test_model.add(Dropout(0.5))
test_model.add(Dense(1))
test_model.add(Activation('sigmoid'))
test_model = load_model('first_model.h5')
def predict(basedir, model):
for i in range(4001,4040):
path = basedir + str(i) + '.jpg'
img = load_img(path,False,target_size=(img_width,img_height))
x = img_to_array(img)
x = x/255
x = np.expand_dims(x, axis=0)
preds = model.predict_classes(x)
probs = model.predict_proba(x)
if preds == 1:
out = "dog"
else:
out = "cat"
print(str(probs) + " " + str(preds) + " " + out)
print ("predict cats")
basedir = "data/test/cat."
predict(basedir, test_model)
print ("predict dogs")
basedir = "data/test/dog."
predict(basedir, test_model)
print('done')
|
Markdown
|
UTF-8
| 1,998
| 2.53125
| 3
|
[] |
no_license
|
# Threading Concepts (OS/Python)
| Topic | Links |
|------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
| <b>Program / Process / Threads Discussion </b>| [View](https://www.backblaze.com/blog/whats-the-diff-programs-processes-and-threads/) |
| <b>Program / Process / Threads Example</b>| [View](https://medium.com/@bishowgurung.c/program-vs-process-vs-thread-vs-task-ff510b741f3e) |
| <b>Choose Process over Thread, or Thread over Process</b>| [View](https://www.backblaze.com/blog/whats-the-diff-programs-processes-and-threads/)|
| <b>Multithreading Overview</b>| [View](https://www.quora.com/What-is-multithreading-in-programming-How-does-it-work/answer/John-Vriezen?ch=10&share=6e5da4bf&srid=vcaUI)|
| <b>Thread / RaceCondition/ Producer Consumer </b>| [View](https://realpython.com/intro-to-python-threading/)|
| <b>COncurrency MultiThreading, MultiProcessing, AsyncIO </b>| [View](https://realpython.com/python-concurrency/)|
| <b> How does asyncio work? </b>| [View](https://stackoverflow.com/questions/49005651/how-does-asyncio-actually-work/51116910#51116910)|
| <b> GIL Python work? </b>| [View](https://realpython.com/python-gil/) |
# Case Study
| Topic | Links |
|------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
| <b>Chrome multi process architecture</b>| [View](https://blog.chromium.org/2008/09/multi-process-architecture.html)|
| <b>GIL Issues When few CPU and Few IO Bound tasks in one python process</b>| [View](http://dabeaz.blogspot.com/2010/01/python-gil-visualized.html)|
| <b>Fix for GIL battle of CPU/IO Bound threads</b>| [View](https://mail.python.org/pipermail/python-dev/2009-October/093321.html)|
| <b>Thread Safe Singleton</b>| [View](https://stackoverflow.com/questions/50566934/why-is-this-singleton-implementation-not-thread-safe)
|
Python
|
UTF-8
| 260
| 3.25
| 3
|
[
"Apache-2.0"
] |
permissive
|
from functools import reduce
def sum(x,y): return x * y
def zero(x):
if x %10 ==0:
return 1+zero(x//10)
return 0
def num_zeroes(L):
#YOUR CODE GOES HERE
S=reduce(sum, L)
ans=zero(S)
return ans
L=[2, 5, 6, 100]
ans=num_zeroes(L)
print(ans)
|
Java
|
UTF-8
| 473
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.linkb.jstx.adapter.viewholder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.linkb.R;
public class OrganizationViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public View icon;
public OrganizationViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
icon = itemView.findViewById(R.id.icon);
}
}
|
Java
|
UTF-8
| 497
| 2.140625
| 2
|
[] |
no_license
|
//
// Decompiled by Procyon v0.5.36
//
package Output;
public enum BaudRate
{
B_115200("B_115200"),
B_230400("B_230400"),
B_250000("B_250000"),
B_500000("B_500000"),
B_921600("B_921600"),
B_1000000("B_1000000"),
B_1250000("B_1250000");
private final String displayed_text;
private BaudRate(final String s) {
this.displayed_text = s;
}
@Override
public String toString() {
return this.displayed_text;
}
}
|
PHP
|
UTF-8
| 391
| 2.859375
| 3
|
[] |
no_license
|
<?php
/*
* 可变长度参数列表
* */
function test(){
var_dump(func_get_args());//然后做一些其他的操作
var_dump(func_get_arg(4));//调用这个函数的时候可以传入一个值表示获取第几个实际参数(重0开始)
var_dump(func_num_args());//返回传入所在自定义函数的参数的个数!
}
test(21,323232,4343,'单位取得完全','dwqdwqdqw');
?>
|
JavaScript
|
UTF-8
| 616
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
var expect = require('chai').expect;
var remove = require('./index.js');
describe('tests for checkign removal of index from orderd array', function() {
it('should return array without element 3 in orderd form', function() {
expect(remove([1, 2, 3, 4, 5], 3)).to.eql([1, 2, 4, 5]);
});
it('should return array without element "c" in orderd form', function() {
expect(remove(['a', 'b', 'c', 'd'], 'c')).to.eql(['a', 'b', 'd']);
});
it('should return original array if element not found in array', function() {
expect(remove(['a', 'b', 'c', 'd'], 'z')).to.eql(['a', 'b', 'c', 'd']);
});
});
|
Markdown
|
UTF-8
| 687
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
# apply-classes
[](https://www.npmjs.com/package/apply-classes) [](https://www.npmjs.com/package/apply-classes)
A small utility to apply classes, the use case to use it is in React.
## Install
```sh
npm i --save apply-classes
yarn add apply-classes
```
## Usage
```js
import applyClasses from 'apply-classes'
```
```jsx
const Example = () => (
<div className={applyClasses({
'example': true,
'hidden': false
})}></div>
)
```
It will render only the truthy conditions
## License
MIT. Copyright (C) [Gabriel García Seco](https://ggseco.com)
|
Java
|
UTF-8
| 422
| 1.882813
| 2
|
[] |
no_license
|
package com.lisasmith.findAGig.repository;
import org.springframework.data.repository.CrudRepository;
import com.lisasmith.findAGig.entity.GigStatus;
public interface GigStatusRepository extends CrudRepository<GigStatus, Long> {
public Iterable<GigStatus> findByGigId(Long gigId);
public Iterable<GigStatus> findByMusicianId(Long musicianId);
public Iterable<GigStatus> findByInstrumentId(Long instrumentId);
}
|
Markdown
|
UTF-8
| 725
| 2.515625
| 3
|
[] |
no_license
|
---
title: plot()に凡例を追加する
date: 2013-07-29T22:12:15+09:00
draft: false
tags: [R言語]
aliases:
- /archives/44
---
サンプルコードを載せておく。
<pre>
plot(1:10,1:10, type="l", lty=1)
lines(1:10,seq(1,5.5,by=0.5),lty=2)
legend(locator(1), c("実線","点線"),lty=1:2)
</pre>
出力は、下のようになる。
<img src="http://img.gepuro.net/image/legend_example.png">
locator(1)を使うと、凡例をどこに表示させるかをマウスポインタで選択できるので便利。
また、ltyをcolにすれば、色ごとに表示できる。
(普段良く使うコードをまとめて置くと、忘れた時に楽になると信じてる
|
Python
|
UTF-8
| 640
| 2.9375
| 3
|
[] |
no_license
|
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
count = 0
s = set(nums)
k = abs(k)
lst = sorted(list(s))
if k == 0:
for i in s:
if nums.count(i) > 1:
count += 1
return count
for i, v in enumerate(lst):
if v + k in s:
count += 1
return count
if __name__ == '__main__':
s = Solution
nums = [x for x in range(9999, 0, -1)]
print(nums)
k = 1
print(s.findPairs(s, nums, k))
|
Markdown
|
UTF-8
| 6,255
| 3.046875
| 3
|
[
"LicenseRef-scancode-generic-cla",
"CC-BY-3.0"
] |
permissive
|
---
title: Dependencies in Resource Manager templates | Microsoft Docs
description: Describes how to set one resource as dependent on another resource during deployment to ensure resources are deployed in the correct order.
services: azure-resource-manager
documentationcenter: na
author: tfitzmac
manager: timlt
editor: ''
ms.assetid: 34ebaf1e-480c-4b4d-9bf6-251bd3f8f2cf
ms.service: azure-resource-manager
ms.devlang: na
ms.topic: article
ms.tgt_pltfrm: na
ms.workload: na
ms.date: 09/12/2016
ms.author: tomfitz
---
# Defining dependencies in Azure Resource Manager templates
For a given resource, there can be other resources that must exist before the resource is deployed. For example, a SQL server must exist before attempting to deploy a SQL database. You define this relationship by marking one resource as dependent on the other resource. Typically, you define a dependency with the **dependsOn** element, but you can also define it through the **reference** function.
Resource Manager evaluates the dependencies between resources, and deploys them in their dependent order. When resources are not dependent on each other, Resource Manager deploys them in parallel.
## dependsOn
Within your template, the dependsOn element enables you to define one resource as a dependent on one or more resources. Its value can be a comma-separated list of resource names.
The following example shows a virtual machine scale set that depends on a load balancer, virtual network, and a loop that creates multiple storage accounts. These other resources are not shown in the following example, but they would need to exist elsewhere in the template.
{
"type": "Microsoft.Compute/virtualMachineScaleSets",
"name": "[variables('namingInfix')]",
"location": "[variables('location')]",
"apiVersion": "2016-03-30",
"tags": {
"displayName": "VMScaleSet"
},
"dependsOn": [
"storageLoop",
"[concat('Microsoft.Network/loadBalancers/', variables('loadBalancerName'))]",
"[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
...
}
To define a dependency between a resource and resources that are created through a copy loop, set the dependsOn element to name of the loop. For an example, see [Create multiple instances of resources in Azure Resource Manager](resource-group-create-multiple.md).
While you may be inclined to use dependsOn to map relationships between your resources, it's important to understand why you're doing it because it can impact the performance of your deployment. For example, to document how resources are interconnected, dependsOn is not the right approach. You cannot query which resources were defined in the dependsOn element after deployment. By using dependsOn, you potentially impact deployment time because Resource Manager does not deploy in parallel two resources that have a dependency. To document relationships between resources, instead use [resource linking](resource-group-link-resources.md).
## Child resources
The resources property allows you to specify child resources that are related to the resource being defined. Child resources can only be defined five levels deep. It is important to note that an implicit dependency is not created between a child resource and the parent resource. If you need the child resource to be deployed after the parent resource, you must explicitly state that dependency with the dependsOn property.
Each parent resource accepts only certain resource types as child resources. The accepted resource types are specified in the [template schema](https://github.com/Azure/azure-resource-manager-schemas) of the parent resource. The name of child resource type includes the name of the parent resource type, such as **Microsoft.Web/sites/config** and **Microsoft.Web/sites/extensions** are both child resources of the **Microsoft.Web/sites**.
The following example shows a SQL server and SQL database. Notice that an explicit dependency is defined between the SQL database and SQL server, even though the database is a child of the server.
"resources": [
{
"name": "[variables('sqlserverName')]",
"type": "Microsoft.Sql/servers",
"location": "[resourceGroup().location]",
"tags": {
"displayName": "SqlServer"
},
"apiVersion": "2014-04-01-preview",
"properties": {
"administratorLogin": "[parameters('administratorLogin')]",
"administratorLoginPassword": "[parameters('administratorLoginPassword')]"
},
"resources": [
{
"name": "[parameters('databaseName')]",
"type": "databases",
"location": "[resourceGroup().location]",
"tags": {
"displayName": "Database"
},
"apiVersion": "2014-04-01-preview",
"dependsOn": [
"[variables('sqlserverName')]"
],
"properties": {
"edition": "[parameters('edition')]",
"collation": "[parameters('collation')]",
"maxSizeBytes": "[parameters('maxSizeBytes')]",
"requestedServiceObjectiveName": "[parameters('requestedServiceObjectiveName')]"
}
}
]
}
]
## reference function
The [reference function](resource-group-template-functions.md#reference) enables an expression to derive its value from other JSON name and value pairs or runtime resources. Reference expressions implicitly declare that one resource depends on another.
reference('resourceName').propertyPath
You can use either this element or the dependsOn element to specify dependencies, but you do not need to use both for the same dependent resource. Whenever possible, use an implicit reference to avoid inadvertently adding an unnecessary dependency.
To learn more, see [reference function](resource-group-template-functions.md#reference).
## Next steps
* To learn about creating Azure Resource Manager templates, see [Authoring templates](resource-group-authoring-templates.md).
* For a list of the available functions in a template, see [Template functions](resource-group-template-functions.md).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.