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
| 3,074
| 2.546875
| 3
|
[] |
no_license
|
# title
要允许中国互联网适度腐败
# author
老编辑
# publisher
老道消息
# date
2017-05
# chapter
游侠
# tag
创投, 管理, 社会
# remarks
某反腐大剧告诉我们,腐败的主要是农民的儿子、老领导的女婿,而干部家庭出身的领导不太容易腐败,通常是对手造谣,或者用错了人,替下面的腐败分子背锅。
所以《共享单车的名义》也严格按照这个套路创作。
摩拜创始人胡玮炜,出身浙江东阳,曾经靠乡镇企业致富的百强县,如今以横店闻名全国的县级市。
她是典型的小镇文艺女青年被理想主义感召去读了新闻,然后去大城市大媒体做记者。
而 ofo 的创始人戴威,北大浓眉大眼的学生会主席,他父亲的行政级别,前女友父亲的行政级别都是副部级,典型的比你聪明比你有钱还比你努力。
于是在谣言中,摩拜腐败的是领导,消息来源是知乎上一个匿名回答,涉案金额高达数千万人民币。ofo腐败的是基层的运营,创始人戴威没有腐败而是被架空,涉案金额比较低,几万几十万,消息来源是脉脉上前员工和员工的匿名爆料。
尽管这些消息的来源都不确凿,但是谣言从来不止于智者,吃瓜群众认定了如此栩栩如生的谣言一定不是空穴来风。
更早一周前著名投资人周亚辉先生和空空狐创始人余小丹隔空对怼升级,最后周亚辉亮出了空空狐花20万置装买包的发票。
还有化妆品国货百雀羚上周用3000万制造了多起刷屏营销事件,最后的转化率只有0.00……008%什么的,又让甲方想起了去年被微信大号刷量骗钱的恐惧。
2012年后被职业经理人吃相吓到的刘强东至今一朝被蛇咬,十年怕井绳,只信任自己培养的管培生。废掉了好几个宝洁出身的市场负责人之后,如今把老同志徐雷放到了CMO这个首席花钱官的岗位上。
某位“独角兽捕手”所在的基金,纸面上业绩还很好,但是实际上投的公司还都没有上市退出,所以新办公装修得过于“堂而皇之”让LP颇有微词。
还有一家过去以改革僵化VC行业为己任的新基金,合伙人在基金投资之前就提前让直系亲属低价建仓,让基金为自己接盘。
如今互联网投资的热点从纯线上到O2O,再到网红美食和共享充电宝,自动售货机,基本上已经是纯线下了。纯线上的大平台,也在搞内容采购。一个MC天佑花了今日头条2000万,一张朴树专辑也要了网易云音乐2000万。
一旦涉足了采购、供应、BD,又在短期拿到巨额融资,互联网公司反腐败的难度就和传统企业拉平了。
互联网已经是我们国家的支柱产业,也是中国跻身G2,中国人实现中国梦的重要资本,因此要辩证地看待中国互联网的腐败问题,借腐败问题把整个行业一棍子打死,否定我们广大的独角兽和投资人队伍,更是不可取的。
|
Python
|
UTF-8
| 7,419
| 3.28125
| 3
|
[] |
no_license
|
import pygame
import numpy as np
import ChessBoard
import Piece
class ChessGraphics:
def __init__(self):
self.grid_s = 100
self.radius = round(self.grid_s / 8)
self.board_white = (200, 200, 200)
self.board_black = (10, 10, 90)
self.piece_white = (220, 150, 130)
self.piece_black = (50, 20, 10)
self.selected_square_color = (20, 120, 20)
self.legal_move_green = (20, 90, 20)
self.legal_capture_red = (90, 20, 20)
pygame.init()
self.selected_square = None
self.scr = pygame.display.set_mode((8 * self.grid_s, 8 * self.grid_s))
self.font = pygame.font.SysFont("Calibri", 64, 4)
self.promoting = False
def draw_board(self, chessboard, bottom_player):
for x in range(8):
for y in range(8):
rec = pygame.Rect((x*self.grid_s, y*self.grid_s), (self.grid_s, self.grid_s))
if (x + y) % 2 == 0:
color = self.board_white
else:
color = self.board_black
pygame.draw.rect(self.scr, color, rec)
if self.selected_square is not None:
if bottom_player == "white":
rec = pygame.Rect((self.selected_square[0] * self.grid_s, (7-self.selected_square[1]) * self.grid_s),
(self.grid_s, self.grid_s))
else:
rec = pygame.Rect(((7-self.selected_square[0]) * self.grid_s, self.selected_square[1] * self.grid_s),
(self.grid_s, self.grid_s))
pygame.draw.rect(self.scr, self.selected_square_color, rec)
def draw_pieces(self, chessboard, bottom_player):
b = chessboard.board
for x in range(8):
for y in range(8):
if b[(x, y)] is not None:
if b[(x, y)].color == "white":
text_color = self.piece_white
else:
text_color = self.piece_black
text = self.font.render(b[(x, y)].text, 0, text_color)
if bottom_player == "white":
self.scr.blit(text, (x * self.grid_s, (7 - y) * self.grid_s))
else:
self.scr.blit(text, ((7 - x) * self.grid_s, y * self.grid_s))
# Draws the squares corresponding to the legal moves of the piece being selected
def draw_moves(self, moves, bottom_player):
if moves is None:
return
for m in moves:
# If the move is a capture
if m.move_type == "capture":
color = self.legal_capture_red
# If the move is not a capture
else:
color = self.legal_move_green
x, y = m.move_square
if bottom_player == "white":
draw_x = self.grid_s * x + int(self.grid_s / 2)
draw_y = self.grid_s * (7 - y) + int(self.grid_s / 2)
else:
draw_x = self.grid_s * (7 - x) + int(self.grid_s / 2)
draw_y = self.grid_s * y + int(self.grid_s / 2)
pygame.draw.circle(self.scr, color, (draw_x, draw_y), self.radius)
def draw_promotion(self):
outer_rec = pygame.rect.Rect((round(1.9*self.grid_s), round(3.4*self.grid_s)),
(4.2*self.grid_s, 1.2*self.grid_s))
inner_rec = pygame.rect.Rect((round(2*self.grid_s), round(3.5*self.grid_s)),
(round(4*self.grid_s), round(1*self.grid_s)))
pygame.draw.rect(self.scr, (0, 0, 0), outer_rec)
pygame.draw.rect(self.scr, self.board_black, inner_rec)
promotions = [Piece.Knight, Piece.Bishop, Piece.Rook, Piece.Queen]
start_x = round(2*self.grid_s)
start_y = round(3.5*self.grid_s)
for prom in range(4):
text = self.font.render(promotions[prom].text, 0, self.board_white)
self.scr.blit(text, (start_x + prom * self.grid_s, start_y))
def promotion_mouse_select(self):
(x, y) = np.array(pygame.mouse.get_pos()).astype(int)
if y > round(4.5*self.grid_s) or y < round(3.5*self.grid_s):
return None
elif x > round(6*self.grid_s) or y < round(2*self.grid_s):
return None
promotions = [Piece.Knight, Piece.Bishop, Piece.Rook, Piece.Queen]
return promotions[(x-round(2*self.grid_s))//self.grid_s]
def legal_moves(self, chess_board):
pos = self.selected_square
if pos is None:
return []
if chess_board.is_p(pos, color=chess_board.player_to_move):
return chess_board.board[pos].legal_moves(chess_board)
else:
return []
def board_mouse_pos(self, bottom_player):
mouse_pos = np.array(pygame.mouse.get_pos()).astype(int)
grid_pos = mouse_pos//self.grid_s
if bottom_player == "white":
return grid_pos[0], 7-grid_pos[1]
else:
return 7-grid_pos[0], grid_pos[1]
if __name__ == "__main__":
gr = ChessGraphics()
b = ChessBoard.ChessBoard()
bottom_player = "white"
running = True
moved = False
while running:
pressed = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
pressed = True
gr.draw_board(b, bottom_player)
possible_moves = gr.legal_moves(b)
gr.draw_moves(possible_moves, bottom_player)
gr.draw_pieces(b, bottom_player)
if gr.promoting:
gr.draw_promotion()
pygame.display.flip()
if pressed:
if gr.promoting:
piece = gr.promotion_mouse_select()
if piece is not None:
b = b.make_promotion_move(piece)
gr.promoting = False
moved = True
else:
mouse_square = gr.board_mouse_pos(bottom_player)
# If you hadn't selected a square yet, select the one you clicked
if gr.selected_square is None:
gr.selected_square = mouse_square
# If you clicked the one you had selected, unselect it
elif gr.selected_square == mouse_square:
gr.selected_square = None
# If you had selected a square and then clicked another square
else:
# If you are making a move
for move in possible_moves:
if np.array_equal(move.move_square, mouse_square):
b = move
moved = True
if b.move_note == "promotion":
gr.promoting = True
moved = False
break
# Otherwise just select the square you clicked on
else:
gr.selected_square = mouse_square
# Check to see if this move ends the game
if not b.has_legal_moves():
if b.is_in_check():
print(f"{ChessBoard.n(b.player_to_move)} wins")
else:
print("Stalemate")
# running = False
|
Markdown
|
UTF-8
| 1,522
| 2.75
| 3
|
[] |
no_license
|
---
layout: post
title: Road Trip - with my boy j
---
Jeremy (my boy j) called last night and we talked for over an hour… It
was awesome to hear how things are going for him now that he’s back with
his rents…
He is working two jobs. The first is construction with one of the guys
from the church he goes to… The second job is a waiting job at a family
restuarant…
God is teaching him a lot right now. Jer’s had a rough last year, and
finally when he hit bottom he decided to go live in an atmosphere he
could actually grow in… Now that he is there God is breaking him down,
teaching him not to rely on his own strengths, but focus upward… Many
little small setbacks here and there can really get a person into a
depressive state focusing on themselves… But it seems to me Jer is
looking at everything as an opportunity… He went and worked 6 hours last
night and because of some mixups left with less than 10 bucks, barely
enough to cover the gas it cost to get there and back… But when I talked
to him he was totally cool and relaxed and not worried about the little
stuff.
Him and I are planning on getting together in Florida early to mid July
and we’re going to road trip back with a bunch of my sisters stuff…
I’m really excited :-)\
…nuf said
P.S. update on the van, its fixed (again!) and God provided everything
needed to get it fixed. I am still looking for another vehicle, so if
you see anything in the \$1500 to \$2000 range shoot me an email
jonmagic (~~at~~) gmail d0t com
|
C#
|
UTF-8
| 2,043
| 2.828125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// DDA Line Algorithm.
/// </summary>
public class CRayGridQuery2D
{
int _x;
int _y;
int _stepX;
int _stepY;
int _boundX;
int _boundY;
Vector2 _tMax;
Vector2 _tDelta;
/// <summary>
/// Construct a ray grid query
/// Ray must be in cell co-ords
/// </summary>
public CRayGridQuery2D(Vector2 Start, Vector2 Direction)
{
_x = (int)Start.x;
_y = (int)Start.y;
_stepX = Math.Sign(Direction.x);
_stepY = Math.Sign(Direction.y);
_boundX = _x + (_stepX > 0 ? 1 : 0);
_boundY = _y + (_stepY > 0 ? 1 : 0);
// TODO: Start should be cast to int here??
_tMax = new Vector2(
(_boundX - Start.x) / Direction.x,
(_boundY - Start.y) / Direction.y);
//if (Single.IsNaN(_tMax.x)) _tMax.x = Single.PositiveInfinity;
//if (Single.IsNaN(_tMax.y)) _tMax.y = Single.PositiveInfinity;
_tDelta = new Vector2(
_stepX / Direction.x,
_stepY / Direction.y);
if (Direction.x == 0)
{
_tDelta.x = Single.PositiveInfinity;
_tMax.x = Single.PositiveInfinity;
}
if (Direction.y == 0)
{
_tDelta.y = Single.PositiveInfinity;
_tMax.y = Single.PositiveInfinity;
}
//if (Single.IsNaN(_tDelta.x)) _tDelta.x = Single.PositiveInfinity;
//if (Single.IsNaN(_tDelta.y)) _tDelta.y = Single.PositiveInfinity;
}
public void GetNextCell(ref int X, ref int Y)
{
//return current cell
X = _x;
Y = _y;
//step to next cell
if (_tMax.x < _tMax.y)
{
_x += _stepX;
_tMax.x += _tDelta.x;
}
else
{
_y += _stepY;
_tMax.y += _tDelta.y;
}
}
public void GetNextCell(ref int X, ref int Y, ref int DX, ref int DY)
{
//return current cell
X = _x;
Y = _y;
DX = 0;
DY = 0;
//step to next cell
if (_tMax.x < _tMax.y)
{
_x += _stepX;
_tMax.x += _tDelta.x;
DX = _stepX;
}
else
{
_y += _stepY;
_tMax.y += _tDelta.y;
DY = _stepY;
}
}
}
|
Python
|
UTF-8
| 4,143
| 3.0625
| 3
|
[] |
no_license
|
import sys
import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
import requests
from urllib.parse import urlparse
class Blockchain(object):
difficulty_target = "0000"
def hash_block(self, block):
block_encoded = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_encoded).hexdigest()
def __init__(self):
# stores all the blocks in the entire blockchain
self.chain = []
# temporarily stores the transactions for the
# current block
self.current_transactions = []
# create the genesis block with a specific fixed hash
# of previous block genesis block starts with index 0
genesis_hash = self.hash_block("genesis_block")
self.append_block
(hash_of_previous_block= genesis_hash,
nonce=self.proof_of_work(0, genesis_hash, []))
# use PoW to find the nonce for the current block
def proof_of_work(self, index, hash_of_previous_block, transactions):
# try with nonce = 0
nonce = 0
# try hashing the nonce togheter with the hash of the
# previous block until it is valid
while self.valid_proof
(index, hash_of_previous_block, transactions, nonce) is False:
nonce += 1
return nonce
def valid_proof(self, index, hash_of_previous_block, transactions, nonce):
# create a string containing the hash of the previous
# block and the block content, including the nonce
content =
f'{index}{hash_of_previous_block}{transactions}{nonce}'.encode()
# hash using sha256
content_hash = hashlib.sha256(content).hexdigest()
# check if the hash meets the difficulty target
return content_hash[:len(self.difficulty_target)] ==
self.difficulty_target
# creates a new block and adds it to the blockchain
def append_block(self, nonce, hash_of_previous_block):
block = {
'index': len(self.chain),
'timestamp': time(),
'transactions': self.current_transactions,
'nonce': nonce,
'hash_of_previous_block': hash_of_previous_block
}
# reset the current list of transactions
self.current_transactions = []
# add the new block to the blockchain
self.chain.append(block)
def add_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'amount': amount,
'recipient': recipient,
'sender': sender,
})
return self.last_block['index']+1
@property
def last_block(self):
# returns the last block of the blockchain
return self.chain[-1]
app = Flask(__name__)
# generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')
# instantiate the Blockchain
blockchain = Blockchain()
#return the entire blockchain
@app.route('/blockchain', methods['GET'])
def full_chain():
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain),
}
return jsonify(response), 200
@app.route('/mine', methods['GET'])
def mine_block():
blockchain.add_transaction(
sender="0",
recipient=node_identifier,
amount=1,
)
# obtain the hash of last block in the blockchain
last_block_hash = blockchain.hash_block(blockchain.last_block)
# using PoW, get the nonce for the new block to be added
# to the blockchain
index = len(blockchain.chain)
nonce = blockchain.proof_of_work(index, last_block_hash,
blockchain.current_transactions)
# add the new block to the blockchain using the last block
# hash and the current nonce
block = blockchain.append_block(nonce, last_block_hash)
response = {
'message': "New Blcok Mined",
'index': block['index'],
'hash_of_previous_block': block['hash_of_previous_block'],
'nonce': block['nonce'],
'transactions': block['transactions'],
}
return jsonify(response), 200
|
C#
|
UTF-8
| 10,388
| 3.203125
| 3
|
[] |
no_license
|
using System;
using System.Threading;
using System.Collections.Generic;
namespace _11.FallingRocks
{
class FallingRocks
{
// for game objects printing
static void PrintOnField(int col, int row, char sign,
ConsoleColor color = ConsoleColor.Gray)
{
Console.SetCursorPosition(col, row);
Console.ForegroundColor = color;
Console.Write(sign);
}
// for score printing
static void PrintStringOnField(int col, int row, string str,
ConsoleColor color = ConsoleColor.Gray)
{
Console.SetCursorPosition(col, row);
Console.ForegroundColor = color;
Console.Write(str);
}
static void Main()
{
// player playing field dimensions
int playFieldWidth = 30;
int playFieldHeight = 20;
// dwarf creation
Dwarf dwarf = new Dwarf(playFieldHeight - 1, playFieldWidth / 2, ConsoleColor.Yellow, '0');
// for random color generation
ConsoleColor[] randomColor = new ConsoleColor[5];
randomColor[0] = ConsoleColor.Green;
randomColor[1] = ConsoleColor.Magenta;
randomColor[2] = ConsoleColor.Cyan;
randomColor[3] = ConsoleColor.Blue;
randomColor[4] = ConsoleColor.White;
// for random char generation
char[] randomChar = new char[11];
randomChar[0] = '^';
randomChar[1] = '@';
randomChar[2] = '*';
randomChar[3] = '&';
randomChar[4] = '+';
randomChar[5] = '%';
randomChar[6] = '$';
randomChar[7] = '#';
randomChar[8] = '!';
randomChar[9] = '.';
randomChar[10] = ';';
// random numbers generator
Random randomGenerator = new Random();
// rocks
List<GameObject> rocks = new List<GameObject>();
// game field and cursor visibility
Console.CursorVisible = false;
Console.BufferHeight = Console.WindowHeight = 20;
Console.BufferWidth = Console.WindowWidth = 60;
int gameFieldBoundaries = playFieldWidth + 1;
// game end conditions, speed and score
int lives = 3;
double sleepTime = 0.5;
double speed = 150;
int score = 0;
// Game Rules
PrintStringOnField(0, 0, "Welcome to the game Falling Rocks!", ConsoleColor.White);
PrintStringOnField(0, 1, "You are a brave dwarf who is facing a rock-hurling troll!", ConsoleColor.White);
PrintStringOnField(0, 2, "For each rock you avoid you gain 10 points.", ConsoleColor.White);
PrintStringOnField(0, 3, "You lose 50 points and 1 life for each rock that hits you!", ConsoleColor.White);
PrintStringOnField(0, 4, "The game speed increases over time.", ConsoleColor.White);
PrintStringOnField(0, 5, "Good Luck!!!", ConsoleColor.White);
PrintStringOnField(0, 6, "To start the game press \"y\", to exit press \"n\"", ConsoleColor.Green);
Console.SetCursorPosition(0, 7);
ConsoleKeyInfo yesOrNo = Console.ReadKey(true);
if (yesOrNo.Key == ConsoleKey.Y)
// game start
{
while (true)
{
// game speed;
if (speed < 425)
{
speed += sleepTime;
}
// hit flag
bool hit = false;
// Randomly create rocks
// Maximum of 5 rocks per row
// Create List newRocks, which holds the newly created rocks
// And checks if they are not already created
// Without this, the game sometimes creates two rocks at the same position
// Which translates to two lives taken if the player is hit
List<GameObject> newRocks = new List<GameObject>();
for (int i = 0; i < randomGenerator.Next(0, 5); i++)
{
GameObject newRock = new GameObject(
0,
randomGenerator.Next(0, playFieldWidth),
randomColor[randomGenerator.Next(0, 4)],
randomChar[randomGenerator.Next(0, 10)]);
bool exists = false;
// Checks all rocks in the newRock list for duplicates
foreach (var rock in newRocks)
{
if (newRock.row == rock.row && newRock.col == rock.col)
{
exists = true;
}
}
// If there aren't any duplicates, add the rock to the newRock list
if (exists != true)
{
newRocks.Add(newRock);
}
}
// Append the newRocks list to all rocks
rocks.AddRange(newRocks);
// Move Dwarf
while (Console.KeyAvailable)
{
ConsoleKeyInfo pressedKey = Console.ReadKey(true);
while (Console.KeyAvailable)
{
Console.ReadKey(true);
}
if (pressedKey.Key == ConsoleKey.LeftArrow || pressedKey.Key == ConsoleKey.A)
{
if (dwarf.col - 1 > 0)
{
dwarf.col = dwarf.col - 1;
dwarf.colTwo = dwarf.colTwo - 1;
dwarf.colThree = dwarf.colThree - 1;
}
}
if (pressedKey.Key == ConsoleKey.RightArrow || pressedKey.Key == ConsoleKey.D)
{
if (dwarf.colThree + 1 < playFieldWidth)
{
dwarf.col = dwarf.col + 1;
dwarf.colTwo = dwarf.colTwo + 1;
dwarf.colThree = dwarf.colThree + 1;
}
}
}
// Move Rocks
// @hits holds how many times the dwarf was hit. I.e. if there are two or more rocks "glued" together on a single row, count the hits
// and don't subtract more than 1 life
int hits = 0;
List<GameObject> newList = new List<GameObject>();
for (int i = 0; i < rocks.Count; i++)
{
GameObject oldRock = rocks[i];
GameObject newRock = new GameObject(oldRock.row + 1, oldRock.col, oldRock.color, oldRock.sign);
if (newRock.row == dwarf.row && (newRock.col == dwarf.col || newRock.col == dwarf.colTwo || newRock.col == dwarf.colThree)) // unit collision
{
hits++;
if (hits > 1)
{
continue;
}
hit = true;
lives -= 1;
if (lives <= 0)
{
PrintStringOnField(10, 9, "GAME OVER!", ConsoleColor.Red);
PrintStringOnField(6, 10, "Your score is: " + score, ConsoleColor.Red);
PrintStringOnField(5, 11, "Press [Enter] to exit", ConsoleColor.Red);
Console.ReadLine();
Environment.Exit(0);
}
}
if (newRock.row < playFieldHeight)
{
newList.Add(newRock);
}
else // scoring system
{
score += 10;
}
}
rocks = newList;
// Clear the console
Console.Clear();
// ReDraw playfield
if (hit)
{
rocks.Clear();
if (score <= 50)
{
score = 0;
}
else
{
score -= 50;
}
PrintOnField(dwarf.col, dwarf.row, 'X', ConsoleColor.Red);
PrintOnField(dwarf.colTwo, dwarf.row, 'X', ConsoleColor.Red);
PrintOnField(dwarf.colThree, dwarf.row, 'X', ConsoleColor.Red);
}
else
{
dwarf.Print();
}
foreach (GameObject rock in rocks)
{
rock.Print();
}
for (int i = 0; i < playFieldHeight; i++) // playfield boundaries
{
PrintOnField(playFieldWidth, i, '|', ConsoleColor.Gray);
}
// Print Score
PrintStringOnField(40, 9, "Lives: " + lives, ConsoleColor.White);
PrintStringOnField(40, 10, "Speed: " + speed, ConsoleColor.White);
PrintStringOnField(40, 11, "Score: " + score, ConsoleColor.White);
// Slow down the console
Thread.Sleep(500 - (int)speed);
}
}
if (yesOrNo.Key == ConsoleKey.N)
return;
else
{
Main();
}
}
}
}
|
Java
|
UTF-8
| 2,369
| 2.21875
| 2
|
[] |
no_license
|
package com.mobiroller.views;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import com.google.android.material.textfield.TextInputLayout;
import com.mobiroller.mobi942763453128.R;
import java.util.ArrayList;
public class CreditCardNumberTextWatcher implements TextWatcher {
public static Integer[] patternLogos = {Integer.valueOf(R.drawable.ic_e_commerce_visa_icon), Integer.valueOf(R.drawable.ic_e_commerce_master_card_icon)};
private boolean isEmpty = true;
private ArrayList<String> listOfPattern;
private EditText mEditText;
private TextInputLayout textInputLayout;
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public CreditCardNumberTextWatcher(EditText editText, TextInputLayout textInputLayout2) {
this.mEditText = editText;
this.textInputLayout = textInputLayout2;
this.listOfPattern = getListOfPattern();
}
public void afterTextChanged(Editable editable) {
String obj = editable.toString();
if (obj.length() <= 3 && obj.length() != 0) {
Log.e("CreditCard", "afterTextChanged 2");
if (obj.length() == 2) {
for (int i = 0; i < this.listOfPattern.size(); i++) {
if (obj.substring(0, 2).matches((String) this.listOfPattern.get(i))) {
this.textInputLayout.setError(null);
this.mEditText.setError(null);
this.mEditText.setCompoundDrawablesWithIntrinsicBounds(0, 0, patternLogos[i].intValue(), 0);
this.isEmpty = false;
return;
}
if (!this.isEmpty) {
this.mEditText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
} else if (obj.length() == 1) {
this.mEditText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
}
public static ArrayList<String> getListOfPattern() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("^4[0-9]$");
arrayList.add("^5[1-8]$");
return arrayList;
}
}
|
JavaScript
|
UTF-8
| 1,659
| 3.296875
| 3
|
[
"CC-BY-3.0"
] |
permissive
|
var Question = function (game, id, question, answer1, answer2, answer3, correctAnswer) {
this.game = game;
this.id = id;
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
this.answer3 = answer3;
this.correctAnswer = correctAnswer;
this.questionText = game.add.text(20, 20, this.question, { font: "14px Arial", fill: "#ffffff", align: "center" });
this.answer1Text = game.add.text(40, 50, "1. " + this.answer1, { font: "16px Arial", fill: "#ffffff", align: "center" });
this.answer2Text = game.add.text(40, 80, "2. " + this.answer2, { font: "16px Arial", fill: "#ffffff", align: "center" });
this.answer3Text = game.add.text(40, 110, "3. " + this.answer3, { font: "16px Arial", fill: "#ffffff", align: "center" });
this.questionText.fixedToCamera = true;
this.answer1Text.fixedToCamera = true;
this.answer2Text.fixedToCamera = true;
this.answer3Text.fixedToCamera = true;
this.questionText.visible = false;
this.answer1Text.visible = false;
this.answer2Text.visible = false;
this.answer3Text.visible = false;
this.done = false;
this.correct = false;
};
Question.prototype.showQuestion = function () {
this.questionText.visible = true;
this.answer1Text.visible = true;
this.answer2Text.visible = true;
this.answer3Text.visible = true;
readyToAnswer = true;
};
Question.prototype.hideQuestion = function () {
game.add.tween(this.questionText).to({ alpha: 0 }, 750).start();
game.add.tween(this.answer1Text).to({ alpha: 0 }, 750).start();
game.add.tween(this.answer2Text).to({ alpha: 0 }, 750).start();
game.add.tween(this.answer3Text).to({ alpha: 0 }, 750).start();
readyToAnswer = false;
};
|
C++
|
UTF-8
| 3,431
| 3.125
| 3
|
[
"Zlib"
] |
permissive
|
#ifndef PLAYER_H
#define PLAYER_H
#include "SDL.h"
#include "Texture.h"
#include "Generate.h"
#include <cmath>
#include <time.h>
const int PLAYER_MOVEMENT_SPEED = 1; //In number of blocks.
const int MOVEMENT_INTERVAL = 2;//In 15ms // was 10
const int KICKDOWNS = 3;
class Player
{
public:
//default constructor.
Player();
//Overloaded constructor.
//@param int - x value to init player.
//@param int - y value to init player.
//@param int - radius of player object.
//@param int - width of screen.
//@param int - height of screen.
Player(int x, int y, int r, int screenWidth, int screenHeight);
//GetPlayerX - returns the player's X.
//@return int - value of player's x.
int GetPlayerX();
void breakDownWall(int x, int y, Generate* maze);
//GetPlayerY - returns the player's Y.
//@return int - value of player's Y.
int GetPlayerY();
//SetPlayerX - Sets the player's X value.
//@param int - x value to set.
void SetPlayerX(int x);
//SetPlayerY - Sets the player's Y value.
//@param int - y value to set.
void SetPlayerY(int y);
//GetPlayerXVel - returns the player's xVel.
//@return int - value of player's x velocity.
int GetPlayerXVel();
//GetPlayerYVel - returns the player's y velocity.
//@return int - value of player's Y velocity.
int GetPlayerYVel();
//Update - updates the player object in game loop.
//@param SDL_Event - Event for the player class to handle.
//@param SDL_Surface - screen to render the player to.
void Update(SDL_Event* Event, SDL_Surface* screen, Generate* maze); //Normally takes the block vector
//Render - renders the player object.
void Render();
//Shuts down the player's object.
void Shutdown();
void ResetKickdown();
int GetKickdown() {return kickdown;};
void StopMovement() {canMove = false;};
void StartMovement() {canMove = true;};
public:
//Steps taken, used to calculate score.
int steps;
private:
//X location of player.
int x;
//Y location of player.
int y;
//Radius of player object.
int r;
//xVelocity of player.
int xVel;
//yVelocity of player.
int yVel;
//Render X
int renderX;
//Render Y
int renderY;
//previous x location of player.
int prevX;
//previous y location of player.
int prevY;
//Width of the screen.
int screenWidth;
//Height of the screen.
int screenHeight;
//canmove.
bool canMove;
//Pointer to the players texture in memory.
Texture* playerTexture;
//Player's timer class to regulate movement.
int movement;
//Walls to kick down.
int kickdown;
private:
//Distance - Calculates distance between the player and a object.
//@param int - X2 - location of object to compare.
//@param int - y location of object to compare.
//@return double - returns the distance.
double Distance(int x2, int y2);
//OnKeyDown - calculates player based on keydown.
//@param SDLKey sym - key value.
//@param SDLMod mod - modification on key.
//@param Uint16 - unicode value of key.
void OnKeyDown(SDLKey sym, SDLMod mod, Uint16 unicode, Generate* maze, SDL_Surface* screen);
//OnKeyUp - calculates player based on keyup
//@param SDLKey sym - key value.
//@param SDLMod mod - modification on key.
//@param Uint16 - unicode value of key.
void OnKeyUp(SDLKey sym, SDLMod mod, Uint16 unicode);
//CheckCollision - checks if movement is valid.
//@return bool - true if valid movement.
};
#endif
|
TypeScript
|
UTF-8
| 2,147
| 3.4375
| 3
|
[] |
no_license
|
import { of, from, fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';
import { MOCK_CARS, MOCK_USERS } from './mock-data';
console.clear();
/* Task 1 **/
// Data Source
const dataSource = [3, 1, '939', null, 3, { numb: 3 }, undefined, 'number'];
const source$ = from(dataSource);
// create variable result$ that sums all numbers in array
// extend with pipe operators, so that you will get expected result
// for example for array [1, 'a', 4, null, '8']
// you should get 1 + 4 + 8 = 13
// const result$ = source$.pipe()
// result$.subscribe((value) => console.log(value))
// expected result: 3 + 1 + 939 + 3 = 946
/* Task 2 **/
// Data Source
const fetchUsers = {
users: MOCK_USERS
};
const fetchData$ = of(fetchUsers);
// lets imagine that it is some kind of http call
// that returns us some users
// you should create variable countUsers$
// it will return us number of users which name starts with 'a' or 'A' or 'c' or 'C'
// const countUsers$ = fetchData$.pipe()
// countUsers$.subscribe((numberOfUsers) => console.log(numberOfUsers))
/* Task 3 **/
const cars$ = from(MOCK_CARS);
// lets imagine that you have web application that sells cars
// some user want to buy a car which price is less than 22000 (if its price is 22000 - it is ok for user)
// and not older than 4 years old (if its age is 4 - it is ok for user)
// so we need to filter all cars that are older or more expensive
// and also you should return cars as string
// '#model - #age: #price $'
// for example
// {
// "age": 14,
// "model": "Oldsmobile",
// "price": 32966
// }
// this car you should return as 'Oldsmobile - 14: 32966 $'
// const filteredCars$ = cars$.pipe()
// filteredCars$.subscribe((car) => console.log(car))
/* Task 4 **/
// Last one will be easy
// const valueAEl = document.getElementById('valueA');
// const valueBEl = document.getElementById('valueB');
// fromEvent(valueAEl, 'input')
// fromEvent(valueBEl, 'input')
// you need to calculate sum of values from both inputs
// only if they are both numbers and both are present
// const sum$ = ...
// Tip: look for operators that somehow merge or combine streams
|
Java
|
UTF-8
| 2,452
| 2.390625
| 2
|
[] |
no_license
|
package com.G3Tingeso.PrivateServices.services;
import com.G3Tingeso.PrivateServices.repositories.Diplomado_docente_Repository;
import com.G3Tingeso.PrivateServices.models.Diplomado_docente;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Diplomado_docenteService
*/
@CrossOrigin
@RestController
public class Diplomado_docenteService {
private final Diplomado_docente_Repository Diplomado_docenteRepository;
Diplomado_docenteService(Diplomado_docente_Repository Diplomado_docenteRepository){
this.Diplomado_docenteRepository = Diplomado_docenteRepository;
}
@GetMapping("/diplomado_docentes")
public List<Diplomado_docente> getAllDiplomado_docente(){
return Diplomado_docenteRepository.getAllDiplomado_docentes();
}
@GetMapping("/diplomado_docentes/{id}")
public Diplomado_docente getDiplomado_docente(@PathVariable int id){
return Diplomado_docenteRepository.getDiplomado_docente(id);
}
@GetMapping("/diplomado_docentes/count")
public String countDiplomado_docente(){
int total = Diplomado_docenteRepository.countDiplomado_docente();
return String.format("Tienes en total, %s de la lista.", total);
}
@PostMapping("/diplomado_docentes/create")
@ResponseBody
public Boolean createDiplomado_docente(@RequestBody Diplomado_docente Diplomado_docente){
boolean result = Diplomado_docenteRepository.createDiplomado_docente(Diplomado_docente);
return result;
}
@DeleteMapping("/diplomado_docentes/delete/{id}")
public boolean deleteDiplomado_docente(@PathVariable int id){
return Diplomado_docenteRepository.deleteDiplomado_docente(id);
}
@PutMapping("/diplomado_docentes/update")
public boolean updateDiplomado_docente(@RequestBody Diplomado_docente Diplomado_docente){
return Diplomado_docenteRepository.updateDiplomado_docente(Diplomado_docente);
}
}
|
Markdown
|
UTF-8
| 5,474
| 2.765625
| 3
|
[] |
no_license
|
{{nurse-kun|12|15}}
## Part Fourteen (February 14th) ##
### 20543035 ###
Hey, /b/. I know this is considerably sooner than I've found tends to work well, but I did say yesterday that I'd check in today, to see if anyone had anymore valentine ideas for a certain limbs/eye-reduced little girl. If so, I can print them out and bring them in for her to see, if not to leave them laying around afterward. Non-appropriate contributions aren't unwelcome, though they'd likely remain within the thread for the amusement of ourselves, rather than her perusal. Hit me with your best shop, /b/ and whoever else read the wiki or whatnot!
### 20543251 ###
On a non-valentine related note, not much happened last night, save for my burning some filet mignon so badly that Mama told me I suck and she laughed herself, quite nearly, sick.
I already went out and picked up some candy and some pink origami paper (as she was running low), so suggestions of that sort aren't really needed, at the moment.
### 20543719 ###
> _Aid- No... To obvious. Dunno. I don't think you should get her something. Too creepy._
Well, if I do bring anything in for her to see, it'd be because it's funny and lighthearted, not romantically inclined. Something to cheer her up in general, because she can rarely afford to pass up such a thing at any given time.
### 20543913 ###
> _Nurse-kun? Twice in a week? I CALL SHENANIGANS!_
No, it's me. I did say, last night, that I'd be checking in tonight, so here I am. IGNORE ME!
### 20544341 ###
> **(posts a picture of a left handed glove)** _Go to your local comic book store and see if they have anything she might be interested in_
I don't think baseball's really her thing, what with the lack of depth perception, and all. I'd post a picture of her trying to catch a ball and getting hit in the face, but I don't have the MS Paint talent.
### 20544403 ###
> _I just love you. That girl is awesome. You should totally take pics of her, even though you have reasons not to. especially because the odds of us knowing some random internet chick are low. i cant remember why you wont do it, explain it again._
The interbutt is forever, you are not anonymous, a picture is considerably easier to spread around to places it shouldn't be than a text post on /b/, I'm not comfortable with exposing her THAT much, etc.
### 20544551 ###
> _because we could send that picture around to all the major hospitals and the like, and if she gets identified refer them to the wiki for enough evidence to bring down Nurse-Kun and THEN copy paste his excruciating description of giving her an enema and the hook paragraph. And get him fired and perhaps even legal action. "Anyway, my question: Should I stick it in her pooper (among other things)? I mean, she isn't going to be able to resist, and I can go in there when she's asleep, then cover up her good eye and mouth before she even knows I'm there, with all the drugs she's on. She's so messed up mentally that she probably wouldn't tell anyone, considering she's barely talked to all the shrinks they've had her seeing since the accident. I'm a pretty gentle guy, and there's plenty of lube around here (obviously), and it'd be pretty easy to clean her up afterward, too." ONE MISTAKE AND WE HAVE YOU._
I'm happy to have provided a new hobby to people so desperately lacking in things to do.
### 20544816 ###

> _>>20544341 was it anything like this? If so don't throw it so hard you fuck._ **(image of soccerball impact a man's face)**
...I was speaking hypothetically. I haven't actually had an opportunity to play catch with her yet, and probably wouldn't, since she'd just wind up embarassed, most likely. Particularly since there was an incident with one of my colleagues, though, who tossed her something, playfully, once, not thinking, and when she missed catching it by a foot or so, kind of surprised it'd been tossed at her in the first place, she dropped into a depressive state for the rest of the day, refusing to speak to anyone about anything. Until I came in later, and she complained to me, bitterly, about how the nurse in question was 'making fun of her', and almost started crying as she talked about it.
Catch isn't on the agenda, no. Besides, she isn't some emo hacker fag; if she's going to be anybody, it's Motoko.
### 20544979 ###
> _At least give her a Waha printout from us._
Heh, well, who can find Waha objectionable...?
But should it be one big page-sized Waha, or a ton of tiled mini-Wahas?
### 20545034 ###
> _print those nana valentine's day cards from dan kim's website_
Somehow, I'm not sure Nana-themed cards would be the most warmly recieved by her. Call it a hunch. The fact that they exist, though, is certainly par for the course for Mr. Kim.
### 20546837 ###
> _What kind of candy was it that you got her, Nurse-kun?_
I got her a special valentine package with chocolate, gummies, skittles, and some licorice. Should be at least one thing she likes in there, depending on her mood!
### 20547395 ###
> _(more waha suggestions.)_
Ok, ok, I'm already planning on the Waha printout...it's just additional 'winners' at this point.
### 20548067 ###
> _NURSE-KUN. print out a pic of nana, cum on it, take pic and post it here. srsly_
Um, maybe another time. It sounds like a great way to celebrate this day of love, but there's the whole lacking digital camera thing and suchlike.
{{nurse-kun|12|15}}
|
C++
|
UTF-8
| 549
| 2.640625
| 3
|
[] |
no_license
|
#include<cstdio>
#include<deque>
std::deque<int> dq;
int N, M, t, ret;
int main() {
scanf("%d%d", &N, &M);
for (int i = 1; i <= N; i++) dq.push_back(i);
while (M--) {
scanf("%d", &t);
int f, b;
for (f = 0; f < N; f++) if (dq[f] == t) break;
b = dq.size() - f;
if (f < b) {
ret += f;
for (int i = 0; i < f; i++) {
dq.push_back(dq.front()); dq.pop_front();
}
}
else {
ret += b;
for (int i = 0; i < b; i++) {
dq.push_front(dq.back()); dq.pop_back();
}
}
dq.pop_front();
}
printf("%d", ret);
return 0;
}
|
JavaScript
|
UTF-8
| 807
| 2.59375
| 3
|
[] |
no_license
|
const Elevator = require('./elevator.js');
const Person = require('./person.js');
var elevator = new Elevator();
const person1 = new Person("person1", 0, 2);
elevator.call(person1);
const person2 = new Person("person2", 0, 7);
elevator.call(person2);
const person3 = new Person("person3", 3, 2);
elevator.call(person3);
const person4 = new Person("person4", 10, 2);
elevator.call(person4);
const person5 = new Person("person5", 9, 8);
elevator.call(person5);
const person6 = new Person("person6", 6, 1);
elevator.call(person6);
const person7 = new Person("person7", 4, 5);
elevator.call(person7);
const person8 = new Person("person8", 2, 1);
elevator.call(person8);
const person9 = new Person("person9", 3, 9);
elevator.call(person9);
const person10 = new Person("person10", 4, 8);
elevator.call(person10);
|
Java
|
UTF-8
| 1,489
| 2.234375
| 2
|
[] |
no_license
|
package den.graduation;
import den.graduation.model.Role;
import den.graduation.model.User;
import den.graduation.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MockTestUser {
// @Mock
// private UserService service;
//
// private DataJPAUserRepository repository;
private static final UserService serviceMock = mock(UserService.class);
private static final User user = new User(null, "User", "user@yandex.ru", "password", Role.USER);
private static final User user1 = new User(100000, "User", "user@yandex.ru", "password", Role.USER);
@Test
public void create() {
when(serviceMock.getByEmail("user@yandex.ru")).thenReturn(new User(100000, "User", "user@yandex.ru", "password", Role.USER));
Assert.assertEquals(serviceMock.getByEmail("user@yandex.ru"), new User(100000, "User", "user@yandex.ru", "password", Role.USER));
assertEquals(serviceMock.getByEmail("user@yandex.ru"), user1);
assertThat(serviceMock.getByEmail("user@yandex.ru")).isEqualToIgnoringGivenFields(user1,"id", "registered");
when(serviceMock.getByEmail("user1@yandex.ru")).thenReturn(null);
Assert.assertEquals(serviceMock.getByEmail("user1@yandex.ru"), null);
}
}
|
Swift
|
UTF-8
| 1,234
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// MainRouter.swift
// TodoManager
//
// Created by Anton Polyakov on 12/05/2018.
// Copyright © 2018 ton252. All rights reserved.
//
import UIKit
final class MainRouter: Router {
// MARK: - Public Methods
func initialViewController() -> UINavigationController {
let pm = TasksListPresentationModel()
let vc = TasksViewController(presentationModel: pm)
let nc = UINavigationController(rootViewController: vc)
let baseRouter = MainRouter(presenter: vc)
pm.openNewTaskHandler = baseRouter.presentNewTask
pm.openTaskHandler = baseRouter.presentTask(_:)
return nc
}
func presentTask(_ task: TaskViewModel) {
let pm = DetailTaskPresentationModel(task: task)
let vc = DetailTaskViewController(presentationModel: pm)
let nc = UINavigationController(rootViewController: vc)
presentModally(viewController: nc)
}
func presentNewTask() {
let pm = DetailTaskPresentationModel()
let vc = DetailTaskViewController(presentationModel: pm)
let nc = UINavigationController(rootViewController: vc)
presentModally(viewController: nc)
}
}
|
JavaScript
|
UTF-8
| 9,875
| 2.828125
| 3
|
[] |
no_license
|
let id1;
//UPDATE EMPLOYEES
//SET VALUES INTO THE MODAL TABLE
$(document).on("click", ".btn-edit", function(){
fila = $(this).closest("tr");
id1= fila.find('td:eq(0)').text();
fname= fila.find('td:eq(1)').text();
lname= fila.find('td:eq(2)').text();
department= fila.find('td:eq(4)').text();
mail= fila.find('td:eq(5)').text();
$('#updateName').val(fname);
$('#updateLastName').val(lname);
$('#UpdateEmail').val(mail);
$.ajax({
url: "libs/php/getAllDepartments.php",
type: 'POST',
error: function (err) {
alert("Error: " + err.responseText.toString())
},
success: function (result) {
$('#updateDepartment option').remove();
for(let i = 0; i < result['data'].length ; i++){
let department = result['data'][i]['name'];
var tag = document.createElement('option');
tag.value= result['data'][i]["id"] ;
tag.text = result['data'][i]["name"] ;
var element = document.getElementById('updateDepartment');
element.appendChild(tag);
}
$('#updateDepartment option:contains("'+department+'")').attr('selected', true);
}
});
});
// UPDATE DATES EMPLOYEES
$('#btn-update').on('click',()=>{
$.ajax({
url: "libs/php/update.php",
type: 'POST',
data:{
firstName : $('#updateName').val(),
lastName: $('#updateLastName').val(),
email: $('#UpdateEmail').val(),
department: $('#updateDepartment').val(),
id: id1
},
error: function (err) {
alert("Error: " + err.responseText.toString())
},
success: function (result) {
let firstName = result['data'][0]['firstName'] ;
let lastName =result['data'][0]['lastName'];
let location =result['data'][0]['location'];
let department =result['data'][0]['department'];
let email =result['data'][0]['email'];
let id1= result['data'][0]['id'];
var tableRow1 = $("td").filter(function() {
return $(this).text() == id1;
}).closest("tr");
tableRow1.remove();
$("#directory-tbody").append($("<tr><td style='display:none'>"+ id+"</td>"+ "<td>" + firstName + "</td>" + "<td>" + lastName +"<td class='mobile'>"+ location + "</td>" + "<td class='mobile'>" + department+ "</td>" +"<td class='mobile'>"+ email +"</td> <td><button class='btn btn-danger btn-sm rounded-0 btn-delete' type='button' data-toggle='tooltip' data-placement='top' data-bs-toggle='modal' data-bs-target='#deleteModal'><i class='far fa-trash-alt'></i></button>"+
" <button class='btn btn-success btn-sm btn-edit rounded-0' type='button' data-toggle='tooltip' data-placement='top' title='Edit'data-bs-toggle='modal' data-bs-target='#UpdateEmployeeModal'><i class='fa fa-edit'></i></button> <button class='btn btn-sm btn-info rounded-0' type='button' data-toggle='tooltip' data-placement='top' title='Info' data-bs-toggle='modal' data-bs-target='#InfoEmployeeModal'> <i class='fa fa-info'></i></button></td></tr>"));
}
});
});
//INFORMATIO SET VALUES EMPLOYEES
$(document).on("click", ".btn-info", function(){
fila = $(this).closest("tr");
id1= fila.find('td:eq(0)').text();
fname= fila.find('td:eq(1)').text();
lname= fila.find('td:eq(2)').text();
location1= fila.find('td:eq(3)').text();
department= fila.find('td:eq(4)').text();
mail= fila.find('td:eq(5)').text();
$('#infoName').val(fname);
$('#infoLastName').val(lname);
$('#infoDepartment').val(department);
$('#infoEmail').val(mail);
$('#infoLocation').val(location1);
});
let idD;
let locationD;
let departmentD;
/*DEPARTMENT UPDATES */
//CREATE DROPDOWN DEPARTMENT
$(document).on("click", ".btn-department", function(){
filaDrop = $(this).closest("tr");
idD= filaDrop.find('td:eq(0)').text();
departmentD= filaDrop.find('td:eq(1)').text();
locationD= filaDrop.find('td:eq(2)').text();
$.ajax({
url: "libs/php/getAllDepartments.php",
type: 'POST',
error: function (err) {
alert("Error: " + err.responseText.toString())
},
success: function (result) {
$('#updateDepartmentDropOptionsData option').remove();
departmentDrop= filaDrop.find('td:eq(1)').text();
for(let i = 0; i < result['data'].length ; i++){
var tagl = document.createElement('option');
tagl.value = result['data'][i]['name'];
var elementl = document.getElementById('updateDepartmentDropOptionsData');
elementl.appendChild(tagl);
}
$('#updateDepartmentDrop').val(departmentDrop);
}
});
});
$(document).on("click", ".btn-department", function(){
$.ajax({
url: "libs/php/getAllLocation.php",
type: 'POST',
error: function (err) {
alert("Error: " + err.responseText.toString())
},
success: function (result) {
$("#updateLocationDepartment option").remove();
for(let i = 0; i < result['data'].length ; i++){
var tagl = document.createElement('option');
tagl.value= result['data'][i]["id"] ;
tagl.text = result['data'][i]["name"] ;
var elementl = document.getElementById('updateLocationDepartment');
elementl.appendChild(tagl);
}
$('#updateLocationDepartment option:contains("'+locationD+'")').attr('selected', true);
}
});
});
/*
$(document).on("click", ".btn-department", function(){
filaD = $(this).closest("tr");
idD= filaD.find('td:eq(0)').text();
departmentD= filaD.find('td:eq(1)').text();
locationD= filaD.find('td:eq(2)').text();
$('#updateDepartmentD').val(departmentD);
$('#updateLocationD').val(locationD);
});*/
$('#btn-updateDepartment').on('click', ()=>{
$.ajax({
url: "libs/php/updateDepartment.php",
type: 'POST',
data:{
location : $('#updateLocationDepartment option:selected').text(),
department: $('#updateDepartmentDrop').val(),
id: idD,
locationD: locationD,
departmentD: departmentD
},
error: function (err) {
alert("Error: " + err.responseText.toString())
},
success: function (result) {
var tableRow1 = $("td").filter(function() {
return $(this).text() == idD;
}).closest("tr");
tableRow1.remove();
let id = result['data'][0]['id'];
let departmentName= result['data'][0]['name'];
let locationName = result['data'][0]['loca'];
$("#department-tbody").append($("<tr><td style='display:none'>" + id + "</td><td>" + departmentName + "</td><td>" + locationName +"</td><td><button class='btn btn-danger btn-sm rounded-0 btn-delete' type='button' data-toggle='tooltip' data-placement='top' data-bs-toggle='modal' data-bs-target='#deleteModal1'><i class='far fa-trash-alt'></i></button> <button class='btn btn-success btn-sm btn-edit btn-department rounded-0' type='button' data-toggle='tooltip' data-placement='top' title='Edit' data-bs-toggle='modal' data-bs-target='#UpdateDepartmentModal' id='btn-editDepartment'><i class='fa fa-edit'></i></button> </td></tr>"));
}
});
});
let idDrop;
let filaDrop;
//Create dropdown location
$(document).on("click", "#btnEditLocation", function(){
filaDrop = $(this).closest("tr");
idDrop= filaDrop.find('td:eq(0)').text();
$.ajax({
url: "libs/php/getAllLocation.php",
type: 'POST',
error: function (err) {
alert("Error: " + err.responseText.toString())
},
success: function (result) {
$('#locationOptionsData option').remove();
locationDrop= filaDrop.find('td:eq(1)').text();
for(let i = 0; i < result['data'].length ; i++){
var tagl = document.createElement('option');
tagl.value = result['data'][i]['name'];
var elementl = document.getElementById('locationOptionsData');
elementl.appendChild(tagl);
}
$('#locationDepartmentUpdate').val(locationDrop);
// $("#locationDepartment option[value='" + locationDrop + "']").attr('selected', true)
}
});
});
//UPDATE LOCATION
$('#btn-updateLocation').on('click', ()=>{
$.ajax({
url: "libs/php/updateDepartmentLocation.php",
type: 'POST',
data:{
name : $("#locationDepartmentUpdate").val(),
id: idDrop
},
error: function (err) {
alert("Error: " + err.responseText.toString())
},
success: function (result) {
filaDrop.remove();
let locationName = result['data'][0]['name'];
let id=result['data'][0]['id'];
$("#location-tbody").append($("<tr><td style='display:none'>" + id + "</td><td>" + locationName +"</td><td><button class='btn btn-danger btn-sm rounded-0 btn-delete' type='button' id='deleteLocation'><i class='far fa-trash-alt'></i></button> <button class='btn btn-success btn-sm btn-edit rounded-0' type='button' data-toggle='tooltip' data-placement='top' title='Edit' data-bs-toggle='modal' data-bs-target='#UpdateLocationModal' id='btnEditLocation'><i class='fa fa-edit'></i></button> </td></tr>"));
}
});
})
|
PHP
|
UTF-8
| 18,979
| 2.609375
| 3
|
[] |
no_license
|
<?php
/* Copyright (c) 1998-2014 ILIAS open source, Extended GPL, see docs/LICENSE */
/**
* Track access to ILIAS learning modules
*
* @author Alex Killing <alex.killing@gmx.de>
* @version $Id$
* @ingroup ModulesLearningModule
*/
class ilLMTracker
{
const NOT_ATTEMPTED = 0;
const IN_PROGRESS = 1;
const COMPLETED = 2;
const FAILED = 3;
const CURRENT = 99;
protected $lm_ref_id;
protected $lm_obj_id;
protected $lm_tree;
protected $lm_obj_ids = array();
protected $tree_arr = array(); // tree array
protected $re_arr = array(); // read event data array
protected $loaded_for_node = false; // current node for that the tracking data has been loaded
protected $dirty = false;
protected $page_questions = array();
protected $all_questions = array();
protected $answer_status = array();
protected $has_incorrect_answers = false;
protected $current_page_id = 0;
static $instances = array();
static $instancesbyobj = array();
////
//// Constructing
////
/**
* Constructor
*
* @param ilObjLearningModule $a_lm learning module
*/
private function __construct($a_id, $a_by_obj_id = false, $a_user_id)
{
$this->user_id = $a_user_id;
if ($a_by_obj_id)
{
$this->lm_ref_id = 0;
$this->lm_obj_id = $a_id;
}
else
{
$this->lm_ref_id = $a_id;
$this->lm_obj_id = ilObject::_lookupObjId($a_id);
}
include_once("./Modules/LearningModule/classes/class.ilLMTree.php");
$this->lm_tree = ilLMTree::getInstance($this->lm_obj_id);
}
/**
* Get instance
*
* @param
* @return
*/
static function getInstance($a_ref_id, $a_user_id = 0)
{
global $ilUser;
if ($a_user_id == 0)
{
$a_user_id = $ilUser->getId();
}
if (!isset(self::$instances[$a_ref_id][$a_user_id]))
{
self::$instances[$a_ref_id][$a_user_id] = new ilLMTracker($a_ref_id, false, $a_user_id);
}
return self::$instances[$a_ref_id][$a_user_id];
}
/**
* Get instance
*
* @param
* @return
*/
static function getInstanceByObjId($a_obj_id, $a_user_id = 0)
{
global $ilUser;
if ($a_user_id == 0)
{
$a_user_id = $ilUser->getId();
}
if (!isset(self::$instancesbyobj[$a_obj_id][$a_user_id]))
{
self::$instancesbyobj[$a_obj_id][$a_user_id] = new ilLMTracker($a_obj_id, true, $a_user_id);
}
return self::$instancesbyobj[$a_obj_id][$a_user_id];
}
////
//// Tracking
////
/**
* Track access to lm page
*
* @param int $a_page_id page id
*/
function trackAccess($a_page_id)
{
if ($this->lm_ref_id == 0)
{
die("ilLMTracker: No Ref Id given.");
}
// track page and chapter access
$this->trackPageAndChapterAccess($a_page_id);
// track last page access (must be done after calling trackPageAndChapterAccess())
$this->trackLastPageAccess($this->user_id, $this->lm_ref_id, $a_page_id);
// #9483
// general learning module lp tracking
include_once("./Services/Tracking/classes/class.ilLearningProgress.php");
ilLearningProgress::_tracProgress($this->user_id, $this->lm_obj_id,
$this->lm_ref_id, "lm");
// obsolete?
include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php");
ilLPStatusWrapper::_updateStatus($this->lm_obj_id, $this->user_id);
// mark currently loaded data as dirty to force reload if necessary
$this->dirty = true;
}
/**
* Track last accessed page for a learning module
*
* @param int $usr_id user id
* @param int $lm_id learning module id
* @param int $obj_id page id
*/
function trackLastPageAccess($usr_id, $lm_id, $obj_id)
{
global $ilDB;
// first check if an entry for this user and this lm already exist, when so, delete
$q = "DELETE FROM lo_access ".
"WHERE usr_id = ".$ilDB->quote((int) $usr_id, "integer")." ".
"AND lm_id = ".$ilDB->quote((int) $lm_id, "integer");
$ilDB->manipulate($q);
$title = "";
$q = "INSERT INTO lo_access ".
"(timestamp,usr_id,lm_id,obj_id,lm_title) ".
"VALUES ".
"(".$ilDB->now().",".
$ilDB->quote((int) $usr_id, "integer").",".
$ilDB->quote((int) $lm_id, "integer").",".
$ilDB->quote((int) $obj_id, "integer").",".
$ilDB->quote($title, "text").")";
$ilDB->manipulate($q);
}
/**
* Track page and chapter access
*/
protected function trackPageAndChapterAccess($a_page_id)
{
global $ilDB;
$now = time();
//
// 1. Page access: current page
//
$set = $ilDB->query("SELECT obj_id FROM lm_read_event".
" WHERE obj_id = ".$ilDB->quote($a_page_id, "integer").
" AND usr_id = ".$ilDB->quote($this->user_id, "integer"));
if (!$ilDB->fetchAssoc($set))
{
$fields = array(
"obj_id" => array("integer", $a_page_id),
"usr_id" => array("integer", $this->user_id)
);
// $ilDB->insert("lm_read_event", $fields);
$ilDB->replace("lm_read_event", $fields, array()); // #15144
}
// update all parent chapters
$ilDB->manipulate("UPDATE lm_read_event SET".
" read_count = read_count + 1 ".
" , last_access = ".$ilDB->quote($now, "integer").
" WHERE obj_id = ".$ilDB->quote($a_page_id, "integer").
" AND usr_id = ".$ilDB->quote($this->user_id, "integer"));
//
// 2. Chapter access: based on last page accessed
//
// get last accessed page
$set = $ilDB->query("SELECT * FROM lo_access WHERE ".
"usr_id = ".$ilDB->quote($this->user_id, "integer")." AND ".
"lm_id = ".$ilDB->quote($this->lm_ref_id, "integer"));
$res = $ilDB->fetchAssoc($set);
if($res["obj_id"])
{
include_once('Services/Tracking/classes/class.ilObjUserTracking.php');
$valid_timespan = ilObjUserTracking::_getValidTimeSpan();
$pg_ts = new ilDateTime($res["timestamp"], IL_CAL_DATETIME);
$pg_ts = $pg_ts->get(IL_CAL_UNIX);
$pg_id = $res["obj_id"];
if(!$this->lm_tree->isInTree($pg_id))
{
return;
}
$time_diff = $read_diff = 0;
// spent_seconds or read_count ?
if (($now-$pg_ts) <= $valid_timespan)
{
$time_diff = $now-$pg_ts;
}
else
{
$read_diff = 1;
}
// find parent chapter(s) for that page
$parent_st_ids = array();
foreach($this->lm_tree->getPathFull($pg_id) as $item)
{
if($item["type"] == "st")
{
$parent_st_ids[] = $item["obj_id"];
}
}
if($parent_st_ids && ($time_diff || $read_diff))
{
// get existing chapter entries
$ex_st = array();
$set = $ilDB->query("SELECT obj_id FROM lm_read_event".
" WHERE ".$ilDB->in("obj_id", $parent_st_ids, "", "integer").
" AND usr_id = ".$ilDB->quote($this->user_id, "integer"));
while($row = $ilDB->fetchAssoc($set))
{
$ex_st[] = $row["obj_id"];
}
// add missing chapter entries
$missing_st = array_diff($parent_st_ids, $ex_st);
if(sizeof($missing_st))
{
foreach($missing_st as $st_id)
{
$fields = array(
"obj_id" => array("integer", $st_id),
"usr_id" => array("integer", $this->user_id)
);
// $ilDB->insert("lm_read_event", $fields);
$ilDB->replace("lm_read_event", $fields, array()); // #15144
}
}
// update all parent chapters
$ilDB->manipulate("UPDATE lm_read_event SET".
" read_count = read_count + ".$ilDB->quote($read_diff, "integer").
" , spent_seconds = spent_seconds + ".$ilDB->quote($time_diff, "integer").
" , last_access = ".$ilDB->quote($now, "integer").
" WHERE ".$ilDB->in("obj_id", $parent_st_ids, "", "integer").
" AND usr_id = ".$ilDB->quote($this->user_id, "integer"));
}
}
}
////
//// Tracking
////
/**
* Set current page
*
* @param id $a_val current page id
*/
public function setCurrentPage($a_val)
{
$this->current_page_id = $a_val;
}
/**
* Get current page
*
* @return id current page id
*/
public function getCurrentPage()
{
return $this->current_page_id;
}
/**
* Load LM tracking data. Loaded when needed.
*
* @param
* @return
*/
protected function loadLMTrackingData()
{
global $ilDB;
// we must prevent loading tracking data multiple times during a request where possible
// please note that the dirty flag works only to a certain limit
// e.g. if questions are answered the flag is not set (yet)
// or if pages/chapter are added/deleted the flag is not set
if ($this->loaded_for_node === (int) $this->getCurrentPage() && !$this->dirty)
{
return;
}
$this->loaded_for_node = (int) $this->getCurrentPage();
$this->dirty = false;
// load lm tree in array
$this->tree_arr = array();
$nodes = $this->lm_tree->getSubTree($this->lm_tree->getNodeData($this->lm_tree->readRootId()));
foreach ($nodes as $node)
{
$this->tree_arr["childs"][$node["parent"]][] = $node;
$this->tree_arr["parent"][$node["child"]] = $node["parent"];
$this->tree_arr["nodes"][$node["child"]] = $node;
}
// load all lm obj ids of learning module
include_once("./Modules/LearningModule/classes/class.ilLMObject.php");
$this->lm_obj_ids = ilLMObject::_getAllLMObjectsOfLM($this->lm_obj_id);
// load read event data
$this->re_arr = array();
$set = $ilDB->query("SELECT * FROM lm_read_event ".
" WHERE ".$ilDB->in("obj_id", $this->lm_obj_ids, false, "integer").
" AND usr_id = ".$ilDB->quote($this->user_id, "integer"));
while ($rec = $ilDB->fetchAssoc($set))
{
$this->re_arr[$rec["obj_id"]] = $rec;
}
// load question/pages information
$this->page_questions = array();
$this->all_questions = array();
include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php");
$q = ilLMPageObject::queryQuestionsOfLearningModule($this->lm_obj_id, "", "", 0, 0);
foreach ($q["set"] as $quest)
{
$this->page_questions[$quest["page_id"]][] = $quest["question_id"];
$this->all_questions[] = $quest["question_id"];
}
// load question answer information
include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php");
$this->answer_status = ilPageQuestionProcessor::getAnswerStatus($this->all_questions, $this->user_id);
$this->has_incorrect_answers = false;
$has_pred_incorrect_answers = false;
$has_pred_incorrect_not_unlocked_answers = false;
$this->determineProgressStatus($this->lm_tree->readRootId(), $has_pred_incorrect_answers, $has_pred_incorrect_not_unlocked_answers);
$this->has_incorrect_answers = $has_pred_incorrect_answers;
}
/**
* Have all questoins been answered correctly (and questions exist)?
*
* @return bool true, if learning module contains any question and all questions (in the chapter structure) have been answered correctly
*/
function getAllQuestionsCorrect()
{
$this->loadLMTrackingData();
if (count($this->all_questions) > 0 && !$this->has_incorrect_answers)
{
return true;
}
return false;
}
/**
* Determine progress status of nodes
*
* @param int $a_obj_id lm object id
* @return int status
*/
protected function determineProgressStatus($a_obj_id, &$a_has_pred_incorrect_answers, $a_has_pred_incorrect_not_unlocked_answers)
{
$status = ilLMTracker::NOT_ATTEMPTED;
if (isset($this->tree_arr["nodes"][$a_obj_id]))
{
$this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"] = $a_has_pred_incorrect_answers;
$this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"] = $a_has_pred_incorrect_not_unlocked_answers;
if (is_array($this->tree_arr["childs"][$a_obj_id]))
{
// sort childs in correct order
$this->tree_arr["childs"][$a_obj_id] = ilUtil::sortArray($this->tree_arr["childs"][$a_obj_id], "lft", "asc", true);
$cnt_completed = 0;
foreach ($this->tree_arr["childs"][$a_obj_id] as $c)
{
// if child is not activated/displayed count child as implicitly completed
// rationale: everything that is visible for the learner determines the status
// see also bug #14642
if (!self::_isNodeVisible($c))
{
$cnt_completed++;
continue;
}
$c_stat = $this->determineProgressStatus($c["child"], $a_has_pred_incorrect_answers,
$a_has_pred_incorrect_not_unlocked_answers);
if ($status != ilLMTracker::FAILED)
{
if ($c_stat == ilLMTracker::FAILED)
{
$status = ilLMTracker::IN_PROGRESS;
}
else if ($c_stat == ilLMTracker::IN_PROGRESS)
{
$status = ilLMTracker::IN_PROGRESS;
}
else if ($c_stat == ilLMTracker::COMPLETED || $c_stat == ilLMTracker::CURRENT)
{
$status = ilLMTracker::IN_PROGRESS;
$cnt_completed++;
}
}
// if an item is failed or in progress or (not attempted and contains questions)
// the next item has predecessing incorrect answers
if ($c_stat == ilLMTracker::FAILED || $c_stat == ilLMTracker::IN_PROGRESS ||
($c_stat == ilLMTracker::NOT_ATTEMPTED && is_array($this->page_questions[$c["child"]]) && count($this->page_questions[$c["child"]]) > 0))
{
$a_has_pred_incorrect_answers = true;
if (!$this->tree_arr["nodes"][$c["child"]]["unlocked"])
{
$a_has_pred_incorrect_not_unlocked_answers = true;
}
}
}
if ($cnt_completed == count($this->tree_arr["childs"][$a_obj_id]))
{
$status = ilLMTracker::COMPLETED;
}
}
else if ($this->tree_arr["nodes"][$a_obj_id]["type"] == "pg")
{
// check read event data
if (isset($this->re_arr[$a_obj_id]) && $this->re_arr[$a_obj_id]["read_count"] > 0)
{
$status = ilLMTracker::COMPLETED;
}
else if ($a_obj_id == $this->getCurrentPage())
{
$status = ilLMTracker::CURRENT;
}
$unlocked = false;
if (is_array($this->page_questions[$a_obj_id]))
{
// check questions, if one is failed -> failed
$unlocked = true;
foreach ($this->page_questions[$a_obj_id] as $q_id)
{
if (is_array($this->answer_status[$q_id])
&& $this->answer_status[$q_id]["try"] > 0
&& !$this->answer_status[$q_id]["passed"])
{
$status = ilLMTracker::FAILED;
if (!$this->answer_status[$q_id]["unlocked"])
{
$unlocked = false;
}
}
}
// check questions, if one is not answered -> in progress
if ($status != ilLMTracker::FAILED)
{
foreach ($this->page_questions[$a_obj_id] as $q_id)
{
if (!is_array($this->answer_status[$q_id])
|| $this->answer_status[$q_id]["try"] == 0)
{
if ($status != ilLMTracker::NOT_ATTEMPTED)
{
$status = ilLMTracker::IN_PROGRESS;
}
}
}
$unlocked = false;
}
}
$this->tree_arr["nodes"][$a_obj_id]["unlocked"] = $unlocked;
$this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"] = $a_has_pred_incorrect_answers;
$this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"] = $a_has_pred_incorrect_not_unlocked_answers;
}
}
else // free pages (currently not called, since only walking through tree structure)
{
}
$this->tree_arr["nodes"][$a_obj_id]["status"] = $status;
return $status;
}
/**
* Get icon for lm object
*
* @param array $a_node node array
* @param int $a_highlighted_node current node id
* @return string image path
*/
public function getIconForLMObject($a_node, $a_highlighted_node = 0)
{
$this->loadLMTrackingData();
if ($a_node["child"] == $a_highlighted_node)
{
return ilUtil::getImagePath('scorm/running.svg');
}
if (isset($this->tree_arr["nodes"][$a_node["child"]]))
{
switch ($this->tree_arr["nodes"][$a_node["child"]]["status"])
{
case ilLMTracker::IN_PROGRESS:
return ilUtil::getImagePath('scorm/incomplete.svg');
case ilLMTracker::FAILED:
return ilUtil::getImagePath('scorm/failed.svg');
case ilLMTracker::COMPLETED:
return ilUtil::getImagePath('scorm/completed.svg');
}
}
return ilUtil::getImagePath('scorm/not_attempted.svg');
}
/**
* Has predecessing incorrect answers
*
* @param int $a_obj_id
* @return bool true if incorrect/unsanswered questions exist in predecessing pages
*/
function hasPredIncorrectAnswers($a_obj_id, $a_ignore_unlock = false)
{
$this->loadLMTrackingData();
$ret = false;
if (is_array($this->tree_arr["nodes"][$a_obj_id]))
{
if ($a_ignore_unlock)
{
$ret = $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"];
}
else
{
$ret = $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"];
}
}
return $ret;
}
////
//// Blocked Users
////
/**
* Get blocked users information
*
* @param
* @return
*/
function getBlockedUsersInformation()
{
global $ilDB, $lng, $ilPluginAdmin, $ilUser;
$blocked_users = array();
// load question/pages information
$this->page_questions = array();
$this->all_questions = array();
$page_for_question = array();
include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php");
$q = ilLMPageObject::queryQuestionsOfLearningModule($this->lm_obj_id, "", "", 0, 0);
foreach ($q["set"] as $quest)
{
$this->page_questions[$quest["page_id"]][] = $quest["question_id"];
$this->all_questions[] = $quest["question_id"];
$page_for_question[$quest["question_id"]] = $quest["page_id"];
}
// get question information
include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionList.php");
$qlist = new ilAssQuestionList($ilDB, $lng, $ilPluginAdmin, 0);
$qlist->addFieldFilter("question_id", $this->all_questions);
$qlist->load();
$qdata = $qlist->getQuestionDataArray();
// load question answer information
include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php");
$this->answer_status = ilPageQuestionProcessor::getAnswerStatus($this->all_questions);
include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php");
foreach ($this->answer_status as $as)
{
if ($as["try"] >= $qdata[$as["qst_id"]]["nr_of_tries"] && $qdata[$as["qst_id"]]["nr_of_tries"] > 0 && !$as["passed"])
{
//var_dump($qdata[$as["qst_id"]]);
$name = ilObjUser::_lookupName($as["user_id"]);
$as["user_name"] = $name["lastname"].", ".$name["firstname"]." [".$name["login"]."]";
$as["question_text"] = $qdata[$as["qst_id"]]["question_text"];
$as["page_id"] = $page_for_question[$as["qst_id"]];
$as["page_title"] = ilLMPageObject::_lookupTitle($as["page_id"]);
$blocked_users[] = $as;
}
}
return $blocked_users;
}
/**
* Is node visible for the learner
*
* @param mixed $a_node node object/array
* @return boolean node visible true/false
*/
static function _isNodeVisible($a_node)
{
include_once("./Services/COPage/classes/class.ilPageObject.php");
if ($a_node["type"] != "pg")
{
return true;
}
$lm_set = new ilSetting("lm");
$active = ilPageObject::_lookupActive($a_node["child"], "lm",
$lm_set->get("time_scheduled_page_activation"));
if(!$active)
{
$act_data = ilPageObject::_lookupActivationData((int) $a_node["child"], "lm");
if ($act_data["show_activation_info"] &&
(ilUtil::now() < $act_data["activation_start"]))
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
}
?>
|
Java
|
UTF-8
| 2,013
| 2.4375
| 2
|
[] |
no_license
|
package br.edu.ifce.cgt.application.controller.dialogs;
import br.edu.ifce.cgt.application.Main;
import br.edu.ifce.cgt.application.util.Config;
import cgt.game.CGTSpriteSheet;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
/**
* Created by infolev on 06/02/15.
*/
public class ListSpriteDialog extends VBox {
@FXML private ListView<String> listViewSprites;
private Stage stage;
public ListSpriteDialog() {
FXMLLoader view = new FXMLLoader(Main.class.getResource("/view/dialogs/ListSprite.fxml"));
view.setRoot(this);
view.setController(this);
try {
view.load();
} catch (IOException e) {
e.printStackTrace();
}
stage = new Stage();
stage.setScene(new Scene(this));
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(Main.getApp().getScene().getWindow());
stage.sizeToScene();
ObservableList<String> a = FXCollections.observableArrayList(Config.get().getGame().getSpriteDB().findAllId());
listViewSprites.setItems(a);
}
public void editSprite() {
String teste = listViewSprites.getSelectionModel().getSelectedItem();
if (teste != null) {
CGTSpriteSheet sheet = Config.get().getGame().getSpriteDB().find(teste);
if (sheet != null) {
SpriteSheetDialog dialog = new SpriteSheetDialog(sheet);
dialog.show();
}
}
}
public void delSprite() {
String teste = listViewSprites.getSelectionModel().getSelectedItem();
if (teste != null) {
if (Config.get().getGame().getSpriteDB().delete(teste)) {
listViewSprites.getItems().remove(teste);
}
}
}
public void show() {
stage.show();
}
}
|
Markdown
|
UTF-8
| 1,691
| 2.90625
| 3
|
[] |
no_license
|
# Creating Universal App Using Sencha ExtJS 6
## Overview
This CodeLab will introduce you to the Universal App concept introduced in Sencha Ext JS 6 and will walk you through the steps required to create, build, deply, and run an universal application.
### What you'll learn?
1. What is an Universal App?
2. What Classic and Modern toolkits are?
3. How to create a starter project using Sencha Cmd?
4. How to create modern specific views?
5. How to create classic specific views?
6. How to create shared views?
7. How to build an universal app using Sencha Cmd?
8. How to test the application?
### What you'll need?
1. [Sencha Cmd 6](https://www.sencha.com/products/sencha-cmd/)
2. [Sencha ExtJS 6.x SDK](https://www.sencha.com/products/extjs/#overview)
3. Google Chrome Browser
4. [XAMPP - Web Server](https://www.apachefriends.org/index.html)
## Environment Setup
1. Install Sencha Cmd
2. Extract Sencha Ext JS SDK
3. Install XAMPP - this is optional if you intend to use the Web Server built into Sencha Cmd
## Creating the app
In this section, let us create the starter project for our universal application.
### Generating project using Sencha Cmd
1. Create a folder - `myfirstunivapp`
2. Open Command Prompt or Terminal
3. Change directory to `myfirstunivapp`
4. Run the following Sencha Cmd to generate a sample universal application:
```
sencha -sdk /path/to/ExtSDK generate app MyApp ./myfirstunivapp
```
5. Understand generated folders/files/code
### Run the default generated project
## Extending the app for Desktop and Phone
### Adding a new classic view
### Adding a new modern view
### Adding a new shared view
## Running the modified application
## What's next?
|
C++
|
UTF-8
| 664
| 2.96875
| 3
|
[] |
no_license
|
// ADCS_Eigen.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include "Eigen/Dense"
using Eigen::Matrix3d;
int main()
{
Matrix3d m = Matrix3d::Random();
std::cout << "Here is the randomly generated matrix:" << std::endl;
std::cout << m << std::endl << std::endl;
std::cout << "Its transpose is:" << std::endl << m.transpose() << std::endl << std::endl;
std::cout << "Its inverse is:" << std::endl <<m.inverse() << std::endl << std::endl;
std::cout << "Its pseudo-inverse is:" << std::endl << m.completeOrthogonalDecomposition().pseudoInverse() << std::endl << std::endl;
}
|
Java
|
BIG5
| 39,813
| 1.570313
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* TradingBot - A Java Trading system..
*
* Copyright (C) 2013 Philipz (philipzheng@gmail.com)
* http://www.tradingbot.com.tw/
* http://www.facebook.com/tradingbot
*
* 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.
*
* Apache License, Version 2.0 v廡
* http://www.openfoundry.org/licenses/29
* Q Apache-2.0 {uqȳWw
* http://www.openfoundry.org/tw/legal-column-list/8950-obligations-of-apache-20
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.TimeZone;
import jna.OMSignAPI;
import messenger.CalendarSample;
import messenger.PlurkApi;
import messenger.facebook;
import messenger.gtalk;
public class NewDdeClient {
int current = 0;
Queue<Integer> queue = new LinkedList<Integer>();
List<Integer> ls = new LinkedList<Integer>();
Options[] options = { null, null, null};
int size = 400;
int lsize = 25;
int range = 16; // ܰʽd
double win = 0;
double lost = 0;
double total = 0;
int high = 0;
int low = 0;
int higho = 0;
int lowo = 0;
int preSettle;
static final String Email = "YOUR_EMAIL";
static final String fb = "FB_ID_SN";
static final String botname = "bot";
double nowpercent;
//double percent;
static int delay = 270000;
int multiple = 40;
String version = "";
boolean runflag = true;
LogFile txt;
int hlflag = 0;
int signalflag = 0;
String optionssignal = "xv,TXO,"; // 2010/5,8100,P,A
int opprice;
int opweek;
int opday;
int currentmulti = 1;
String YYMMDD;
boolean inoutflag = false;
static gtalk c = gtalk.getInstance();
static PlurkApi p = PlurkApi.getInstance();
static facebook f = facebook.getInstance();
static CalendarSample cal = CalendarSample.getInstance();
boolean close = false;
boolean SGXclose = false;
int upbound = 0;
int lowbound = 0;
int closeint = 0;
int vol;
int totalvol;
SGXindex sgx;
double SGXGap = 0.0015;
double SGXGapA = 0.00185;
double SGXGapB = 0.00285;
double SGXGapC = 0.00162;
double SGXGapL = 0.00123;
double SGXpercent = 0;
double SGXPreSettle = 0;
double SGXindex = 0;
String NextSGXSymbol;
int Gapvolout = 26;
String SGXTime;
boolean into = false;
int money = 100;
double preSGXGap;
boolean outsell = true;
double inPcentGap = 0.022;
boolean SGXflag = false;
double kspercent = 0;
double ksPreSettle = 0;
int countSize = 100;
int counter = 0;
int counterPos = 0;
boolean isOpen = false;
boolean intoflag = true;
double percent = 0.0; // оv
public static void main(String args[]) throws IOException {
NewDdeClient client = new NewDdeClient();
client.doit("Test");
}
public NewDdeClient(){
try {
FileInputStream fis = new FileInputStream("D:\\Dropbox\\SGX.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
sgx = (SGXindex) ois.readObject();
ois.close();
SGXPreSettle = sgx.getOpenindex();
preSGXGap = sgx.getlastSGX();
if (Math.abs(preSGXGap) > 0.00282) {
SGXflag = true;
SGXGapB = 0.0032;
}
fis = new FileInputStream("D:\\Dropbox\\KS.ser");
ois = new ObjectInputStream(fis);
KSindex ks = (KSindex) ois.readObject();
ois.close();
ksPreSettle = ks.getOpenindex();
fis = new FileInputStream("D:\\Dropbox\\Updown.ser");
ois = new ObjectInputStream(fis);
UpdownNew ud = (UpdownNew) ois.readObject();
ois.close();
percent = ud.getDirection() * 0.1;
} catch (Exception ex) {
System.out.println(ex);
c.alert(botname, Email, "Object Loading Error!! " + ex);
f.alert(botname, fb, "Object Loading Error!! " + ex);
System.exit(0);
}
try {
FileInputStream fis = new FileInputStream("D:\\Dropbox\\Op.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Options op = (Options) ois.readObject();
ois.close();
new File("D:\\Dropbox\\Op.ser").delete();
// Clean up the file
options[signalflag] = op;
opprice = op.getOpprice();
current = op.getCurrent();
if (op.isCallorput()) {
txt.setOutput("W@饼" + opprice + "CALL "
+ Math.abs(current) + "f!!");
c.alert(botname, Email, "W@饼" + opprice + "CALL "
+ Math.abs(current) + "f!!");
f.alert(botname, fb, "W@饼" + opprice + "CALL "
+ Math.abs(current) + "f!!");
}
else {
txt.setOutput("W@饼" + opprice + "PUT "
+ Math.abs(current) + "f!!");
c.alert(botname, Email, "W@饼" + opprice + "PUT "
+ Math.abs(current) + "f!!");
f.alert(botname, fb, "W@饼" + opprice + "PUT "
+ Math.abs(current) + "f!!");
}
} catch (Exception ex) {
}
boolean result = OMSignAPI.INSTANCE.IniDllAndPosition("TXO001", Math
.abs(current));
if (!result) {
System.out.println("OMSignAPI IniDllAndPosition Error!!");
c.alert(botname, Email, "OMSignAPI IniDllAndPosition Error!!");
f.alert(botname, fb, "OMSignAPI IniDllAndPosition Error!!");
}
c.alert(botname, Email, "Start Trading System!!");
f.alert(botname, fb, "Start Trading System!!");
optionssignal = optionssignal + GetWednesday.compareWed1() + ",";
YYMMDD = GetWednesday.gettoday();
new File("D:\\Runtime").mkdir();
txt = new LogFile("D:\\Runtime\\" + YYMMDD + "_OPlog.txt");
opweek = GetWednesday.getOpweek();
opday = GetWednesday.getOpday(YYMMDD);
if (opday == 0) {
SGXGapB = 0.0020;
}
if (YYMMDD.equals(GetWednesday.compareWed2(YYMMDD)))
close = true;
if (GetWednesday.isSGXClose()) {
SGXclose = true;
NextSGXSymbol = GetWednesday.getNextSGXSymbol();
}
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void doit(String input) {
String[] temp = input.split(",");
if (temp[0].equals("TX00")) {
int a = Integer.parseInt(temp[5]);
totalvol = Integer.parseInt(temp[7]);
if (a != 0 && totalvol > 0) {
preSettle = Integer.parseInt(temp[10]);
high = Integer.parseInt(temp[8]);
low = Integer.parseInt(temp[9]);
vol = Integer.parseInt(temp[6]);
detect(a);
if (runflag) {
add(a);
if (isOpen) {
check(a);
if (counterPos != 0)
counter++;
}
check_runtime();
}
}
// txt.setOutput(getNowTime() + " " + a);
} else if (temp[0].equals("TWN")) {
SGXindex = Double.parseDouble(temp[1]);
if (SGXindex != 0)
SGXpercent = (SGXindex / SGXPreSettle) - 1;
else
SGXpercent = 0;
setSGXTime();
} else if (temp[0].equals("KOSPI")) {
double ksindex = Double.parseDouble(temp[1]);
kspercent = (ksindex / ksPreSettle) - 1;
}
}
public double writetxt(String signal,int opprice, boolean buy, int abs) {
String optionssignal1;
if (buy) {
optionssignal1 = optionssignal + opprice + ",C,A";
} else {
optionssignal1 = optionssignal + opprice + ",P,A";
}
double opprice1 = GetOpPrice.getprice(opprice, buy);
//opprice1 = priceTrans(buy, opprice1); RC
boolean result = OMSignAPI.INSTANCE.GoOrder(signal, optionssignal1,
getNowTime(), abs, opprice1);
if (!result) {
System.out.println("OMSignAPI GoOrder Error!!");
c.alert(botname, Email, "OMSignAPI GoOrder Error!!");
f.alert(botname, fb, "OMSignAPI GoOrder Error!!");
}
txt.setOutput(getNowTime() + " current:" + abs + ", price:" + opprice1);
System.out.println("current:" + abs + ", price:" + opprice1);
return opprice1;
}
private void makeprice(int input, boolean buy) {
double i = new Integer(input).doubleValue();
i = i / 100;
double d;
if (buy) {
if (opday < 5) {
d = Math.floor(i) * 100;
opprice = (int) d;
} else {
d = (Math.floor(i) + opweek) * 100;
opprice = (int) d;
}
} else {
if (opday < 5) {
d = Math.ceil(i) * 100;
opprice = (int) d;
} else {
d = (Math.ceil(i) - opweek) * 100;
opprice = (int) d;
}
}
}
/* private int[] getbound(int input) {
double i = new Integer(input).doubleValue();
i = i / 100;
double d;
int[] bound = new int[2];
d = Math.floor(i) * 100;
bound[0] = (int) d;
d = Math.ceil(i) * 100;
bound[1] = (int) d;
return bound;
}*/
public void check(int input) {
/*double p1 = new Double(input).doubleValue();
* double p2 = new Double(preSettle).doubleValue();
* percent = new Double(Math.abs(1 - (p1 / p2)));
* double p3 = new Double(high).doubleValue(); double p4 = new
* Double(low).doubleValue(); percent1 = new Double(Math.abs(1 - (p3 /
* p4))); if (current != 0 || percent > 0.005 || percent1 > 0.015) {
*/
if (current == 0) {
checkin(input);
} else {
checkout(input);
}
// }
}
private void detect(int input) {
double p1 = new Double(input).doubleValue();
double p2 = new Double(preSettle).doubleValue();
nowpercent = (p1 / p2) - 1;
double percent = Math.abs(nowpercent);
if (!SGXflag) {
if ((0.02 > percent) && (percent > 0.01)) {
SGXGapB = 0.00291;
}
}
if (0.008 > percent)
multiple = 40;
else if ((0.02 > percent) && (percent > 0.008))
multiple = 10;
else
multiple = 30;
if (higho == 0) {
higho = input + multiple;
inoutflag = false;
}
if (lowo == 0) {
lowo = input - multiple;
inoutflag = false;
}
if (input > higho) {
higho = input;
inoutflag = true;
if (((hlflag == 0) || (hlflag == -1)) && inoutflag) {
hlflag = 1;
}
}
if (input < lowo) {
lowo = input;
inoutflag = true;
if (((hlflag == 0) || (hlflag == 1))&& inoutflag) {
hlflag = -1;
}
}
}
/* private int[] getQueryMaxMin(int input) {
Object[] t = ls.toArray();
Arrays.sort(t);
List<Object> list = Arrays.asList(t);
int min = (Integer) list.get(0);
int max = (Integer) list.get(lsize - 1);
int[] pair = { min, max };
return pair;
}*/
private void checkin(int input) {
if (into)
SGXGapB = 0.0039;
if (ls.size() >= lsize) {
int[] pair = getQueryModel();
if (pair[0] == 3) {
if ((SGXTWGap() - SGXGap) > 0 && outsell) {
makeprice(input, true);
currentmulti(GetOpPrice.getprice(opprice, true));
current = 1 * currentmulti;
int abs = Math.abs(current);
signalflag = 0;
Options op;
op = new Options(opprice, current, writetxt("TXO001", opprice,
true, abs));
options[signalflag] = op;
alertIn(op, true, abs, "max1");
into = true;
}
} else if (pair[0] == 4) {
if ((SGXTWGap() + SGXGap) < 0 && outsell) {
makeprice(input, false);
currentmulti(GetOpPrice.getprice(opprice, false));
current = -1 * currentmulti;
int abs = Math.abs(current);
signalflag = 0;
Options op;
op = new Options(opprice, current, writetxt("TXO001", opprice,
false, abs));
options[signalflag] = op;
alertIn(op, false, abs, "min1");
into = true;
}
}
}
if ((SGXTWGap() - SGXGapB) > 0 && outsell && intoflag && !close) {
counterPos++;
if (counter > countSize) {
if (counterPos > (countSize * 3 / 4)) {
makeprice(input, true);
currentmulti(GetOpPrice.getprice(opprice, true));
current = 1 * currentmulti;
int abs = Math.abs(current);
signalflag = 0;
Options op;
op = new Options(opprice, current, writetxt("TXO001", opprice,
true, abs));
options[signalflag] = op;
alertIn(op, true, abs, "counter:" + counterPos);
into = true;
intoflag = false;
} else {
counter = 0;
counterPos = 0;
}
}
} else if ((SGXTWGap() + SGXGapB) < 0 && outsell && intoflag && !close) {
counterPos--;
if (counter > countSize) {
if (counterPos < (countSize * -3 / 4)) {
makeprice(input, false);
currentmulti(GetOpPrice.getprice(opprice, false));
current = -1 * currentmulti;
int abs = Math.abs(current);
signalflag = 0;
Options op;
op = new Options(opprice, current, writetxt("TXO001", opprice,
false, abs));
options[signalflag] = op;
alertIn(op, false, abs, "counter:" + counterPos);
into = true;
intoflag = false;
} else {
counter = 0;
counterPos = 0;
}
}
}
}
/**
* ˬd@}LO_optionsI{HApGANRiC
* @param input
*/
private void scancheck(int input) {
double i = new Integer(input).doubleValue();
i = i / 100;
int price = (int) Math.ceil(i);
Double[] callprice = new Double[9];
Double[] putprice = new Double[9];
int y = 0;
for(int x = price - 4; x <= price + 4; x++){
callprice[y] = GetOpPrice.getprice(x * 100, true);
putprice[y] = GetOpPrice.getprice(x * 100, false);
y++;
}
y = 1;
for(int x = price - 3; x <= price + 3; x++){
double complex_price = x * 100 + callprice[y] - putprice[y];
if (complex_price > (input + 25) || complex_price < (input - 25))
scancheck1(x, y, callprice, putprice);
y++;
}
}
private void scancheck1(int x, int y, Double[] callprice, Double[] putprice) {
if (!(callprice[y - 1] > callprice[y - 1] && callprice[y] > callprice[y + 1])) {
opprice = x * 100;
currentmulti(GetOpPrice.getprice(opprice, true));
current = 1 * currentmulti;
int abs = Math.abs(current);
signalflag = 0;
Options op;
op = new Options(x * 100, current, writetxt("TXO001", opprice,
true, abs));
options[signalflag] = op;
alertIn(op, true, abs, "I{HRiCALL");
into = true;
} else if (!(putprice[y - 1] < putprice[y] && putprice[y] < putprice[y + 1])) {
opprice = x * 100;
currentmulti(GetOpPrice.getprice(opprice, false));
current = -1 * currentmulti;
int abs = Math.abs(current);
signalflag = 0;
Options op;
op = new Options(x * 100, current, writetxt("TXO001", opprice,
false, abs));
options[signalflag] = op;
alertIn(op, false, abs, "I{HRiPUT");
into = true;
}
}
/**
* 1.@}LA[Ĥ@ɡAcall + put > 120ANjiʡC 2.call + put < 120
* N}WUtA]O|^ɨ쥭LC 3.Q@IΤQGIHAT{ call + put < 11XAN|^ɡC 4.T{ call +
* putdecaytV֡ANtrendvVCC
*/
/*private void closecheckin(int input) {
int[] bound = new int[2];
if (upbound == 0 && lowbound == 0)
bound = getbound(input);
upbound = bound[1];
lowbound = bound[0];
double upprice = GetOpPrice.getprice(lowbound, true);
double lowprice = GetOpPrice.getprice(upbound, false);
if (closeint == 1) {
if ((upprice + lowprice) > 119) {
c.alert(botname, Email, getNowTime() + " " + lowbound + "CALL! +"
+ upbound + "PUT! j120");
currentmulti = (int) ((upprice + lowprice) - 119);
int callputflag = 0;
if (Math.abs(upprice - lowprice) > 50) {
if (upprice > lowprice)
callputflag = 2;
else if (upprice < lowprice)
callputflag = 1;
} else {
if (upprice > lowprice)
callputflag = 1;
else if (upprice < lowprice)
callputflag = 2;
}
if (callputflag == 1) {
if (current < 0){
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001", opprice, false, 0));
totalsum(op,abs);
alertOut(op, false, abs);
}
current = 1 * currentmulti;
int abs = Math.abs(current);
makeprice(input, true);
signalflag = 0;
Options op = new Options(opprice, current, writetxt("TXO001", opprice, true, abs));
options[signalflag] = op;
alertIn(op, true, abs);
} else if (callputflag == 2) {
if (current > 0){
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001",
opprice, true, 0));
totalsum(op,abs);
alertOut(op, true, abs);
}
current = -1 * currentmulti;
int abs = Math.abs(current);
makeprice(input, false);
signalflag = 0;
Options op = new Options(opprice, current, writetxt("TXO001", opprice, false, abs));
options[signalflag] = op;
alertIn(op, false, abs);
}
}
} else if (closeint == 2) {
if ((upprice + lowprice) > 109) {
c.alert(botname, Email, getNowTime() + " " + lowbound + "CALL! +"
+ upbound + "PUT! j110");
currentmulti = (int) ((upprice + lowprice) - 109);
int callputflag = 0;
if (Math.abs(upprice - lowprice) > 50) {
if (upprice > lowprice)
callputflag = 2;
else if (upprice > lowprice)
callputflag = 1;
} else {
if (upprice > lowprice)
callputflag = 1;
else if (upprice > lowprice)
callputflag = 2;
}
if (callputflag == 1) {
if (current < 0){
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001", opprice, false, 0));
totalsum(op,abs);
alertOut(op, false, abs);
}
current = 1 * currentmulti;
int abs = Math.abs(current);
makeprice(input, true);
signalflag = 0;
Options op = new Options(opprice, current, writetxt("TXO001", opprice, true, abs));
options[signalflag] = op;
alertIn(op, true, abs);
} else if (callputflag == 2) {
if (current > 0){
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001",
opprice, true, 0));
totalsum(op,abs);
alertOut(op, true, abs);
}
current = -1 * currentmulti;
int abs = Math.abs(current);
makeprice(input, false);
signalflag = 0;
Options op = new Options(opprice, current, writetxt("TXO001", opprice, false, abs));
options[signalflag] = op;
alertIn(op, false, abs);
}
} else if (current != 0) {
int abs = Math.abs(current);
if (current > 0) {
Options op;
op = new Options(opprice, 0, writetxt("TXO001", opprice, true, 0));
totalsum(op,abs);
alertOut(op, true, abs);
current = 0;
} else {
Options op;
op = new Options(opprice, 0, writetxt("TXO001", opprice, false, 0));
totalsum(op,abs);
alertOut(op, false, abs);
current = 0;
}
}
}
}*/
private void checkout(int input) {
checkout1(input);
HighMcheckout(input);
}
private void HighMcheckout(int input) {
if (current > 0) {
if (percent != 1) {
if ((input <= (high - Gapvolout)) && hlflag == 1 && (SGXTWGap() - SGXGapB) < 0) { // P_O_I^
if (((SGXTWGap() - SGXGapA) < 0) || close) {
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001",
opprice, true, 0));
totalsum(op, abs);
alertOut(op, true, abs, "HighMcheckout");
current = 0;
higho = 0;
lowo = 0;
hlflag = 0;
signalflag = signalflag + 1;
if (signalflag > 2)
signalflag = 1;
if (Math.abs(nowpercent) > inPcentGap)
outsell = false;
}
}
}
} else if (current < 0) {
if (percent != -1) {
if ((input >= (low + Gapvolout)) && hlflag == -1 && (SGXTWGap() + SGXGapB) > 0) { // P_O_CI^
if (((SGXTWGap() + SGXGapA) > 0) || close) {
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001",
opprice, false, 0));
totalsum(op, abs);
alertOut(op, false, abs, "HighMcheckout");
current = 0;
higho = 0;
lowo = 0;
hlflag = 0;
signalflag = signalflag + 1;
if (signalflag > 2)
signalflag = 1;
if (Math.abs(nowpercent) > inPcentGap)
outsell = false;
}
}
}
}
}
private void checkout1(int input) {
if (current > 0) {
if (percent != 1) {
if ((SGXTWGap() + SGXGapC) < 0) {
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001", opprice,
true, 0));
totalsum(op, abs);
alertOut(op, true, abs, "checkout1");
current = 0;
higho = 0;
lowo = 0;
hlflag = 0;
signalflag = signalflag + 1;
if (signalflag > 2)
signalflag = 1;
if (Math.abs(nowpercent) > inPcentGap)
outsell = false;
}
}
} else if (current < 0) {
if (percent != -1) {
if ((SGXTWGap() - SGXGapC) > 0) {
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001", opprice,
false, 0));
totalsum(op, abs);
alertOut(op, false, abs, "checkout1");
current = 0;
higho = 0;
lowo = 0;
hlflag = 0;
signalflag = signalflag + 1;
if (signalflag > 2)
signalflag = 1;
if (Math.abs(nowpercent) > inPcentGap)
outsell = false;
}
}
}
}
void check_runtime() {
java.util.Date now = new java.util.Date(); // o{bɶ
SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss E",
java.util.Locale.TAIWAN);
String sGMT = sf.format(now);
int hour = Integer.valueOf(sGMT.substring(0, 2)).intValue();
int min = Integer.valueOf(sGMT.substring(3, 5)).intValue();
int sec = Integer.valueOf(sGMT.substring(6, 8)).intValue();
CheckSGXTime(min); //bx|X{o runflag = false; ]13:30HᰱC
if (current != 0) {
if (hour > 12 && min > 28 && sec > 45) {
if (close) {
clear();
runflag = false;
}
}
if (hour > 12 && min > 43 && sec > 45) {
clear();
runflag = false;
}
} else {
if (hour > 12 && min > 0 && (close || SGXclose)) {
runflag = false;
}
if (hour > 12 && min > 20) {
runflag = false;
}
}
if (hour > 8 && min > 1 && sec > 0 && !isOpen) {
isOpen = true;
if (SGXindex != 0)
runflag = true;
else
runflag = false;
}
}
private String getNowTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
java.util.Date date = new java.util.Date();
String datetime = dateFormat.format(date);
return datetime;
}
private void clear() {
if (current != 0) {
double SGXPercent;
if (SGXclose)
SGXPercent = NextSGXTWGap();
else
SGXPercent = SGXTWGap();
if (current > 0) {
if (percent != 1) {
if (close || ((SGXPercent - SGXGapL) < 0)) {
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001",
opprice, true, 0));
totalsum(op, abs);
alertOut(op, true, abs, "clear");
current = 0;
}
}
} else {
if (percent != -1) {
if (close || ((SGXPercent + SGXGapL) > 0)) {
int abs = Math.abs(current);
Options op;
op = new Options(opprice, 0, writetxt("TXO001",
opprice, false, 0));
totalsum(op, abs);
alertOut(op, false, abs, "clear");
current = 0;
}
}
}
}
runflag = false;
}
public void close(){
if (!close) {
if (current != 0) {
try {
FileOutputStream fos = new FileOutputStream("D:\\Dropbox\\Op.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(options[signalflag]);
oos.close();
} catch (Exception ex) {
System.out.println("Exception thrown during writing Options: " + ex.toString());
}
txt.setOutput("OPdܡG" + options[signalflag].getOpprice() + " " + options[signalflag].getCurrent());
c.alert(botname, Email, "OPdܡG" + options[signalflag].getOpprice() + " " + options[signalflag].getCurrent());
f.alert(botname, fb, "OPdܡG" + options[signalflag].getOpprice() + " " + options[signalflag].getCurrent());
}
}
c.alert(botname, Email, getNowTime() + " Trading System Stop!!");
f.alert(botname, fb, getNowTime() + " Trading System Stop!!");
p.logout();
txt.setOutput("Win:" + win);
txt.setOutput("Lost:" + lost);
txt.setOutput("Total:" + total);
txt.close();
}
private void alertIn(Options op, boolean callorput, int abs, String input) {
if (callorput) {
if (op.getSpouse() != null) {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% Ri " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f"
+ " X " + op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " Ri " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f"
+ " X " + op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " Ri " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f" + " X "
+ op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " Ri " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f" + " X "
+ op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " Ri " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f" + " X "
+ op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " Ri " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f"
+ " X " + op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
} else {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% Ri " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " Ri " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " Ri " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " Ri " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " Ri " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " Ri " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f");
}
} else {
if (op.getSpouse() != null) {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% Ri " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f"
+ " X " + op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " Ri " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f"
+ " X " + op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " Ri " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f" + " X "
+ op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " Ri " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f" + " X "
+ op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " Ri " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f" + " X "
+ op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " Ri " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f"
+ " X " + op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
} else {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% Ri " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " Ri " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " Ri " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " Ri " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " Ri " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " Ri " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f");
}
}
}
private void alertOut(Options op, boolean callorput, int abs, String input) {
if (callorput) {
if (op.getSpouse() != null) {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% X " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f"
+ " Ri " + op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " X " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f"
+ " Ri " + op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " X " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f" + " Ri "
+ op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " X " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f" + " Ri "
+ op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " X " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f" + " Ri "
+ op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " X " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f"
+ " Ri " + op.getSpouse().getOpprice() + "CALL! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
} else {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% X " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " X" + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " X " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " X " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " X " + opprice + "CALL! cost:"
+ op.getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " X " + opprice
+ "CALL! cost:" + op.getPrice() + " " + abs + "f");
}
} else {
if (op.getSpouse() != null) {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% X " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f"
+ " Ri " + op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " X" + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f"
+ " Ri " + op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " X " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f" + " Ri "
+ op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " X " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f" + " Ri "
+ op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " X " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f" + " Ri "
+ op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " X " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f"
+ " Ri " + op.getSpouse().getOpprice() + "PUT! cost:"
+ op.getSpouse().getPrice() + " " + abs + "f");
} else {
c.alert(botname, Email, getNowTime() + " Gap: " + (SGXTWGap() * 100) + "% :" + (kspercent * 100) + "% X " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f " + input);
f.alert(botname, getNowTime() + " X " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f " + input);
p.plurkAdd(getNowTime() + " X " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f");
cal.addEvent(getNowTime() + " X " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f");
txt.setOutput(getNowTime() + " X " + opprice + "PUT! cost:"
+ op.getPrice() + " " + abs + "f");
System.out.println(getNowTime() + " X " + opprice
+ "PUT! cost:" + op.getPrice() + " " + abs + "f");
}
}
}
public void totalsum(Options op, int abs) {
if (options[signalflag].getSpouse() != null) {
if (op.getPrice() > options[signalflag].getPrice()) {
win = win
+ (((op.getPrice() - options[signalflag].getPrice()) - (op
.getSpouse().getPrice() - options[signalflag]
.getSpouse().getPrice())) * abs);
total = total
+ (((op.getPrice() - options[signalflag].getPrice()) - (op
.getSpouse().getPrice() - options[signalflag]
.getSpouse().getPrice())) * abs);
} else {
lost = lost
+ (((options[signalflag].getPrice() - op.getPrice()) - (options[signalflag]
.getSpouse().getPrice() - op.getSpouse()
.getOpprice())) * abs);
total = total
- (((options[signalflag].getPrice() - op.getPrice()) - (options[signalflag]
.getSpouse().getPrice() - op.getSpouse()
.getOpprice())) * abs);
}
} else {
if (op.getPrice() > options[signalflag].getPrice()) {
win = win
+ ((op.getPrice() - options[signalflag].getPrice()) * abs);
total = total
+ ((op.getPrice() - options[signalflag].getPrice()) * abs);
} else {
lost = lost
+ ((options[signalflag].getPrice() - op.getPrice()) * abs);
total = total
- ((options[signalflag].getPrice() - op.getPrice()) * abs);
}
}
}
private double SGXTWGap(){
return SGXpercent - nowpercent;
}
private void currentmulti(double input) {
double multi = money / input;
multi = Math.floor(multi);
currentmulti = (int) multi;
}
private double NextSGXTWGap(){
double SGXNextChange = GetOpPrice.getchange(NextSGXSymbol);
double SGXNextPrepercent = GetOpPrice.getprice(NextSGXSymbol) - SGXNextChange;
double SGXNextpercent = SGXNextChange / SGXNextPrepercent;
return SGXNextpercent - nowpercent;
}
private void CheckSGXTime(int mm){
if (SGXTime != null) {
int min = Integer.valueOf(SGXTime.substring(3, 5)).intValue();
if (mm > (min + 1) && runflag) {
c.alert(botname, Email, getNowTime() + " Optionsbot SGXIndex Stop Error!!");
f.alert(botname, fb, getNowTime() + " Optionsbot SGXIndex Stop Error!!");
System.out.println("Optionsbot SGXIndex Stop Error!!");
runflag = false;
}
}
}
private void setSGXTime(){
java.util.Date now = new java.util.Date(); // o{bɶ
SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss E",
java.util.Locale.TAIWAN);
SGXTime = sf.format(now);
}
/*
* vQ10IHUG0.1I(5)
* vQ10IHWA50IHUG0.5I(25)
* vQ50IHWA500IHUG1I(50)
* vQ500IHWA1000IHUG5I(250)
* */
private double priceTrans(boolean buy, double price) {
int updown = 0;
if (buy)
updown = 1;
else
updown = -1;
if (price < 10) {
price = price + (updown * 0.1);
} else if (price < 50) {
price = price + (updown * 0.5);
} else if (price < 500) {
price = price + (updown * 1);
} else if (price < 1000) {
price = price + (updown * 5);
} else {
price = price + (updown * 10);
}
return price;
}
private Integer[] fhw(Object in[]) {
int size = in.length;
Integer[] tmp = new Integer[size / 2];
for (int i = 0; i < size; i += 2) {
tmp[i / 2] = ((Integer) in[i] + (Integer) in[i + 1]) / 2;
}
return tmp;
}
private Integer[] dwt(Object in[]) {
Integer[] temp = null;
switch (size) {
case 1600:
temp = fhw(fhw(fhw(fhw(fhw(fhw(in))))));
break;
case 800:
temp = fhw(fhw(fhw(fhw(fhw(in)))));
break;
case 400:
temp = fhw(fhw(fhw(fhw(in))));
break;
case 200:
temp = fhw(fhw(fhw(in)));
break;
case 100:
temp = fhw(fhw(in));
break;
}
return temp;
}
public void add(int input) {
queue.add(input);
if (queue.size() >= size) {
Object[] I = queue.toArray();
Integer[] w = dwt(I);
ls = Arrays.asList(w);
queue.remove();
}
}
private int[] getQueryModel() {
Object[] t = ls.toArray();
Arrays.sort(t);
List<Object> list = Arrays.asList(t);
int min = (Integer) list.get(0);
int max = (Integer) list.get(lsize - 1);
int minpos = ls.lastIndexOf(min);
int maxpos = ls.lastIndexOf(max);
/*int q1 = ls.get(0);
int q2 = ls.get(lsize/5);
int q3 = ls.get(lsize/5*2);
int q4 = ls.get(lsize/5*3);
int q5 = ls.get(lsize/5*4);
int q6 = ls.get(lsize-1);*/
int vol = max - min;
int[] pair = { 0, vol };
if (vol > range) {
if ((5 >= minpos) && (maxpos >= 20)) {
pair[0] = 1;
} else if ((5 >= maxpos) && (minpos >= 20)) {
pair[0] = 2;
}
if ((16 <= minpos) && (minpos <= 20) && (maxpos >= 23)) {
pair[0] = 3;
} else if ((16 <= maxpos) && (maxpos <= 20) && (minpos >= 23)) {
pair[0] = 4;
}
}
return pair;
}
}
/*
* </PRE> </BODY> </HTML>
*/
|
Markdown
|
UTF-8
| 3,533
| 3.15625
| 3
|
[] |
no_license
|
# 챕터 2-2 : CSS Module
> 참고 : https://react.vlpt.us/styling/02-css-module.html
#### 📕 주로 배운 내용
- CSS Module 기본 개념
- **고유 클래스명**을 사용할 수 있도록 하는 서드파티 라이브러리
- 클래스명에 해쉬값을 붙여주므로 중복 된 클래스명으로 인한 충돌을 방지할 수 있다.
- 기존 레거시 프로젝트에 리액트를 도입할 때 유용하다.
- webpack 기본 내장 라이브러리이기에 CRA 프로젝트에서 설치 없이 사용 가능하다.
<br>
- 사용하기
- CSS 파일의 확장자를 `.module.css`로 설정하여 사용할 수 있다.
- 스타일시트 내부에 작성한 각 클래스 별 스타일 코드를, 클래스명 지정 시 지정하여 사용한다.
##### `PinkBg.module.css`
```
.pinkBg {
background: #ff80c0;
}
.pinkBg h1 {
font-weight: bold;
}
```
##### `PinkBg.js`
```
import style from "./PinkBg.module.css";
function PinkBg({ children }) {
return (
// 클래스명 작성 방법
<div className={style.pinkBg}>
<h1>{children}</h1>
</div>
);
}
```
- Sass 또한 사용 가능하다. Scss의 경우 확장자를 `.module.scss`로 지정하면 된다.
##### `PinkBg.module.scss`
```
$pink: #ff80c0;
.pinkBg {
background: $pink;
h1 {
font-weight: bold;
}
}
```
<br>
- classnames 라이브러리를 이용한 바인딩
- <a href="https://github.com/uncyclocity/study_react/tree/main/2-1_sass">이전에 사용했던 classnames 라이브러리</a>를 이용하여 스타일시트를 바인딩을 시켜주면, 클래스명만 명시하여 적용할 수 있다.
- import 할 때 `classnames/bind`를 가져옴으로써 사용할 수 있다.
```
import styles from "./PinkBg.module.css";
import classNames from "classnames/bind";
// 변수에 바인딩 적용
const cx = classNames.bind(styles);
function PinkBg({ children }) {
return (
// 한층 간결해진 클래스명 지정
<div className={cx(pinkBg)}>
<h1>{children}</h1>
</div>
);
}
export default PinkBg;
```
<br>
- [번외] react-icon : 컴포넌트 형식으로 아이콘 불러오기
```
$ yarn add react-icons
```
- 예쁜 디자인이 적용 된 아이콘들을 컴포넌트 형태로 사용할 수 있다.
- <a href="https://react-icons.github.io/react-icons">공식 문서</a>에서 원하는 아이콘을 선택하여, 이를 컴포넌트로 적용하면 된다.
##### 사용 예시 : 머태리얼 체크박스 적용하기
```
import styles from "./CheckBox.module.css";
// 머태리얼 아이콘(react-icons/md)의 체크박스 ON/OFF 컴포넌트를 가져옴
import { MdCheckBox, MdCheckBoxOutlineBlank } from "react-icons/md";
// props : 체크박스 체크 여부, 눌렀을 때 checked가 바뀌는 함수
function CheckBox({checked, onClick}) {
return (
<div>
<input type="checkbox" className={styles.hidden_cb} onClick={onClick}/>
{
// 각 컴포넌트에 맞춤형 스타일을 적용할 수 있다.
// ex) 색깔(color), 너비 및 높이 등...
checked ?
<MdCheckBox style={style.cb_true}/> :
<MdCheckBoxOutlineBlank style={style.cb_false}/>
}
</div>
);
}
export default CheckBox;
```
|
C++
|
UTF-8
| 1,374
| 2.75
| 3
|
[] |
no_license
|
#include "monster.h"
#include <time.h>
monster::monster()
{
//ctor
}
void monster::moveMonster(int &MonsterX, int &MonsterY,int &PlayerX, int &PlayerY)
{
srand(time(0));
memcpy( tmp_map, m.map, sizeof(m.map) ); // tmp_map paverciam m.map perkopijuojam visus simbolius char
int distancex = PlayerX - MonsterX;
int distancey = PlayerY - MonsterY;
if (distancex > 0)
{
if(tmp_map[MonsterY][MonsterX] != '#')
{
MonsterX++;
}
else
{
MonsterX--;
MonsterY++;
}
}
else if (distancex < 0)
{
if(tmp_map[MonsterY][MonsterX] != '#')
{
MonsterX--;
}
else{
MonsterX++;
MonsterY--;
}
}
if (distancey > 0)
{
if(tmp_map[MonsterY][MonsterX] != '#')
{
MonsterY++;
}
else
{
MonsterX++;
MonsterY--; // MonsterY = rand() % 13 + 1;
}
}
else if (distancey <0)
{
if(tmp_map[MonsterY][MonsterX] != '#')
{
MonsterY--;
}
else
{
MonsterX--;
MonsterY++; // MonsterY = rand() % 13 + 1;
}
}
}
monster::~monster()
{
//dtor
}
|
Java
|
UTF-8
| 3,016
| 2.953125
| 3
|
[] |
no_license
|
package dao;
import connection.JDBC;
import entities.Content;
import java.io.IOException;
import java.sql.*;
public class ContentDAO {
private String jdbcDriver;
private String jdbcURL;
private String jdbcUsername;
private String jdbcPassword;
public ContentDAO(String jdbcDriver, String jdbcURL, String jdbcUsername, String jdbcPassword) {
this.jdbcDriver = jdbcDriver;
this.jdbcURL = jdbcURL;
this.jdbcUsername = jdbcUsername;
this.jdbcPassword = jdbcPassword;
}
public boolean insertContent(Content content) throws SQLException, IOException {
String sql = "INSERT INTO content (text) VALUES (?)";
Connection connection = JDBC.connect(jdbcDriver, jdbcURL, jdbcUsername, jdbcPassword);
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, content.getText());
boolean row = (statement.executeUpdate()) > 0;
statement.close();
JDBC.closeConnection();
return row;
}
public Content getContentById(int id) throws SQLException, IOException {
Content content = null;
String sql = "SELECT * FROM content WHERE id = ?";
Connection connection = JDBC.connect(jdbcDriver, jdbcURL, jdbcUsername, jdbcPassword);
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String text = resultSet.getString("text");
content = new Content(id, text);
}
resultSet.close();
statement.close();
return content;
}
public boolean updateContent(Content content) throws SQLException, IOException {
String sql = "UPDATE content SET text = ? WHERE id = ?";
Connection connection = JDBC.connect(jdbcDriver, jdbcURL, jdbcUsername, jdbcPassword);
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, content.getText());
statement.setInt(2, content.getId());
boolean count = statement.executeUpdate() > 0;
statement.close();
JDBC.closeConnection();
return count;
}
public Content getLastContent() throws SQLException, IOException {
String sql = "SELECT * FROM content ORDER BY id DESC LIMIT 1;";
Connection connection = JDBC.connect(jdbcDriver, jdbcURL, jdbcUsername, jdbcPassword);
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
Content content = null;
if (resultSet.next()) {
int id = Integer.valueOf(resultSet.getString("id"));
String text = resultSet.getString("text");
content = new Content(id, text);
}
resultSet.close();
statement.close();
statement.close();
JDBC.closeConnection();
return content;
}
}
|
Shell
|
UTF-8
| 149
| 2.78125
| 3
|
[] |
no_license
|
#!/bin/sh
# Toggle lemonbar
BAR_PID=$(pidof lemonbar)
if [ $BAR_PID ]; then
kill -9 $BAR_PID
herbstclient pad 0 0
else
$HOME/bin/bar &
fi
|
Java
|
UTF-8
| 2,559
| 2.046875
| 2
|
[] |
no_license
|
package site.imcoder.blog.controller.view.old;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import site.imcoder.blog.common.Utils;
import site.imcoder.blog.common.id.IdUtil;
import site.imcoder.blog.controller.BaseController;
import site.imcoder.blog.service.message.IRequest;
import site.imcoder.blog.setting.Config;
import site.imcoder.blog.setting.ConfigConstants;
import javax.servlet.http.HttpServletRequest;
/**
* description: 站点控制器
*
* @author dengchao
* @date 2016-9-1
*/
@Controller
@RequestMapping("/site")
public class OldSiteController extends BaseController {
@RequestMapping()
public ModelAndView defaultHandle(HttpServletRequest request) {
String path = Utils.getRequestPath(request);
ModelAndView mv = new ModelAndView();
if (path.matches("^/[^/]*/?$") && !"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
buildRedirectView(mv, "/about", Config.getInt(ConfigConstants.SITE_OLD_PAGE_REDIRECT_CODE));
} else {
mv.setViewName(PAGE_NOT_FOUND_ERROR);
}
return mv;
}
/**
* 查询公告列表
*/
@RequestMapping(value = "notices")
public ModelAndView listNotices(IRequest iRequest) {
return getModelAndView("/notices" + appendQueryString(iRequest.getQueryString()));
}
// 公告页
@RequestMapping(value = "notice")
public ModelAndView notice(@RequestParam(defaultValue = "0") int id, IRequest iRequest) {
String notice_id = IdUtil.convertToShortPrimaryKey(IdUtil.convertOldPrimaryKeyToNew(id));
return getModelAndView("/notice/" + notice_id + appendQueryString(iRequest.getQueryString().replaceFirst("(^|&)id=\\d+", "")));
}
// 关于页
@RequestMapping(value = "about")
public ModelAndView about(IRequest iRequest) {
return getModelAndView("/about" + appendQueryString(iRequest.getQueryString()));
}
// 帮助页
@RequestMapping(value = "help")
public ModelAndView help(String module) {
if (Utils.isEmpty(module)) {
return getModelAndView("/help");
} else {
return getModelAndView("/help/" + Utils.encodeURL(module));
}
}
private ModelAndView getModelAndView(String page) {
return buildRedirectView(page, Config.getInt(ConfigConstants.SITE_OLD_PAGE_REDIRECT_CODE));
}
}
|
C++
|
UTF-8
| 220
| 2.703125
| 3
|
[] |
no_license
|
#include <iostream>
#include "EAN.h"
using namespace std;
int main()
{
EAN e("9780674062313");
cout << e.isValid() << endl << endl << endl;
cout << e.convertISBNToEAN("ISBN 0-13-222220-5") << endl;
}
|
Python
|
UTF-8
| 632
| 3.703125
| 4
|
[] |
no_license
|
#The ran python file will recieve a random number called 'seed' based on the question seed.
#You should then set 'question' equal to the question you wish to ask and 'answer' equal to the question's answer.
import sys
import math
import random
random.seed(int(seed))
posAns = random.randint(0,255)
def BinaryConverter(num):
output = "";
for i in range(7, -1, -1):
print(i)
if pow(2, i) <= num:
num = num - math.pow(2, i)
output += "1"
else:
output += "0"
return output
question = "What is " + str(posAns) + " in binary?"
answer = BinaryConverter(posAns)
|
C#
|
UTF-8
| 659
| 2.71875
| 3
|
[] |
no_license
|
using FilmeOnline.Logica.Entidades;
using FilmeOnline.Logica.Utils;
namespace FilmeOnline.Logica.Repositorios
{
public abstract class Repositorio<T>
where T : Entidade
{
protected readonly UnitOfWork _unitOfWork;
protected Repositorio(UnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public T RecuperarPorId(long id)
{
return _unitOfWork.Get<T>(id);
}
public void Adicionar(T entity)
{
_unitOfWork.SaveOrUpdate(entity);
}
public void Commitar()
{
_unitOfWork.Commit();
}
}
}
|
PHP
|
UTF-8
| 5,355
| 2.6875
| 3
|
[] |
no_license
|
<?php
/**
* @todo add support for Doctrine profiler
*/
abstract class ReportSqlQuery
{
/**
* @var Doctrine_Table
*/
protected $table;
/**
* @var string
*/
protected $tableName;
/**
* @var PDO
*/
protected $pdo;
/**
* @var PDOStatement
*/
protected $pdoStatement;
/**
* @var sfDoctrineConnectionProfiler
*/
protected $profiler;
/**
* @var array
*/
protected $params = array();
/**
* @var array string[]
*/
protected $selects = array();
/**
* @var array string[]
*/
protected $joins = array();
/**
* @var array string[]
*/
protected $wheres = array();
/**
* @var array groupBys[]
*/
protected $groupBys;
/**
* @var string
*/
protected $labelColumn;
/**
* @var string
*/
protected $groupByColumn;
/**
* @var string
*/
protected $groupByModel;
/**
* @var array
*/
protected $tableNames = array();
/**
* @param Doctrine_Table $table
* @param PDO $pdo
*/
public function __construct(Doctrine_Table $table, PDO $pdo = null)
{
$this->table = $table;
$this->tableName = $table->getTableName();
$this->pdo = $pdo ? $pdo : $this->table->getConnection()->getDbh();
}
/**
* @param array $filters
*/
public function addFilters(array $filters)
{
foreach ($filters as $key => $value) {
$this->applyFilter($key, $value);
}
}
/**
* @param string $column
* @param string $model
*/
public function setLabelColumn($column, $model = null)
{
$this->labelColumn = $this->sanitize($column);
$tableName = $model
? $this->getTableName($model)
: $this->table->getTableName();
$this->selects[] = "$tableName.$this->labelColumn";
}
/**
* @param string $column
* @param string $model
*/
public function setGroupBy($column, $model = null)
{
$this->groupByColumn = $this->sanitize($column);
if ($model) {
$this->groupByModel = $this->sanitize($model);
$foreignTable = $this->getTableName($model);
}
$this->selects[] = $this->groupByColumn;
}
/**
* @param string $string
* @return string
*/
protected function sanitize($string)
{
if (preg_match('/[^A-Za-z0-9_]/', $string)) {
throw new RuntimeException("Unsafe characters in string '$string'");
}
return $string;
}
/**
* @param string $key
* @param string $value
*/
protected function applyFilter($key, $value)
{
$key = $this->sanitize($key);
switch ($key) {
case 'timestamp':
foreach ($value as $subkey => $subvalue) {
$this->applyFilter($subkey, $subvalue);
}
break;
case 'from':
$this->params[":$key"] = $value;
$this->wheres[] = "SUBSTR(timestamp, 1, 7) >= :$key";
break;
case 'to':
$this->params[":$key"] = $value;
$this->wheres[] = "SUBSTR(timestamp, 1, 7) <= :$key";
break;
default:
$this->wheres[] = "$key = :$key";
$this->params[":$key"] = $value;
break;
}
}
protected function addSelectsAndJoinsForGroupBy()
{
if ($this->groupByModel) {
$foreignTableName = $this->getTableName($this->groupByModel);
$this->joins[] = "$foreignTableName ON "
. "$this->tableName.$this->groupByColumn = $foreignTableName.id";
}
}
/**
* @param string $model
* @return string
*/
protected function getTableName($model)
{
return isset($this->tableNames[$model])
? $this->tableNames[$model]
: Doctrine_Core::getTable($model)->getTableName();
}
/**
* Set table names manually for dependency injection
*
* @param array $names
*/
public function setTableNames(array $names)
{
foreach ($names as $model => $name) {
if (!is_string($name)) {
throw new InvalidArgumentException('Table names must be strings');
}
$this->tableNames[$model] = $name;
}
}
protected function setSfDatabase(sfDoctrineDatabase $database)
{
$this->profiler = $database->getProfiler();
}
/**
* @return string
*/
protected function getSql()
{
$this->addDefaultSelectsAndJoins();
$this->addSelectsAndJoinsForGroupBy();
$this->selects = array_unique($this->selects);
$this->joins = array_unique($this->joins);
$this->wheres = array_unique($this->wheres);
$sql = 'SELECT '
. implode(', ', $this->selects) . ' '
. "FROM $this->tableName "
;
if ($this->joins) {
$sql .= 'JOIN ' . implode(' JOIN ', $this->joins) . ' ';
}
if ($this->wheres) {
$sql .= 'WHERE ' . implode(' AND ', $this->wheres) . ' ';
}
if ($this->groupBys) {
$sql .= 'GROUP BY ' . implode(', ', $this->groupBys) . ' ';
}
return $sql;
}
protected function execute()
{
if ($this->pdoStatement) {
throw new RuntimeException('Already executed');
}
$this->pdoStatement = $this->pdo->prepare($this->getSql());
$this->pdoStatement->execute($this->params);
}
/**
* @return array
*/
protected function fetchRow()
{
if (!$this->pdoStatement) {
throw new RuntimeException('Not yet executed');
}
return $this->pdoStatement->fetch(PDO::FETCH_ASSOC);
}
abstract protected function addDefaultSelectsAndJoins();
}
|
C#
|
UTF-8
| 2,430
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
using NJsonSchema;
using NJsonSchema.CodeGeneration.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JsonSchemaCodegen
{
internal static class CodeGenerator
{
public static void GenerateJsonSchema(List<string> filePaths, string outputPath, string nmespace, bool overwriteRootObjectName)
{
if (!Directory.Exists(outputPath))
{
Console.WriteLine($"Creating output directory: {outputPath}");
Directory.CreateDirectory(outputPath);
}
filePaths.ForEach(path =>
{
Console.WriteLine($"Generating c# classes from path: ${path}");
try
{
var task = JsonSchema4.FromFileAsync(path);
task.Wait();
var fileName = Path.GetFileNameWithoutExtension(path);
var schema = task.Result;
var settings =
new CSharpGeneratorSettings
{
GenerateDataAnnotations = false,
ClassStyle = CSharpClassStyle.Poco,
Namespace = nmespace
};
var generator = new CSharpGenerator(schema, settings);
var file = generator.GenerateFile();
if (overwriteRootObjectName)
{
file = file.Replace("public partial class Json ", $"public partial class {fileName}");
file = file.Replace("public static Json FromJson(string data)", $"public static {fileName} FromJson(string data)");
file = file.Replace("return Newtonsoft.Json.JsonConvert.DeserializeObject<Json>(data);",
$"return Newtonsoft.Json.JsonConvert.DeserializeObject<{fileName}>(data);");
}
var outputFilePath = Path.Combine(outputPath, $"{fileName}.cs");
File.WriteAllText(outputFilePath, file);
}
catch (Exception e)
{
Console.WriteLine($"There were some error when parsing file from path: ${path}");
Console.WriteLine(e.StackTrace);
}
});
}
}
}
|
Python
|
UTF-8
| 152
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
k = int(input())
count1 = 0
count2 = 0
for i in range(k):
if i % 2 != 0:
count1 += 1
else:
count2 += 1
print(count1 * count2)
|
Python
|
UTF-8
| 24,429
| 2.53125
| 3
|
[
"CC0-1.0"
] |
permissive
|
#!/usr/bin/env python3 -u
'''
Author: Yotam Gingold <yotam@yotamgingold.com>
Home: https://github.com/yig/mturk.py
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
'''
import boto3
from datetime import datetime
import xml.dom.minidom
## From: https://stackoverflow.com/questions/54198700/how-to-delete-still-available-hits-using-boto3-client
def expire_hit( mturk, HITId ):
mturk.update_expiration_for_hit(
HITId = HITId,
ExpireAt = datetime(2015, 1, 1)
)
## From: https://stackoverflow.com/questions/46692234/how-to-submit-mechanical-turk-externalquestions-with-boto3/56903989#56903989
class ExternalQuestion:
"""
An object for constructing an External Question.
"""
schema_url = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd"
template = '<ExternalQuestion xmlns="%(schema_url)s"><ExternalURL>%%(external_url)s</ExternalURL><FrameHeight>%%(frame_height)s</FrameHeight></ExternalQuestion>' % vars()
def __init__(self, external_url, frame_height):
self.external_url = external_url
self.frame_height = frame_height
def get_as_params(self, label='ExternalQuestion'):
return {label: self.get_as_xml()}
def get_as_xml(self):
return self.template % vars(self)
def create_mturk( sandbox = True ):
## From: https://stackoverflow.com/questions/43013914/how-to-connect-to-mturk-sandbox-with-boto3
endpoint_url = ( 'https://mturk-requester-sandbox.us-east-1.amazonaws.com' if sandbox else 'https://mturk-requester.us-east-1.amazonaws.com' )
print('[MTurkConnection( %s )]' % (endpoint_url,))
## Set the credentials with a config file in "~/.aws/credentials":
'''
[Credentials]
aws_access_key_id = <your access key>
aws_secret_access_key = <your secret key>
'''
## or with environment variables.
## https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration
mturk = boto3.client(
'mturk',
#aws_access_key_id = '...',
#aws_secret_access_key = '...',
endpoint_url = endpoint_url,
## This shouldn't be necessary, because we specify a full endpoint_url, but it is.
region_name = 'us-east-1'
)
## With debug set to 2, all requests are printed to stdout.
## I can examine it by copying and pasting it into a python
## console and calling urllib.unquote() on it.
# debug = 1
## UPDATE: boto3 doesn't use a debug parameter when opening the connection.
## From: https://stackoverflow.com/questions/29929540/how-to-view-boto3-https-request-string
boto3.set_stream_logger( name = 'botocore' )
import logging
logging.getLogger('botocore').setLevel( logging.INFO )
return mturk
def total_payment_from_worker_payment( amount, max_assignments ):
'''
Given a floating-point amount to pay a worker for completing a HIT in US dollars,
returns the total amount that will be deducted from the Amazon account
once Amazon's overhead is taken as well.
'''
## The formula for Amazon's overhead is 10% or .005 per HIT, whichever is larger:
return amount + max( .01, .2*amount if max_assignments < 10 else .4*amount )
def create_HITs_for_external_URLs( mturk, URLs, **kwargs ):
'''
Given 'mturk', an object returned from create_mturk(),
a sequence of URL strings 'URLs',
a keyword argument 'frame_height' specifying the height of the frame
in which the URL will be displayed to workers,
a dollar amount 'Reward' (minimum ".01") to pay workers,
and the various other keyword arguments to
boto3.client('mturk').create_hit(),
creates one HIT per URL and returns the resulting HIT objects
(which have a .HITId field).
NOTE: The keyword argument 'RequesterAnnotation', if present will be used
for every HIT.
If the keyword argument 'RequesterAnnotations' is present instead,
it must be a sequence the same length as 'URLs', and the
corresponding element in 'RequesterAnnotations' will be used as the
annotation for each URL in 'URLs'.
Neither, one, or the other or 'RequesterAnnotation' and 'RequesterAnnotations'
may be present, but not both.
'''
kwargs = dict( kwargs )
frame_height = kwargs['frame_height']
del kwargs['frame_height']
## 'annotation' and 'annotations' cannot both be in kwargs.
assert not ( 'RequesterAnnotation' in kwargs and 'RequesterAnnotations' in kwargs )
if 'RequesterAnnotation' in kwargs:
RequesterAnnotations = [ kwargs['RequesterAnnotation'] ] * len( URLs )
del kwargs['RequesterAnnotation']
elif 'RequesterAnnotations' in kwargs:
RequesterAnnotations = kwargs['RequesterAnnotations']
del kwargs['RequesterAnnotations']
else:
RequesterAnnotations = [ '' ] * len( URLs )
if len( URLs ) == 0:
print('create_HITs_for_external_URLs() called with zero URLs')
return []
if not have_enough_balance_for_N_assignments_at_P_dollars_amount( mturk, len( URLs ) * kwargs['MaxAssignments'], kwargs['Reward'] ):
raise RuntimeError('Not enough balance!')
HITs = []
assert len( URLs ) == len( RequesterAnnotations )
for URL, RequesterAnnotation in zip( URLs, RequesterAnnotations ):
Question = ExternalQuestion( URL, frame_height ).get_as_xml()
create_hit_result = mturk.create_hit(
Question = Question,
## The default for create_hit() is Minimal;
## also add 'HITDetail' for CreationTime,
## 'HITQuestion' for ExternalURL and FrameHeight,
## and 'HITAssignmentSummary' for NumberofAssignmentsPending,
## NumberofAssignmentsAvailable, or NumberofAssignmentsCompleted.
# response_groups = ( 'Minimal', 'HITDetail', 'HITQuestion', 'HITAssignmentSummary' ),
## The default is Minimal; also get HITDetail for CreationTime.
# response_groups = ( 'Minimal', 'HITDetail' ),
RequesterAnnotation = RequesterAnnotation,
**kwargs
)
hit = create_hit_result['HIT']
HITs.append( hit )
print('[create_hit( %s, $%s ): %s]' % ( URL, kwargs['Reward'], hit['HITId'] ))
return HITs
def create_HIT_for_external_URL( mturk, URL, **kwargs ):
'''
Given 'mturk', an object returned from create_mturk(),
a URL strings 'URL',
a keyword argument 'frame_height' specifying the height of the frame
in which the URL will be displayed to workers,
a dollar amount 'amount' (minimum .01) to pay workers,
and the various other keyword arguments to
boto3.mturk.connection.MTurkConnection.create_hit(),
creates one HIT per URL and returns the resulting HIT objects
(which have a .HITId field).
'''
frame_height = kwargs['frame_height']
del kwargs['frame_height']
if not have_enough_balance_for_N_assignments_at_P_dollars_amount( mturk, kwargs['MaxAssignments'], kwargs['Reward'] ):
raise RuntimeError('Not enough balance!')
Question = ExternalQuestion( URL, frame_height ).get_as_xml()
create_hit_result = mturk.create_hit(
Question = Question,
# response_groups = ( 'Minimal', 'HITDetail' ), ## The default is Minimal; also get HITDetail for CreationTime.
**kwargs
)
HIT = create_hit_result['HIT']
print('[create_hit( %s, $%s ): %s]' % ( URL, kwargs['Reward'], hit['HITId'] ))
return HIT
def have_enough_balance_for_N_assignments_at_P_dollars_amount( mturk, N, P ):
P = float(P)
return float(mturk.get_account_balance()['AvailableBalance']) >= total_payment_from_worker_payment( P, N )
def get_assignments_for_HITId( mturk, HITId, max_assignments ):
assignments = mturk.list_assignments_for_hit( HITId = HITId, MaxResults = max_assignments, AssignmentStatuses = [ 'Submitted', 'Approved', 'Rejected' ] )
assert assignments['NumResults'] == max_assignments
## Make sure that NumResults and TotalNumResults agree; if they don't,
## we need to properly handle the 'page_number', and we're not right now.
## assignments.NumResults and assignments.TotalNumResults are given as strings.
assert int( assignments['NumResults'] ) == len( assignments['Assignments'] )
print('[get_assignments_for_HITId( %s, %s ): %d assignments]' % ( HITId, max_assignments, len( assignments['Assignments'] ) ))
return assignments['Assignments']
def get_all_assignments_for_HITId( mturk, HITId ):
'''
Returns all Assignment objects for the given HITId.
tested
'''
## NOTE: This routine has been tested for N equal to 1, 10, and 100
## for a HITId that had 10 assignments.
N = 100
NextToken = None
results = []
while True:
kwargs = dict( HITId = HITId, MaxResults = N, NextToken = NextToken )
if NextToken is None: del kwargs['NextToken']
assignments = mturk.list_assignments_for_hit( **kwargs )
results.extend( assignments['Assignments'] )
## Make sure that NumResults and TotalNumResults agree; if they don't,
## we need to properly handle the 'page_number', and we're not right now.
## assignments.NumResults and assignments.TotalNumResults are given as strings.
assert int( assignments['NumResults'] ) == len( assignments['Assignments'] )
#assert int( assignments.NumResults ) == int( assignments.TotalNumResults )
if len( assignments['Assignments'] ) == 0: break
NextToken = assignments['NextToken']
print('[get_all_assignments_for_HITId( %s ): %d assignments]' % ( HITId, len( results ) ))
return results
def remove_HITId( mturk, HITId ):
'''
Removes the given HITId, approving any pending reviewable assignments.
'''
HITobj = mturk.get_hit( HITId = HITId )['HIT']
print('Removing HITId %s with current status %s' % ( HITId, HITobj['HITStatus'] ))
if HITobj['HITStatus'] == 'Disposed':
return
elif HITobj['HITStatus'] == 'Reviewable':
assignments = get_all_assignments_for_HITId( mturk, HITId )
print('Approving reviewable assignments...')
num_approved = 0
for assignment in assignments:
if assignment.AssignmentStatus == 'Submitted':
mturk.approve_assignment( AssignmentId = assignment.AssignmentId )
num_approved += 1
print('Approved', num_approved, 'assignments.' if num_approved != 1 else 'assignment.')
mturk.delete_hit( HITId = HITId )
else:
## UPDATE: There is no more disable_hit()
# mturk.disable_hit( HITId )
expire_hit( mturk, HITId )
def HITIds2HITs( mturk, HITIds ):
'''
Given a sequence of HITIds, return corresponding
boto3.mturk.connection.HIT objects.
'''
HITs = []
for HITId in HITIds:
get_hit_result = mturk.get_hit(
HITId = HITId
## The default for get_hit() is HITDetail, HITQuestion and Minimal;
## also add HITAssignmentSummary for NumberofAssignmentsPending,
## NumberofAssignmentsAvailable, or NumberofAssignmentsCompleted.
# response_groups = ( 'Minimal', 'HITDetail', 'HITQuestion', 'HITAssignmentSummary' ),
)
hit = get_hit_result['HIT']
# assert get_hit_result.status
HITs.append( hit )
return HITs
def HITIds2CSV( mturk, HITIds ):
return HITs2CSV( HITIds2HITs( mturk, HITIds ) )
def HITs2CSV( HITs ):
'''
Given a sequence of boto3.mturk.connection.HIT objects, as returned by
boto3.mturk.connection.MTurkConnection.create_hit() or
boto3.mturk.connection.MTurkConnection.get_hit(),
returns a string of CSV data representing the assignments.
NOTE: In order to get the CreationTime field,
it is necessary to have passed 'HITDetail'
as an element of 'response_groups':
response_groups = ( 'Minimal', 'HITDetail' )
to create_hit() or get_hit().
NOTE: In order to get the NumberofAssignmentsPending,
NumberofAssignmentsAvailable, or NumberofAssignmentsCompleted
fields, it is necessary to have passed 'HITAssignmentSummary'
as an element of 'response_groups':
response_groups = ( 'Minimal', 'HITDetail', 'HITAssignmentSummary' )
to create_hit() or get_hit().
NOTE: In order to get the ExternalURL and FrameHeight fields,
it is necessary to have passed 'HITQuestion'
as an element of 'response_groups':
response_groups = ( 'Minimal', 'HITDetail', 'HITQuestion', 'HITAssignmentSummary' )
to create_hit() or get_hit().
'''
import sys, csv, io
## Column names:
primary_fields = [ 'HITId', 'HITTypeId', 'CreationTime', 'Title', 'Description', 'Keywords', 'HITStatus', 'Reward', 'LifetimeInSeconds', 'AssignmentDurationInSeconds', 'MaxAssignments', 'AutoApprovalDelayInSeconds', 'ExternalURL', 'FrameHeight', 'RequesterAnnotation', 'NumberOfSimilarHITs', 'HITReviewStatus', 'NumberofAssignmentsPending', 'NumberofAssignmentsAvailable', 'NumberofAssignmentsCompleted' ]
## A sequence of dictionaries mapping field names to values.
rows = []
for hit in HITs:
row = {}
for field in primary_fields:
## There are a few special cases:
if field == 'ExternalURL':
if 'Question' in hit:
'''
d = xml.dom.minidom.parseString( hit.Question )
ExternalURL = d.getElementsByTagName( 'ExternalURL' )[0].firstChild.data
row[ field ] = ExternalURL
'''
row[ field ] = xml.dom.minidom.parseString( hit['Question'] ).getElementsByTagName( 'ExternalURL' )[0].firstChild.data
elif field == 'FrameHeight':
if 'Question' in hit:
'''
d = xml.dom.minidom.parseString( hit.Question )
FrameHeight = d.getElementsByTagName( 'FrameHeight' )[0].firstChild.data
row[ field ] = FrameHeight
'''
row[ field ] = xml.dom.minidom.parseString( hit['Question'] ).getElementsByTagName( 'FrameHeight' )[0].firstChild.data
## The general case:
elif field in hit:
row[ field ] = hit[ field ]
rows.append( row )
out = io.StringIO()
dw = csv.DictWriter( out, primary_fields, lineterminator = '\n' )
dw.writeheader()
dw.writerows( rows )
return out.getvalue()
def assignments2CSV( assignments ):
'''
Given a sequence of boto3.mturk.connection.Assignment objects as returned by
boto3.mturk.connection.MTurkConnection.get_assignments(),
returns a string of CSV data representing the assignments.
'''
import sys, csv, io, json
## Column names:
primary_fields = [ 'HITId', 'AssignmentId', 'WorkerId', 'AssignmentStatus', 'AutoApprovalTime', 'AcceptTime', 'SubmitTime', 'ApprovalTime', 'RejectionTime', 'Deadline', 'RequesterFeedback' ]
qid_fields = set()
## A sequence of dictionaries mapping field names to values.
rows = []
for a in assignments:
row = {}
for field in primary_fields:
if field in a:
row[ field ] = a[field]
### Now, question ids.
## My older forked boto:
#answers = [ ( answer.QuestionIdentifier, answer.FreeText ) for answer in a.answers ]
## My current forked boto:
# answers = [ ( answer.qid, answer.fields ) for answer in a.answers[0] ]
## UPDATE: boto3 doesn't parse this for us.
answersdom = xml.dom.minidom.parseString( a['Answer'] )
# def getData( node ): return node.data if node.nodeType == node.TEXT_NODE else node.firstChild.data
## ET.fromstring(answersdom.getElementsByTagName( 'Answer' )[0].toxml()))[0].text
answers = [ ( a.childNodes[0].firstChild.data, a.childNodes[1].firstChild.data ) for a in answersdom.getElementsByTagName( 'Answer' ) ]
for qid, fields in answers:
qid_fields.add( qid )
assert qid not in row
row[ qid ] = json.dumps( fields )
rows.append( row )
## Combine the primary column names with the question ids:
qid_fields = list( qid_fields )
qid_fields.sort()
all_fields = primary_fields + qid_fields
out = io.StringIO()
dw = csv.DictWriter( out, all_fields, lineterminator = '\n' )
dw.writeheader()
dw.writerows( rows )
return out.getvalue()
def upload_filepaths_to_server(
filepaths, remote_host = None, remote_dir = None
):
'''
Given an iterable collection of distinct file paths 'filepaths' and
a remote host 'remote_host' and remote directory 'remote_dir'
in which to store the files on the server,
uploads the files intelligently (doesn't re-upload if the
identical file is already on the 'remote_host' at 'remote_dir').
'''
import os, subprocess
filepaths = list( set( filepaths ) )
if len( filepaths ) == 0:
print('upload_filepaths_to_server() called with zero filepaths.')
return
## A filepath shouldn't appear twice in the input list.
assert len( set( filepaths ) ) == len( filepaths )
## All paths in 'filepaths' should be to files.
assert all([ os.path.isfile( filepath ) for filepath in filepaths ])
assert remote_host is not None
assert remote_dir is not None
assert str( remote_host ) == remote_host
assert str( remote_dir ) == remote_dir
## Create 'remote_dir' if it doesn't exist.
## UPDATE: Calling this often can introduce unnecessary pauses,
## because chances are the directory exists.
print('[ssh "%s" mkdir -p "%s"]' % ( remote_host, remote_dir ))
err = subprocess.Popen( [ 'ssh', remote_host, 'mkdir', '-p', remote_dir ] ).wait()
assert 0 == err
## Upload all the files together in the foreground.
## NOTE: I think the trailing "/" will cause scp
## to abort with an error code if "remote_dir" is not a directory.
#print '[scp "%s" "%s"]' % ( filepaths, remote_host + ':' + remote_dir + '/' )
#err = os.spawnvp( os.P_WAIT, 'scp', [ 'scp' ] + filepaths + [ remote_host + ':' + remote_dir + '/' ] )
## UPDATE: Better yet, use rsync.
print('[rsync "%s" "%s"]' % ( filepaths, remote_host + ':' + remote_dir + '/' ))
err = os.spawnvp( os.P_WAIT, 'rsync', [ 'rsync', '--progress' ] + filepaths + [ remote_host + ':' + remote_dir + '/' ] )
assert 0 == err
def main():
import sys, json
def usage():
print('Usage:', sys.argv[0], '[really] submit path/to/job.json', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] info HITId', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] retrieve HITId', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] approve AssignmentId [feedback]', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] reject AssignmentId [feedback]', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] bonus WorkerId AssignmentId dollars feedback', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] extend HITId number-of-additional-assignments', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] expire HITId', file=sys.stderr)
print('Usage:', sys.argv[0], '[really] remove HITId', file=sys.stderr)
## TODO:
#print >> sys.stderr, 'Usage:', sys.argv[0], 'extend HITId additional_assignments ?additional_time?'
print('Example:', sys.argv[0], 'submit debug.json', file=sys.stderr)
print('Example "debug.json":', file=sys.stderr)
print('''{
"create_hit_kwargs": {
"title": "Nothing",
"description": "Testing parameters in and out of sandbox.",
"keywords": [ "debug, debugging" ],
"frame_height": 900,
"amount": 0.1,
"max_assignments": 10,
"qualifications": [
[ "PercentAssignmentsApprovedRequirement", "GreaterThan", "95" ],
[ "NumberHitsApprovedRequirement", "GreaterThan", "100" ],
[ "LocaleRequirement", "EqualTo", "US" ]
],
"duration": 360,
"lifetime": 604800,
"approval_delay": 0
},
"URLs": [ "http://example.com/page.html" ]
}''', file=sys.stderr)
print('Note: Commands run in the sandbox unless "really" is present.', file=sys.stderr)
print('Note: The "qualifications" field is optional. The default is to have no qualifications. Any qualification type supported by boto3 is allowed.', file=sys.stderr)
sys.exit(-1)
def submit( argv ):
if len( argv ) != 1: usage()
params_path = argv[0]
params = json.load( open( params_path ) )
create_hit_kwargs = params['create_hit_kwargs']
del params['create_hit_kwargs']
URLs = params['URLs']
del params['URLs']
if len( params ) > 0: usage()
create_HITs_for_external_URLs( mturk, URLs, **create_hit_kwargs )
def info( argv ):
if len( argv ) != 1: usage()
HITId = argv[0]
print(HITIds2CSV( mturk, [ HITId ] ), end=' ')
def retrieve( argv ):
if len( argv ) != 1: usage()
HITId = argv[0]
assignments = get_all_assignments_for_HITId( mturk, HITId )
print(assignments2CSV( assignments ), end=' ')
def expire( argv ):
if len( argv ) != 1: usage()
HITId = argv[0]
expire_hit( mturk, HITId )
def remove( argv ):
if len( argv ) != 1: usage()
HITId = argv[0]
remove_HITId( mturk, HITId )
def approve( argv ):
if len( argv ) not in (1,2): usage()
AssignmentId = argv.pop(0)
feedback = None if len( argv ) == 0 else argv[0]
mturk.approve_assignment( AssignmentId = AssignmentId, RequesterFeedback = feedback )
def reject( argv ):
if len( argv ) not in (1,2): usage()
AssignmentId = argv.pop(0)
feedback = None if len( argv ) == 0 else argv[0]
mturk.reject_assignment( AssignmentId = AssignmentId, RequesterFeedback = feedback )
def extend( argv ):
if len( argv ) != 2: usage()
HITId, number_of_additional_assignments = argv
try:
number_of_additional_assignments = int( number_of_additional_assignments )
except ValueError: usage()
if number_of_additional_assignments < 0: usage()
print('[extend_hit( %s, %d additional assignments )]' % ( HITId, number_of_additional_assignments ))
mturk.create_additional_assignments_for_hit( HITId = HITId, NumberOfAdditionalAssignments = number_of_additional_assignments )
def bonus( argv ):
if len( argv ) != 4: usage()
WorkerId, AssignmentId, BonusAmount, Reason = argv
mturk.send_bonus( WorkerId = WorkerId, AssignmentId = AssignmentId, BonusAmount = BonusAmount, Reason = Reason )
def debug( argv ):
print('sandbox:', sandbox)
argv = list( sys.argv )
del argv[0]
if len( argv ) == 0: usage()
sandbox = True
if 'really' == argv[0]:
sandbox = False
del argv[0]
mturk = create_mturk( sandbox = sandbox )
if len( argv ) == 0: usage()
commands = [ submit, info, retrieve, approve, reject, bonus, extend, expire, remove, debug ]
name2func = dict([ ( f.__name__, f ) for f in commands ])
try:
func = name2func[ argv[0] ]
except KeyError:
usage()
func( argv[1:] )
if __name__ == '__main__': main()
|
Go
|
UTF-8
| 784
| 2.640625
| 3
|
[] |
no_license
|
package main
import (
"flag"
"fmt"
"log"
"os"
"github.com/ostlerc/voter/election"
)
var (
o = flag.String("o", "dot", "graph output type. [json,dot]")
i = flag.String("i", "json", "graph input type. ["+election.CSVFlat(election.Parsers())+"]")
)
func main() {
flag.Parse()
election.Setup()
if *o != "dot" && *o != "json" {
log.Fatal("invalid type ", *o)
}
stat, err := os.Stdin.Stat()
if err != nil {
log.Fatal(err)
}
hasStdin := (stat.Mode() & os.ModeCharDevice) == 0
if !hasStdin {
log.Fatal("No stdin to read")
}
e := election.ParseFrom(*i, os.Stdin)
if e == nil {
log.Fatal("Incorrect input type '", *i, "'")
}
edges := e.Graph().Edges()
if *o == "dot" {
fmt.Println(edges.Dot())
} else if *o == "json" {
fmt.Println(edges.JSON())
}
}
|
Python
|
UTF-8
| 1,720
| 3.359375
| 3
|
[] |
no_license
|
# To run the program cd to the folder and the output of this program will be copied in the minisat solver.
def main():
alph = []
minisat = []
graph = []
alpha = 'a'
for i in range(0, 26):
alph.append(alpha)
alpha = chr(ord(alpha) + 1)
extra = [" ", "\n"]
name = input("Name of the file: ")
try:
file = open(name, 'r')
except FileNotFoundError:
print("Wrong file name please re-run the program")
exit(-1)
temp1 = file.readlines()
i = 0
num = 0
for x in temp1:
graph.append([])
for y in x:
if y not in extra:
graph[i].append(y)
num = num + 1
i = i + 1
minisat.append(['p', 'cnf', str(len(graph)*3), str((len(graph)*4) + (num*3))])
for i in range(len(graph)):
var = [(i*3)+1, (i*3)+2, (i*3)+3]
minisat.append([str(var[0]), str(var[1]), str(var[2]), '0'])
minisat.append([str(var[0]*-1), str(var[1]*-1), '0'])
minisat.append([str(var[0]*-1), str(var[2]*-1), '0'])
minisat.append([str(var[1]*-1), str(var[2]*-1), '0'])
for i in range(len(graph)):
for y in graph[i]:
y = alph.index(y)
var1 = [(i*3)+1, (i*3)+2, (i*3)+3]
var2 = [(y*3)+1, (y*3)+2, (y*3)+3]
minisat.append([str(var1[0] * -1), str(var2[0] * -1), '0'])
minisat.append([str(var1[1] * -1), str(var2[1] * -1), '0'])
minisat.append([str(var1[2] * -1), str(var2[2] * -1), '0'])
print("Output needed to be copied to Minisat Solver: \n")
for x in minisat:
for y in x:
print(y, end=" ")
print("")
if __name__ == '__main__':
main()
|
C++
|
UTF-8
| 901
| 2.6875
| 3
|
[] |
permissive
|
#include "GLFog.h"
#include "GL.h"
using namespace GLDraw;
GLFog::GLFog()
:type(None),start(0),end(1),density(1)
{
}
void GLFog::setCurrent()
{
glFogfv(GL_FOG_COLOR, color.rgba);
switch(type) {
case None:
glDisable(GL_FOG);
break;
case Linear:
glEnable(GL_FOG);
glFogi(GL_FOG_MODE, GL_LINEAR);
glFogf(GL_FOG_START, start);
glFogf(GL_FOG_END, end);
break;
case Exponential:
glEnable(GL_FOG);
glFogi(GL_FOG_MODE, GL_EXP);
glFogf(GL_FOG_DENSITY, density);
break;
case ExponentialSquared:
glEnable(GL_FOG);
glFogi(GL_FOG_MODE, GL_EXP2);
glFogf(GL_FOG_DENSITY, density);
break;
}
}
void GLFog::unsetCurrent()
{
glDisable(GL_FOG);
}
void GLFog::setLinear(Real s, Real e)
{
type=Linear;
start=s;
end=e;
}
void GLFog::setExponential(Real d)
{
type=Exponential;
density=d;
}
void GLFog::setExponentialSquared(Real d)
{
type=ExponentialSquared;
density=d;
}
|
C#
|
UTF-8
| 679
| 2.515625
| 3
|
[] |
no_license
|
namespace AAA.Utils.CloudProvider
{
/// <summary>
/// Contains all supported types of cloud providers.
/// </summary>
public enum CloudTypeEnum
{
/// <summary>
/// Dropbox cloud provider.
/// </summary>
Dropbox,
/// <summary>
/// Flickr cloud provider.
/// </summary>
Flickr,
/// <summary>
/// Google cloud provider.
/// </summary>
GoogleDrive,
/// <summary>
/// Microsoft cloud provider.
/// </summary>
OneDrive,
/// <summary>
/// Cloud provider is not specified.
/// </summary>
None
}
}
|
Markdown
|
UTF-8
| 23,377
| 3.109375
| 3
|
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
---
---
title: 况钟和周忱
---
一从《十五贯》说起
1956年浙江昆苏剧团上演了改编的昆曲《十五贯》之后,各地其他剧种也纷纷改编上演,况钟这个封建时代的好官,逐渐为成千上万的观众所熟识了。这戏中另一个好官周忱,是况钟的上司和同乡,也被赋予和况钟不同的性格,成为舞台上的人物。
《十五贯》成功地塑造了况钟这个历史人物,刻画了他的性格、思想感情。他通过具体分析,进行现场调查研究,得出正确结论,终于纠正了主观主义、官僚主义的错误判断,平反了冤狱,为人民办了好事。这个戏形象地突出了反对主观主义、反对官僚主义这个主题,是具有现实的教育意义的,是个好戏。
但是,《十五贯》这个故事,其实和况钟并不相干。
《十五贯》的故事出自《宋元话本》的《错斩崔宁》,大概是宋朝的故事。明朝末年,有人把这故事编在一部书里,题名为《十五贯戏言成巧祸》,清初的戏剧家朱素臣又把它改编为《十五贯传奇》。现在上演的本子,是根据朱素臣的本子改编的。从故事改编的发展来说,一次比一次好,迷信成分去掉了,复杂的头绪减少了,人物的形象更典型了,深刻了,也就更生动了;艺术感染力量更强烈了;教育主观主义、官僚主义者的效果也就更好了。
那么,问题就来了,《十五贯》既然是宋朝的故事,况钟却是明朝人,从宋末到明前期,相差有一百几十年,为什么戏剧家一定要把这故事算在况钟名下呢?
这是因为况钟的确是历史上的好官,也的确替当时负屈的老百姓申过冤,救活了不少人命,在当时人民中威信很高。其次,朱素臣是苏州人,对《十五贯》的故事和况钟这个人物的传说都比较熟悉。戏剧家为了集中地突出故事情节,集中地突出历史人物,把民间流传已久的《十五贯》故事,和当时民间极有威望的好官况钟结合起来,一方面符合人民对于清官好官的迫切要求,一方面也反映了一定时期的历史情况,是完全可以允许的艺术处理。
正因为如此,这故事不但得到广大人民的喜爱,连况钟的子孙也认为确有其事了。况钟九世孙况延秀编的《太守列传编年》上说:
折狱明断,民有奇冤,无不昭雪。有熊友兰、友惠兄弟冤狱,公为雪之,阖郡有包龙图之颂,为作传奇,以演其事。惜一切谳断,不能尽传于世。
二况青天
封建时代的官僚,被人民表扬为青天,是很不容易的事。
由于封建统治阶级一贯剥削、虐待人民,和人民对立,老百姓在平常时候,是怕官的。老百姓和官的关系是,一要完粮,二要当差,三呢,遭到冤枉要打官司。这三件事都使老百姓怕官,一有差错,就得挨板子、上夹板,受到种种非刑,关进班房,以至充军、杀头等,老百姓怎能不怕?
但是,一到了阶级矛盾十分尖锐,老百姓忍无可忍,团结起来暴动的时候,情况就完全改变了。人民自己已有了武装,也有了班房,那时候,老百姓就不再怕官了,害怕发抖的是官。以此,历史上每次农民起义,矛头总是首先针对着本地的官员,口号总有杀尽贪官污吏这一条。
由于封建统治阶级的统治基础是建立在对广大农民的剥削、掠夺上面的,封建官僚是为了地主阶级利益服务的;一切政治设施的最后目的,都是为了巩固和加强封建统治。这样,也就不难理解在封建官僚的压迫、奴役下,广大人民对于比较清明、宽大、廉洁政治的向往,对于能够采取一些措施,减轻人民负担,申雪人民冤枉的好官的拥护了。对于这样的好官,人民作了鉴定,叫作青天。
也正由于封建时代的青天极少,所以历史上屈指可数的几个青天,也就成为箭垛式的人物,许多人民理想中的好事都被堆砌到他们身上了。像宋朝的包拯,明朝的况钟和海瑞,都是著名的例子。
也还必须指出,尽管历史上出现了几个青天,是当时人民给的称号。但是,也绝不可以由此得出结论,以为青天就是站在人民立场的政治家。不是的,恰恰相反,他们都是为封建统治阶级利益服务的官僚,在这一点上,也和当时其他封建官僚一样,是和人民对立的。不过,由于他们的出身和其他关系,比较接近人民,了解人民的痛苦,比较正直,有远见,为了维持封建统治阶级的长远利益,缓和阶级矛盾,在不损害封建统治阶级的根本利益前提下,有意识地办了一些好事。这些好事是和封建统治阶级的长远利益一致的,也是和被压迫被剥削的广大人民当前利益一致的,对当时的生产发展,对历史的进展有好处的。因此,他们在当时被人民叫作青天,在历史上也就应该是被肯定的,值得纪念的,在某些方面,还是值得今天学习的人物。
况钟(1383—1442),江西靖安人。从1430年起任苏州知府,一直到1442年死在任上,连任苏州知府十三年。
苏州地方殷富,人口稠密,土地集中,人民贫困,阶级关系比较紧张。在况钟以前,做知府的不要说久任,连称职能够做满任期的也没有一个。况钟以后,也还出过几个好官,不过都比不上他这样有名,为人民所爱戴歌颂。
从唐宋以来,封建王朝任命官僚,主要是用科举出身的人,上过学,会写一定格式的诗、文,通过考试,成为叫作进士或者举人的知识分子。一般在衙门里办事的吏(科员),地位很低,只能一辈子做吏,是做不了官的。明朝初期,科举出身的人还不够多,官和吏的区别还不十分严格,以后就不同了。况钟的父亲是一家地主的养子。况钟从小也念过一点书,但没有考上学校。到成年以后,1406年被选作靖安县的礼曹(管礼仪、祭祀一类事务),一直做了九年的吏。他为人干练精明,通达事务,廉介无私,为县官所重视。也正因为他做了多年的吏,直接和人民打交道,不但了解民间痛苦,也深知吏的贪污害民行径,到后来做了官,便有办法来制裁这些恶吏了。
靖安知县和当朝的礼部尚书(管礼仪、祭祀、考试的部长)是好朋友,当况钟做满九年的吏,照例要到吏部(管任免、考核官员的部)去考绩的时候,靖安知县便写信给这个朋友,推荐况钟的才能。礼部尚书和况钟谈了话,也很器重,便特别向皇帝推荐。明成祖召见况钟,特任为礼部仪制司主事,以后升为郎中,一连做了十五年京官。
在这十五年中,况钟和当时许多有名的政治家来往,成为朋友,交换了对政治上的许多看法。其中主要的是江西同乡的京官。在封建时代,交通很不方便,官僚们对同乡是很看重的,来往较多,政治上也互相影响,这种关系称为乡谊,是一种封建关系。况钟的同乡中有许多是当权的大官,有声名的政治家,况钟深受他们的影响,在况钟以后的政治活动中,也得到他们的支持。
明成祖在打到南京,做了皇帝以后,任命七个官员替他管理机密事务,叫作“入阁”,后来叫作“拜相”。这七个人中有五个是江西人,其中泰和人杨士奇和况钟关系最深,南昌人胡俨、湖北石首人杨溥也是况钟的朋友。此外,江西吉水人周忱和况钟也很要好。
明成祖死后,三杨当国,三杨就是原来七人内阁中的三个,是杨士奇、杨溥和杨荣。这三人都是有能力的政治家,在他们当国时期,政治是比较清明的。
1430年,明封建王朝经过讨论,为了进一步加强统治,增加财政收入,认为全国有九个大府,人众事多,没有管好,其中特别是苏州府,交的税粮比任何一省都多,政治情况却十分不好,官吏奸贪,人民困苦,欠粮最多,百姓逃亡。要百官保举京官中有能力而又廉洁的外任做知府,来加强控制。礼部和吏部都推荐况钟,首相杨士奇也特荐况钟做苏州知府。为了加重况钟的权力,明宣宗还特别给以“敕书”(书面命令),许以便宜行事,并特许他可以直接向皇帝写报告,提建议。
我国在过去漫长时期是农业国,封建王朝的经济基础是农业。王朝的全部收入百分之九十以上出自农民交纳的粮食,服兵役和无偿劳役的也主要是农民。要是农民交不起粮或者少交粮了,农民大量逃亡外地,不当差役了,便会发生严重的政治危机,危害封建王朝的统治地位。
由于宋元以来的历史发展,东南地区的农业经济大大发展了,显出一片繁荣气象。况钟所处的十五世纪前期,正是明王朝的全盛时期。但是,这个地区的繁荣,这个时期的全盛都只是表面上的,内部却包含着严重的危机。
危机是农民负担过重。
就东南一带而说,农民负担之重居全国第一。这时全国的实物收入,夏税秋粮总数约三千万石,其中浙江一省占二百七十五万多石,约占全国收入十分之一弱。苏州一府七个县却占二百八十一万石,比浙江一省交的粮还多。松江府一百二十一万石,也很重。以苏州而论,垦田数只有九万六千五百零六顷,占全国垦田数百分之一点一,交纳税粮呢,却占全国税收的百分之九点五。
为什么江南地区的农民负担特别重呢?这是因为从南宋以来,由于这一带土地肥沃,经济发展,贵族、官僚用种种方法兼并土地,到了政治局面发生变化,旧的贵族、官僚被推翻了,他们所占有的土地就被没收为官田,经过多次变化,官田就越来越多,民田就越来越少了。到明太祖取得这带地方以后,又把原来的豪族地主的田地没收为官田,并且按私租收税,这样,这带地方的官田租税就特别重了。
民田的租税虽然也很重,但是农民向地主交租,多在本地,当天或者几天就可以来回,一改为官田,不但田租特别重,而且收的粮食要交官了,得由农民运送到指定的仓库交纳。在交通不便的情势下,陆运、水运,要用几个月以至更多时间,不但占用了大量劳动力,不能投入生产,而且交纳一石官粮,往往要用两三石以至四五石的运费,有时候遭风翻船了,或者被人抢劫,都得重新补交,所有这些巨大的运费和意外的赔垫,都要由农民负担,农民怎么负担得起?苏州农民因为官田特别多,负担就特别重。
苏州七个县完纳的二百八十一万石税粮中,民粮只有十五万石,官田田租最重的每亩要交三石粮。官粮中有一百零六万石要远运到山东临清交纳,有七十万石要运到南京交纳,运到临清的每一石要用运费四石,运到南京的也要六斗。这样残酷的剥削使人民无法负担,在况钟到苏州以前,四年的欠粮数就达到七百六十多万石。老百姓完不了粮是要挨板子,坐班房的,农民要活下去,就只好全家逃亡,流离外地了。
占全国税粮近十分之一的苏州,欠粮这样多,人口大量外流,是不能不严重地影响到封建王朝的统治基础的。首相杨士奇提出补救方案:蠲免欠粮,官田减租,清理冤狱,惩办贪官,安抚逃民,特派知府等六项措施。况钟就是在这样情况下,被特派到苏州执行这些措施的。
官田减租是得到明宣宗的同意,用诏书(皇帝的命令)下达全国的。但是,有人认为,减掉了租,就减少了王朝的收入,遭到封建统治阶级内部的反对,没有能够贯彻;蠲免欠粮,也同样行不通。隔了两年,还是没有解决。尽管明宣宗和杨士奇为了缓和阶级矛盾,巩固统治基础,下了极大决心要办,并且严厉申斥户部官员,不奉行减租免粮命令的就要办罪,还是办不了,办不好。
况钟在苏州坚决执行封建王朝的政策,在巡抚周忱的支持下,他多次提出官田减租和蠲免欠粮的具体办法,都被户部批驳不准。况钟并不妥协,坚持要办,一直到1432年3月,才得到批准,减去官田租七十二万一千六百多石,荒田租十五万石,官粮远运临清的减去六十万石,运到南京的改为驻军到苏州自运,连同其他各项。每年减省了苏州人民一百五十六万石的负担,假如连因此而省掉的运费、劳力计算,数目就更大了。这对苏州人民来说,确是一件了不起的大好事,对明王朝的统治来说,也确是起了巩固作用。而且,官田虽然减了一些租,因为不欠粮了,王朝的实际收入比前几年反而增加了。
由于官田田租减轻了,逃民回来后复业的就有三万六千六百多户。人民的生活虽然还是很苦,但是毕竟比过去稍微好了一些,生产情绪也提高了。他们欢欣鼓舞,感谢况钟的恩德,到处刻碑纪念这件好事。
况钟在人民中间的威信日益提高,主要的是他还办了以下这几件事:
第一是惩办贪吏。况钟是从吏出身的,精于吏事。在上任以后,却假装不懂公事,许多吏拿着案卷请批,况钟问他们该怎么办,都一一照批。吏们喜欢极了,以为这知府真好对付,以后的事好办了。况钟在经过充分的调查研究,弄清情况以后,过了一个多月,突然叫官员和吏们都来开会,当场宣读“敕书”,其中有“属员人等作奸害民,尔即提问解京”的话,就问这些吏,那一天你办了什么事,受了多少贿赂,对不对?一一问过,立时杀了六个。官员中有十二个不认真办事,疲沓庸懦的,都革了职。另外有几个贪赃枉法的,拿到京师法办。这一来,官吏们都害怕了,守法了,老百姓也少吃苦头了。人们叫他做青天。
苏州人民好容易有了一个青天,松了一口气。第二年,况钟的继母死了,按封建礼制辞官回家守孝。这一来,苏州的天又黑了,风气又变了,官们吏们又重新做坏事了,百姓又吃苦头了。他们想了又想,都是况钟不在的缘故,三万七千多人便联名请求况钟回来。隔了十个多月,况钟又被特派回到苏州,这一回用不着调查了,立刻把做坏事的官吏们都法办了,天又变好了,况钟更加得到人民的支持。
第二是清理冤狱。苏州有七个县,况钟每天问一个县的案,排好日程,周而复始,不到一年工夫,清理了一千五百多件案子,该办的办,该放的放,做得百姓不叫冤枉,豪强不敢为非,老百姓都叫他是包龙图再世。现在舞台上演唱的《十五贯》,虽然事实上和况钟无关,但确也反映了他在这一方面的工作作风,取得的成绩和威信,是符合历史实际的。
第三是抑制豪强。明朝制度,军民籍贯是分开的,军户绝了,要勾追原籍本家男丁补缺。封建王朝派的清军御史蛮横不讲道理,强迫平民充军,弄得老百姓无处诉冤,况钟据理力争,免掉一百六十个平民的军役,免掉一千四百多平民的世役,只是本身当军,不累及子孙。七县的圩田设有圩长圩老九千多人,大部分都是积年退役(在衙门做过事)的恶霸,这制度和这些人得到大官的支持,为非作恶,况钟不管上官的反对,也把它一起革除了。沿海沿江有些地方的军官,借名巡察河道,劫掠商船,为害商旅,况钟都一一拿办。
第四是为民兴利。苏州河道,淤塞成灾,况钟把它疏浚了,成为水利。人民因粮重贫困,向地主借高利贷,弄得卖儿卖女,况钟想法筹划了几十万石粮食,建立济农仓,每到农民耕作青黄不接的时候,便开仓借贷,每人二石,到秋收时如数偿还,遇有灾荒,也用这粮食赈济。又推广义役仓制度,用公共积累的粮食,供应上官采办物料的赔垫消费,免去中间地主们的剥削和贪污,从而减轻人民的负担。
况钟刚正廉洁,极重视细小事件,设想周密,不怕是小事,只要有利于百姓就做,对百姓有害的就加以改革。兴利除害,反对豪强,扶持良善,百姓敬他爱他,把他看作天神一样。第一次回家守孝,百姓想念他,作歌说:
况太守,民父母,众怀思,因去后,愿复来,养田叟。
又有歌说:
众人齐说使君贤,只剪轻蒲为作鞭,兵仗不烦森画戟,歌谣曾唱是青天。
三年任满,到京师朝见,百姓怕他升官,很担心,到回来复任,百姓又唱道:
太守朝京,我民不宁,太守归来,我民忻哉!
到九年任满,又照例到吏部候升,吏部已经委派了新的苏州知府了,苏州人民不答应,有一万八千多人联名保留况钟,结果,况钟虽然升了官,又回到苏州管知府的事。
况钟做了十三年知府,死的时候,老百姓伤心痛哭,连做生意的也罢市了。送丧的沿路沿江不绝。苏州和七个县都建立了祠堂,画像祭祀,有的人家甚至把他的画像供在家里。
生性俭朴,住的房子没有什么陈设,吃饭也只用一荤一素。做官多年,没有添置过田产,死后归葬,船上只有书籍和日用器物,苏州人民看了,十分感动。做官办事,不用秘书,一切报告文件都亲自动手,文字质直简劲,不作长篇大论,说清楚了就算。在请求官田减租的报告上,直率批评皇帝失信,毫不隐讳。
和巡抚周忱志同道合,他每次有事到南京,上岸时虽然天黑了,周忱也立刻接见,谈到深夜。况钟在苏州办的许多好事是和周忱的支持分不开的,周忱在巡抚任上办的许多好事,也有况钟的贡献在内。
三周忱
周忱(1381—1453)从1430年任江南巡抚,一直到1451年,前后共21年,是明朝任期最长的封疆大员,最会理财最能干的好官。
他是进士出身,在刑部(管司法、审判的部)做了二十多年的员外郎(官名,专员),不为人所知。直到大学士(宰相)杨荣推荐为江南巡抚、总督税粮,才出了名。
周忱不摆官僚架子,接近人民,倾听群众意见,心思周密,精打细算,会出主意,极会办事,人民很喜欢他。
江南其他各府县,也和苏州一样,欠了很多税粮。周忱首先找老年农民研究,问是什么缘故。农民们说,交粮食照规矩得加“耗”(附加税),因为仓库存的粮食日子久了分量就减少了,加上麻雀老鼠都要吃粮食,这样,就会有耗损。官府把预计必有的耗损分量在完粮时附加交纳,叫作“耗”。但是,地主们都不肯交纳,光勒掯农民负担全部耗损,农民交纳不起,只好逃亡,税粮越欠越多了。
周忱弄清原因,就创立平米法,把完粮附加的耗米,合理安排,不管是地主是农民,都一律负担,又进一步由工部(管工程的部)制定铁斛,地方准式制造,凡是收放粮食都用同一的标准量器,革除了过去大斗进小斗出的弊病。农民交粮,一向由粮长(地主)经手存放运输,制度紊乱,粮长巧立名目,从中取利,农民负担便越发重了。周忱经过细心研究,制定一套办法,大大减少了粮长做坏事的机会,也减少了耗损。又精打细算,改进了粮食由水路运到北京的办法,节省了人力和粮食。把这些节约的粮食和多出的附加耗米单独设仓贮存,叫作余米,逐年积累,作为机动用费。又和况钟举办了济农仓,减免了苏州和其他各府的官田租粮。经过亲自考察,发现松江、嘉定、上海一带的河流淤塞,就用余米动工疏浚,兴办了许多水利工程。通过这些措施,人民负担减轻了,加上遇有天灾,可以得到及时的救济,不但荒年不必逃荒,连税粮也不欠了,仓库富足了,民生也安定了。
周忱遇事留心研究,找出关键问题,提出解决办法,随时改革不适用的旧办法,适应新的情况。他有便宜行事的职权,地方性和局部性的问题,可以全权管理,以此,他在江南多年,先后办了不少好事。
他有良好的工作习惯,每天都记日记,除记重要的事项以外,也记下这一天的气候,阴、晴、风、雨。有一回,有人谎说,某天长江大风,把米船打翻了。周忱说不对,这一天没有风,一句话把这案子破了。又有一回,一个坏人故意把旧案卷弄乱,想翻案。周忱立刻指出,你在某天告的状,我是怎么判决的。好大胆子,敢来糊弄人!这个坏人只好服罪。江南钱粮的数目上千上万,都记得很清楚,随时算出,谁也欺骗不了他。
也有全局观点,对邻近地区遇事支援。有一年江北闹大饥荒,向江南借米三万石,周忱算了一下账,到明年麦子熟的时候,这点粮食是不够吃的,借给了十万石。
1449年10月瓦剌也先败明军于土木(今河北怀来县),明英宗被俘,北京震动。当国的大臣怕瓦剌进攻,打算把通州存的几百万石粮食烧掉,坚壁清野。这时恰好周忱在北京,他极力主张通州存粮可以支给北京驻军一年的军饷,何不就命令军队自己去运,预支一笔军饷呢?这样,粮食保全住了,驻军的粮饷也解决了。
周忱还善于和下属商量办事,即使对小官小吏,也虚心访问,征求意见。对有能力的好官,如苏州知府况钟、松江知府赵豫、常州知府莫愚、同知赵泰等,则更是推心置腹,遇事反复商量,极力支持,使他们能够各尽所长,办好了事。正因为他有这样好的作风,他出的主意,想的办法,也都能通过这些好官,贯彻执行下去。
他从不摆大官架子,有时候有工夫,骑匹马沿江到处走,见到的人不知道他是巡抚。在江南年代久了,和百姓熟了,像一家人一样,时常到农村去访问,不带随从,在院子里,在田野里,和农夫农妇面对面说家常话,谈谈心,问问有什么困难,什么问题,帮着出主意。
周忱最后还是被地主阶级攻击,罢官离开江南。他刚离开,户部立刻把他积储的余米收为官有,储备没有了,一遇到灾荒、意外,又到处饿死人了。农民完不起粮,又大量欠粮了,逃亡了。百姓越发想念他,到处建立生祠,纪念这个爱民的好官。
过了两年,周忱郁郁地死去。
原载《人民文学》1960年9月号
|
Markdown
|
UTF-8
| 1,810
| 2.890625
| 3
|
[] |
no_license
|
# Topics
- Bastion pattern
- NAT gateway pattern
### Additional command line parameter:
```--parameters ParameterKey=KeyPairName,ParameterValue=bar```
### Diagram

---
## Exercise 1
Create a VPC, IGW, RT, and public + private subnets
- Refer to previous exercise(s) if necessary.
**Verify:**
- Observe network components in VPC console.
---
## Exercise 2
Create a public EC2 instance and a keypair parameter to SSH to it. Apply a SecurityGroup to allow public SSH access. This is the bastion instance.
- [AWS::EC2::SecurityGroup Ingress](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule-1.html)
**Verify:**
- SSH into the instance.
---
## Exercise 3
Create a private EC2 instance that uses the same keypair parameter. Apply a security group to only allow SSH access from the bastion instance. Locally, enable SSH forwarding.
- [AWS::EC2::SecurityGroup Egress](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html)
- [SSH forwarding with -A](https://yakking.branchable.com/posts/ssh-A/)
- [ssh-agent on Git Bash for Windows](https://stackoverflow.com/questions/18404272)
**Verify:**
- `ssh -i mykey.pem -A ec2-user@bastion.ip` then `ssh privateip`
- Confirm failed (100% packet loss) ping to `1.1.1.1` from private instance.
---
## Exercise 4
Add an ElasticIP and a NAT Gateway to the private subnet. Add a route table for the NAT Gateway.
- [AWS::EC2::EIP](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html)
- [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html)
**Verify:**
- Confirm successful (0% packet loss) ping to `1.1.1.1` from private instance.
|
Java
|
UTF-8
| 8,556
| 1.992188
| 2
|
[] |
no_license
|
package org.sputnikdev.esh.binding.bluetooth.handler;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.core.thing.Channel;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.binding.BaseThingHandler;
import org.eclipse.smarthome.core.thing.binding.builder.ThingBuilder;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.eclipse.smarthome.core.types.UnDefType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sputnikdev.bluetooth.URL;
import org.sputnikdev.bluetooth.gattparser.BluetoothGattParser;
import org.sputnikdev.bluetooth.manager.BluetoothGovernor;
import org.sputnikdev.esh.binding.bluetooth.internal.BluetoothBindingConfig;
import org.sputnikdev.esh.binding.bluetooth.internal.BluetoothContext;
import org.sputnikdev.esh.binding.bluetooth.internal.BluetoothUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
/**
* A root thing handler for all bluetooth handlers. Defines overall structure and provides some useful methods
* for its successors.
*
* @author Vlad Kolotov
*/
class BluetoothHandler<T extends BluetoothGovernor> extends BaseThingHandler {
private Logger logger = LoggerFactory.getLogger(BluetoothHandler.class);
private final BluetoothContext bluetoothContext;
private final URL url;
private final Map<ChannelHandler, Set<ChannelUID>> channelHandlers = new ConcurrentHashMap<>();
private final Object updateLock = new Object();
private CompletableFuture<Void> initFuture;
BluetoothHandler(Thing thing, BluetoothContext bluetoothContext) {
super(thing);
this.bluetoothContext = bluetoothContext;
url = BluetoothUtils.getURL(thing);
}
@Override
public void initialize() {
super.initialize();
initFuture = getGovernor().whenReady(governor -> {
initChannelHandlers();
return null;
});
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
findHandler(channelUID, handler -> handler.handleCommand(channelUID, command));
}
@Override
public void dispose() {
logger.info("Disposing Abstract Bluetooth Handler");
super.dispose();
disposeChannelHandlers();
Optional.ofNullable(initFuture).ifPresent(future -> future.cancel(true));
}
@Override
public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
validateConfigurationParameters(configurationParameters);
// can be overridden by subclasses
Configuration configuration = editConfiguration();
for (Map.Entry<String, Object> configurationParmeter : configurationParameters.entrySet()) {
configuration.put(configurationParmeter.getKey(), configurationParmeter.getValue());
}
updateConfiguration(configuration);
updateDevice(configuration);
}
@Override
public void channelLinked(ChannelUID channelUID) {
findHandler(channelUID, ChannelHandler::linked);
super.channelLinked(channelUID);
}
@Override
public void channelUnlinked(ChannelUID channelUID) {
super.channelUnlinked(channelUID);
findHandler(channelUID, channelHandler -> {
if (channelHandlers.get(channelHandler).stream()
.filter(uid -> isLinked(uid.getIdWithoutGroup()) && !uid.equals(channelUID))
.count() == 0) {
channelHandler.unlinked();
}
});
}
@Override
protected void updateState(String channelID, State state) {
super.updateState(channelID, state);
}
@Override
protected void updateState(ChannelUID channelUID, State state) {
super.updateState(channelUID, state);
}
@Override
protected Configuration getConfig() {
return super.getConfig();
}
@Override
protected Configuration editConfiguration() {
return super.editConfiguration();
}
@Override
protected void updateConfiguration(Configuration configuration) {
super.updateConfiguration(configuration);
}
@Override
protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, String description) {
super.updateStatus(status, statusDetail, description);
}
@Override
protected ThingBuilder editThing() {
return super.editThing();
}
@Override
protected void updateThing(Thing thing) {
super.updateThing(thing);
}
protected void updateDevice(Configuration configuration) {
// default implementation
}
protected BluetoothContext getBluetoothContext() {
return bluetoothContext;
}
protected void addChannelHandler(ChannelHandler channelHandler) {
channelHandlers.computeIfAbsent(channelHandler, handler -> new HashSet<>());
}
protected void registerChannel(ChannelUID channelUID, ChannelHandler channelHandler) {
channelHandlers.computeIfAbsent(channelHandler, handler -> {
if (isLinked(channelUID.getIdWithoutGroup())) {
channelHandler.linked();
}
return new HashSet<>();
}).add(channelUID);
}
protected ChannelHandler findHandler(ChannelUID channelUID) {
return channelHandlers.entrySet().stream().filter(entry -> entry.getValue().contains(channelUID))
.findAny().map(Map.Entry::getKey).orElse(null);
}
protected void addChannelHandlers(List<SingleChannelHandler> handlers) {
handlers.forEach(handler -> {
ChannelUID channelUID = new ChannelUID(thing.getUID(), handler.getChannelID());
registerChannel(channelUID, handler);
});
}
protected void updateThingWithChannels(List<Channel> channels) {
if (!channels.isEmpty()) {
logger.debug("Updating thing with channels: {} / {}", url, channels.size());
synchronized (updateLock) {
ThingBuilder thingBuilder = editThing();
channels.forEach(channel -> {
String uid = channel.getUID().getIdWithoutGroup();
if (getChannel(uid) == null) {
logger.debug("Channel to be added: {} {}", url, uid);
thingBuilder.withChannel(channel);
}
});
logger.debug("Updating thing with new channels: {} / {}", url, channels.size());
updateThing(thingBuilder.build());
}
}
}
protected URL getURL() {
return url;
}
protected T getGovernor() {
return (T) bluetoothContext.getManager().getGovernor(getURL());
}
protected BluetoothGattParser getParser() {
return bluetoothContext.getParser();
}
protected BluetoothBindingConfig getBindingConfig() {
return bluetoothContext.getConfig();
}
protected Channel getChannel(URL url) {
return thing.getChannel(BluetoothUtils.getChannelUID(url));
}
protected Channel getChannel(String uid) {
return thing.getChannel(uid);
}
protected List<Channel> getChannels() {
return thing.getChannels();
}
protected ScheduledExecutorService getScheduler() {
return scheduler;
}
protected void updateStatus(ThingStatusDetail detail, String message) {
updateStatus(getGovernor().isReady() ? ThingStatus.ONLINE : ThingStatus.OFFLINE, detail, message);
}
private void initChannelHandlers() {
channelHandlers.keySet().forEach(ChannelHandler::init);
}
private void disposeChannelHandlers() {
channelHandlers.keySet().forEach(ChannelHandler::dispose);
channelHandlers.clear();
}
private void findHandler(ChannelUID channelUID, Consumer<ChannelHandler> consumer) {
channelHandlers.entrySet().stream().filter(entry -> entry.getValue().contains(channelUID))
.findAny().ifPresent(entry -> consumer.accept(entry.getKey()));
}
}
|
Markdown
|
UTF-8
| 1,492
| 2.953125
| 3
|
[] |
no_license
|
# Prediction-Assignment-Writeup
[Prediction-Assignment-Writeup HTML](https://rpubs.com/groupejopa/728147)
## Summary
This document is the final report of the Peer Assessment project from the Practical Machine Learning course, which is a part of the Coursera John’s Hopkins University Data Science Specialization. It was written and coded in RStudio, using its knitr functions and published in the html and markdown format. The goal of this project is to predict the manner in which the six participants performed the exercises. The machine learning algorithm, which uses the classe variable in the training set, is applied to the 20 test cases available in the test data.
## Background
Using devices such as Jawbone Up, Nike FuelBand, and Fitbit it is now possible to collect a large amount of data about personal activity relatively inexpensively. One thing that people regularly do is quantify how much of a particular activity they do, but they rarely quantify how well they do it.
In this project, my goal will be to use data from accelerometers on the belt, forearm, arm, and dumbell of 6 participants to predict the manner in which they did the exercise.
This report describes how a model was built, how cross validation was used, what the expected out of sample error might be, and the rationale behind the choices made. The prediction model will also be used to predict 20 different test cases.
Ref: [Prediction-Assignment-Writeup HTML](https://rpubs.com/groupejopa/728147)
|
Java
|
UTF-8
| 1,477
| 2.4375
| 2
|
[] |
no_license
|
/****************************************************************/
/* Nombre: Carlos Alberto Onorio Torres. */
/* Fecha de creación: 04/05/2018 */
/* Ultima modificación: 04/05/2018 */
/* Descripción: Detalles de una Experiencia Educativa con */
/* Exámenes parciales ingresados por el Coordianador.*/
/****************************************************************/
package mx.fei.sgpa.domain.plantrabajoacademia;
import java.util.ArrayList;
/**
* Detalles de una Experiencia Educativa con Exámenes parciales ingresados por el Coordianador
*/
public class ExperienciaEducativaConParciales {
String experienciaEducativa;
ArrayList<ExamenParcial> examenesParciales;
public ExperienciaEducativaConParciales(String experienciaEducativa, ArrayList<ExamenParcial> examenesParciales) {
this.experienciaEducativa = experienciaEducativa;
this.examenesParciales = examenesParciales;
}
public ExperienciaEducativaConParciales() {
}
public String getExperienciaEducativa() {
return experienciaEducativa;
}
public ArrayList<ExamenParcial> getExamenesParciales() {
return examenesParciales;
}
public void setExperienciaEducativa(String experienciaEducativa) {
this.experienciaEducativa = experienciaEducativa;
}
public void setExamenesParciales(ArrayList<ExamenParcial> examenesParciales) {
this.examenesParciales = examenesParciales;
}
}
|
Shell
|
UTF-8
| 519
| 2.625
| 3
|
[] |
no_license
|
# Clear any old environment that may conflict.
for key in $( set | awk '{FS="="} /^OS_/ {print $1}' ); do unset $key ; done
export OS_PROJECT_DOMAIN_NAME=Default
export OS_USER_DOMAIN_NAME=Default
export OS_PROJECT_NAME=admin
export OS_TENANT_NAME=admin
export OS_USERNAME=admin
export OS_PASSWORD=vQrxWEQqIohz1ZwBkhA1X26K4UbAGzlgV0XDbYF1
export OS_AUTH_URL=http://10.71.104.69:35357/v3
export OS_INTERFACE=internal
export OS_ENDPOINT_TYPE=internalURL
export OS_IDENTITY_API_VERSION=3
export OS_REGION_NAME=RegionOne
export OS_AUTH_PLUGIN=password
|
Java
|
UTF-8
| 5,548
| 1.679688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2017 Syncleus, Inc.
* with portions copyright 2004-2017 Bo Zimmerman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.syncleus.aethermud.game.Abilities.Misc;
import com.syncleus.aethermud.game.Abilities.StdAbility;
import com.syncleus.aethermud.game.Abilities.interfaces.Ability;
import com.syncleus.aethermud.game.Abilities.interfaces.HealthCondition;
import com.syncleus.aethermud.game.Common.interfaces.CMMsg;
import com.syncleus.aethermud.game.Common.interfaces.PhyStats;
import com.syncleus.aethermud.game.MOBS.interfaces.MOB;
import com.syncleus.aethermud.game.Races.interfaces.Race;
import com.syncleus.aethermud.game.core.CMClass;
import com.syncleus.aethermud.game.core.CMLib;
import com.syncleus.aethermud.game.core.CMParms;
import com.syncleus.aethermud.game.core.CMath;
import com.syncleus.aethermud.game.core.interfaces.Physical;
import com.syncleus.aethermud.game.core.interfaces.Tickable;
import java.util.List;
public class WingFlying extends StdAbility implements HealthCondition {
private final static String localizedName = CMLib.lang().L("Winged Flight");
private static final String[] triggerStrings = I(new String[]{"FLAP"});
private volatile boolean isFlying = true;
@Override
public String ID() {
return "WingFlying";
}
@Override
public String name() {
return localizedName;
}
@Override
public String displayText() {
return "";
}
@Override
protected int canAffectCode() {
return CAN_MOBS;
}
@Override
protected int canTargetCode() {
return CAN_MOBS;
}
@Override
public int abstractQuality() {
return Ability.QUALITY_INDIFFERENT;
}
@Override
public boolean putInCommandlist() {
return false;
}
@Override
public String[] triggerStrings() {
return triggerStrings;
}
@Override
public int classificationCode() {
return Ability.ACODE_SKILL | Ability.DOMAIN_RACIALABILITY;
}
@Override
public int usageType() {
return USAGE_MOVEMENT;
}
@Override
public String getHealthConditionDesc() {
return "Weak Paralysis";
}
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats) {
super.affectPhyStats(affected, affectableStats);
if (affected == null)
return;
if (!(affected instanceof MOB))
return;
if ((!CMLib.flags().isSleeping(affected))
&& (!CMLib.flags().isSitting(affected))
&& (isFlying))
affectableStats.setDisposition(affectableStats.disposition() | PhyStats.IS_FLYING);
else
affectableStats.setDisposition(CMath.unsetb(affectableStats.disposition(), PhyStats.IS_FLYING));
}
@Override
public void setMiscText(String newText) {
super.setMiscText(newText);
if (newText.length() == 0)
isFlying = true;
else
isFlying = CMParms.getParmBool(newText, "FLYING", true);
}
@Override
public boolean tick(Tickable ticking, int tickID) {
if ((tickID == Tickable.TICKID_MOB) && (ticking instanceof MOB) && (((MOB) ticking).charStats().getBodyPart(Race.BODY_WING) <= 0))
unInvoke();
return super.tick(ticking, tickID);
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) {
final MOB target = mob;
if (target == null)
return false;
if (target.charStats().getBodyPart(Race.BODY_WING) <= 0) {
mob.tell(L("You can't flap without wings."));
return false;
}
final boolean wasFlying = CMLib.flags().isFlying(target);
Ability A = target.fetchEffect(ID());
if (A != null)
A.unInvoke();
target.recoverPhyStats();
String str = "";
if (wasFlying)
str = L("<S-NAME> stop(s) flapping <S-HIS-HER> wings.");
else
str = L("<S-NAME> start(s) flapping <S-HIS-HER> wings.");
if (!super.invoke(mob, commands, givenTarget, auto, asLevel))
return false;
final boolean success = proficiencyCheck(mob, 0, auto);
if (success) {
final CMMsg msg = CMClass.getMsg(mob, target, this, CMMsg.MSG_NOISYMOVEMENT, str);
if (target.location().okMessage(target, msg)) {
target.location().send(target, msg);
beneficialAffect(mob, target, asLevel, 9999);
A = target.fetchEffect(ID());
if (A != null) {
A.makeLongLasting();
A.setMiscText("FLYING=" + (!wasFlying));
}
target.location().recoverRoomStats();
}
} else
return beneficialVisualFizzle(mob, target, L("<T-NAME> fumble(s) trying to use <T-HIS-HER> wings."));
// return whether it worked
return success;
}
}
|
PHP
|
UTF-8
| 787
| 2.546875
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: programador
* Date: 31/05/18
* Time: 8:05
*/
namespace App\Application\Delivery\GetByOrderId;
use App\Domain\Services\Delivery\DeliveryGetByOrderIdService;
class DeliveryGetOrderId
{
private $deliveryGetOrderIdService;
public function __construct(DeliveryGetByOrderIdService $deliveryGetOrderIdService,
DeliveryGetOrderIdDataTransform $dataTransform)
{
$this->deliveryGetOrderIdService = $deliveryGetOrderIdService;
$this->dataTransform = $dataTransform;
}
public function handle(DeliveryGetOrderIdCommand $deliveryGetOrderIdCommand)
{
return $this->dataTransform->transform($this->deliveryGetOrderIdService->__invoke($deliveryGetOrderIdCommand));
}
}
|
Python
|
UTF-8
| 1,058
| 3.125
| 3
|
[] |
no_license
|
from ntsa.algorithms.solver import Solver
class RungeKutta(Solver):
"""4th Order Classical Runge Kutta ODE Solver."""
def __init__(self, t0, y0, h, dydt):
super().__init__(t0, y0, h, dydt)
def _get_initial_params(self, target_t):
h = self.h
n = int(abs(target_t - self.t0) / h)
t = self.t0
y = self.y0
dydt = self.dydt
return dydt, t, y, h, n
def calculate_y(self, target_t):
dydt, t, y, h, n = self._get_initial_params(target_t)
for i in range(n):
k1 = h * dydt(t, y)
k2 = h * dydt(t + h / 2, y + k1 / 2)
k3 = h * dydt(t + h / 2, y + k2 / 2)
k4 = h * dydt(t + h, y + k3)
# update next value of y
y = y + (k1 + 2 * k2 + 2 * k3 + k4) / 6
# update next value of t
t = t + h
return y
def calculate_y_series(self, start_t, step, n):
points = [start_t + x * step for x in range(n)]
return [{"t": t, "y": self.calculate_y(t)} for t in points]
|
C#
|
UTF-8
| 2,196
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
// Copyright (C) 2005 Sebastian Faltoni
// Copyright (C) 2005 Riccardo Marzi
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Drawing;
using sys = System;
namespace Fireball.Windows.Forms.TuxBar.Graphic
{
/// <summary>
/// Descrizione di riepilogo per Utils.
/// </summary>
public sealed class Utils
{
public static Color GetLightColor(Color color,double light)
{
// double r = color.R + light;
// double g = color.G + light;
// double b = color.B + light;
double r = color.R +((color.R /100)*light);
double g = color.G +((color.G /100)*light);
double b = color.B +((color.B /100)*light);
if(r > 255)
r = 255;
if(g > 255)
g = 255;
if(b > 255)
b = 255;
return Color.FromArgb((int)r,(int)g,(int)b);
}
public static string GetCuttedString(string s,sys.Drawing.Font font,
sys.Drawing.Graphics gfx, int width)
{
int stringWidth = (int)gfx.MeasureString(s,font,width).Width;
if(stringWidth < width)
return s;
int charWidth = (int)gfx.MeasureString("#",font,width).Width;
int finalCut = stringWidth - width;
finalCut = finalCut / charWidth;
string temp = s.Substring(0,s.Length - finalCut - 1);
return temp;
}
public static Color GetForeColor(Color backgroundColor)
{
int sum = backgroundColor.R + backgroundColor.G +backgroundColor.B;
int div = sum / 3;
if(div > 128)
{
return Color.Black;
}
else
{
return Color.White;
}
}
}
}
|
JavaScript
|
UTF-8
| 2,958
| 2.875
| 3
|
[] |
no_license
|
import React, { useState } from "react";
import axios from "axios";
import { Card } from "react-bootstrap";
import API from "../ApiKey";
import WeatherCard from "./WeatherCard";
import Header from "./Layout/Header";
import WeatherSearch from "./Layout/WeatherSearch";
import Error from "./Error";
import Context from "../Context";
import "../App.css";
const MainContainer = () => {
// State variables
const [weatherData, setWeatherData] = useState(null);
const [error, setError] = useState(null);
const weatherApiCall = async (event) => {
event.preventDefault();
// Initializes a location variable based on the value in the searchbox
// Applies .trim() to remove whitespaces
const searchLocation = event.target.elements.city.value.trim();
// Returns an error if the search value is empty
if (!searchLocation) {
return (
setError("Please enter the name of the city"), setWeatherData(null)
);
}
// URL for the Open Weather Map 5-day forecast API, based on the search location and personal API Key
const url = `https://api.openweathermap.org/data/2.5/forecast?q=${searchLocation}&appid=${API.API_KEY}&units=metric`;
// API axios get() request
try {
const request = axios.get(url);
const response = await request;
setError(null);
setWeatherData(response.data);
} catch (error) {
setError("Please enter the city/country name correctly");
setWeatherData(null);
}
};
// Accepts API response as an argument, maps through the JSON data
// Returns only daily data, no 3-hourly data
// Renders WeatherCard components from an object
const loadWeatherCards = (weatherData) => {
const weatherCards = weatherData.list.map((listItem, listItemIndex) => {
if (listItemIndex % 8 === 0) {
return (
<WeatherCard
className="weather-card"
style={{ display: "inline-flex", flexDirection: "row" }}
weatherData={listItem}
cityName={weatherData.city.name}
key={listItemIndex}
/>
);
}
});
return weatherCards;
};
return (
<div
className="bg-light"
style={{ height: "100vh", width: "100vw", overflow: "auto" }}
>
<Header />
<Context.Provider value={{ weatherApiCall }}>
<Card
className="bg-primary"
style={{
width: "80vw",
marginLeft: "10vw",
marginTop: "5vh",
}}
>
<Card.Header className="bg-secondary">
Search for a city/country
</Card.Header>
<WeatherSearch />
<Card.Body style={{ display: "flex", flexDirection: "row" }}>
{error !== null && <Error error={error} />}
{weatherData ? loadWeatherCards(weatherData) : <></>}
</Card.Body>
</Card>
</Context.Provider>
</div>
);
};
export default MainContainer;
|
C
|
UTF-8
| 176
| 2.90625
| 3
|
[] |
no_license
|
#include <stdio.h>
/*
* put a string on output stream.
*/
putstr(f, s, l)
register FILE *f;
register char *s;
register int l;
{
while (l--)
putc(*s++, f);
}
|
JavaScript
|
UTF-8
| 1,114
| 2.546875
| 3
|
[] |
no_license
|
import React, { useState, useEffect } from "react";
import { getData } from "./http/Get";
import Table from "./components/Table";
import Pagination from "./components/Pagination";
import "./App.css";
function App() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [rowPerPage, setrowPerPage] = useState(10);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
const result = await getData();
setData(result.data.children);
setLoading(false);
};
fetchData();
}, []);
const indexOfLastRow = currentPage * rowPerPage;
const indexOfFirstRow = indexOfLastRow - rowPerPage;
const currentRows = data.slice(indexOfFirstRow, indexOfLastRow);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
return (
<div className="App">
<Table data={currentRows} loading={loading} />
<Pagination
rowPerPage={rowPerPage}
totalRows={data.length}
paginate={paginate}
/>
</div>
);
}
export default App;
|
C#
|
UTF-8
| 645
| 3.015625
| 3
|
[] |
no_license
|
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
namespace DataAccessLayer
{
public static class DataListHelper
{
public static object ReadField(DataRowView DRV, string FieldName)
{
Object Ret = null;
int idx = DRV.Row.Table.Columns.IndexOf(FieldName);
Ret = (-1 != idx) ? DRV.Row.ItemArray[idx] : null;
return Ret;
}
public static VarType ReadField<VarType>(DataRowView DRV, string FieldName, VarType DefVal)
{
VarType Ret = DefVal;
object val = ReadField(DRV, FieldName);
if (null != val)
Ret = ConvertHelper.Convert<VarType>(val, DefVal);
return Ret;
}
}
}
|
JavaScript
|
UTF-8
| 317
| 3.8125
| 4
|
[] |
no_license
|
//https://www.hackerrank.com/challenges/permutation-equation/problem
function permutationEquation(p) {
// Write your code here
const result = []
for (let i = 1; i < p.length + 1; i++) {
result.push(p.indexOf(p.indexOf(i) + 1) + 1)
}
return result
}
console.log(permutationEquation([5, 2, 1, 3, 4]))
|
Java
|
UTF-8
| 2,734
| 1.851563
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2/dlp.proto
package com.google.privacy.dlp.v2;
public interface InspectDataSourceDetailsOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.privacy.dlp.v2.InspectDataSourceDetails)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The configuration used for this job.
* </pre>
*
* <code>.google.privacy.dlp.v2.InspectDataSourceDetails.RequestedOptions requested_options = 2;
* </code>
*
* @return Whether the requestedOptions field is set.
*/
boolean hasRequestedOptions();
/**
*
*
* <pre>
* The configuration used for this job.
* </pre>
*
* <code>.google.privacy.dlp.v2.InspectDataSourceDetails.RequestedOptions requested_options = 2;
* </code>
*
* @return The requestedOptions.
*/
com.google.privacy.dlp.v2.InspectDataSourceDetails.RequestedOptions getRequestedOptions();
/**
*
*
* <pre>
* The configuration used for this job.
* </pre>
*
* <code>.google.privacy.dlp.v2.InspectDataSourceDetails.RequestedOptions requested_options = 2;
* </code>
*/
com.google.privacy.dlp.v2.InspectDataSourceDetails.RequestedOptionsOrBuilder
getRequestedOptionsOrBuilder();
/**
*
*
* <pre>
* A summary of the outcome of this inspection job.
* </pre>
*
* <code>.google.privacy.dlp.v2.InspectDataSourceDetails.Result result = 3;</code>
*
* @return Whether the result field is set.
*/
boolean hasResult();
/**
*
*
* <pre>
* A summary of the outcome of this inspection job.
* </pre>
*
* <code>.google.privacy.dlp.v2.InspectDataSourceDetails.Result result = 3;</code>
*
* @return The result.
*/
com.google.privacy.dlp.v2.InspectDataSourceDetails.Result getResult();
/**
*
*
* <pre>
* A summary of the outcome of this inspection job.
* </pre>
*
* <code>.google.privacy.dlp.v2.InspectDataSourceDetails.Result result = 3;</code>
*/
com.google.privacy.dlp.v2.InspectDataSourceDetails.ResultOrBuilder getResultOrBuilder();
}
|
PHP
|
UTF-8
| 4,213
| 2.921875
| 3
|
[] |
no_license
|
<?php
namespace Dao;
use Modelo\Usuario;
class UsuarioBdDao implements UsuarioIDao
{
protected $tabla = "usuarios";
protected $listado;
private static $instancia;
public static function getInstancia()
{
if (!self::$instancia instanceof self) {
self::$instancia = new self();
}
return self::$instancia;
}
private function __construct()
{
}
public function agregar(Usuario $usuario)
{
/** @noinspection SqlResolve */
$sql = "INSERT INTO $this->tabla (correo, pwd, idRol) VALUES (:mail, :pwd, :idRoles)";
$conexion = Conexion::conectar();
$sentencia = $conexion->prepare($sql);
$mail = $usuario->getEmail();
$pwd = $usuario->getPassword();
$r = $usuario->getRol();
$idRoles = $r->getId();
$sentencia->bindParam(":mail", $mail);
$sentencia->bindParam(":pwd", $pwd);
$sentencia->bindParam(":idRoles", $idRoles);
$sentencia->execute();
return $conexion->lastInsertId();
}
public function eliminarPorId($id)
{
/** @noinspection SqlResolve */
$sql = "DELETE FROM $this->tabla WHERE idUsuario = \"$id\"";
$conexion = Conexion::conectar();
$sentencia = $conexion->prepare($sql);
$sentencia->execute();
}
public function eliminarPorMail($mail)
{
/** @noinspection SqlResolve */
$sql = "DELETE FROM $this->tabla WHERE correo = \"$mail\"";
$conexion = Conexion::conectar();
$sentencia = $conexion->prepare($sql);
$sentencia->execute();
}
public function actualizar(Usuario $usuario)
{
/** @noinspection SqlResolve */
$sql = "UPDATE $this->tabla SET correo = :mail, pwd = :pwd, idRol = :idRoles WHERE idUsuario = :idUsuarios";
$conexion = Conexion::conectar();
$sentencia = $conexion->prepare($sql);
$mail = $usuario->getEmail();
$idUsuarios = $usuario->getId();
$pwd = $usuario->getPassword();
$r = $usuario->getRol();
$idRoles = $r->getId();
$sentencia->bindParam(":mail", $mail);
$sentencia->bindParam(":pwd", $pwd);
$sentencia->bindParam(":idRoles", $idRoles);
$sentencia->bindParam(":idUsuarios", $idUsuarios);
$sentencia->execute();
}
public function traerTodo()
{
$sql = "SELECT * FROM $this->tabla";
$conexion = Conexion::conectar();
$sentencia = $conexion->prepare($sql);
$sentencia->execute();
$dataSet = $sentencia->fetchAll(\PDO::FETCH_ASSOC);
$this->mapear($dataSet);
if (!empty($this->listado)) {
return $this->listado;
}
return null;
}
public function traerPorId($id)
{
/** @noinspection SqlResolve */
$sql = "SELECT * FROM $this->tabla WHERE idUsuario = \"$id\" LIMIT 1";
$conexion = Conexion::conectar();
$sentencia = $conexion->prepare($sql);
$sentencia->execute();
$dataSet[] = $sentencia->fetch(\PDO::FETCH_ASSOC);
$this->mapear($dataSet);
if (!empty($this->listado[0])) {
return $this->listado[0];
}
return null;
}
public function traerPorMail($mail)
{
/** @noinspection SqlResolve */
$sql = "SELECT * FROM $this->tabla WHERE correo = \"$mail\" LIMIT 1";
$conexion = Conexion::conectar();
$sentencia = $conexion->prepare($sql);
$sentencia->execute();
$dataSet[] = $sentencia->fetch(\PDO::FETCH_ASSOC);
$this->mapear($dataSet);
if (!empty($this->listado[0])) {
return $this->listado[0];
}
return null;
}
public function mapear($dataSet)
{
$dataSet = is_array($dataSet) ? $dataSet : [];
$this->listado = array_map(function ($p) {
$daoRol = RolBdDao::getInstancia();
$u = new Usuario(
$p['correo'],
$p['pwd'],
$daoRol->traerPorId($p['idRol'])
);
$u->setId($p['idUsuario']);
return $u;
}, $dataSet);
}
}
|
C++
|
UTF-8
| 3,317
| 3.703125
| 4
|
[
"MIT"
] |
permissive
|
/*
#面试刷题# 第94期
#Leetcode# Q0306 加性数字
加性数字是一个字符串,其数字可以形成加性数字序列。
有效的加性数字序列应至少包含三个数字。 除前两个数字外,
序列中的每个后续数字必须为前两个数字的和。
给定一个仅包含数字“ 0”-“ 9”的字符串,编写一个函数以确定它是否为加数。
注意:加法序列中的数字不能有前导零,因此序列1、2、03或1、02、3无效。
约束条件:
num仅由数字“ 0”-“ 9”组成。
1 <=数字长度<= 35
示例1:
Input: "112358"
Output: true
Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
示例2:
Input: "199100199"
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Solution From: https://leetcode.com/problems/additive-number/discuss/507073/C%2B%2B-Simple-DFS-Beats-100-Time-100-space-With-Explanation
*/
#include "leetcode.h"
namespace q0306
{
template<typename T>
bool run_testcases() {
T slt;
// example 01
{
CHECK_RET(true == slt.isAdditiveNumber("112358"));
}
// example 02
{
CHECK_RET(true == slt.isAdditiveNumber("199100199"));
}
return true;
}
// Runtime: 0 ms, faster than 100.00%
// Memory Usage: 6 MB, less than 100.00%
class Solution {
private:
bool _is_valid(long & first, long & second, int start, string & num) {
int n = num.size();
long third = 0;
if (start == n) {return true;}
for (int i = start; i < n; ++i) {
third *= 10;
third += (int)(num[i] - '0');
// find the third number
if (third == first + second) {
// the last char or the next number do not start with 0
if ((i+1==n) || ('0' != num[i+1])) {
return _is_valid(second, third, i+1, num);
}
}
// do not exist the third number
else if (third > first + second) {
return false;
}
}
return false;
}
public:
bool isAdditiveNumber(string num) {
long first = 0, second = 0, n = num.size();
int first_len = n / 2;
// special case
if ("000" == num) {return true;}
// check all posible for first
for (int i = 0; i < first_len; ++i) {
// the first number cannot start with 0 if it is not zero
if (i != 0 && 0 == first) {return false;}
first *= 10; first += (int)(num[i] - '0');
second = 0;
// check all posible for second
for (int j = i + 1; j-i < n-j; ++j) {
// the second number cannot start with 0
if ((0 == second) && (j > i+1)){break;}
second *= 10; second += (int)(num[j] - '0');
// the next number cannot start with 0
if ((j-i < n-j-i) && ('0' == num[j+1])) {continue;}
// check the third number
if (_is_valid(first, second, j+1, num)) {return true;}
}
}
return false;
}
};
TEST(Q0306, Solution) {EXPECT_TRUE(run_testcases<Solution>());}
}; // namespace q0306
|
PHP
|
UTF-8
| 818
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
namespace GuzabaPlatform\Cms\Models;
use Guzaba2\Base\Base;
class Pages extends Base
{
public static function get_by_page_group_id(?int $page_group_id, int $offset = 0, int $limit = 0): array
{
return Page::get_data_by( ['page_group_id' => $page_group_id], $offset, $limit, $use_like = FALSE, 'page_name');
}
public static function get_by_page_group_uuid(?string $parent_page_group_uuid, int $offset = 0, int $limit = 0): array
{
if ($parent_page_group_uuid) {
$PageGroup = new PageGroup($parent_page_group_uuid);
$parent_page_group_id = $PageGroup->get_id();
} else {
$parent_page_group_id = NULL;
}
return static::get_by_page_group_id($parent_page_group_id, $offset, $limit);
}
}
|
C
|
UTF-8
| 1,234
| 2.984375
| 3
|
[] |
no_license
|
#include "io.h"
#include "serial.h"
#include "log.h"
#include <string.h>
void serial_init(int port_idx)
{
uint16_t port = SERIAL_PORT[port_idx];
io_outb(port + 1, 0x00); // Disable interrupts
io_outb(port + 3, 0x80); // Enable DLAB
io_outb(port + 0, 0x03); // (lo) Set divisor to 3
io_outb(port + 1, 0x00); // (hi)
io_outb(port + 3, 0x03); // Disable DLAB, set parity
io_outb(port + 2, 0xC7); // Enable FIFO and clear
io_outb(port + 4, 0x0B); // Enable IRQ, RTS/DSR set
log(LOG_OK, "Serial module initialized\n");
}
int serial_received(int port_idx)
{
uint16_t port = SERIAL_PORT[port_idx];
return io_inb(port + 5) & 1;
}
char serial_read(int port_idx)
{
uint16_t port = SERIAL_PORT[port_idx];
while (!serial_received(port_idx));
return io_inb(port);
}
int serial_transmit_empty(int port_idx)
{
uint16_t port = SERIAL_PORT[port_idx];
return io_inb(port + 5) & 0x20;
}
void serial_putchar(int port_idx, char c)
{
uint16_t port = SERIAL_PORT[port_idx];
while (!serial_transmit_empty(port_idx));
if (c == '\n')
serial_putchar(port_idx, '\r');
io_outb(port, c);
}
void serial_writestring(int port_idx, const char* data)
{
for (size_t i = 0; i < strlen(data); i++) {
serial_putchar(port_idx, data[i]);
}
}
|
Java
|
UTF-8
| 625
| 2.046875
| 2
|
[] |
no_license
|
package br.com.bootcamp.mobile.steps;
import br.com.bootcamp.commons.AppiumRobot;
import br.com.bootcamp.funcionalidade.mobile.HomeFuncionalidade;
import cucumber.api.java.pt.Dado;
public class HomeSteps {
private HomeFuncionalidade homeFuncionalidade;
private AppiumRobot appiumRobot;
public HomeSteps() {
this.homeFuncionalidade = new HomeFuncionalidade();
this.appiumRobot = new AppiumRobot();
}
@Dado("^que toco na opção \"([^\"]*)\"$")
public void queTocoNaOpção(String menu) {
this.homeFuncionalidade.selecionaMenu(menu, menu.equalsIgnoreCase("Swipe"));
}
}
|
Shell
|
UTF-8
| 958
| 3.921875
| 4
|
[] |
no_license
|
#!/bin/bash
# tell the shell to use the bash interpreter so we don't run into compatability issues.
#check if root user
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
#Install OpenSSH Server, a connectivity tool for remote login with SSH protocol.
# -y answers all prompts with yes
apt-get install openssh-server -y
# Change the port inside the sshd_config file from the default 22 to 50000
# Ports 0 - 1023 are reserved by Internet Assigned Numbers Authority
# Registered Ports 1024 - 49151 should also be avoided.
# Dynamic and/or Private Ports are 49152 - 65535.
# sed . means any single character.
# The * means wildcard zero or more (to cover whatever port# it could be)
#-i.bak to create a backup file before editing for safety.
sed -i.bak 's/Port.*/Port 50000/' /etc/ssh/sshd_config
#Restart SSH service and it will swap to the new port.
/etc/init.d/ssh restart
echo "SSH Port Number changed to 50000"
|
Python
|
UTF-8
| 409
| 2.796875
| 3
|
[] |
no_license
|
from ..battle_entity import Entity
class Enemy(Entity):
def __init__(self, roomLocation):
self.roomLocation = roomLocation
self.detected = False
perception = 5
def __repr__(self):
return "%s at location %s." % (self.name, self.roomLocation)
stealth = 0
damageMult = 1
defense = 0
conservativity = 5 # will have an effect on how recklessly they fight
|
Java
|
UTF-8
| 645
| 1.71875
| 2
|
[] |
no_license
|
package com.marriage.grapefruit;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan
@MapperScan(basePackages = "com.marriage.grapefruit.mapper")
public class SpringbootShiroApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootShiroApplication.class, args);
}
}
|
Java
|
ISO-8859-13
| 4,091
| 2.5625
| 3
|
[] |
no_license
|
package it.MirkoGiacchini.menu;
import it.MirkoGiacchini.util.Util;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Disposable;
/**
* etichetta
* @author Mirko
*
*/
public class Label implements Disposable
{
public static GlyphLayout glyph = new GlyphLayout();
public static final float INFW = 9999999f;
String text;
public Menu menu;
float x, y;
BitmapFont font;
float offset;
float maxWidth;
private Color actColor;
private float actSX, actSY;
/**
* @param s testo iniziale
* @param x coordinata x testo
* @param y coordinata y testo
* @param c colore testo
* @param sizeX dimensione testo
* @param sizeY dimensione testo
* @param maxWidth massima larghezza raggiungibile
* @param fontPath font
* @param offset costante proporzionalit del font
*/
public Label(String s, float x, float y, Color c, float sizeX, float sizeY, float maxWidth, String fontPath, float offset)
{
text = s;
this.offset = offset;
this.x = x;
this.y = y;
font = new BitmapFont(Util.getHandle(fontPath));
setColor(c);
setSize(sizeX, sizeY);
font.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
this.maxWidth = maxWidth;
}
public Label(String s, float x, float y, Color c, float sx, float sy, float maxWidth, BitmapFont fnt, float offset)
{
this.font = fnt;
text = s;
this.offset = offset;
this.x = x;
this.y = y;
this.maxWidth = maxWidth;
setSize(sx, sy);
setColor(c);
}
public Label(String s, float sx, float sy, BitmapFont font, float offset)
{
this(s, 0, 0, Color.BLACK, sx, sy, INFW, font, offset);
}
public Label(String s, Color c, String fontPath, float offset)
{
this(s, 0, 0, c, 1, 1, INFW, fontPath, offset);
}
public Label(String s, String fontPath, float offset)
{
this(s, 0, 0, Color.BLACK, 1, 1, INFW, fontPath, offset);
}
public Label(String s, float sizeX, float sizeY, float maxWidth, String fontPath, float offset)
{
this(s, 0, 0, Color.BLACK, sizeX, sizeY, maxWidth, fontPath, offset);
}
public Label(String s, float x, float y, Color c, float sizeX, float sizeY, float maxWidth, String fontPath)
{
this(s, x, y, c, sizeX, sizeY, maxWidth, fontPath, .5f);
}
public Label(String s, float sizeX, float sizeY, float maxWidth, String fontPath)
{
this(s, sizeX, sizeY, maxWidth, fontPath, .5f);
}
public void set(String s, float x, float y, float sizeX, float sizeY, float maxWidth)
{
setText(s);
setX(x);
setY(y);
setSize(sizeX, sizeY);
setMaxWidth(maxWidth);
}
public void setText(String s)
{
text = s;
}
public void setMaxWidth(float mw)
{
maxWidth = mw;
}
public float getMaxWidth()
{
return maxWidth;
}
public String getText()
{
return text;
}
public void setColor(Color c)
{
font.setColor(c);
actColor = c;
}
public void setSize(float sizeX, float sizeY)
{
font.getData().setScale(sizeX * offset, sizeY * offset);
actSX = sizeX;
actSY = sizeY;
}
public void draw(SpriteBatch batch)
{
setSize(actSX, actSY);
setColor(actColor);
font.draw(batch, text, x, y, 0, text.length(), maxWidth, Align.left, true);
//font.getData().drawWrapped(batch, text, x, y, maxWidth);
}
public void setX(float x)
{
this.x = x;
}
public void setY(float y)
{
this.y = y;
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
public float getHeight()
{
glyph.setText(this.font, getText());
return glyph.height;
//return font.getData().getBounds(getText()).height;
}
public float getWidth()
{
glyph.setText(this.font, getText());
return glyph.width;
//return font.getBounds(getText()).width;
}
@Override
public void dispose()
{
font.dispose();
}
}
|
Python
|
UTF-8
| 2,136
| 3.703125
| 4
|
[] |
no_license
|
def f():
# non-local scope for inner functions
msg = "salam"
def test_local():
msg = "khoobi?"
print("in function: " + msg)
def test_nonlocal():
nonlocal msg
msg = "chetori?"
print("in function: " + msg)
def test_global():
global msg
msg = "chera?!"
print("in function: " + msg)
test_local()
print(msg)
test_nonlocal()
print(msg)
test_global()
print(msg)
pass
f()
print(msg)
class Game1:
pass
game = Game1()
print(type(game))
print(type(Game1))
class Person1:
pass
p1 = Person1()
p2 = Person1()
p1.name = 'mohamadreza'
p1.age = 18
print(p1.name, p1.age)
# print(p2.name)
class Game:
def set_money(self, x):
self.money = x
def get_money(self):
return self.money
game = Game()
game.set_money(4)
print(game.get_money())
Game.set_money(game, 5)
print(game.money)
class Person:
def __init__(self, name, age=18):
self.name = name
self.age = age
p1 = Person("Ali", 12)
p2 = Person("Amir")
print(p1.name, p1.age)
print(p2.name, p2.age)
class Game:
goal_money = 3000
def set_money(self, x):
self.money = x
def get_money(self):
return self.money
print("Game.goal_money:", Game.goal_money)
Game.max_people_count = 20
print("Game.max_people_count:", Game.max_people_count)
game = Game()
game.goal_money = 2000
print("game.goal_money:", game.goal_money)
print("Game.goal_money:", Game.goal_money)
del game.goal_money
print("game.goal_money:", game.goal_money)
class Sample:
goal_money = 3000
def __init__(self):
pass
@staticmethod
def increase_goal_money(value):
Sample.goal_money += value
sample = Sample()
print(Sample.goal_money)
Sample.increase_goal_money(100)
print(sample.goal_money)
class Sample:
def __init__(self, x):
self.__x = x
def get_x(self):
return self.__x
def set_x(self, x):
self.__x = x
sample = Sample(2)
print(sample.get_x())
sample.set_x(20)
print(sample.get_x())
print(dir(sample))
# print(sample.__x) has error
print(sample._Sample__x)
|
C#
|
UTF-8
| 3,507
| 2.84375
| 3
|
[] |
no_license
|
using System;
using System.ComponentModel;
using System.Net;
using System.Text;
using Newtonsoft.Json;
namespace OpenWeatherMap
{
public class OpenWeatherMapClient
{
public string AppId { get; }
public HttpStatusCode ResponseCode { get; private set; }
private const string OpenWeatherMapApi = "http://api.openweathermap.org/data/2.5/weather";
public OpenWeatherMapClient(string appId)
{
if (string.IsNullOrEmpty(appId) || string.IsNullOrWhiteSpace(appId))
throw new ArgumentException("Parameter cannot be null", nameof(appId));
AppId = appId;
}
public Weather GetByCityName(string city, UnitsType unitsType = UnitsType.Metric, Language language = Language.English)
{
if (string.IsNullOrEmpty(city) || string.IsNullOrWhiteSpace(city))
throw new ArgumentException("Parameter cannot be null", nameof(city));
dynamic jsonCurrentWeather =
JsonConvert.DeserializeObject(
GetRequest(OpenWeatherMapApi + $"?appid={AppId}&q={city}&units={unitsType}&lang={language.ToDescription()}"));
double unixDateTime = jsonCurrentWeather.dt;
string country = jsonCurrentWeather.sys.country;
string longitude = jsonCurrentWeather.coord.lon;
string latitude = jsonCurrentWeather.coord.lat;
string currentState = Encoding.UTF8.GetString(Encoding.Default.GetBytes((string) jsonCurrentWeather.weather[0].description));
string currentTemperature = jsonCurrentWeather.main.temp;
string windSpeed = jsonCurrentWeather.wind.speed;
double windDegrees = jsonCurrentWeather.wind.deg;
string humidity = jsonCurrentWeather.main.humidity;
string minTemperature = jsonCurrentWeather.main.temp_min;
string maxTemperature = jsonCurrentWeather.main.temp_max;
string cloudiness = jsonCurrentWeather.clouds.all;
double unixSunriseDate = jsonCurrentWeather.sys.sunrise;
double unixSunsetDate = jsonCurrentWeather.sys.sunset;
string pressure = jsonCurrentWeather.main.pressure;
string visibility = jsonCurrentWeather.visibility;
ResponseCode = jsonCurrentWeather.cod;
return new Weather(city, country, unixDateTime, longitude, latitude, currentState,
currentTemperature, windSpeed, windDegrees, humidity, minTemperature,
maxTemperature, cloudiness, unixSunsetDate, unixSunriseDate, pressure, visibility, language);
}
public Weather GetByIPGeoLocation(UnitsType unitsType = UnitsType.Metric, Language language = Language.English)
{
dynamic cityIP = JsonConvert.DeserializeObject(GetRequest("http://ip-api.com/json/"));
return GetByCityName((string) cityIP.city, unitsType, language);
}
private string GetRequest(string url)
{
using (var webClient = new WebClient())
{
return webClient.DownloadString(url);
}
}
}
public static class AttributesHelper
{
public static string ToDescription(this Enum value)
{
var da = (DescriptionAttribute[])(value.GetType().GetField(value.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false);
return da.Length > 0 ? da[0].Description : value.ToString();
}
}
}
|
Python
|
UTF-8
| 800
| 2.921875
| 3
|
[] |
no_license
|
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
def generateCauchyData(N, mean):
return (np.random.standard_cauchy(N) * 100. + mean)
data = generateCauchyData(10000, 42.)
plt.plot(data)
plt.show()
def frequentistCenter(data):
return np.mean(data)
X = frequentistCenter(data)
print("Sample mean: ", X)
def bayesianCenter(data):
with pm.Model():
loc = pm.Uniform('location', lower=-1000., upper=1000.)
scale = pm.Uniform('scale', lower=0.01, upper=1000.)
pm.Cauchy('y', alpha=loc, beta=scale, observed=data)
trace = pm.sample(3000, tune=3000, target_accept=0.92)
pm.traceplot(trace)
plt.show()
return np.mean(trace['location'])
X2 = bayesianCenter(data)
print("Bayesian mode (median, location): ", X2)
|
C++
|
UTF-8
| 1,587
| 2.765625
| 3
|
[] |
no_license
|
#include <texture.hpp>
#include <GLAD/glad.h>
#include <stb_image.h>
#include <stdio.h>
Texture::Texture(std::string path, std::string type) {
int height, width, nChannels;
unsigned int texture, format;
unsigned char *imageData = stbi_load(path.c_str(), &width, &height, &nChannels, 0);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
if (!imageData) {
printf("Failed to load image data from path: %s\n", path);
return;
}
switch (nChannels) {
case 1: {
format = GL_RED;
break;
}
case 3: {
format = GL_RGB;
break;
}
case 4: {
format = GL_RGBA;
break;
}
default: {
printf("Unsupported image channels: %d for image at %s\n", nChannels, path);
stbi_image_free(imageData);
return;
}
}
glTexImage2D(
GL_TEXTURE_2D,
0,
format,
width,
height,
0,
format,
GL_UNSIGNED_BYTE,
imageData
);
int wrap_param = (format == GL_RGBA) ? GL_CLAMP_TO_EDGE : GL_REPEAT;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_param);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_param);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(imageData);
this->id = texture;
this->type = type;
this->path = path;
return;
}
Texture::~Texture() {
glDeleteTextures(1, &this->id);
}
unsigned int Texture::GetID() {
return this->id;
}
std::string Texture::GetType() {
return this->type;
}
std::string Texture::GetPath() {
return this->path;
}
|
Java
|
UTF-8
| 18,361
| 2.875
| 3
|
[] |
no_license
|
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
/**
* This class will make use of it's supplier classes
* and handle the UX design.
*
* @author Chris Hoffman
*/
public class Driver implements ActionListener, MouseListener {
private JFrame gameBoard, endScreen;
private JButton playAgain, deal, re_deal, bet1, bet10, bet100, betMinus1, betMinus10, betMinus100, quit, restart;
private int chips = 100, bet = 0, wins = 0, loss = 0, rounds = 0, maxBet;
private JLabel handOutcome, displayBet, displayChips, bankLabel, betLabel;
private Deck dealer;
private Card sA, s2, s3, s4, s5, s6, s7, s8, s9, s10, sJ, sQ, sK,
hA, h2, h3, h4, h5, h6, h7, h8, h9, h10, hJ, hQ, hK,
dA, d2, d3, d4, d5, d6, d7, d8, d9, d10, dJ, dQ, dK,
cA, c2, c3, c4, c5, c6, c7, c8, c9, c10, cJ, cQ, cK;
private Hand player;
private boolean shouldSwitch = false, shouldBet = false;
private Image card1, card2, card3, card4, deckImage;
private Color newGreen = new Color( 100, 200, 30 );
/**
* Simple main that creates and instance of the class,
* loads up the game, and initializes the deck to be used.
*/
public static void main ( String[] args ) {
Driver game = new Driver();
game.initializeDeck();
game.createGameBoard();
game.playGame();
}
/**
* Creates the layout of the game board.
*/
private void createGameBoard() {
int cardSizeX = 100;
int cardSizeY = 180;
int cardLocationX = 50;
int cardLocationY = 400;
int boardSize = 800;
int boardLocationX = 500;
int boardLocationY = 200;
int deckLocationX = ( boardSize - cardSizeX ) / 2;
int deckLocationY = 70;
int buttonSizeX = 100;
int buttonSizeY = 40;
int buttonLocX = ( boardSize - buttonSizeX ) / 2;
int buttonLocY = 650;
int outcomeSizeX = 120;
int outcomeSizeY = 40;
int outcomeLocX = ( boardSize - outcomeSizeX ) / 2;
int outcomeLocY = 300;
int chipButtonSizeX = 70;
int chipButtonSizeY = 40;
int chipButtonLocX = boardSize - chipButtonSizeX;
int chipButtonLocY = 0;
int quitButtonLocY = boardSize - buttonSizeY * 2 + 5;
Color newYellow = new Color( 255, 255, 100 );
gameBoard = new JFrame( "Poker Game" );
gameBoard.setVisible( true );
gameBoard.setLayout( null );
gameBoard.setSize( boardSize, boardSize );
gameBoard.setLocation( boardLocationX, boardLocationY );
gameBoard.setResizable( false );
gameBoard.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
gameBoard.getContentPane().setBackground( newGreen );
handOutcome = new JLabel();
handOutcome.setLocation( outcomeLocX, outcomeLocY );
handOutcome.setSize( outcomeSizeX, outcomeSizeY );
handOutcome.setOpaque( true );
handOutcome.setVisible( true );
handOutcome.setBackground( newYellow );
bet100 = new JButton( "+100" );
bet100.setSize( chipButtonSizeX, chipButtonSizeY );
bet100.setLocation( chipButtonLocX, chipButtonLocY );
bet100.setVisible( true );
bet100.addActionListener( this );
bet10 = new JButton( "+10" );
bet10.setSize( chipButtonSizeX, chipButtonSizeY );
bet10.setLocation( chipButtonLocX - chipButtonSizeX, chipButtonLocY );
bet10.setVisible( true );
bet10.addActionListener( this );
bet1 = new JButton( "+1" );
bet1.setSize( chipButtonSizeX, chipButtonSizeY );
bet1.setLocation( chipButtonLocX - chipButtonSizeX * 2, chipButtonLocY );
bet1.setVisible( true );
bet1.addActionListener( this );
displayBet = new JLabel( "0" );
displayBet.setLocation( chipButtonLocX - chipButtonSizeX * 3, chipButtonLocY );
displayBet.setSize( chipButtonSizeX, chipButtonSizeY );
displayBet.setOpaque( true );
displayBet.setVisible( true );
displayBet.setBackground( newYellow );
betMinus1 = new JButton( "-1" );
betMinus1.setSize( chipButtonSizeX, chipButtonSizeY );
betMinus1.setLocation( chipButtonLocX - chipButtonSizeX * 4, chipButtonLocY );
betMinus1.setVisible( true );
betMinus1.addActionListener( this );
betMinus10 = new JButton( "-10" );
betMinus10.setSize( chipButtonSizeX, chipButtonSizeY );
betMinus10.setLocation( chipButtonLocX - chipButtonSizeX * 5, chipButtonLocY );
betMinus10.setVisible( true );
betMinus10.addActionListener( this );
betMinus100 = new JButton( "-100" );
betMinus100.setSize( chipButtonSizeX, chipButtonSizeY );
betMinus100.setLocation( chipButtonLocX - chipButtonSizeX * 6, chipButtonLocY );
betMinus100.setVisible( true );
betMinus100.addActionListener( this );
bankLabel = new JLabel( "Bank: " );
bankLabel.setSize( chipButtonSizeX, chipButtonSizeY );
bankLabel.setLocation( 0, 0 );
bankLabel.setVisible( true );
displayChips = new JLabel( chips + "" );
displayChips.setSize( chipButtonSizeX, chipButtonSizeY );
displayChips.setLocation( 0 + chipButtonSizeX, chipButtonLocY );
displayChips.setOpaque( true );
displayChips.setVisible( true );
displayChips.setBackground( newYellow );
betLabel = new JLabel( "Bet: " );
betLabel.setSize( chipButtonSizeX, chipButtonSizeY );
betLabel.setLocation( chipButtonLocX - chipButtonSizeX * 7, chipButtonLocY );
betLabel.setVisible( true );
playAgain = new JButton( "Play Again?" );
playAgain.setSize( buttonSizeX, buttonSizeY );
playAgain.setLocation( buttonLocX, buttonLocY );
playAgain.setVisible( false );
playAgain.addActionListener( this );
deal = new JButton( "Deal" );
deal.setSize( buttonSizeX, buttonSizeY );
deal.setLocation( buttonLocX + buttonSizeX, buttonLocY );
deal.setVisible( true );
deal.addActionListener( this );
re_deal = new JButton( "Re-Deal" );
re_deal.setSize( buttonSizeX, buttonSizeY );
re_deal.setLocation( buttonLocX + buttonSizeX * 2, buttonLocY );
re_deal.setVisible( false );
re_deal.addActionListener( this );
quit = new JButton( "Quit" );
quit.setSize( buttonSizeX, buttonSizeY );
quit.setLocation( 0, quitButtonLocY );
quit.setVisible( true );
quit.addActionListener( this );
card1 = new Image( cardLocationX, cardLocationY, cardSizeX, cardSizeY );
card2 = new Image( cardLocationX + cardSizeX * 2, cardLocationY, cardSizeX, cardSizeY );
card3 = new Image( cardLocationX + cardSizeX * 4, cardLocationY, cardSizeX, cardSizeY );
card4 = new Image( cardLocationX + cardSizeX * 6, cardLocationY, cardSizeX, cardSizeY );
card1.addMouseListener( this );
card2.addMouseListener( this );
card3.addMouseListener( this );
card4.addMouseListener( this );
deckImage = new Image( deckLocationX, deckLocationY, cardSizeX, cardSizeY, "red_back.png" );
gameBoard.add( card1, 0 );
gameBoard.add( card2, 0 );
gameBoard.add( card3, 0 );
gameBoard.add( card4, 0 );
gameBoard.add( deckImage );
gameBoard.add( bet100 );
gameBoard.add( bet10 );
gameBoard.add( bet1 );
gameBoard.add( displayBet );
gameBoard.add( betMinus1 );
gameBoard.add( betMinus10 );
gameBoard.add( betMinus100 );
gameBoard.add( bankLabel );
gameBoard.add( displayChips );
gameBoard.add( betLabel );
gameBoard.add( playAgain );
gameBoard.add( handOutcome );
gameBoard.add( re_deal );
gameBoard.add( deal );
gameBoard.add( quit );
gameBoard.repaint();
}
/**
* Creates an ending screen when the user decides to quit.
* Displays the number of rounds won, number of rounds lost, and
* the number of chips won overall.
*/
private void createEndScreen() {
int screenLocationX = 500;
int screenLocationY = 200;
int screenSize = 500;
int labelSizeX = 100;
int labelSizeY = 30;
int labelLocX = ( screenSize - labelSizeX ) / 2;
int labelLocY = 50;
int graphicSizeX = 200;
int graphicSizeY = 100;
double chipConversion = ( (int) ( ( chips + bet ) * 1.61 * 100 ) ) / 100.0;
endScreen = new JFrame( "Thank's For Playing!" );
endScreen.setSize( screenSize, screenSize );
endScreen.setLocation( screenLocationX, screenLocationY );
endScreen.getContentPane().setBackground( newGreen );
endScreen.setLayout( null );
endScreen.setVisible( true );
gameBoard.setVisible( false );
JLabel endBank = new JLabel( "Bank: $" + chipConversion );
endBank.setLocation( labelLocX, labelLocY );
endBank.setSize( labelSizeX, labelSizeY );
endBank.setVisible( true );
JLabel roundsPlayed = new JLabel( "Rounds: " + rounds );
roundsPlayed.setLocation( labelLocX , labelLocY + labelSizeY );
roundsPlayed.setSize( labelSizeX, labelSizeY );
roundsPlayed.setVisible( true );
JLabel winsAcquired = new JLabel( "Wins: " + wins );
winsAcquired.setLocation( labelLocX , labelLocY + labelSizeY * 2 );
winsAcquired.setSize( labelSizeX, labelSizeY );
winsAcquired.setVisible( true );
JLabel lossesAcquired = new JLabel( "Losses: " + loss );
lossesAcquired.setLocation( labelLocX , labelLocY + labelSizeY * 3 );
lossesAcquired.setSize( labelSizeX, labelSizeY );
lossesAcquired.setVisible( true );
restart = new JButton( "Restart" );
restart.setSize( labelSizeX, labelSizeY );
restart.setLocation( labelLocX , labelLocY + labelSizeY * 5 );
restart.setVisible( true );
restart.addActionListener( this );
Image graphic = new Image( ( endScreen.getWidth() - graphicSizeX ) / 2, labelLocY +labelSizeY * 7, graphicSizeX, graphicSizeY, "honors_spade-14.png" );
endScreen.add( endBank );
endScreen.add( roundsPlayed );
endScreen.add( winsAcquired );
endScreen.add( lossesAcquired );
endScreen.add( graphic );
endScreen.add( restart );
}
/**
* initializes the deck that will be used by the dealer
*/
private void initializeDeck() {
s2 = new Card( "Spade", "2", 2, "2S.png" );
s3 = new Card( "Spade", "3", 3, "3S.png" );
s4 = new Card( "Spade", "4", 4, "4S.png" );
s5 = new Card( "Spade", "5", 5, "5S.png" );
s6 = new Card( "Spade", "6", 6, "6S.png" );
s7 = new Card( "Spade", "7", 7, "7S.png" );
s8 = new Card( "Spade", "8", 8, "8S.png" );
s9 = new Card( "Spade", "9", 9, "9S.png" );
s10 = new Card( "Spade", "10", 10, "10S.png" );
sJ = new Card( "Spade", "Jack", 11, "JS.png" );
sQ = new Card( "Spade", "Queen", 12, "QS.png" );
sK = new Card( "Spade", "King", 13, "KS.png" );
sA = new Card( "Spade", "Ace", 14, "AS.png" );
h2 = new Card( "Heart", "2", 2, "2H.png" );
h3 = new Card( "Heart", "3", 3, "3H.png" );
h4 = new Card( "Heart", "4", 4, "4H.png" );
h5 = new Card( "Heart", "5", 5, "5H.png" );
h6 = new Card( "Heart", "6", 6, "6H.png" );
h7 = new Card( "Heart", "7", 7, "7H.png" );
h8 = new Card( "Heart", "8", 8, "8H.png" );
h9 = new Card( "Heart", "9", 9, "9H.png" );
h10 = new Card( "Heart", "10", 10, "10H.png" );
hJ = new Card( "Heart", "Jack", 11, "JH.png" );
hQ = new Card( "Heart", "Queen", 12, "QH.png" );
hK = new Card( "Heart", "King", 13, "KH.png" );
hA = new Card( "Heart", "Ace", 14, "AH.png" );
d2 = new Card( "Diamond", "2", 2, "2D.png" );
d3 = new Card( "Diamond", "3", 3, "3D.png" );
d4 = new Card( "Diamond", "4", 4, "4D.png" );
d5 = new Card( "Diamond", "5", 5, "5D.png" );
d6 = new Card( "Diamond", "6", 6, "6D.png" );
d7 = new Card( "Diamond", "7", 7, "7D.png" );
d8 = new Card( "Diamond", "8", 8, "8D.png" );
d9 = new Card( "Diamond", "9", 9, "9D.png" );
d10 = new Card( "Diamond", "10", 10, "10D.png" );
dJ = new Card( "Diamond", "Jack", 11, "JD.png" );
dQ = new Card( "Diamond", "Queen", 12, "QD.png" );
dK = new Card( "Diamond", "King", 13, "KD.png" );
dA = new Card( "Diamond", "Ace", 14, "AD.png" );
c2 = new Card( "Club", "2", 2, "2C.png" );
c3 = new Card( "Club", "3", 3, "3C.png" );
c4 = new Card( "Club", "4", 4, "4C.png" );
c5 = new Card( "Club", "5", 5, "5C.png" );
c6 = new Card( "Club", "6", 6, "6C.png" );
c7 = new Card( "Club", "7", 7, "7C.png" );
c8 = new Card( "Club", "8", 8, "8C.png" );
c9 = new Card( "Club", "9", 9, "9C.png" );
c10 = new Card( "Club", "10", 10, "10C.png" );
cJ = new Card( "Club", "Jack", 11, "JC.png" );
cQ = new Card( "Club", "Queen", 12, "QC.png" );
cK = new Card( "Club", "King", 13, "KC.png" );
cA = new Card( "Club", "Ace", 14, "AC.png");
dealer = new Deck( sA, s2, s3, s4, s5, s6, s7, s8, s9, s10, sJ, sQ, sK,
hA, h2, h3, h4, h5, h6, h7, h8, h9, h10, hJ, hQ, hK,
dA, d2, d3, d4, d5, d6, d7, d8, d9, d10, dJ, dQ, dK,
cA, c2, c3, c4, c5, c6, c7, c8, c9, c10, cJ, cQ, cK );
}
/*
* Displays the cards on the game board that are in the
* players hand.
*/
private void displayHand() {
card1.setImage( player.getCard( 0 ).getImg() );
card2.setImage( player.getCard( 1 ).getImg() );
card3.setImage( player.getCard( 2 ).getImg() );
card4.setImage( player.getCard( 3 ).getImg() );
gameBoard.repaint();
}
/**
* displays the outcome of the hand
*/
private void checkHand() {
if( player.isStraightFlush() ) {
handOutcome.setText( "Straight Flush" );
chips += bet * 200;
wins++;
}
else if( player.isStraight() ) {
handOutcome.setText( "Straight" );
chips += bet * 25;
wins++;
}
else if( player.isFlush() ) {
handOutcome.setText( "Flush" );
chips += bet * 50;
wins++;
}
else if( player.isFourOfKind() ) {
handOutcome.setText( "Four Of a Kind" );
chips += bet * 100;
wins++;
}
else if( player.isThreeOfKind() ) {
handOutcome.setText( "Three Of a Kind" );
chips += bet * 15;
wins++;
}
else if( player.isTwoPair() ) {
handOutcome.setText( "Two Pair" );
chips += bet * 10;
wins++;
}
else if( player.isPair() ) {
handOutcome.setText( "Pair" );
chips += bet * 2;
wins++;
}
else {
handOutcome.setText( "Loss" );
loss++;
}
bet = 0;
rounds++;
if( chips == 0 ) {
createEndScreen();
}
shouldSwitch = false;
shouldBet = false;
}
/**
* Hides the cards in the players hand prior to
* being dealt.
*/
private void hideCards() {
card1.setVisible( false );
card2.setVisible( false );
card3.setVisible( false );
card4.setVisible( false );
}
/**
* Shows the cards in the players hand.
*/
private void showCards() {
card1.setVisible( true );
card2.setVisible( true );
card3.setVisible( true );
card4.setVisible( true );
}
/**
* Checks the players bet to make sure it is valid.
* Makes changes to the bet as needed.
*/
private void checkBet() {
if( bet > maxBet ) {
bet = maxBet;
chips = 0;
}
if( bet < 0 ) {
bet = 0;
chips = maxBet;
}
}
/**
* Runs the core mechanics of the game.
*/
private void playGame() {
maxBet = chips;
player = new Hand();
dealer.shuffleDeck();
player.getDeal( dealer );
player.sortHand();
displayHand();
hideCards();
handOutcome.setText( "" );
//play again will only appear after the round is played
playAgain.setVisible( false );
re_deal.setVisible( false );
deal.setVisible( true );
shouldSwitch = true;
shouldBet = true;
}
@Override
public void actionPerformed( ActionEvent e ) {
if( e.getSource() == playAgain ) {
playGame();
}
else if( e.getSource() == re_deal ) {
//re display the cards that disappeared when switching them out
showCards();
re_deal.setVisible( false );
displayHand();
player.sortHand();
//checks the new set of cards
checkHand();
playAgain.setVisible( true );
}
else if( e.getSource() == deal ) {
deal.setVisible( false );
showCards();
shouldBet = false;
re_deal.setVisible( true );
}
else if( e.getSource() == quit ) {
createEndScreen();
endScreen.setVisible( true );
}
else if( e.getSource() == restart ) {
rounds = 0;
wins = 0;
loss = 0;
chips = 100;
bet = 0;
endScreen.setVisible( false );
gameBoard.setVisible( true );
playGame();
}
if( shouldBet ) {
if( e.getSource() == bet1 ) {
bet += 1;
chips -= 1;
checkBet();
}
else if( e.getSource() == bet10 ) {
bet += 10;
chips -= 10;
checkBet();
}
else if( e.getSource() == bet100 ) {
bet += 100;
chips -= 100;
checkBet();
}
else if( e.getSource() == betMinus1 ) {
bet -= 1;
chips += 1;
checkBet();
}
else if( e.getSource() == betMinus10 ) {
bet -= 10;
chips += 10;
checkBet();
}
else if( e.getSource() == betMinus100 ) {
bet -= 100;
chips += 100;
checkBet();
}
displayBet.setText( bet + "" );
displayChips.setText( chips + "" );
}
gameBoard.repaint();
}
@Override
public void mouseClicked( MouseEvent e ) {
//switches out cards when clicked only if it is at the appropriate time
if( shouldSwitch ) {
if( (Image)e.getSource() == card1 ) {
player.exchangeCards( 0, dealer );
card1.setVisible( false );
}
else if( (Image)e.getSource() == card2 ) {
player.exchangeCards( 1, dealer );
card2.setVisible( false );
}
else if( (Image)e.getSource() == card3 ) {
player.exchangeCards( 2, dealer );
card3.setVisible( false );
}
else if( (Image)e.getSource() == card4 ) {
player.exchangeCards( 3, dealer );
card4.setVisible( false );
}
}
}
@Override
public void mouseEntered( MouseEvent e ) {
if( shouldSwitch ) {
if( (Image)e.getSource() == card1 ) {
card1.setLocation( card1.getX(), card1.getY() - 20 );
}
else if( (Image)e.getSource() == card2 ) {
card2.setLocation( card2.getX(), card2.getY() - 20 );
}
else if( (Image)e.getSource() == card3 ) {
card3.setLocation( card3.getX(), card3.getY() - 20 );
}
else if( (Image)e.getSource() == card4 ) {
card4.setLocation( card4.getX(), card4.getY() - 20 );
}
gameBoard.repaint();
}
}
@Override
public void mouseExited( MouseEvent e ) {
if( shouldSwitch ) {
if( (Image)e.getSource() == card1 ) {
card1.setLocation( card1.getX(), card1.getY() + 20 );
}
else if( (Image)e.getSource() == card2 ) {
card2.setLocation( card2.getX(), card2.getY() + 20 );
}
else if( (Image)e.getSource() == card3 ) {
card3.setLocation( card3.getX(), card3.getY() + 20 );
}
else if( (Image)e.getSource() == card4 ) {
card4.setLocation( card4.getX(), card4.getY() + 20 );
}
gameBoard.repaint();
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
|
Java
|
UTF-8
| 893
| 3.5
| 4
|
[
"Apache-2.0"
] |
permissive
|
package com.java.advanced.features.juc.c_020;
import java.util.concurrent.TimeUnit;
/**
* synchronized 是可重入锁
*
* @author wangzhichao
* @since 2020/3/31
*/
public class T01_ReentrantLock1 {
synchronized void m1() {
System.out.println("m1...........start");
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
if (i == 2) {
m2();
}
}
System.out.println("m1...........end");
}
synchronized void m2() {
System.out.println("m2....start");
System.out.println("m2....end");
}
public static void main(String[] args) {
T01_ReentrantLock1 t1 = new T01_ReentrantLock1();
t1.m1();
}
}
|
C++
|
UTF-8
| 2,172
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
// -----------------------------------------------------------------------------
// CreativeCommons BY-SA 3.0 2013 <Thibault Coppex>
//
// -----------------------------------------------------------------------------
#ifndef AER_VIEW_CAMERA_INL_H_
#define AER_VIEW_CAMERA_INL_H_
namespace aer {
Camera::Camera(const View& view, const Frustum& frustum)
: view_(view),
frustum_(frustum),
bRebuild_(true)
{}
const Vector3& Camera::position() const {
return view_.position();
}
const Vector3& Camera::direction() const {
return view_.direction();
}
const Vector3& Camera::up() const {
return view_.up();
}
const Matrix4x4& Camera::view_matrix() const {
return const_cast<Camera*>(this)->view_matrix();
}
const Matrix4x4& Camera::view_matrix() {
bRebuild_ = bRebuild_ || view_.is_dirty();
return view_.view_matrix();
}
const Matrix4x4& Camera::projection_matrix() const {
return const_cast<Camera*>(this)->projection_matrix();
}
const Matrix4x4& Camera::projection_matrix() {
bRebuild_ = bRebuild_ || frustum_.is_dirty();
return frustum_.projection_matrix();
}
const View& Camera::view() const {
return view_;
}
const Frustum& Camera::frustum() const {
return frustum_;
}
const Matrix4x4& Camera::view_projection_matrix() const {
return const_cast<Camera*>(this)->view_projection_matrix();
}
const Matrix4x4& Camera::view_projection_matrix() {
if (is_dirty()) {
build();
}
return view_projection_matrix_;
}
bool Camera::is_dirty() const {
return bRebuild_ || frustum_.is_dirty() || view_.is_dirty();
}
void Camera::set_position(const Vector3& position) {
view_.set_position(position);
}
void Camera::set_direction(const Vector3& direction) {
view_.set_direction(direction);
}
void Camera::set_target(const Vector3& target) {
view_.set_target(target);
}
void Camera::set_view(const View& view) {
view_ = view;
bRebuild_ = true;
}
void Camera::set_frustum(const Frustum& frustum) {
frustum_ = frustum;
bRebuild_ = true;
}
void Camera::build() {
view_projection_matrix_ = frustum_.projection_matrix() * view_.view_matrix();
bRebuild_ = false;
}
} // namespace aer
#endif // AER_VIEW_CAMERA_INL_H_
|
C++
|
UTF-8
| 531
| 2.671875
| 3
|
[] |
no_license
|
#include<iostream>
#include<vector>
using namespace std;
int n,m,x;
vector<int>wt;
vector<int>color;
int solve(int index,int x,int k){
if(index==n){
return 0;
}
int q1=0;
if(wt[index]<=x&&k<=m){
q1=x-solve(index+1,k+1);
}
}
int main(){
cin>>n>>m>>x;
for(int i=0;i<n;i++){
int d;
cin>>d;
wt.push_back(d);
}
for(int i=0;i<n;i++){
int d;
cin>>d;
color.push_back(d);
}
cout<<solve(0,x,1)<<endl;
return 0;
}
|
Java
|
UTF-8
| 939
| 3.96875
| 4
|
[] |
no_license
|
package com.dengmin.demi.exception;
/**
* 面试题:下面方法体中输出的结果是多少?答案:100。
*
* 理由:方法体中的代码必须遵循自上而下顺序依次逐行执行!!!
*/
public class ExceptionTest04 {
public static void main(String[] args) {
int a = m();
System.out.println(a);
}
static int m() {
int i = 100;
try {
return i;
}finally {
i++;
}
}
}
// 将.class文件进行反编译的代码,可以看见执行顺序
/*
static int m(){
int i = 100;
int j = i;
// 可以看出,i++的确还是在return 语句前面执行,return语句还是最后一个执行的语句,
// 但多了一个int j = i;语句,且在返回的时候返回的是return j;。
i++;
return j;
// 可能出现异常的处理
Exception exception;
exception;
i++;
throw exception;
}
*/
|
Shell
|
UTF-8
| 831
| 2.6875
| 3
|
[] |
no_license
|
#!/bin/bash
. configs/main.cfg
cd $PATH_TO_WWW_BETA
BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo $BRANCH
cd $PATH_TO_WWW_MASTER
git pull beta $BRANCH
rm $PATH_TO_SCRIPT_FOLDER/configs/database.beta.yml
rm $PATH_TO_SCRIPT_FOLDER/configs/configuration.yml
cp $PATH_TO_SCRIPT_FOLDER/configs/database.beta.yml $PATH_TO_WWW_MASTER/config/database.yml
cp $PATH_TO_SCRIPT_FOLDER/configs/configuration.yml $PATH_TO_WWW_MASTER/config/configuration.yml
bundle install --without development test postgresql sqlite --verbose
rake generate_secret_token
rake db:migrate RAILS_ENV=production
rake redmine:plugins:migrate RAILS_ENV=production
rake tmp:cache:clear
rake tmp:sessions:clear
echo "You are now set your MASTER@redmine working copy in commit (tag+branch) : "
git log -n 3 --oneline --decorate --color
chmod -R 777 files log tmp
|
Markdown
|
UTF-8
| 5,177
| 2.890625
| 3
|
[] |
no_license
|
一五九
万紫琴大声道:
“琬妹请过来,他不听就算了!”
岳家宇搓搓手道:
“琴妹请等一下,我一会就来……。”
他肃然道:
“小弟,认为化解这三个招,应该……”
只闻司马龙在前面道:
“宇儿过来一下,为师指点一下你的轻功……”
岳家宇耸耸肩说:
“兰姐,待会再研究吧!”
谷中兰面色大变,她相信连司马龙也在怀疑她了,虽然深沉,毕竟搅不住内心的失望和忿慨,冷怒地道:
“岳郎,你去吧!也许轻功比技术更重要,因为必要时可以仗轻功逃命……”
岳家宇道:
“兰姐切莫误会,小弟只是因师命难违而已!”
岳家宇向前掠去,到了万紫琴身边,低声道:
“琴妹莫怪!我……。”
“别理我!”
“琴妹请放心!虽海枯石烂,小兄也不会忘记,你我心里有数……。”
他掠到司马龙身边。道:
“师傅……。”
司马龙宏声道:
“轻功为武学之基础,并非为了必要时逃命!所以为师必须使你的轻功再进一步……。”
他立即以传音入密之术,道:
“大敌当前,家有内贼你要当心了!”
岳家宇心头一震,也以传音入密道:
“师傅,不知内贼是谁?”
司马龙宏声道:
“你要谨记轻功要诀真气上提而不燥,神游物外而不浮。身轻如絮而不摇,血行迟缓而不滞……。”
司马龙又以传音入密,道:
“谷中兰乃岳家仇人之徒,西藏幽谷中石壁上留言,全属子虚,旨在偷学你的‘鹤形八掌’……。”
岳家宇骇然道:
“此学不是她一手研出的么?”
“当然不是!如果此学是她研悟,又岂能向你偷学,相反的,她为了师门之仇,非学‘鹤形八掌’不可!”
“师傅……近日来所发生之事您都知道!”
“恶鸟伤人时,为师不在,回来时该项惨祸已经发生,但因为师知道‘百草大仙’的用意,也知道他能医好几个丫头的眼疾,为师所以没有现身!”
“那么她的师门与家父有何仇恨?”
“大概是杀师之仇!”
“什么?家父杀了她的师傅?”
“不!杀了她的师祖!”
“不知她的师祖是谁?”
司马龙宏声道:
“你且提气试试看,按照为师的口诀,是否快了些?”
二人奔行加速,白琬和万、纪等人回头看了谷中兰一眼,发出一声冷笑,她们虽不知司马龙早就怀疑谷中兰,却相信在这紧要关头,司马龙把岳家宇叫到面前,定有深意。
这工夫已经进入马鞍山,距盟主府不过二三里之遥,司马龙道:
“此刻二更不到,我们在此等候其余两拨人……”
司马龙坐在大石上,向岳家宇道:
“宇儿,你可知道咱们此去九死一生么?”
岳家宇肃然道:
“此行危机四伏,自在意料之中,但徒儿不怕!”
谷中兰焦急地道:
“司马前辈,您既知危机四伏,何不早作安排?如果前辈不嫌碍事,晚辈愿以待从身佛陪岳弟前往!”
司马龙微笑道:
“不必了!设若对方已设下毒计,我们多去三五人也是一样,待会我们进去之后,你们要听程九臬指挥,不可任性单独行动,须知一人失去联络,必能影响大局!”
这时其余两拨人都已赶到,司马龙和程九臬低声谈了一阵,然后对诸人道:
“各位请注意!盟主府中有一旗杆,高可五丈,若此杆倒下,即表示双方已翻脸动手,各位再照预定接应之法进入!”
司马龙对程九臬低声道:
“这里有两个人身份不明,一个是那蒙面人,一个是谷中兰。程兄须暗暗通知所有之人,小心提防。”
程九臬道:
“小弟知道了时已不早,老哥哥起程吧!”
司马龙师徒别了诸人,向盟主府奔去,远远望去,堡门大敞,堡中灯火辉煌,司马龙道:
“虽然对方声势浩大,但依为师猜想,仍以阴谋为主……”
岳家宇道:
“师傅刚才还没有说出谷中兰师祖是谁呢?”
司马龙道:
“她的师傅就是石珊和石瑚,师祖当然是石珊的父亲!”
岳家宇陡然一震,道:
“家父与二位前辈昔年交往不薄,岂能杀死石前辈的父亲?”
司马龙道:
“这件事连为师也不信,但石珊石瑚计划复仇,却非一日了事……。”
岳家宇道:
“如果确有此事,应该是不久发生的,因去年冬天,晚辈在纪晓岚府上,二位石前辈曾去寻仇,目标乃是纪晓岚,当时晚辈曾出手挡了几招,双方功力相差极微,那时石前辈仅是责怪晚辈不该依附纪老贼,却未提及双方仇恨之事,由此可见。石前辈之老父,是那次动手以后才死的!如果确是如此,那就不对了!家父早于十余年前世……。”
|
SQL
|
UTF-8
| 294
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
-- Sub-sample of the donor dataset
SELECT
*
FROM
record_link.donors
WHERE MOD(ABS(FARM_FINGERPRINT(CAST(donor_id AS STRING))), 1000) = 0
-- Sub-sample of the contributions dataset
SELECT
*
FROM
record_link.donors
WHERE MOD(ABS(FARM_FINGERPRINT(CAST(donor_id AS STRING))), 1000) = 0
|
Shell
|
UTF-8
| 687
| 2.875
| 3
|
[] |
no_license
|
#/bin/sh
# This is a Jenkins setup script to ease getting up and running. Download by running
# "wget https://github.com/KarlMcBride/jenkins_playground/blob/master/jenkins_setup.sh && ./jenkins_setup.sh"
sudo apt install -y openjdk-11-jdk
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ > \
/etc/apt/sources.list.d/jenkins.list'
sudo apt update
sudo apt install -y jenkins
sudo systemctl start jenkins
sudo systemctl status jenkins
# You can also use the following commands to control auto-startup of Jenkins
# sudo systemctl disable jenkins
# sudo systemctl enable jenkins
|
Python
|
UTF-8
| 2,042
| 3.65625
| 4
|
[] |
no_license
|
from turtle import Turtle, Screen
from random import randint
def expand_color(character):
color_dict = {
'r': "red",
'o': "orange",
'y': "yellow",
'g': "green",
'b': "blue",
'i': "indigo",
'v': "violet",
}
return color_dict[character]
screen = Screen()
racer_turtles = []
is_game_on = False
winning_color = None
winning_turtle = None
screen.colormode(255)
screen.setup(width=500, height=400)
user_bet = None
while (user_bet not in ['v', 'i', 'b', 'g', 'y', 'o', 'r']) and \
(user_bet not in ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]):
user_bet = screen.textinput(title="Make your bet!",
prompt="Which turtle will win the race? Enter the color: ").lower()
if user_bet in "vibgyor":
user_bet = expand_color(user_bet)
print(f"You have chosen to be {user_bet}!")
colors = {
0: ["red", (255, 0, 0)],
1: ["orange", (255, 165, 0)],
2: ["yellow", (255, 255, 0)],
3: ["green", (0, 255, 0)],
4: ["blue", (0, 0, 255)],
5: ["indigo", (143, 0, 255)],
6: ["violet", (75, 0, 130)]
}
for prepare_turtle in range(0, 7):
new_turtle = Turtle(shape="turtle")
new_turtle.color(colors[prepare_turtle][1])
new_turtle.penup()
new_turtle.goto(x=-230, y=-150 + prepare_turtle * 50)
racer_turtles.append(new_turtle)
if user_bet:
is_game_on = True
while is_game_on:
for turtle in racer_turtles:
if turtle.xcor() > 230:
winning_color = turtle.pencolor()
is_game_on = False
speed = randint(0, 10)
turtle.forward(speed)
for turtle_color in range(0, 7):
if winning_color == colors[turtle_color][1]:
winning_turtle = colors[turtle_color][0]
if winning_turtle == user_bet:
print(f"You have won!! The {winning_turtle} is the winner!!")
else:
print(f"You have lost!! The {winning_turtle} is the winner!!")
screen.exitonclick()
|
JavaScript
|
UTF-8
| 933
| 3.296875
| 3
|
[] |
no_license
|
'use strict';
module.exports = tokens => {
let current = 0;
const walk = () => {
let token = tokens[current];
if (token.type === 'number') {
current++;
return {
type: 'NumberLiteral',
value: token.value
};
}
if (token.type === 'paren' && token.value === '(') {
token = tokens[++current];
const node = {
type: 'CallExpression',
name: token.value,
params: []
};
token = tokens[++current];
while (
token.type !== 'paren' ||
(token.type === 'paren' && token.value !== ')')
) {
node.params.push(walk());
token = tokens[current];
}
current++;
return node;
}
throw new TypeError(`Unknown type: ${token.type}`);
};
const ast = {
type: 'Program',
body: []
};
while (current < tokens.length) {
ast.body.push(walk());
}
return ast;
};
|
Java
|
UTF-8
| 762
| 1.96875
| 2
|
[] |
no_license
|
package com.valentsolutions.xml.statepattern.providedstates;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* @
*/
public class ProvidedStateTests
{
public static Test suite()
{
TestSuite suite =
new TestSuite("Test for com.valentsolutions.xml.statepattern.providedstates");
//$JUnit-BEGIN$
suite.addTest(new TestSuite(GenericBooleanValueStateTest.class));
suite.addTest(new TestSuite(GenericByteValueStateTest.class));
suite.addTest(new TestSuite(GenericShortValueStateTest.class));
suite.addTest(new TestSuite(GenericIntValueStateTest.class));
suite.addTest(new TestSuite(GenericLongValueStateTest.class));
//$JUnit-END$
return suite;
}
}
|
Java
|
UTF-8
| 709
| 2.046875
| 2
|
[] |
no_license
|
//package idv.woody.jgroup;
//
//import org.jgroups.JChannel;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Scope;
//import org.springframework.stereotype.Component;
//import org.springframework.stereotype.Service;
//
///**
// * Created by chun-chiao on 2016/5/8.
// */
//@Component
//@Scope("singleton")
//public class SenderChannel {
// @Autowired
// private JChannel channel;
// private String cluster;
//
// public void start() throws Exception {
// if (channel.isConnected()) {
// System.out.println("connected already");
// } else {
// channel.connect("cluster");
// }
// }
//}
|
Java
|
UTF-8
| 3,440
| 2.28125
| 2
|
[] |
no_license
|
package cooble.ch.location;
import cooble.ch.core.Game;
import cooble.ch.entity.IMovable;
import cooble.ch.entity.Mover;
import cooble.ch.entity.Position;
import cooble.ch.entity.Weather;
import cooble.ch.event.LocationLoadEvent;
import cooble.ch.graphics.Bitmap;
import cooble.ch.graphics.BitmapProvider;
import cooble.ch.graphics.BitmapStack;
import cooble.ch.graphics.Renderer;
import cooble.ch.module.Modules;
import cooble.ch.music.MPlayer2;
import cooble.ch.world.Location;
import java.util.function.Supplier;
/**
* Created by Matej on 12.12.2015.
*/
public final class LocationBusTrip extends Location {
IMovable bus;
int[] pos;
BitmapProvider bitmapProviderBus;
Weather weather;
public LocationBusTrip() {
super("ice_plain");
setJoeProhibited(true);
}
@Override
public void onStart() {
super.onStart();
MPlayer2.playSound("bus");
Game.getWorld().inventory().lock(true);
registerTickable(new Mover(bus, new Position(220*2, -5*2), 2, () -> {
//todo demo
/* Game.core.EVENT_BUS.addEvent(new LocationLoadEvent("intro"));
GameExitEvent event = new GameExitEvent();
event.setRestart(false);
event.setClear(true);
Game.core.EVENT_BUS.addEvent(event);*/
Game.core.EVENT_BUS.addEvent(new LocationLoadEvent("party", Modules.moduleParty.MID));
}));
Game.input.muteInput(true);
for (int i = 0; i < Game.core.TARGET_TPS * 10; i++) {
weather.tick();
}
}
@Override
public void onStartRendering(Renderer renderer) {
super.onStartRendering(renderer);
Game.renderer.registerBitmapProvider(bitmapProviderBus);
}
@Override
public void onStop() {
super.onStop();
MPlayer2.stopSound("bus");
Game.input.muteInput(false);
}
@Override
public void loadTextures() {
setBackground(Bitmap.get("location/ice_plain"));
Bitmap busMap = Bitmap.get("item/bus").flip(false);
pos = new int[2];
pos[0] = -250*2;
pos[1] = 0;
bus = new IMovable() {
@Override
public int getX() {
return pos[0];
}
@Override
public int getY() {
return pos[1];
}
@Override
public void setX(int x) {
pos[0] = x;
}
@Override
public void setY(int y) {
pos[1] = y;
}
@Override
public void setIsMoving(boolean isMoving) {
}
};
bitmapProviderBus = new BitmapProvider() {
@Override
public Bitmap getCurrentBitmap() {
return busMap;
}
@Override
public int[] getOffset() {
return pos;
}
};
weather = new Weather(new Supplier<Bitmap>() {
BitmapStack b = BitmapStack.getBitmapStackFromFolder("item/snow_spark").resize(0.5);
@Override
public Bitmap get() {
return b.getBitmap(Game.random.nextInt(b.getMaxLength())).copy();
}
});
weather.setSpeed(-5,0.85);
weather.setCadence(35);
weather.spawnWidth(3);
registerTickable(weather);
weather.setEnabled(true);
}
}
|
Java
|
UTF-8
| 1,240
| 2.78125
| 3
|
[] |
no_license
|
package org.selliott.atm.server;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.selliott.atm.common.Config;
/**
* Main entry point for the Jetty server.
*/
public class Main {
private static final Logger log = Logger.getLogger(Main.class);
/**
* Main entry point.
*
* @param args
* Command line arguments including the path to the configuration
* file.
* @throws Exception
* Unhandled exception that needs to be passed to the Java and
* displayed to the user in a ugly manner.
*/
public static void main(String[] args) throws Exception {
log.info("Begin main.");
// TODO: getInstance is called here not to get the instance, but so that
// the configuration parameters can be accessed directly. Perhaps there
// is a more encapsulated way of doing this.
Config.getInstance(args);
// TODO: Parse command line arguments.
// TODO: The port should be configurable.
Server server = new Server(8080);
server.setHandler(new HTTPHandler());
server.start();
server.join();
log.info("End main.");
}
}
|
Java
|
UTF-8
| 295
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package eu.leads.crawler.concurrent;
/**
* Task interface
*/
public interface Task {
/**
* You can limit number of parallel processing task with the same sequence name.
* Limit is ignored if sequence name is {@code null}.
* @return
*/
String getSequenceName();
}
|
Ruby
|
UTF-8
| 966
| 3.3125
| 3
|
[] |
no_license
|
#---
# Excerpted from "Mazes for Programmers",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/jbmaze for more book information.
#---
class Sidewinder
def self.on(grid)
grid.each_row do |row|
run = []
row.each do |cell|
run << cell
at_eastern_boundary = (cell.east == nil)
at_northern_boundary = (cell.north == nil)
should_close_out =
at_eastern_boundary ||
(!at_northern_boundary && rand(2) == 0)
if should_close_out
member = run.sample
member.link(member.north) if member.north
run.clear
else
cell.link(cell.east)
end
end
end
grid
end
end
|
Python
|
UTF-8
| 1,367
| 4.125
| 4
|
[] |
no_license
|
poem = '''\
Programing is fun
when the work is done
if you wanna make your work also fun
use python!
'''
#以'w'riting方式打开文件
f = open('poem.txt', 'w')
#向文件编写文本
f.write(poem)
#关闭文件
f.close()
#如果没有特别指定,将启用默认的阅读('r'ead)模式
f = open('poem.txt')
while True:
line = f.readline()
#0长度指示
if len(line) == 0:
break
#每行的末尾,都已经有了换行符,因为它是从一个文件中进行读取
print(line,end='')
f.close()
#pickle
import pickle
#我们存储相关对象的文件的名称
shoplistfile = 'shoplist.data'
#需要购买的物品清单
shoplist = ['apple', 'mango', 'carrot']
#准备写入文件
f = open(shoplistfile, 'wb')
#存储对象至文件
pickle.dump(shoplist, f)
f.close()
#清除shoplist变量
del shoplist
#重新打开存储文件
f = open(shoplistfile, 'rb')
#从文件中载入对象
storedlist = pickle.load(f)
print(storedlist)
#unicode
import io
f = io.open('abc.txt', 'wt', encoding='utf-8')
f.write(u'imagine non-english here')
f.close()
text = io.open('abc.txt', encoding='utf-8').read()
print(text)
#当我们阅读或者写入某一个文件或者放我们希望与其他计算机交互的时候,我们将我们的unicode
#字符串转换成一个能被发送和接收的格式,这个格式就是utf-8。
|
JavaScript
|
UTF-8
| 3,977
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
var assert = require('assert');
var JsBarcode = require('../../bin/JsBarcode.js');
var Canvas = require("canvas");
describe('CODE128', function() {
it('should be able to include the encoder(s)', function () {
CODE128 = JsBarcode.getModule("CODE128");
CODE128A = JsBarcode.getModule("CODE128A");
CODE128B = JsBarcode.getModule("CODE128B");
CODE128C = JsBarcode.getModule("CODE128C");
});
it('should encode CODE128A', function () {
var enc = new CODE128A("ABC" + String.fromCharCode(25));
assert.equal("1101000010010100011000100010110001000100011011011011110100011101101100011101011"
, enc.encode().data);
});
it('should encode CODE128B', function () {
var enc = new CODE128B("a@B=1");
assert.equal("110100100001001011000011000110110100010110001110011001010011100110110111001001100011101011"
, enc.encode().data);
});
it('should encode CODE128C', function () {
var enc = new CODE128C("123456");
assert.equal("11010011100101100111001000101100011100010110100011011101100011101011"
, enc.encode().data);
});
it('should remove unprintable characters', function () {
var enc = new CODE128C("A\n\x00B \x04\x10\x1FC");
assert.equal("AB C", enc.encode().text);
});
it('should encode CODE128 (auto)', function () {
var enc = new CODE128("12345Hejsan123456\tA");
assert.equal("110100111001011001110010001011000101111011101101110010011000101000101100100001000011001010111100100100101100001100001010010111011110101100111001000101100011100010110111010111101000011010010100011000111011110101100011101011",
enc.encode().data);
var enc = new CODE128("Hi\n12345");
assert.equal("110100100001100010100010000110100111010111101000011001010011100110101110111101110110111010111011000111001100101100011101011"
, enc.encode().data);
var enc = new CODE128("HI\nHi");
assert.equal("11010000100110001010001100010001010000110010110001010001011110111010000110100110110011001100011101011"
, enc.encode().data);
var enc = new CODE128("HI\n" + String.fromCharCode(201) + "Hi" + String.fromCharCode(202) + "123456" + String.fromCharCode(207));
assert.equal("1101000010011000101000110001000101000011001010111100010110001010001011110111010000110100111101010001011101111010110011100100010110001110001011011110101110110011100101100011101011"
, enc.encode().data);
var enc = new CODE128(String.fromCharCode(207) + "42184020500");
assert.equal("110100111001111010111010110111000110011100101100010100011001001110110001011101110101111010011101100101011110001100011101011"
, enc.encode().data);
var enc = new CODE128("Should\nshift");
assert.equal("1101001000011011101000100110000101000111101010011110010110010100001000010011011110100010100001100101011110010010011000010100001101001011000010010011110100100011010001100011101011"
, enc.encode().data);
var enc = new CODE128("\tHi\nHI");
assert.equal("1101000010010000110100110001010001111010001010000110100100001100101100010100011000100010111101101101100011101011"
, enc.encode().data);
});
it('should warn with invalid text', function () {
var enc = new CODE128("ABC" + String.fromCharCode(500));
assert.equal(false, enc.valid());
var enc = new CODE128A("Abc");
assert.equal(false, enc.valid());
var enc = new CODE128B("Abc\t123");
assert.equal(false, enc.valid());
var enc = new CODE128C("1234ab56");
assert.equal(false, enc.valid());
var enc = new CODE128C("12345");
assert.equal(false, enc.valid());
});
it('should pass valid text', function () {
var enc = new CODE128("ABC" + String.fromCharCode(207));
assert.equal(true, enc.valid());
var enc = new CODE128A("ABC\t\n123");
assert.equal(true, enc.valid());
var enc = new CODE128B("Abc123" + String.fromCharCode(202));
assert.equal(true, enc.valid());
var enc = new CODE128C("123456");
assert.equal(true, enc.valid());
});
});
|
C++
|
UTF-8
| 15,369
| 2.828125
| 3
|
[] |
no_license
|
#ifndef AUTOMATA_HPP
#define AUTOMATA_HPP
#include <iostream>
#include <vector>
#include "../parse/ast.hpp"
namespace rv_xjtu_yangyan
{
///////////////////////////////////////////////////////////
//数据结构的定义
///////////////////////////////////////////////////////////
struct automata_node;
struct automata_scope;
struct automata_key_vars
{
std::vector<std::string> vars;
};
struct automata_nonkey_vars
{
std::vector<std::string> vars;
};
struct automata_solution
{
std::string solution_name;
std::vector<std::string> paras;
};
struct automata_action
{
std::string action_name;
std::vector<std::string> paras;
};
struct automata_type
{
std::string type;
automata_solution *solution;
automata_action *action;
automata_scope *scope;
automata_key_vars *keyvar;
automata_nonkey_vars *nonkeyvar;
};
struct automata_leaf:automata_type
{
automata_leaf()
{
type = "leaf";
}
void set_event(std::string name, std::vector<std::string> &vars)
{
event_name = name;
//下面是不变的
is_negative = false;
is_true_leaf = false;
is_acceptable = true;
next_node = NULL;
for(std::vector<std::string>::iterator it = vars.begin();
it != vars.end(); it++)
{
paras.push_back((*it));
}
}
void set_next_node(bool acceptable, automata_type *next)
{
is_acceptable = acceptable;
next_node = next;
//下面不变
is_true_leaf = true;
is_negative = false;
event_name = "true";
}
bool is_true_leaf; //区分事件还是true
bool is_acceptable; //区分可接受true还是不可接受true
bool is_negative; //区分事件
std::string event_name;
std::vector<std::string> paras;
automata_type *next_node;
};
struct automata_node:automata_type
{
automata_node()
:left_result("ambiguous"),right_result("ambiguous")
{
type = "node";
left_automata = NULL;
right_automata = NULL;
extra_automata = NULL;
}
std::string relationship; //"and" "or"
std::string left_result; //"true" "false" "ambiguous"
std::string right_result; //"true" "false" "ambiguous"
automata_type *left_automata;
automata_type *right_automata;
automata_type *extra_automata; //这个用于left和right中都不包含,但是会用到的情况。
};
struct automata_scope
{
bool samelevel;
automata_leaf *begin;
automata_leaf *end;
};
//表示一个rule结构中的所有自动机
struct automata_rule
{
std::string program_name;
std::string rule_name;
std::vector<automata_type *> automatas;
};
//表示所有自动机的集合
struct automata_collection
{
std::vector<automata_rule *> automata_rules;
};
#define LEAF_P(p) ((automata_leaf *)p)
#define NODE_P(p) ((automata_node *)p)
}
namespace rv_xjtu_yangyan
{
////////////////////////////////////////////////////////////////////
//获取一个自动机中所有非关键变量
////////////////////////////////////////////////////////////////////
struct get_nonkey_vars_from_at//automata_type
{
get_nonkey_vars_from_at(automata_key_vars *av, automata_nonkey_vars *anv)
:top_anv_(anv), top_av_(av)
{
}
void operator()(automata_type *at)
{
if(at->type == "leaf" && LEAF_P(at)->is_true_leaf == false)
{
automata_leaf *al = LEAF_P(at);
for(std::vector<std::string>::iterator it = al->paras.begin();
it != al->paras.end(); it++)
{
//确保变量不在key中
std::vector<std::string>::iterator it0 =
find(top_av_->vars.begin(), top_av_->vars.end(), (*it));
if(it0 == top_av_->vars.end())
{
//确保变量不在nonkey中
std::vector<std::string>::iterator it1 =
find(top_anv_->vars.begin(), top_anv_->vars.end(), (*it));
if(it1 == top_anv_->vars.end())
top_anv_->vars.push_back(*it);
}
}
}
else if(at->type == "node")
{
get_nonkey_vars_from_at(top_av_, top_anv_)(NODE_P(at)->left_automata);
get_nonkey_vars_from_at(top_av_, top_anv_)(NODE_P(at)->right_automata);
}
}
automata_nonkey_vars *top_anv_;
automata_key_vars *top_av_;
};
///////////////////////////////////////////////////////////////////////////
// 标准化后的抽象语法树转化为自动机
///////////////////////////////////////////////////////////////////////////
struct ast_event_to_automata
{
ast_event_to_automata() { }
automata_type *operator()(ast_event *ae)
{
automata_leaf *rv_al = new automata_leaf();
rv_al->set_event(ae->event_name, ae->paras);
return (automata_type *)rv_al;
}
};
struct ast_unary_expr_to_automata
{
ast_unary_expr_to_automata() {}
automata_type *operator()(ast_unary_expr *aue);
};
struct ast_binary_expr_to_automata
{
ast_binary_expr_to_automata(){}
automata_type *operator()(ast_binary_expr *abe);
};
struct ast_expr_to_automata
{
ast_expr_to_automata() {}
automata_type *operator()(ast_expr *ae)
{
if(is_unary_operator(ae->op_name))
{
return ast_unary_expr_to_automata()((ast_unary_expr *)ae);
}
else if(is_binary_operator(ae->op_name))
{
return ast_binary_expr_to_automata()((ast_binary_expr *)ae);
}
else if(is_event(ae->op_name))
{
return ast_event_to_automata()((ast_event *)ae);
}
return NULL;
}
};
automata_type *ast_unary_expr_to_automata::operator()(ast_unary_expr *aue)
{
if(aue->op_name == "~")
{
automata_leaf *rv_al = (automata_leaf *)ast_expr_to_automata()(aue->subexpr);
rv_al->is_negative = true;
return rv_al;
}
else if(aue->op_name == "G")
{
//G a = true(*) & a()
automata_node *rv_an = new automata_node();
automata_leaf *true_al = new automata_leaf();
true_al->set_next_node(true, rv_an);
rv_an->relationship = "and";
rv_an->left_automata = true_al;
rv_an->right_automata = ast_expr_to_automata()(aue->subexpr);
return rv_an;
}
else if(aue->op_name == "F")
{
//F a = true | a()
automata_node *rv_an = new automata_node();
automata_leaf *true_al = new automata_leaf();
true_al->set_next_node(false, rv_an);
rv_an->relationship = "or";
rv_an->left_automata = true_al;
rv_an->right_automata = ast_expr_to_automata()(aue->subexpr);
return rv_an;
}
else if(aue->op_name == "N")
{
//N a = "true" & true 为了符合二叉表达的特点
automata_node *rv_an = new automata_node();
automata_leaf *l_true_al = new automata_leaf();
l_true_al->set_next_node(true, NULL);
automata_type *next_at = ast_expr_to_automata()(aue->subexpr);
automata_leaf *r_true_al = new automata_leaf();
r_true_al->set_next_node(false, next_at);
rv_an->relationship = "and";
rv_an->left_automata = l_true_al;
rv_an->right_automata = r_true_al;
rv_an->extra_automata = next_at;
return rv_an;
}
else if(aue->op_name == "X")
{
//X a = "true" & true 为了符合二叉表达的特点
automata_node *rv_an = new automata_node();
automata_leaf *l_true_al = new automata_leaf();
l_true_al->set_next_node(true, NULL);
automata_type *next_at = ast_expr_to_automata()(aue->subexpr);
automata_leaf *r_true_al = new automata_leaf();
r_true_al->set_next_node(true, next_at); //弱下一个,要设置成true,表示没有下一个也能结束
rv_an->relationship = "and";
rv_an->left_automata = l_true_al;
rv_an->right_automata = r_true_al;
rv_an->extra_automata = next_at;
return rv_an;
}
std::cerr << "自动机转化时遇到了没有定义的结点:" << aue->op_name << std::endl;
return NULL;
}
automata_type *ast_binary_expr_to_automata::operator()(ast_binary_expr *abe)
{
if(abe->op_name == "&")
{
//a & b = a & b
automata_node *rv_an = new automata_node();
rv_an->relationship = "and";
rv_an->left_automata = ast_expr_to_automata()(abe->lh_subexpr);
rv_an->right_automata = ast_expr_to_automata()(abe->rh_subexpr);
return rv_an;
}
else if(abe->op_name == "|")
{
//a | b = a | b
automata_node *rv_an = new automata_node();
rv_an->relationship = "or";
rv_an->left_automata = ast_expr_to_automata()(abe->lh_subexpr);
rv_an->right_automata = ast_expr_to_automata()(abe->rh_subexpr);
return rv_an;
}
else if(abe->op_name == "U")
{
// a U b = b | (a & true)
automata_node *rv_an = new automata_node();
automata_leaf *true_al = new automata_leaf();
true_al->set_next_node(false, rv_an);
automata_node *right_an = new automata_node();
right_an->relationship = "and";
right_an->left_automata = ast_expr_to_automata()(abe->lh_subexpr);
right_an->right_automata = true_al;
rv_an->relationship = "or";
rv_an->left_automata = ast_expr_to_automata()(abe->rh_subexpr);
rv_an->right_automata = right_an;
return rv_an;
}
else if(abe->op_name == "W")
{
// a W b = b | (a & true(*))
automata_node *rv_an = new automata_node();
automata_leaf *true_al = new automata_leaf();
true_al->set_next_node(true, rv_an);
automata_node *right_an = new automata_node();
right_an->relationship = "and";
right_an->left_automata = ast_expr_to_automata()(abe->lh_subexpr);
right_an->right_automata = true_al;
rv_an->relationship = "or";
rv_an->left_automata = ast_expr_to_automata()(abe->rh_subexpr);
rv_an->right_automata = right_an;
return rv_an;
}
std::cerr << "自动机转化时遇到了没有定义的结点:" << abe->op_name << std::endl;
return NULL;
}
struct ast_scope_to_automata
{
ast_scope_to_automata() {}
automata_scope *operator()(ast_scope *as)
{
automata_scope *rv;
rv = new automata_scope();
rv->samelevel = as->samelevel;
rv->begin = LEAF_P(ast_event_to_automata()(as->begin));
rv->end = LEAF_P(ast_event_to_automata()(as->end));
return rv;
}
};
struct ast_key_vars_to_automata
{
automata_key_vars *operator()(ast_key_vars *akv)
{
automata_key_vars *rv;
rv = new automata_key_vars();
for(std::vector<std::string>::iterator it = akv->vars.begin();
it != akv->vars.end(); it++)
{
rv->vars.push_back((*it));
}
return rv;
}
};
struct ast_solution_to_automata
{
ast_solution_to_automata() { }
automata_solution *operator()(ast_solution *as)
{
automata_solution *rv_as = new automata_solution();
rv_as->solution_name = as->solution_name;
BOOST_FOREACH(std::string ¶, as->paras)
{
rv_as->paras.push_back(para);
}
return rv_as;
}
};
struct ast_action_to_automata
{
ast_action_to_automata() { }
automata_action *operator()(ast_action *as)
{
automata_action *rv_as = new automata_action();
rv_as->action_name = as->action_name;
BOOST_FOREACH(std::string ¶, as->paras)
{
rv_as->paras.push_back(para);
}
return rv_as;
}
};
struct ast_item_to_automata
{
ast_item_to_automata() {}
automata_type *operator()(ast_item *ai)
{
automata_type *rv;
rv = ast_expr_to_automata()(ai->expr);
rv->solution = ast_solution_to_automata()(ai->solution);
rv->action = ast_action_to_automata()(ai->action);
rv->scope = ast_scope_to_automata()(ai->scope);
rv->keyvar = ast_key_vars_to_automata()(ai->keyvars);
rv->nonkeyvar = new automata_nonkey_vars();
get_nonkey_vars_from_at(rv->keyvar, rv->nonkeyvar)(rv);
BOOST_FOREACH(std::string &var, rv->keyvar->vars)
{
std::cout << "关键变量为:" << var << std::endl;
}
BOOST_FOREACH(std::string &var, rv->nonkeyvar->vars)
{
std::cout << "非关键变量为:" << var << std::endl;
}
return rv;
}
};
struct ast_rule_to_automata
{
ast_rule_to_automata() {}
automata_rule *operator()(ast_rule *ar)
{
automata_rule *rv_ar = new automata_rule();
rv_ar->program_name = ar->program_name;
rv_ar->rule_name = ar->rule_name;
for(std::vector<ast_item *>::iterator it = ar->items.begin(); it != ar->items.end(); it++)
{
rv_ar->automatas.push_back(ast_item_to_automata()(*it));
}
return rv_ar;
}
};
struct ast_file_to_automata
{
ast_file_to_automata() {}
automata_collection *operator()(ast_file *af)
{
automata_collection *rv_ac = new automata_collection();
for(std::vector<ast_rule *>::iterator it = af->rules.begin(); it != af->rules.end(); it++)
{
automata_rule *ar;
ar = ast_rule_to_automata()(*it);
rv_ac->automata_rules.push_back(ar);
}
return rv_ac;
}
};
}
#endif
|
C
|
UTF-8
| 1,427
| 2.578125
| 3
|
[] |
no_license
|
PRACTICE
COMPETE
JOBS
LEADERBOARD
Search
shantanumallik
PracticeTutorials30 Days of CodeDay 0: Hello, World.
Day 0: Hello, World.
2 more challenges to get your first star!
Points: 0/2
Days of Code
Problem
Submissions
Leaderboard
Discussions
Editorial
Tutorial
You made this submission 2 years ago.
Score:30.00Status:Accepted
People who solved Day 0: Hello, World. attempted this next:
Day 4: Class vs. Instance
Learn the difference between class variables and instance variables.
Solve Challenge
Submitted Code
Language: C
Open in editor
6
int main() {
7
// Declare a variable named 'input_string' to hold our input.
8
char input_string[105];
9
10
// Read a full line of input from stdin and save it to our variable, input_string.
11
scanf("%[^\n]", input_string);
12
13
// Print a string literal saying "Hello, World." to stdout using printf.
14
printf("Hello, World.\n");
15
16
// TODO: Write a line of code here that prints the contents of input_string to stdout.
17
printf("%s",input_string);
18
return 0;
19
}
Test case 0
Test case 1
Compiler Message
Success
Input (stdin)
Download
Welcome to 30 Days of Code!
Expected Output
Download
Hello, World.
Welcome to 30 Days of Code!
NEED HELP?
View tutorial
View discussions
View editorial
View top submissions
Contest CalendarBlogScoringEnvironmentFAQAbout UsSupportCareersTerms Of ServicePrivacy PolicyRequest a Feature
|
C
|
UTF-8
| 11,998
| 3.1875
| 3
|
[] |
no_license
|
#include "hashmap.h"
#include "stdbool.h"
#define LOAD_FACTOR_ERR -1
#define VACANT -1
#define INSERT 5
#define DELETE 4
/**
* allocates a new buckets array for the hash map;
* @param hash_map a hash map
* @return a new buckets array
* @if_fail return NULL.
*/
vector** buckets_alloc(hashmap* hash_map){
// first alloc an array of pointers
vector** new_buckets = calloc(hash_map->capacity, sizeof(vector*));
if (new_buckets == NULL){
return NULL;
}
for (int i = 0; i < hash_map->capacity; ++i) {
// allocate every vector
new_buckets[i] = vector_alloc(pair_copy, pair_cmp, pair_free);
// in case the memory allocation has not succeeded we need to free all
// vectors
if (new_buckets[i] == NULL){
for (int j = 0; j < i; ++j) {
vector_free(&new_buckets[j]);
}
// the hash map and the pointer array of buckets
// also needs to be freed
return NULL;
}
}
return new_buckets;
}
/**
* frees all the buckets until the current vector
* @param hash_map a hash map
* @param index the index of the current vector
*/
void free_all_buckets(vector** buckets , int index) {
for (int i = 0; i < index; ++i) {
vector_clear(buckets[i]);
vector_free(&buckets[i]);
buckets[i] = NULL;
}
free(buckets);
buckets = NULL;
}
/**
* Allocates dynamically new hash map element.
* @param func a function which "hashes" keys.
* @return pointer to dynamically allocated hashmap.
* @if_fail return NULL.
*/
hashmap *hashmap_alloc (hash_func func){
// first create a new hash map and allocate the memory
hashmap *new_hash_map = malloc(sizeof(hashmap));
if (new_hash_map == NULL){
return NULL;
}
// initialize the hash map data members.
new_hash_map->capacity = HASH_MAP_INITIAL_CAP;
new_hash_map->size = 0;
new_hash_map->hash_func = func;
new_hash_map->buckets = buckets_alloc(new_hash_map);
if (new_hash_map->buckets == NULL){
return NULL;
}
// if code got here everything is okay, return the new allocated hashmap
return new_hash_map;
}
/**
* Frees a hash map and the elements the hash map itself allocated.
* @param p_hash_map pointer to dynamically allocated pointer to hash_map.
*/
void hashmap_free (hashmap **p_hash_map){
hashmap *hash_map_ptr = *p_hash_map;
// first we need to free all the vectors
free_all_buckets(hash_map_ptr->buckets, (int) hash_map_ptr->capacity);
// now free the hash map itself
free(hash_map_ptr);
}
/**
* re hashes all values in the hash map
* @param hash_map a hash map
* @return 1 if the re assign succeeded, 0 otherwise.
*/
int assign_all_pairs(hashmap *hash_map, int action){
// first initialize a new buckets array to assign the pairs to.
vector **temp_buckets = buckets_alloc(hash_map);
if (temp_buckets == NULL){
return false;
}
for (int i = 0; i < hash_map->size; ++i) {
// get the current bucket/vector
vector* cur_vector = hash_map->buckets[i];
for (int j = 0; j < cur_vector->size ; ++j) {
//get the pair object in that bucket and its hash key.
pair *cur_pair = cur_vector->data[j];
size_t hash_key = hash_map->hash_func(cur_pair->key) &
(hash_map->capacity - 1);
// put the pair in the proper bucket key.
int is_success = vector_push_back(temp_buckets[hash_key], cur_pair);
if (!is_success) {
// couldn't assign one of the pairs,
free_all_buckets(temp_buckets, i);
return false;
}
}
}
// we should now free the former buckets array of hash map
switch (action) {
case INSERT:
for (int i = 0; i < (hash_map->capacity) /
VECTOR_GROWTH_FACTOR; ++i) {
vector_free(&hash_map->buckets[i]);
}
break;
case DELETE:
for (int i = 0; i < (hash_map->capacity) *
VECTOR_GROWTH_FACTOR; ++i) {
vector_free(&hash_map->buckets[i]);
}
break;
}
free(hash_map->buckets);
// assign the temp buckets array to the buckets array of the hash map
hash_map->buckets = temp_buckets;
return true;
}
/**
* gets a vector and a key and checks if a pair with a key is in the vector
* @param vector a bucket in hash map
* @param key the key to find
* @return the index of the pair with that key, -1 otherwise.
*/
int get_pair_by_key(vector* vector , const_keyT key){
pair* cur_pair;
for (int i = 0; i < vector->size ; ++i) {
cur_pair = vector->data[i];
if (cur_pair->key_cmp(cur_pair->key, key) == true){
return i;
}
}
return VACANT;
}
/**
* Inserts a new in_pair to the hash map.
* The function inserts *new*, *copied*, *dynamically allocated* in_pair,
* NOT the in_pair it receives as a parameter.
* @param hash_map the hash map to be inserted with new element.
* @param in_pair a in_pair the hash map would contain.
* @return returns 1 for successful insertion, 0 otherwise.
*/
int hashmap_insert (hashmap *hash_map, const pair *in_pair){
if (hash_map == NULL || in_pair == NULL){
return false;
}
// activate hash function on the pair.
size_t hash_key = hash_map->hash_func(in_pair->key) &
(hash_map->capacity - 1);
// get to the proper bucket in the vector.
vector* cur_vector = hash_map->buckets[hash_key];
if (get_pair_by_key(cur_vector,in_pair->key) == VACANT){
// this means there is no value like this in the vector so we can
// insert it.
int value_addition = vector_push_back(cur_vector, in_pair);
// check the insertion to the vector was ok
if (!value_addition) {
return false;
}
hash_map->size += 1;
if (hashmap_get_load_factor(hash_map) > HASH_MAP_MAX_LOAD_FACTOR){
// there are too many values in hashmap, so it needs to be resized.
hash_map->capacity *= HASH_MAP_GROWTH_FACTOR;
int is_success = assign_all_pairs(hash_map, INSERT);
if (!is_success) {
// the reassign of the pairs was unsuccessful so size and
// capacity changes needs to be undone.
hash_map->size -= 1;
hash_map->capacity /= HASH_MAP_GROWTH_FACTOR;
vector_erase(cur_vector, hash_map->size);
return false;
}
}
// finally, the new value is in the hash map.
return true;
}
// this means that the value with the same key is already in hash map.
return false;
}
/**
* The function returns the value associated with the given key.
* @param hash_map a hash map.
* @param key the key to be checked.
* @return the value associated with key if exists, NULL otherwise (the value itself,
* not a copy of it).
*/
valueT hashmap_at (const hashmap *hash_map, const_keyT key){
if (key == NULL || hash_map == NULL){
return NULL;
}
// first get the hash code for the key and the vector in that index.
size_t hash_key = hash_map->hash_func(key) & (hash_map->capacity - 1);
const vector *cur_vector = hash_map->buckets[hash_key];
for (int i = 0 ; i < cur_vector->size ; ++i){
// get the current pair for every index
pair *cur_Value = vector_at(cur_vector, i);
// compare between the key given and the key in that pair, if they are
// the same this is the value we need to return.
if (cur_Value->key_cmp(key, cur_Value->key) == true){
return cur_Value->value;
}
}
// if the loop has ended it means there is no pair with that key in the cur
// bucket, and that means pair with this key is not in hashmap.
return NULL;
}
/**
* The function erases the pair associated with key.
* @param hash_map a hash map.
* @param key a key of the pair to be erased.
* @return 1 if the erasing was done successfully, 0 otherwise. (if key not in map,
* considered fail).
*/
int hashmap_erase (hashmap *hash_map, const_keyT key){
if (hash_map == NULL || key == NULL){
return false;
}
// first we need to check if hash map contains a value with this key.
valueT given_key_value = hashmap_at(hash_map, key);
if (given_key_value == NULL){
// there is nothing to delete
return false;
}
int erase_succsses = false;
pair* cur_pair = NULL;
// get the hash key and the vector in that index
size_t hash_value = hash_map->hash_func(key) & (hash_map->capacity - 1);
vector* proper_vector = hash_map->buckets[hash_value];
// find the pair in the vector
for (int i = 0; i < proper_vector->size; ++i) {
cur_pair = proper_vector->data[i];
if (cur_pair->key_cmp(cur_pair->key, key)){
erase_succsses = vector_erase(proper_vector, i);
break;
}
}
// iteration on the pairs in the vector has ended, check if a value was
// deleted successfully
if (!erase_succsses){
return erase_succsses;
}
hash_map->size -= 1;
// now check if a resizing of the hash map is required
if (hashmap_get_load_factor(hash_map) < HASH_MAP_MIN_LOAD_FACTOR){
hash_map->capacity /= HASH_MAP_GROWTH_FACTOR;
int is_success = assign_all_pairs(hash_map, DELETE);
if (!is_success){
// the reassign wasn't successful, so everything must be back in
// place
hash_map->size += 1;
hash_map->capacity *= HASH_MAP_GROWTH_FACTOR;
vector_push_back(proper_vector, cur_pair);
return false;
}
// if we got here then the re assign was successful and the
// pair is of the hash map
return true;
}
return true;
}
/**
* This function returns the load factor of the hash map.
* @param hash_map a hash map.
* @return the hash map's load factor, -1 if the function failed.
*/
double hashmap_get_load_factor (const hashmap *hash_map){
if (hash_map == NULL){
return LOAD_FACTOR_ERR;
}
return (double) hash_map->size / (double) hash_map->capacity;
}
/**
* This function receives a hashmap and 2 functions, the first checks a condition on the keys,
* and the seconds apply some modification on the values. The function should apply the modification
* only on the values that are associated with keys that meet the condition.
*
* Example: if the hashmap maps char->int, keyT_func checks if the char is a capital letter (A-Z),
* and val_t_func multiples the number by 2, hashmap_apply_if will change the map:
* {('C',2),('#',3),('X',5)}, to: {('C',4),('#',3),('X',10)}, and the return value will be 2.
* @param hash_map a hashmap
* @param keyT_func a function that checks a condition on keyT and return 1 if true, 0 else
* @param valT_func a function that modifies valueT, in-place
* @return number of changed values
*/
int hashmap_apply_if (const hashmap *hash_map, keyT_func keyT_func,
valueT_func valT_func){
int changed_values = 0;
for (int i = 0; i < hash_map->capacity ; ++i) {
//get the current vector
vector* cur_vector = hash_map->buckets[i];
for (int j = 0; j < cur_vector->size; ++j) {
//get the cur pair
pair* cur_pair = vector_at(cur_vector, j);
// check if the condition applies on the cur pair key
if (keyT_func(cur_pair->key) == true){
// the condition applies so activate the val func on the cur
// pair value.
valT_func(cur_pair->value);
changed_values += 1;
}
}
}
return changed_values;
}
|
C#
|
UTF-8
| 682
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
namespace Radical.Windows.Messaging
{
#pragma warning disable 0618
/// <summary>
/// Domain event that identifies that a view model has been closed.
/// </summary>
public class ViewModelClosed
{
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelClosed"/> class.
/// </summary>
/// <param name="viewModel">The view model.</param>
public ViewModelClosed(object viewModel )
{
ViewModel = viewModel;
}
/// <summary>
/// Gets the view model.
/// </summary>
public object ViewModel { get; private set; }
}
#pragma warning restore 0618
}
|
Java
|
UTF-8
| 798
| 1.734375
| 2
|
[] |
no_license
|
package de.hawhamburg.microservices.composite.revenue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* Created by unknown on 27.10.15.
*/
//SOF TODO enable client in live system
//@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan({"de.hawhamburg.microservices.composite.revenue", "se.callista.microservices.util","de.hawhamburg.microservices.composite.price"})
//@ComponentScan({"de.hawhamburg.microservices.composite.revenue", "se.callista.microservices.util"})
public class RevenueCompositeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(RevenueCompositeServiceApplication.class,args);
}
}
|
C#
|
UTF-8
| 1,301
| 2.75
| 3
|
[] |
no_license
|
using Flower.Extensions.Validators;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Flower.Models
{
[Table("Customer")]
public class Customer
{
[Key]
[Display(Name = "ID")]
public int CustomerID { get; set; }
[Capitalized]
[Required(ErrorMessage = "Enter Name")]
public string Name { get; set; }
[Capitalized]
[Required(ErrorMessage = "Enter Surname")]
public string Surname { get; set; }
[PhoneCheck]
[Required(ErrorMessage = "Enter Phone")]
public string Phone { get; set; }
[Email]
[Required(ErrorMessage = "Enter Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Enter Country Name")]
public string Country { get; set; }
[Required(ErrorMessage = "Enter City Name")]
public string City { get; set; }
[Display(Name = "Purchases")]
public ICollection<Purchase> Purchases { get; set; }
public string FullName
{
get
{
return Name + " " + Surname;
}
}
}
}
|
Java
|
UTF-8
| 1,134
| 2.5
| 2
|
[] |
no_license
|
package com.example.thymeleaf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.print.DocFlavor;
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model){
model.addAttribute("data","cl");
return "cl";
}
@GetMapping("hello-mvc")
public String hello_mvc(@RequestParam(required = false) String name, Model model){
model.addAttribute("name", name);
return "name";
}
@GetMapping("hello-api")
@ResponseBody
public Apple helloApi(@RequestParam String sentence){
Apple apple = new Apple();
apple.setApple(sentence);
return apple;
}
static class Apple{
private String apple;
public String getApple() {
return apple;
}
public void setApple(String apple) {
this.apple = apple;
}
}
}
|
C++
|
UTF-8
| 297
| 3.109375
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
int main() {
int v = 10;
//program asks for the memory MMU
//then memory address is returned
int *address; //how to declare pointer
address = &v; //return address of the memory location
cout << address << endl; //outs location
return 0;
}
|
TypeScript
|
UTF-8
| 8,384
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
import { timeWeek, timeDays, timeDay } from 'd3-time'
import { timeFormat } from 'd3-time-format'
import { DateOrString } from '../types'
import { isDate } from 'lodash'
// Interfaces
interface ComputeBaseProps {
direction: 'horizontal' | 'vertical'
}
interface ComputeBaseSpaceProps {
daySpacing: number
offset: number
}
interface ComputeBaseDimensionProps {
cellWidth: number
cellHeight: number
}
interface ComputeCellSize extends ComputeBaseProps, ComputeBaseSpaceProps {
totalDays: number
width: number
height: number
square: boolean
}
interface ComputeCellPositions
extends ComputeBaseProps,
ComputeBaseSpaceProps,
ComputeBaseDimensionProps {
from?: DateOrString
to?: DateOrString
data: {
date: Date
day: string
value: number
}[]
colorScale: (value: number) => string
emptyColor: string
}
interface ComputeWeekdays
extends Omit<ComputeBaseProps, 'daysInRange'>,
Omit<ComputeBaseSpaceProps, 'offset'>,
ComputeBaseDimensionProps {
ticks?: number[]
arrayOfWeekdays?: string[]
}
interface Day {
coordinates: {
x: number
y: number
}
firstWeek: number
month: number
year: number
date: Date
color: string
day: string
value?: number
}
interface Month {
date: Date
bbox: {
x: number
y: number
width: number
height: number
}
firstWeek: number
month: number
year: number
}
interface ComputeMonths
extends ComputeBaseProps,
Omit<ComputeBaseSpaceProps, 'offset'>,
ComputeBaseDimensionProps {
days: Day[]
}
interface ComputeTotalDays {
from?: DateOrString
to?: DateOrString
data: {
date: Date
day: string
value: number
}[]
}
// used for days range and data matching
const dayFormat = timeFormat('%Y-%m-%d')
/**
* Compute day cell size according to
* current context.
*/
export const computeCellSize = ({
direction,
daySpacing,
offset,
square,
totalDays,
width,
height,
}: ComputeCellSize) => {
const daysInRange = 7
let rows
let columns
let widthRest = width
let heightRest = height
if (direction === 'horizontal') {
widthRest -= offset
rows = daysInRange
columns = Math.ceil(totalDays / daysInRange)
} else {
heightRest -= offset
columns = daysInRange
rows = Math.ceil(totalDays / daysInRange)
}
// + 1 since we have to apply spacing to the rigth and left
const cellHeight = (heightRest - daySpacing * (rows + 1)) / rows
const cellWidth = (widthRest - daySpacing * (columns + 1)) / columns
// do we want square?
const size = Math.min(cellHeight, cellWidth)
return {
columns,
rows,
cellHeight: square ? size : cellHeight,
cellWidth: square ? size : cellWidth,
}
}
function computeGrid({
startDate,
date,
direction,
}: {
startDate: Date
date: Date
direction: 'horizontal' | 'vertical'
}) {
const firstWeek = timeWeek.count(startDate, date)
const month = date.getMonth()
const year = date.getFullYear()
let currentColumn = 0
let currentRow = 0
if (direction === 'horizontal') {
currentColumn = firstWeek
currentRow = date.getDay()
} else {
currentColumn = date.getDay()
currentRow = firstWeek
}
return { currentColumn, year, currentRow, firstWeek, month, date }
}
export const computeCellPositions = ({
direction,
colorScale,
emptyColor,
from,
to,
data,
cellWidth,
cellHeight,
daySpacing,
offset,
}: ComputeCellPositions) => {
let x = daySpacing
let y = daySpacing
if (direction === 'horizontal') {
x += offset
} else {
y += offset
}
// we need to determine whether we need to add days to move to correct position
const start = from ? from : data[0].date
const end = to ? to : data[data.length - 1].date
const startDate = isDate(start) ? start : new Date(start)
const endDate = isDate(end) ? end : new Date(end)
const dateRange = timeDays(startDate, endDate).map(dayDate => {
return {
date: dayDate,
day: dayFormat(dayDate),
}
})
const dataWithCellPosition = dateRange.map(day => {
const dayData = data.find(item => item.day === day.day)
const { currentColumn, currentRow, firstWeek, year, month, date } = computeGrid({
startDate,
date: day.date,
direction,
})
const coordinates = {
x: x + daySpacing * currentColumn + cellWidth * currentColumn,
y: y + daySpacing * currentRow + cellHeight * currentRow,
}
if (!dayData) {
return {
...day,
coordinates,
firstWeek,
month,
year,
date,
color: emptyColor,
width: cellWidth,
height: cellHeight,
}
}
return {
...dayData,
coordinates,
firstWeek,
month,
year,
date,
color: colorScale(dayData.value),
width: cellWidth,
height: cellHeight,
}
})
return dataWithCellPosition
}
export const computeWeekdays = ({
cellHeight,
cellWidth,
direction,
daySpacing,
ticks = [1, 3, 5],
arrayOfWeekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
],
}: ComputeWeekdays) => {
const sizes = {
width: cellWidth + daySpacing,
height: cellHeight + daySpacing,
}
return ticks.map(day => ({
value: arrayOfWeekdays[day],
rotation: direction === 'horizontal' ? 0 : -90,
y: direction === 'horizontal' ? sizes.height * (day + 1) - sizes.height / 3 : 0,
x: direction === 'horizontal' ? 0 : sizes.width * (day + 1) - sizes.width / 3,
}))
}
export const computeMonthLegends = ({
direction,
daySpacing,
days,
cellHeight,
cellWidth,
}: ComputeMonths) => {
const accumulator: {
months: { [key: string]: Month }
weeks: Day[]
} = {
months: {},
weeks: [],
}
return days.reduce((acc, day) => {
if (acc.weeks.length === day.firstWeek) {
acc.weeks.push(day)
const key = `${day.year}-${day.month}`
if (!Object.keys(acc.months).includes(key)) {
const bbox = { x: 0, y: 0, width: 0, height: 0 }
if (direction === 'horizontal') {
bbox.x = day.coordinates.x - daySpacing
bbox.height = cellHeight + daySpacing
bbox.width = cellWidth + daySpacing * 2
} else {
bbox.y = day.coordinates.y - daySpacing
bbox.height = cellHeight + daySpacing * 2
bbox.width = cellWidth + daySpacing * 2
}
acc.months[key] = {
date: day.date,
bbox,
firstWeek: day.firstWeek,
month: 0,
year: 0,
}
} else {
// enhance width/height
if (direction === 'horizontal') {
acc.months[key].bbox.width =
(day.firstWeek - acc.months[key].firstWeek) * (cellWidth + daySpacing)
} else {
acc.months[key].bbox.height =
(day.firstWeek - acc.months[key].firstWeek) * (cellHeight + daySpacing)
}
}
}
return acc
}, accumulator)
}
export const computeTotalDays = ({ from, to, data }: ComputeTotalDays) => {
let startDate
let endDate
if (from) {
startDate = isDate(from) ? from : new Date(from)
} else {
startDate = data[0].date
}
if (from && to) {
endDate = isDate(to) ? to : new Date(to)
} else {
endDate = data[data.length - 1].date
}
return startDate.getDay() + timeDay.count(startDate, endDate)
}
|
Java
|
UTF-8
| 1,425
| 3.703125
| 4
|
[] |
no_license
|
package easy.other;
/**
* @Time : 2020年2月26日00:00:17
* @Author : yyw@ustc
* @E-mail : yang0@mail.ustc.edu.cn
* @Github : https://github.com/ustcyyw
* @desc :
*/
import java.util.HashSet;
/**
* 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
* <p>
* 示例1:
* <p>
* 输入: 5
* 输出: True
* 解释: 1 * 1 + 2 * 2 = 5
*
* <p>
* 示例2:
* <p>
* 输入: 3
* 输出: False
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/sum-of-square-numbers
*/
public class judgeSquareSum633 {
/**
* 执行用时 :5 ms, 在所有 Java 提交中击败了36.36%的用户
* 内存消耗 :36.3 MB, 在所有 Java 提交中击败了5.18%的用户
*/
public boolean judgeSquareSum(int c) {
int end = (int) Math.sqrt(c);
for (int i = 0; i <= end; i++) {
double temp = Math.sqrt(c - i * i);
if (temp == (int) temp)
return true;
}
return false;
}
/**
* 其它人解法
*/
public boolean judgeSquareSum2(int c){
int end = (int) Math.sqrt(c);
int start = 0;
while(start <= end){
int temp = start * start + end * end;
if(temp == c)
return true;
else if(temp < c)
start++;
else end--;
}
return false;
}
}
|
Java
|
UTF-8
| 3,657
| 2.59375
| 3
|
[] |
no_license
|
package create.data;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Random;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.TreeModel;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import config.EntityConfig;
import config.FileConfig;
import entities.Time;
import read.file.FileReader;
import store.data.StoreData;
/**
* Tạo ngẫu nhiên các thực thể Time và lưu vào database.
*
* @author Viet Hung
*
*/
public class TimeCreator {
// Mảng lưu trữ tên hiển thị, mô tả, ngày tháng trích rút link của thực thể thời gian
private ArrayList<String> listTimeLabel;
private ArrayList<String> listTimeDescription;
private ArrayList<String> listTimeDate;
// Đối tượng định dạng ngày tháng
private DateTimeFormatter dtf;
// Lưu trữ các triple để chuẩn bị lưu vào cơ sở dữ liệu
Model model;
/**
* Constructor: khi tạo mới một đối tượng Time thì cũng đọc file tương
* ứng với đối tượng Time và cập nhật vào các mảng tương ứng.
*/
public TimeCreator() {
FileReader fileReader = new FileReader();
dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
model = new TreeModel();
listTimeLabel = fileReader.readData(FileConfig.FILE_TIME_LABEL);
listTimeDescription = fileReader.readData(FileConfig.FILE_TIME_DESCRIPTION);
listTimeDate = fileReader.readData(FileConfig.FILE_TIME_DATE);
}
/**
* Tạo ngẫu nhiên một đối tượng Time với các dữ liệu đọc được từ file.
*
* @param timeId
* số Identifier của đối tượng Time.
* @return đối tượng Time vừa tạo.
*/
public Time randomTime(int timeId) {
Random random = new Random();
int randomRange = listTimeLabel.size() - 1;
// Random số trong đoạn [0, randoRange]
int index = random.nextInt(randomRange);
String id = EntityConfig.TIME_ID + Integer.toString(timeId);
String name = listTimeLabel.get(index);
String description = listTimeDescription.get(index);
String link = EntityConfig.TIME_LINK + id;
LocalDate date = LocalDate.parse(listTimeDate.get(index), dtf);
Time time = new Time(id, name, description, link, date);
return time;
}
/**
* Tạo ra một số lượng Time và thêm vào database.
*
* @param numberTime
* Số lượng Time muốn tạo.
* @param conn:
* kết nối đến repository của GraphDB.
* @return : list các IRI Id của Time đã thêm vào Database.
*/
public ArrayList<IRI> createTime(int numberTime, RepositoryConnection conn) {
ValueFactory vf = conn.getValueFactory();
StoreData storeData = new StoreData();
ArrayList<IRI> listTimeIri = new ArrayList<IRI>();
int count = 1;
for (int i = 1; i <= numberTime; i++) {
Time time = randomTime(i);
IRI timeIri = storeData.addToModel(time, vf, model);
listTimeIri.add(timeIri);
if (i % 10000 == 0) {
try {
storeData.addToDB(model, conn);
model.clear();
System.out.println("Đã thêm 10000 Time lần " + count);
count++;
} catch (Exception e) {
e.getMessage();
}
}
}
// Lưu model vào cơ sở dữ liệu
try {
conn.add(model);
} catch (Exception e) {
e.getMessage();
}
System.out.println("Đã thêm vào cơ sở dữ liệu");
return listTimeIri;
}
}
|
Shell
|
UTF-8
| 335
| 2.734375
| 3
|
[] |
no_license
|
# run following function to remove carriage returns in Windows:
# d2u signJars.sh
shopt -s nullglob
# cd dist
for f in *.jar
do
jarsigner -keystore jnlpKey -storepass abcdef $f jdc
echo "signed dist/$f"
done
cd lib
for f in *.jar
do
jarsigner -keystore ../jnlpKey -storepass abcdef $f jdc
echo "signed dist/lib/$f"
done
|
Markdown
|
UTF-8
| 1,893
| 2.671875
| 3
|
[] |
no_license
|
---
date: 2015-03-15T19:22:05+09:00
draft: true
title: google-code-prettifyでコードブロックをかっこよくする
---
このライブラリ以外にも[SyntaxHighlighter](http://alexgorbatchev.com/SyntaxHighlighter)とか強力なものもあるが、複数のスクリプトを読む必要があったり(結合すればいいんだが)でややめんどくさい。
その点、google-code-prettifyは1スクリプトの読み込みだけでOKだし、シンプルなのでこれで十分だと思ってる。
### 準備
下記スクリプトを追加しておく。
```
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
```
### 利用
表示させるコードをタグで囲う。
```
<pre class="prettyprint linenums">
function say(str) {
console.log("hello " + str);
}
say("world");
</pre>
```
表示は次のようになる。
```
function say(str) {
console.log("hello " + str);
}
say("world");
```
スクリプトがクラス`prettyprint`を見つけ出してスタイルをあてている。
クラス`linenums`は行番号の表示を意味する。
### カスタマイズ
エディタで毎回コードを`<pre class="prettyprint linenums"></pre>`で囲うのは面倒なので、`<pre></pre>`を見つけたら動的に`prettyprint linenums`クラスを付加するようにする。
```
<script type="text/javascript">
$("pre").addClass("prettyprint linenums");
</script>
```
### まとめ
google-code-prettifyを用いてコードブロックをかっこよく整形した。
外部エディタを用いてMarkdownで書いたものをtumblrに投稿するとエディタによって展開のされ方が違ったりしてやや手こずった。
今度はHTML/CSS/Javascriptをセットにしたモジュールとか表示させてみようかな。
|
Python
|
UTF-8
| 1,069
| 4.25
| 4
|
[] |
no_license
|
def greet(name, time_of_day):
return "Good " + time_of_day + ", " + name
name_1 = "David"
time_of_day_1 = "afternoon"
greeting = greet(name_1, time_of_day_1)
print(greeting)
name_2 = "Kyle"
time_of_day_2 = "evening"
greeting = greet(name_2, time_of_day_2)
print(greeting)
chickens = [
{ "name": "Margaret", "age": 2, "eggs": 0 },
{ "name": "Hetty", "age": 1, "eggs": 2 },
{ "name": "Henrietta", "age": 3, "eggs": 1 },
{ "name": "Audrey", "age": 2, "eggs": 0 },
{ "name": "Mabel", "age": 5, "eggs": 1 },
]
chickens_2 = [
{ "name": "Davinia", "age": 4, "eggs": 3 },
{ "name": "Kylie", "age": 2, "eggs": 6 },
{ "name": "Jo", "age": 2, "eggs": 2 },
{ "name": "Rose", "age": 3, "eggs": 0 },
{ "name": "Agnes", "age": 5, "eggs": 2 },
]
def count_eggs( list ):
total_eggs = 0
for bird in list:
total_eggs += bird["eggs"]
bird["eggs"] = 0 # eggs have been collected
return f"{total_eggs} eggs collected"
print(count_eggs(chickens))
print(count_eggs(chickens_2))
for chicken in chickens_2:
print(chicken["name"])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.