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
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 1,162 | 3.09375 | 3 |
[] |
no_license
|
from nufi.basefilters import Summer, Counter
class Mean(Summer, Counter):
def __init__(self):
Summer.__init__(self)
Counter.__init__(self)
def process(self, number):
Summer.process(self, number)
Counter.process(self, number)
def output(self):
print float(self.total) / self.count
class Sum(Summer):
def __init__(self):
Summer.__init__(self)
def process(self, number):
Summer.process(self, number)
def output(self):
print self.total
class Min:
def __init__(self):
self.minimum = 0
self.first = True
def process(self, number):
if self.first or number < self.minimum:
self.minimum = number
if self.first:
self.first = False
def output(self):
print self.minimum
class Max:
def __init__(self):
self.maximum = 0
self.first = True
def process(self, number):
if self.first or number > self.maximum:
self.maximum = number
if self.first:
self.first = False
def output(self):
print self.maximum
|
C++
|
UTF-8
| 1,963 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#include "vertex_binding.hpp"
#include "vertex_layout.hpp"
#include "buffer.hpp"
_agpu_vertex_binding::_agpu_vertex_binding()
{
}
void _agpu_vertex_binding::lostReferences()
{
// Release vertex buffer references.
for (auto buffer : vertexBuffers)
{
if (buffer)
buffer->release();
}
}
agpu_vertex_binding* _agpu_vertex_binding::create(agpu_device* device, agpu_vertex_layout *layout)
{
if (!layout)
return nullptr;
auto binding = new agpu_vertex_binding();
binding->device = device;
binding->layout = layout;
binding->vertexBufferViews.resize(layout->vertexBufferCount);
binding->vertexBuffers.resize(layout->vertexBufferCount);
return binding;
}
agpu_error _agpu_vertex_binding::bindVertexBuffers(agpu_uint count, agpu_buffer** vertex_buffers)
{
CHECK_POINTER(vertex_buffers);
if (count != layout->vertexBufferCount)
return AGPU_ERROR;
for (agpu_uint i = 0; i < count; ++i)
{
auto buffer = vertex_buffers[i];
if (!buffer)
return AGPU_ERROR;
// Store a reference to the vertex buffer
buffer->retain();
if (vertexBuffers[i])
vertexBuffers[i]->release();
vertexBuffers[i] = buffer;
// Store the view.
vertexBufferViews[i] = buffer->view.vertexBuffer;
}
return AGPU_OK;
}
// Exported C interface
AGPU_EXPORT agpu_error agpuAddVertexBindingReference(agpu_vertex_binding* vertex_binding)
{
CHECK_POINTER(vertex_binding);
return vertex_binding->retain();
}
AGPU_EXPORT agpu_error agpuReleaseVertexBinding(agpu_vertex_binding* vertex_binding)
{
CHECK_POINTER(vertex_binding);
return vertex_binding->release();
}
AGPU_EXPORT agpu_error agpuBindVertexBuffers(agpu_vertex_binding* vertex_binding, agpu_uint count, agpu_buffer** vertex_buffers)
{
CHECK_POINTER(vertex_binding);
return vertex_binding->bindVertexBuffers(count, vertex_buffers);
}
|
Python
|
UTF-8
| 4,904 | 2.78125 | 3 |
[] |
no_license
|
import wx
from db_script import SQLiteDatabase, RedisDatabase
class CustomFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Yo!')
# Здесь вместо SQLiteDatabase можно указать RedisDatabase при условии, что у вас работает локальный
# Redis-сервер
self.db = SQLiteDatabase()
self.dict = self.db.load_data()
self.state = 1
self.current_table = None
#self.SetMinSize((700, 700))
#self.SetMaxSize((700, 700))
self.SetSize((700, 700))
panel1 = wx.Panel(self)
btnPanel = wx.Panel(panel1)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
self.list_wgt = wx.ListBox(panel1)
self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnListBoxDClick, self.list_wgt)
self.list_wgt.SetFont(wx.Font(25, wx.DEFAULT, wx.DEFAULT, wx.DEFAULT))
hbox1.Add(self.list_wgt, wx.ID_ANY, wx.EXPAND | wx.ALL)
self.TablesButton = wx.Button(btnPanel, label='These are Tables', size=(90, 30))
self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.TablesButton)
self.NewButton = wx.Button(btnPanel, label='New', size=(90, 30))
self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.NewButton)
self.DeleteButton = wx.Button(btnPanel, label='Delete', size=(90, 30))
self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.DeleteButton)
vbox1 = wx.BoxSizer(wx.VERTICAL)
vbox1.Add(self.TablesButton, wx.ID_ANY)
vbox1.Add(self.NewButton, wx.ID_ANY)
vbox1.Add(self.DeleteButton, wx.ID_ANY)
btnPanel.SetSizer(vbox1)
hbox1.Add(btnPanel, 0.6, wx.EXPAND | wx.RIGHT, 20)
panel1.SetSizer(hbox1)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self._update_tables()
self.Show()
def OnButtonClick(self, e: wx.Event):
source = e.GetEventObject()
if source == self.TablesButton:
self.state = 1
self.TablesButton.SetLabel('These are Tables')
self.current_table = None
self._update_tables()
elif source == self.NewButton:
if self.state == 1:
new_table_name = wx.GetTextFromUser('Enter a new table name', 'Create a new table')
if new_table_name == '':
return
self.dict[new_table_name] = list()
self._update_tables()
elif self.state == 2:
selected_table = self.current_table
new_article_text = wx.GetTextFromUser('Enter a new article text', 'Create an article')
if new_article_text == '':
return
articles_list = self.dict[selected_table]
articles_list.append(new_article_text)
self.dict[selected_table] = articles_list
self._update_articles(selected_table)
elif source == self.DeleteButton:
if self.state == 1:
table_name = self.list_wgt.GetStringSelection()
del self.dict[table_name]
self._update_tables()
elif self.state == 2:
selected_table = self.current_table
selected_text = self.list_wgt.GetStringSelection()
articles_list = self.dict[selected_table]
for x in range(len(articles_list)):
if articles_list[x] == selected_text:
articles_list.pop(x)
break
self._update_articles(selected_table)
def OnListBoxDClick(self, e):
if self.state == 1:
selected_table = self.list_wgt.GetStringSelection()
self._update_articles(selected_table)
self.state = 2
self.TablesButton.SetLabel('These are Articles')
self.current_table = selected_table
elif self.state == 2:
selected_text = self.list_wgt.GetStringSelection()
selected_table = self.current_table
edit_text = wx.GetTextFromUser('Edit text')
if edit_text == '':
return
articles_list = self.dict[selected_table]
for x in range(len(articles_list)):
if articles_list[x] == selected_text:
articles_list[x] = edit_text
self.dict[selected_table] = articles_list
self._update_articles(selected_table)
def _update_articles(self, selected_table):
self.list_wgt.Clear()
articles = self.dict[selected_table]
for x in articles:
self.list_wgt.Append(x)
def _update_tables(self):
self.list_wgt.Clear()
entries = self.dict.keys()
for x in entries:
self.list_wgt.Append(x)
def OnClose(self, e):
self.db.save_data(self.dict)
self.Destroy()
|
JavaScript
|
UTF-8
| 422 | 4.53125 | 5 |
[] |
no_license
|
//create secretNumber
var secretNumber = 24;
//asks user for guess
var stringGuess = prompt("Guess a number");
//converts the input from string to number
var guess = Number(stringGuess);
//checks if guess is right
if(guess === secretNumber) {
alert("YOU GOT IT RITGHT");
}
//checks if guess is higher
else if(guess > secretNumber){
alert("Too high. Guess again.");
}
else {
alert("Too low. Guess again!");
}
|
Python
|
UTF-8
| 2,103 | 3.8125 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
""" A Program to find the anagram words from a file """
# Importing collections
from collections import OrderedDict
# importing itertools.groupby
# Itertools is used to handle iterators operation fastly
from itertools import groupby
# To get execution time imported time module
import time
# Defined the start time of the program
start_time = time.time()
try:
# Opening the file anagram.txt to get the words
with open("anagram.txt") as fileobj:
words = fileobj.read().splitlines()
except FileNotFoundError as e:
print(e)
# *************************************************** #
# Processing to find anagram words
# Step 1 - dividing the large file into small sub files
# Finding the len of the words and storing it in the words_len
words_len = list(map(len, words))
# Framimg a dictionary containing the words as keys and len as their values
final_word_dict = dict(zip(words, words_len))
# Sorting the dictionary according to length
final_word_dict = dict(OrderedDict(sorted(final_word_dict.items(),key=lambda x: x[1])))
# Storing the unique lenght from the dictionary
unique_len = set(final_word_dict.values())
# Modified word list
modified_word_list = []
# Used as index for modified_word_list in for loop
count = 0
# dividing the dictionary on the basis of length
for var in unique_len:
modified_word_list.append([])
for k, v in final_word_dict.items():
if v == var:
modified_word_list[count].append(k)
count += 1
# Step2 - to find anagram words from modified list
# set to hold anagram words
anagram_words = []
# Function to filter anagram words
anagram_filter = lambda w: sorted(w)
# applying loop and groupby functions going to seperate anagrams and non-anagrams words
for var2 in modified_word_list:
anagram_words.extend([list(v) for k, v in groupby(sorted(var2, key=anagram_filter), anagram_filter)])
# Extracting the anagrams words by list comphrehension
anagram_words = [x for lis in anagram_words if len(lis) > 1 for x in lis]
# To get the final execution time
print(time.time() - start_time)
|
Python
|
UTF-8
| 3,350 | 2.9375 | 3 |
[] |
no_license
|
import math
from objects import symbol, bar
#standard
#narrow = 0.5
#wide = 1.0
#half time
narrow = 1.0
wide = 2.0
#defining the integer symbols
symbol0 = ['n','n','w','w','n']
symbol1 = ['w','n','n','n','w']
symbol2 = ['n','w','n','n','w']
symbol3 = ['w','w','n','n','n']
symbol4 = ['n','n','w','n','w']
symbol5 = ['w','n','w','n','n']
symbol6 = ['n','w','w','n','n']
symbol7 = ['n','n','n','w','w']
symbol8 = ['w','n','n','w','n']
symbol9 = ['n','w','n','w','n']
#appending the integer symbols
symbols = [symbol0,symbol1,symbol2,symbol3,symbol4,symbol5,symbol6,symbol7,symbol8,symbol9]
#special symbols
frameIdentifier1 = symbol(value=-1,bars=[
bar(False),
bar(False),
bar(True),
bar(False),
bar(False),
bar(False),
bar(False),
bar(True),
bar(False),
bar(True),
bar(False),
bar(True),
bar(False),
bar(False),
bar(False),
bar(False)])
#frameIdentifier2 = Symbol(value=-2,bars=[Bar(False),Bar(False),Bar(True),Bar(False),Bar(True),Bar(False),Bar(True),Bar(False),Bar(False),Bar(False),Bar(False),Bar(False)])
#frameIdentifier3 = Symbol(value=-3,bars=[Bar(False),Bar(False),Bar(True),Bar(False),Bar(True),Bar(False),Bar(True),Bar(False),Bar(False),Bar(False),Bar(False),Bar(False),Bar(False)])
identifiers = [frameIdentifier1]
def generateIdentifiers():
return identifiers
def generateSymbols():
newSymbols = []
for i in range(100): #for all of the possible symbols
#print int(math.floor(i/10)),i % 10
peaks = symbols[int(math.floor(i/10))]
valleys = symbols[i % 10]
bars = []
for j in range(len(peaks)):
wide = False
if peaks[j] == 'w':
wide = True
bars.append(bar(True,wide=wide))
wide = False
if valleys[j] == 'w':
wide = True
bars.append(bar(False,wide=wide))
newSymbols.append(symbol(value=i,bars=bars))
return newSymbols
# def write(chirps,path='./',fileName='symbols.xml'):
# import os
# path = os.path.join(path,fileName)
# if not os.path.isdir(os.path.dirname(path)):
# raise IOError('Path is not valid')
# myFile = file(path,'w')
# writer = MarkupWriter(myFile,indent=u'yes')
# writer.startDocument()
# writer.xmlFragment('<?xml-stylesheet type="text/xsl" href="teledrill.xsl"?>\n')
# writer.startElement(u'Symbols')
# for c in chirps:
# c.writeToXml(writer)
# writer.endElement(u'Symbols')
# writer.endDocument()
# myFile.close()
# return path
if __name__ == '__main__':
symbols = generateSymbols()
test_frame1_data = [symbols[0],symbols[1]]
test_frame1 = [frameIdentifier1,symbols[0],symbols[1]]
test_sequence = [
frameIdentifier1,
symbols[10],
symbols[0],
symbols[8],
frameIdentifier1,
symbols[11],
symbols[1],
symbols[27],
frameIdentifier1,
symbols[12],
symbols[0],
symbols[15],
frameIdentifier1,
symbols[13],
symbols[10],
frameIdentifier1,
]
#print generateSymbols()
#print generateIdentifiers()
|
Markdown
|
UTF-8
| 1,712 | 4.25 | 4 |
[] |
no_license
|
# JS - Object Array 賦值問題
## 關於我遇到的問題
這是我在寫小 DEMO 發現的,關於 JS 的賦值問題,這裡涉及到了 Pointer。
下面是我用簡單的 Code 描述我遇到的問題,`object` 是一個 Object Array,然後傳入函數進行局域變量賦值。
```js
let object = [
{
name: "John",
age: 18
},
{
name: "Amy",
age: 20
},
]
function Test(object) {
let newOne = object;
for (let i = 0; i < newOne.length; i++) {
newOne[i].name = "Rose";
}
}
Test(object)
console.log(object)
```
結果輸出如下:
```js
// object
[
{
name: "Rose",
age: 18
},
{
name: "Rose",
age: 20
},
]
```
從這個輸出結果來看,我們可以判定,這個函式**修改 `newOne` 這個局部變量時,也修改到了 `object`**。
我網上爬了文,大致知道這是 JS 的一個像是語法 Bug 的問題,**賦值給 `newOne` 時其實是給了指針位置,所以導致修改 `newOne` 時也修改到了 `object`**。
所以要改寫成下面的寫法:
利用聲明一個臨時局部變量然後賦值,再 Push 進 Array。
```js
let object = [
{
name: "John",
age: 18
},
{
name: "Amy",
age: 20
},
]
function Test(object) {
let newOne = [];
for (let i = 0; i < object.length; i++) {
let temp = {
name: "Rose",
age: object[i].age
}
newOne.push(temp);
}
}
Test(object)
console.log(object)
```
輸出結果:
```js
// object
[
{
name: "John",
age: 18
},
{
name: "Amy",
age: 20
},
]
```
|
Java
|
UTF-8
| 450 | 1.78125 | 2 |
[] |
no_license
|
package com.censpeed.shop.mapper;
import com.censpeed.shop.entity.CHomePage;
import java.util.List;
public interface CHomePageMapper {
int deleteByPrimaryKey(Integer id);
int insert(CHomePage record);
int insertSelective(CHomePage record);
CHomePage selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(CHomePage record);
int updateByPrimaryKey(CHomePage record);
List<CHomePage> selectAllHomePage();
}
|
JavaScript
|
UTF-8
| 2,973 | 2.71875 | 3 |
[] |
no_license
|
/***********************
* Adobe Edge Animate Composition Actions
*
* Edit this file with caution, being careful to preserve
* function signatures and comments starting with 'Edge' to maintain the
* ability to interact with these actions from within Adobe Edge Animate
*
***********************/
(function($, Edge, compId){
var Composition = Edge.Composition, Symbol = Edge.Symbol; // aliases for commonly used Edge classes
//Edge symbol: 'stage'
(function(symbolName) {
Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 0, function(sym, e) {
sym.stop();
});
//Edge binding end
Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 1500, function(sym, e) {
sym.stop();
});
//Edge binding end
Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 1000, function(sym, e) {
sym.stop();
});
//Edge binding end
Symbol.bindTriggerAction(compId, symbolName, "Default Timeline", 500, function(sym, e) {
sym.stop();
});
//Edge binding end
Symbol.bindElementAction(compId, symbolName, "${btn_Next}", "click", function(sym, e) {
var imgCount = sym.getVariable("imgCount");
if (imgCount == 4) {
imgCount = 1;
} else {
imgCount = imgCount + 1;
};
sym.$("container").html("<img src='images/img00"+imgCount+".jpg'>"+"</img>");
sym.setVariable("imgCount", imgCount);
sym.play();
});
//Edge binding end
Symbol.bindElementAction(compId, symbolName, "${btn_Prev}", "click", function(sym, e) {
var imgCount = sym.getVariable("imgCount");
if (imgCount <= 1) {
imgCount = 4;
} else {
imgCount = imgCount - 1;
};
sym.$("container").html("<img src='images/img00"+imgCount+".jpg'>"+"</img>");
sym.setVariable("imgCount", imgCount);
sym.playReverse();
});
//Edge binding end
Symbol.bindSymbolAction(compId, symbolName, "creationComplete", function(sym, e) {
var imgCount = 0;
sym.setVariable("imgCount", imgCount);
});
//Edge binding end
Symbol.bindElementAction(compId, symbolName, "${container}", "click", function(sym, e) {
/*
var imgCount = sym.getVariable("imgCount");
sym.$("container").html("<img src='images/img00"+imgCount+".jpg'>"+"</img>");
if (imgCount > 3) {
imgCount = 1;
} else {
imgCount = imgCount + 1;
};
sym.setVariable("imgCount", imgCount);
console.log(imgCount);
*/
});
//Edge binding end
})("stage");
//Edge symbol end:'stage'
})(window.jQuery || AdobeEdge.$, AdobeEdge, "EDGE-205935031");
|
Markdown
|
UTF-8
| 13,149 | 3.53125 | 4 |
[] |
no_license
|
---
layout: post
title: "Beersweeper with React and Jest"
---
Over the weekend, I worked on a browser-based minesweeper clone called Beersweeper. The main focus was to practice TDD and learn Jest. Jest is Facebook's javascript unit testing framework, and it works well with React. They use Jasmine 1.X as the lower level framework, which is nice, although Jasmine 2.X has a bit cleaner API for async operations.
I'm not a big fan of TDD, having tried it in the past. One could attribute that to my own laziness mostly. It requires writing software in way that is testable, which is a noble goal. But sometimes it adds unnecessary complexity in software design. The other issue has been testing UI components, however that is less of an issue with newer unit-testing frameworks, such as Karma and Jest.
In terms of pros for TDD:
- Writing the tests first makes sure that they get written. Leaving until later usually results in no tests.
- Writing testable code does end up making the code more flexible in the long run since dependency injection (constructor injection, etc) is necessary for the code to be testable.
- The tests are self-documenting and provide usage examples.
- Also if working in a team, there's less worry about breaking other parts of the code.
- Tests are going to be required if you're developing serious software.
Whether TDD is the best solution, I don't know, but I definitely know that testing is an aspect of Software Engineering.
**Fig. 1 - Beersweeper gameplay screenshot**

For this project, I used a simplified Flux architecture. Basically I simply allowed components to directly call actions on the Store object. Normally action creators and dispatchers are used, but this game does not use any AJAX calls and does not need to dispatch actions to multiple stores. This keeps the one-way binding, but removes unnecessary layers of abstraction.
**Fig. 2 - Beersweeper diagram**

The game is broken up into three modules. The idea is to separate the logic and data from the view. The GameStore acts sort of like a controller in this case.
This makes testing the logic with units tests much easier and can allow for alternate UIs to be used.
#### GameEngine
Just a bunch of functions that operate on the Minesweeper board model. Functionality includes:
- Generating a board of Y height and X width
- Adding mines
- Calculating the digits that indicate number of adjacent mines
- Correctly unvealing squares on the board after a square is clicked
- Checking for winners
#### GameStore
The GameStore is created from a GameFactory. This allows options to be passed into the store. For example, to change the dimensions of the board or the number of mines.
#### ReactApp
The ReactApp contains the following components:
- **App**: This is where the store data gets passed down to the various components. The other components get their data through props.
- **MinesweeperBoard**: Renders the minesweeper board with the correct number of squares
- **MinesweeperSquare**: Renders an individual square based on data passed from props
- **MineCounter**: Counts the number of mines remaining (total mines - flagged squares)
- **Timer**: Counts the time elapsed
**Fig. 3 - Beersweeper component layout**

### GameEngine
Since I've used Jasmine before, writing tests for the GameEngine was straightforward. There's not much to say, other than Jest provides good instructions on how to run the unit tests.
The GameEngine consists of a bunch of functions that operate on the minesweeper board model.
#### Data structure
The data structure used is a 2D-array of "squares," where "squares" are regular objects with two values:
1. The value of the square: Can be 0-9, where 0 is a blank square with no adjacent mines and 9 represents a mine. The numbers 1-8, represent the number of adjacent mines.
2. There is also a state value associated with the square. This can be hidden, visible, or flagged.
One could say that you only need to generate a board with 0 and 1, where 0 is for an empty square and 1 is for a square with a mine. The adjacency numbers could then be calculated each time, but the thing is that those numbers never change, so it makes sense to do this calculation once.
The state value seems controversial, but this data is integral to the logic of the game. For example flagged squares are not revealed even if the square is empty. In addition, the algorithm to reveal squares needs to know if the a square is hidden or visible. If it's visible, that's a signal to stop.
The data structure was designed as just data. All operations are handled through functions. Although it didn't work out perfectly, the idea was to make the data structure (array and squares) immutable, or at least treat them that way. This seems to have the benefit of making testing easier.
#### Generating mines
This function is relatively straightforward. It will throw an error if the number of mines is greater than the number of squares. This could cause an infinite loop.
The algorithm for generating the mines is: Randomly pick a y and x position. If it is empty, change the square to a mine. If it already contains a mine, repeat until an empty square is found.
```js
var generateMines = function(board, numMines) {
var size = getBoardSize(board);
if (numMines > size.width * size.height) {
throw "Number of mines is greater than board size";
}
var clonedBoard = cloneBoard(board);
for (var mineCount = 0; mineCount < numMines; ++mineCount) {
while (true) {
var y = Math.floor(Math.random() * size.height);
var x = Math.floor(Math.random() * size.width);
if (clonedBoard[y][x].value === SquareValue.EMPTY) {
clonedBoard[y][x] = createMineSquare();
break;
}
}
}
return clonedBoard;
};
```
#### Generating adjaceny numbers
The brute force way to do it is to manually look at each adjacent square, but this can be error prone and repetitive.
An interesting solution that I learned a few days ago is to create an array of the offsets and loop through them.
I added try and catch block to avoid edge cases, such as the top row or bottom row of squares. Although these are not exceptional cases, it's cleaner than using a convoluted if statement. Using try/except blocks like this is something that is advocated in Python code.
```js
var countAdjacentMines = function(board, y, x) {
var adjacentSquares = [
[-1, -1], [-1, 0], [-1, 1],
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1],
];
var mineCount = 0;
for (var i = 0; i < adjacentSquares.length; ++i) {
try {
var adjacentY = y + adjacentSquares[i][0];
var adjacentX = x + adjacentSquares[i][1];
if (board[adjacentY][adjacentX].value === SquareValue.MINE) {
++mineCount;
}
} catch (error) {}
}
return mineCount;
};
```
#### Revealing squares
In minesweeper, if you click on a square that is empty, then all adjacent squares will be revealed up to the numbered squares.
If you click on a numbered square, then only that square is revealed.
This can easily be done by thinking of the 2D array as a highly connected graph. Then a depth-first search with pre-order traversal can recursively reveal the squares. The algorithm stops whenever a numbered square is encountered.
```js
var revealSquares = function(board, y, x) {
var clonedBoard = cloneBoard(board);
var adjacentSquares = [
[-1, -1], [-1, 0], [-1, 1],
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1],
];
var _revealSquares = function(board, y, x) {
if (board[y][x].state === SquareState.VISIBLE || board[y][x].state === SquareState.FLAG) {
return;
}
if (board[y][x].value === SquareValue.MINE) {
return;
}
board[y][x].state = SquareState.VISIBLE;
if (board[y][x].value === SquareValue.EMPTY) {
for (var i = 0; i < adjacentSquares.length; ++i) {
try {
var adjacentY = y + adjacentSquares[i][0];
var adjacentX = x + adjacentSquares[i][1];
_revealSquares(board, adjacentY, adjacentX);
} catch (error) {}
}
}
};
_revealSquares(clonedBoard, y, x);
return clonedBoard;
};
```
### GameStore
There's not much to say about the GameStore. It's uses many of the same concepts as the typical React Store.
One change is that this module return a factory function. This allows for user specific options to be passed into the Store.
Example usage:
```js
var GameFactory = require('./minesweeper/GameFactory');
var MinesweeperGame = GameFactory.create({
width: 50,
height: 10,
numMines: 5
});
```
The other change, as mentioned earlier, is the lack of a dispatcher. This is because the Store actions are called directly by components.
This module does not have unit tests yet.
##$ React Components
Jest made it fairly easy to unit test React components. Admittedly, these tests were written after all the components were written. So not very TDD of me.
The mock timers were a bit confusing to use when testing the Timer component, but everything else made sense.
#### App Component
The AppFactory module returns a create function that allows the GameStore to be injected into the App.
This use of factories is something that I was experimenting with to avoid the use of singleton modules, which seems limit the modularity of components. I'll have to experiment with this more to see if it is useful. This minesweeper game would have no problems with a global store since the components aren't likely to be re-used for other purposes.
#### MinesweeperBoard Component
The MinesweeperBoard is also created via a create function. It requires that a MinesweeperSquare
component be passed in.
The original version of this component included a minesweeper row component, which basically did nothing but wrap a div around each row of squares.
This version generates the row divs without the use of a wrapper component.
```js
var React = require('react/addons');
var GameStatus = require('../Constants').GameStatus;
module.exports = {
create: function(MinesweeperSquare) {
return React.createClass({
render: function() {
var minesweeperRows = [];
var size = Math.floor(this.props.width / this.props.board[0].length).toString() + "px";
var minesweeperRows = this.props.board.map(function(row, y) {
return <div key={"row" + y} className="minesweeper-row">{this.renderRow(row, y, size)}</div>;
}.bind(this));
return <div className="minesweeper-board">{minesweeperRows}</div>
},
renderRow: function(row, y, size) {
return row.map(function(square, x) {
return <MinesweeperSquare
key={"y" + y + "x" + x}
size={size}
visible={this.props.status === GameStatus.LOST}
state={square.state}
value={square.value}
x={x} y={y} />;
}.bind(this));
}
});
}
}
```
#### MinesweeperSquare Component
The MinesweeperSquareFactory module returns a create function that accepts a callback for when a square is clicked. This was done to avoid passing the callback from the App to the MinesweeperBoard to the MinesweeperSquare.
The MinesweeperSquare component takes the square state as two separate props. This loosens the coupling a bit since we are just passing in two primitives instead of an object reference.
With this component, I considered different squares for each type of square, but that seemed like overkill to implement a Strategy/State pattern.
#### Timer Component
The timer component was kind of tricky to implement, and I'm not sold that this is the best solution. It keeps track of the time elapsed using it's own state. Start/Stop/Reset are passed in via props.
In terms of minesweeper:
1. The timer starts when the first square is clicked.
2. The timer stops when the user when wins or loses.
3. The timer resets to 0 when restart is clicked.
### Design
In terms of design, there is a tendency to want to emulate the old school look of the game. I avoided that by taking inspiration from the Windows Phone version of Minesweeper, which has a much more modern and minimal look.
Instead of right clicking to flag a square, buttons are used. This proved to be a tedious gameplay mechanic. The benefit is that mobile users should be able to play the game correctly.
There is more work to do before it is usable on mobile devices though.
### TODO
I'm not entirely finished with this project. There are few more things todo:
1. Add test coverage for GameStore
2. Add test coverage for MinesweeperApp component
3. Add win/loss message
4. Add hotkeys "d" and "f" to switch from dig mode and flag mode. Clicking the buttons can be tedious.
5. Make the game play well on mobile devices of different sizes.
### Links
- [Working Demo](http://richard.to/projects/beersweeper/)
- [Github Repository](https://github.com/richard-to/minesweeper)
|
Python
|
UTF-8
| 4,706 | 2.515625 | 3 |
[] |
no_license
|
import requests
import json
from contextlib import closing
import time
import threading
import queue
# print(reqs["data"]["next_offset"])
class bili(threading.Thread):
def __init__(self,url,next_offset,video_queue):
threading.Thread.__init__(self)
self.url = url
self.next_offset = next_offset
self.video_queue = video_queue
def ua(self):
headers = {
"origin": "https://vc.bilibili.com",
"referer": "https://vc.bilibili.com/p/eden/hot",
"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
}
return headers
def get_req(self,url):
response = requests.get(url,headers=self.ua())
if response.status_code == 200:
response = response.content.decode('utf-8')
#response = response.text
else:
response = None
return response
def get_video(self,res):
res = res["data"]["items"]
for i in res:
video_name = i["item"]["description"]
video_name = video_name.replace(" ", "")
video_url = i["item"]["video_playurl"]
self.video_queue.put((video_name,video_url))
print(video_name)
# print(video_url)
def run(self):
#while True:
url = self.url.format(next_offset=self.next_offset)
res = self.get_req(url)
if res:
res = json.loads(res)
try:
self.next_offset = res["data"]["next_offset"]
except:
print("可能无next_offset")
return ""
try:
self.get_video(res)
except:
print("视频获取出错...")
class download(threading.Thread):
def __init__(self,video_queue):
threading.Thread.__init__(self)
self.video_queue=video_queue
def ua(self):
headers = {
"origin": "https://vc.bilibili.com",
"referer": "https://vc.bilibili.com/p/eden/hot",
"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
}
return headers
def run(self):
while True:
if video_queue.empty():
break
try:
video_desc = video_queue.get()
video_name = video_desc[0]
video_url = video_desc[1]
print("准备下载!")
file_path = '抖音/{name}.mp4'.format(name=video_name)
# proxies={'https': 'https://127.0.0.1:1080', 'http': 'http://127.0.0.1:1080'},
with closing(requests.get(video_url, headers=self.ua(), stream=True)) as response:
chunk_size = 1024 # 单次请求最大值
print(response.status_code)
content_size = int(response.headers['content-length']) # 内容体总大小
print(content_size)
data_count = 0
with open(file_path, "wb") as file:
for data in response.iter_content(chunk_size=chunk_size):
file.write(data)
data_count = data_count + len(data)
now_jd = (data_count / content_size) * 100
print("\r 文件下载进度:%d%%(%d/%d) - %s" % (now_jd, data_count, content_size, file_path), end=" ")
print("\n>>> 获取视频成功了!")
except Exception as e:
print("视频下载出错:", e)
with open(r"抖音/log.txt", 'a+', encoding='utf-8') as f:
f.write("视频下载出错,错误代码:{error},采集视频:{video_url}|{video_name}内容".format(error=e, video_url=video_url,video_name=video_name))
time.sleep(2)
if __name__ == '__main__':
video_queue = queue.Queue()
next_offset = "178718"
url = "https://api.vc.bilibili.com/clip/v1/video/search?page_size=30&next_offset={next_offset}&tag=&need_playurl=1&order=new&platform=pc"
thread_url = bili(url, next_offset, video_queue)
thread_video = download(video_queue)
thread_video1 = download(video_queue)
thread_video2 = download(video_queue)
thread_url.start()
thread_url.join()
thread_video.start()
thread_video1.start()
thread_video2.start()
# new_video = bili(url,next_offset,video_queue)
# new_video.run()
|
C#
|
UTF-8
| 1,592 | 3.625 | 4 |
[] |
no_license
|
using System;
namespace BankingApplication
{
public class CheckingAccount : Account
{
int warningCounter;
public CheckingAccount(double initialBalance = 0)
{
this.Balance = initialBalance;
warningCounter = 0;
this.status = true;
}
public void deposit(double depositAmount)
{
if (this.status)
{
this.Balance += depositAmount;
Console.WriteLine($"{depositAmount} deposited. New balance: {this.Balance}");
}
else
{ Console.WriteLine("This Account is closed."); }
}
public void withdraw(double withdrawAmount)
{
if (this.status)
{
if (this.Balance >= withdrawAmount)
{
this.Balance -= withdrawAmount;
Console.WriteLine($"{withdrawAmount} withdrawn. New balance: {this.Balance}");
}
else
{
Console.WriteLine("Insufficient funds. Fee incurred.");
this.Balance -= 50;
this.warningCounter += 1;
if (this.warningCounter == 3)
{
this.status = false;
Console.WriteLine("Too many fees incurred. Account is now closed.");
}
}
}
else
{
Console.WriteLine("This Account is closed.");
}
}
}
}
|
JavaScript
|
UTF-8
| 3,872 | 2.859375 | 3 |
[] |
no_license
|
import React, { useEffect, useState } from 'react';
import Course from './Course';
import axios from 'axios'
const Calc = () => {
const [hours, setHours] = useState(0);
const [gpa, setGpa] = useState(0);
const [newCourse, setNewCourse] = useState("");
const [catPic, setCatPic] = useState("https://cdn2.thecatapi.com/images/MTU1NzE4MQ.jpg");
const [courses, setCourses] = useState([
{
name: "CS 125",
hours: 4,
qualityPoints: 4,
},
{
name: "Calc 2",
hours: 3,
qualityPoints: 4
},
{
name: "Calc 3",
hours: 3,
qualityPoints: 4
}
]);
const uiucGrades = {
'A+': 4.0,
'A': 4.0,
'A-': 3.67,
'B+': 3.33,
'B': 3.00,
'B-': 2.67,
'C+': 2.33,
'C': 2.00,
'C-': 1.67,
'D+': 1.33,
'D': 1.00,
'D-': 0.67,
'F': 0.00
}
const calculateGpa = (hours, gpa, courses) => {
let totalHours = hours;
let totalPoints = hours * gpa;
for (let i = 0; i < courses.length; i++) {
totalHours += courses[i].hours;
totalPoints += courses[i].hours * courses[i].qualityPoints;
}
const newGpa = (totalPoints / totalHours).toPrecision(3);
return newGpa;
}
const updatePoints = (courseName, newPoints) => {
const newCourses = courses.map(course =>
course.name === courseName ? {...course, qualityPoints: newPoints} : course
);
setCourses(newCourses);
};
const updateHours = (courseName, newHours) => {
const newCourses = courses.map(course =>
course.name === courseName ? {...course, hours: newHours} : course
);
setCourses(newCourses);
};
const addCourse = (courseName) => {
setCourses([...courses, {name: courseName, hours: 3, qualityPoints: 4}]);
};
const removeCourse = (courseName) => {
const newCourses = courses.filter(course => course.name !== courseName)
setCourses(newCourses);
};
const handleAddForm = (e) => {
e.preventDefault();
addCourse(newCourse);
setNewCourse("");
axios.get("https://api.thecatapi.com/v1/images/search")
.then(response => {
setCatPic(response.data[0].url)
})
}
useEffect(() => {
document.title = `Current GPA: ${calculateGpa(hours, gpa, courses)}`
}, [hours, gpa, courses]);
return (
<div>
<h2>Calculate your GPA</h2>
<label htmlFor="gpa">Enter your GPA so far:</label>
<input type="number" id="gpa" onChange={e => setGpa(e.target.value)}></input>
<br />
<label htmlFor="hours">Enter your credit hours so far:</label>
<input type="number" id="hours" onChange={e => setHours(parseInt(e.target.value))}></input>
<br />
<table>
{courses.map(course =>
<Course course={course}
possibleGrades={uiucGrades}
handleHourUpdate={updateHours}
handlePointUpdate={updatePoints}
handleRemove={removeCourse}
/>
)}
</table>
<form onSubmit={handleAddForm}>
<label htmlFor="courseName">New Course:</label>
<input type="text" id="courseName" value={newCourse} onChange={e => setNewCourse(e.target.value)}></input>
</form>
<h2 class="gpa-display">New GPA: {calculateGpa(hours, gpa, courses)}</h2>
<img src={catPic} alt="cute kitty" height="200"></img>
</div>
);
}
export default Calc;
|
Java
|
UTF-8
| 224 | 2.328125 | 2 |
[] |
no_license
|
package main;
public class Sector {
public int id;
public Trein trein;
public Sector(int id){
this.id=id;
trein=null;
}
public boolean vrij(){
if (trein==null)
return true;
else return false;
}
}
|
C#
|
UTF-8
| 1,941 | 2.78125 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shelf: MonoBehaviour
{
public List<Slot> slots;
void Start()
{
slots = new List<Slot>();
for (int i = 0; i < transform.childCount; i++)
{
Transform child = transform.GetChild(i);
if (child.tag == "Slot")
{
var slot = child.GetComponent<Slot>();
slots.Add(slot);
}
}
}
// we pick where it goes on this one
// returns the slot that was selected
public Slot AvailableSpot(Transform plant)
{
Slot slot = slots[0];
var closest = float.MaxValue;
foreach (var point in slots)
{
if (!point.hasPlant)
{
var distance = Vector3.Distance(plant.position, point.transform.position);
if (distance < closest)
{
slot = point;
closest = distance;
}
}
}
return slot;
}
// this method assumes you have already checked you CAN store a plant here
private void StorePlant(Transform plant, Slot slot)
{
var position = slot.transform.position;
position.y += 0.5f;
plant.position = position;
plant.rotation = Quaternion.identity;
plant.parent = null;
//plant.parent = slot.transform;
plant.SetParent(slot.transform);
Debug.Log($"parent: {plant.transform.parent.name}");
}
// we put it exactly where we clicked
public void PlacePlant(Transform plant, Slot spot)
{
StorePlant(plant, spot);
}
// need to make it so that shelves can change the properties of their slots properties
// basiclly we want a global "change the settings please" mode
// that can then be hooked up to the UI and we can show it as needed
}
|
Java
|
UTF-8
| 1,314 | 2.234375 | 2 |
[] |
no_license
|
package pagefactorypom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class RegisterPOM {
WebDriver driver;
@FindBy(id="gender-female")
WebElement gender;
@FindBy(id="gender-male")
WebElement genderm;
@FindBy(name="FirstName")
WebElement fn;
@FindBy(name="LastName")
WebElement ln;
@FindBy(name="Email")
WebElement emails;
@FindBy(name="Password")
WebElement passw;
@FindBy(name="ConfirmPassword")
WebElement conpass;
@FindBy(name="register-button")
WebElement register;
public RegisterPOM(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements(driver, this);
}
public void entergender()
{
gender.click();
}
public void entergenderm()
{
genderm.click();
}
public void enterfn(String fname)
{
fn.sendKeys(fname);
}
public void enterln(String lname)
{
ln.sendKeys(lname);
}
public void enem(String em)
{
emails.sendKeys(em);
}
public void enpass(String ps)
{
passw.sendKeys(ps);
}
public void enterconpass(String cp)
{
conpass.sendKeys(cp);
}
public void clickonregister()
{
register.click();
}
}
|
C++
|
UTF-8
| 1,267 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <vpp/fwd.hpp>
#include <string>
namespace vpp
{
vk::PfnVoidFunction vulkanProc(vk::Instance instance, const char* name);
vk::PfnVoidFunction vulkanProc(vk::Device device, const char* name);
}
///Macro for calling a vulkan function pointer.
///\param iniOrDev vulkan instance or device (depending on which kind of function pointer).
///\param name the name of the function without vk prefix (e.g. CreateSurfaceKHR)
///Can be e.g. used like VPP_PROC(instance, CreateSurfaceKHR)(instance, info);
///If the function pointer cannot be retrieved this macro will evaluate to nullptr,
///so direct calling should be used with care.
#define VPP_PROC(iniOrDev, name) \
reinterpret_cast<::vk::Pfn##name>(::vpp::vulkanProc(iniOrDev, "vk"#name))
///Macro for storing a vulkan function pointer.
///\param iniOrDev vulkan instance or device (depending on which kind of function pointer).
///\param name the name of the function pointer without vk prefix.
///This macro creates a variable in the current scope with the name pf<name> that
///holds a pointer to the vulkan function or a nullptr if it could not be retrieved.
#define VPP_LOAD_PROC(iniOrDev, name) \
auto pf##name = reinterpret_cast<::vk::Pfn##name>(::vpp::vulkanProc(iniOrDev, "vk"#name))
|
Java
|
UTF-8
| 3,479 | 2.453125 | 2 |
[] |
no_license
|
package forge.toolbox;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.SwingWorker;
import forge.UiCommand;
@SuppressWarnings("serial")
public class FHyperlink extends FLabel {
public static class Builder extends FLabel.Builder {
private String bldUrl;
public Builder() {
bldHoverable = true;
bldReactOnMouseDown = true;
bldCmd = null;
}
@Override
public FHyperlink build() {
final StringBuilder sb = new StringBuilder();
sb.append("<html><a href='").append(bldUrl).append("'>");
sb.append((null == bldText || bldText.isEmpty()) ? bldUrl : bldText);
sb.append("</a></html>");
final boolean browsingSupported = _isBrowsingSupported();
if (browsingSupported) {
tooltip(bldUrl);
}
else {
tooltip(bldUrl + " (click to copy to clipboard)");
}
final URI uri;
try {
uri = new URI(bldUrl);
}
catch (final URISyntaxException e) {
throw new RuntimeException(e);
}
// overwrite whatever command is there -- we could chain them if we wanted to, though
cmdClick(new UiCommand() {
@Override
public void run() {
if (browsingSupported) {
// open link in default browser
new _LinkRunner(uri).execute();
}
else {
// copy link to clipboard
final StringSelection ss = new StringSelection(bldUrl);
try {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}
catch (final IllegalStateException ex) {
FOptionPane.showErrorDialog(
"Sorry, a problem occurred while copying this link to your system clipboard.",
"A problem occurred");
}
}
}
});
return new FHyperlink(this);
}
public Builder url(final String url) { bldUrl = url; return this; }
private static boolean _isBrowsingSupported() {
if (!Desktop.isDesktopSupported()) {
return false;
}
return Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
}
}
// Call this using FLabel.Builder()...
private FHyperlink(final Builder b) {
super(b);
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
private static class _LinkRunner extends SwingWorker<Void, Void> {
private final URI uri;
private _LinkRunner(final URI u) {
if (u == null) {
throw new NullPointerException();
}
uri = u;
}
@Override
protected Void doInBackground() throws Exception {
Desktop.getDesktop().browse(uri);
return null;
}
}
}
|
Markdown
|
UTF-8
| 821 | 2.78125 | 3 |
[] |
no_license
|
# DengAI-Predicting-Disease-Spread
Predict the number of dengue cases each week (in each location) based on environmental variables
Using environmental data collected by various U.S. Federal Government agencies—from the Centers for Disease Control and Prevention to the National Oceanic and Atmospheric Administration in the U.S. Department of Commerce, predict the number of dengue fever cases reported each week in San Juan, Puerto Rico and Iquitos, Peru?
Main task is to predict the number of dengue cases each week (in each location) based on environmental variables describing changes in temperature, precipitation, vegetation, and more.
An understanding of the relationship between climate and dengue dynamics can improve research initiatives and resource allocation to help fight life-threatening pandemics.
|
C#
|
UTF-8
| 1,207 | 3.046875 | 3 |
[] |
no_license
|
using System;
using ThreeTierArchitecture.BussinessLayer;
using ThreeTierArchitecture.DomainModel;
namespace ThreeTierArchitecture.ui
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Enter EmailId");
string emailId = Console.ReadLine();
Console.WriteLine(" Enter Password");
string password = Console.ReadLine();
IAuthenticationBussiness authenticationobject = BussinessLayerFactory.GetAuthenticationRepo();
string studentId = authenticationobject.ValidateLogin(emailId, password);
Console.WriteLine(studentId);
if(studentId != null)
{
IStudentBussiness studentObject = BussinessLayerFactory.GetStudentRepo();
Student studentobj = studentObject.GetStudentDetails(studentId);
PrintDetails(studentobj);
}
Console.ReadKey();
}
static void PrintDetails(Student studentobj)
{
Console.WriteLine(studentobj.StudentId);
Console.WriteLine(studentobj.StudentName);
Console.WriteLine(studentobj.PhoneNumber);
}
}
}
|
Python
|
UTF-8
| 8,059 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
"""
Training a Recurrent Neural Network for Text Generation
=======================================================
This implements a char-rnn, which was heavily inspired from
Andrei Karpathy's work on text generation and adapted from
example code introduced by keras.
(http://karpathy.github.io/2015/05/21/rnn-effectiveness/)
It is recommended to run this script on GPU, as
recurrent networks are quite computationally intensive.
Make sure your corpus has >100k characters at least, but
for the best >1M characters. That is around the size,
of Harry Potter Book 7.
"""
from __future__ import print_function
import keras
import operator
import pathlib
import random
import sys
import os
import argparse
import functools
import numpy as np
from builtins import str as stringify
from itertools import chain
from keras.callbacks import ModelCheckpoint, Callback, TensorBoard, EarlyStopping, ReduceLROnPlateau
from keras.layers.core import Dense, Activation, Dropout, Masking
from keras.engine.topology import Input
from keras.layers.recurrent import LSTM, RNN
from keras.losses import categorical_crossentropy
from keras.models import Sequential
from keras.optimizers import RMSprop
from past.builtins import basestring
from keras.models import load_model
from keras.layers.wrappers import TimeDistributed
from keras.layers.core import Flatten
def build_model(args):
"""
Build a Stateful Stacked LSTM Network with n-stacks specified by args.layers
"""
layers = list(reversed(range(1, args.layers)))
params = dict(return_sequences=True, dropout=args.dropout, stateful=True,
batch_input_shape=(args.batch, args.window, len(args.chars)))
model = Sequential()
while layers:
layers.pop()
model.add(LSTM(args.batch, **params))
else:
# Last Layer is Flat
del params['return_sequences']
model.add(LSTM(args.batch, **params))
model.add(Dense(len(args.chars), activation='softmax', name='output'))
model.compile(loss=categorical_crossentropy,
optimizer='rmsprop',
metrics=['accuracy'])
return model
def command_line(setup='encoder'):
"""
Parameterze training and prediction scripts for encoder and decoder character rnn's
"""
parser = argparse.ArgumentParser(description='Train a neural network')
parser.add_argument('--verbose', '-v', action='count', default=0,
help='Keras verbose output')
parser.add_argument('--batch', '-b', metavar='size', default=128,
type=int, help='Specify the input batch size')
parser.add_argument('--model', '-m', metavar='file',
default='models/model.h5',
help='Specify the output model hdf5 file to save to: [default]: models/model.h5')
parser.add_argument('--layers', '-l', default=3, type=int, metavar='deep',
help='Specify the number of layers deep of LSTM nodes: [default]: 3')
parser.add_argument('--dropout', '-d', default=0.2, type=float, metavar='amount',
help='Amount of LSTM dropout to apply between 0.0 - 1.0: [default]: 0.2')
parser.add_argument('--resume', action='count',
help='Resume from saved model file rather than creating a new model')
parser.add_argument('--window', '-w', default=40, type=int, metavar='length',
help='Specify the size of the window size to train on: [default]: 40')
parser.add_argument('--log_dir', '-r', default=None, metavar='directory',
help='Specify the output directory for tensorflow logs: [default]: None')
parser.add_argument('--split', '-p', default=0.15, type=float, metavar='size',
help='Specify the split between validation and training data [default]: 0.15')
if setup == 'decoder':
parser.add_argument('--temperature', '-t', default=1.0, type=float, metavar='t',
help='Set the temperature value for prediction on batch: [default]: 1.0')
parser.add_argument('--output', '-s', default=2000, type=int, metavar='size',
help='Set the desired size of the characters decoded: [default]: 20000', )
if setup == 'encoder':
parser.add_argument('--epochs', '-e', default=50, type=int, metavar='num',
help='Specify for however many epochs to train over [default]: 50')
args = parser.parse_args()
args.sentences = []
args.next_chars = []
return args
def printer(args):
"""
Helper print function on statistics
"""
p = functools.partial(print, sep='\t')
p('Total Chars:', len(args.chars))
p('Corpus Length:', len(args.text))
p('NB Sequences:', len(args.sentences),
'of [{window}]'.format(window=args.window))
p('Outout File:', args.model)
p('Log Directory:', args.log_dir)
p('LSTM Layers:', args.layers)
p('LSTM Dropout:', args.dropout)
def get_text(datasets):
"""
Grab all the text dataset in the datasets directory
"""
text = []
for f in os.listdir(datasets):
filepath = '/'.join([datasets, f])
if f.startswith('.'):
continue
with open(filepath, encoding='utf8 ') as fp:
try:
text.append(fp.read())
print('Read:', filepath, sep='\t')
except UnicodeDecodeError:
print('Could Not Read', filepath, sep='\t')
return '\n'.join(text)
def train_validation_split(args):
"""
Split training and validation data specified by args.split
"""
v_split = round((len(args.X) // args.batch) * (1 - args.split)) * args.batch
args.x_train, args.y_train = args.X[:v_split], args.y[:v_split]
args.x_val, args.y_val = args.X[v_split:], args.y[v_split:]
return args
def parameterize(args):
"""
Parameterize argparse namespace with more parameters generated from dataset
"""
args.text = get_text('datasets')
args.chars = sorted(list(set(args.text)))
args.char_indices = dict((c, i) for i, c in enumerate(args.chars))
args.indices_char = dict((i, c) for i, c in enumerate(args.chars))
for i in range(0, len(args.text) - args.window, 1):
args.sentences.append(args.text[i: i + args.window])
args.next_chars.append(args.text[i + args.window])
# Print all the params
printer(args)
max_window = len(args.sentences) - (len(args.sentences) % args.batch)
args.sentences = args.sentences[0: max_window]
args.next_chars = args.next_chars[0: max_window]
args.X = np.zeros((max_window, args.window, len(args.chars)), dtype=np.bool)
args.y = np.zeros((max_window, len(args.chars)), dtype=np.bool)
for i, sentence in enumerate(args.sentences):
for t, char in enumerate(sentence):
args.X[i, t, args.char_indices[char]] = 1
args.y[i, args.char_indices[args.next_chars[i]]] = 1
return train_validation_split(args)
def main():
"""
Main entry point for training network
"""
args = parameterize(command_line())
# Build Model
model = (
load_model(args.model) if os.path.exists(args.model) and args.resume else build_model(args)
)
print(model.summary())
callbacks = [
ModelCheckpoint(args.model, save_best_only=True, monitor='val_loss', verbose=args.verbose),
ReduceLROnPlateau(factor=0.2, patience=2, monitor='val_loss', verbose=args.verbose)
]
if args.log_dir:
callbacks.append(TensorBoard(log_dir=args.log_dir, histogram_freq=10,
write_grads=True, batch_size=args.batch))
# Go Get Some Coffee
model.fit(x=args.x_train, y=args.y_train,
batch_size=args.batch,
epochs=args.epochs,
callbacks=callbacks,
shuffle=False,
validation_data=(args.x_val, args.y_val))
if __name__ == '__main__':
sys.exit(main())
|
Python
|
UTF-8
| 3,152 | 2.640625 | 3 |
[] |
no_license
|
#coding:utf-8
from wxpy import *
from random import choice
import time,datetime
bot = Bot(cache_path=True)
tuling = Tuling(api_key='0e8d70b241fcc4a898ee0410937b0551220')
naXienian=bot.groups().search(u'那些年')[0]
fristHello=[u'亲们有没有想我?',u'Hello,我来啦!!',u'都出来聊天呢!']
naXienian.send(choice(fristHello))
msgReceiveTime=str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
@bot.register(naXienian)
def reply_naXienian(msg):
global msgReceiveTime
msgReceiveTime=str(msg.receive_time).split('.')[0]
tuling.do_reply(msg)
def checkMessageTime():
autoReply=[u'Hello,我来啦!!',u'都出来聊天呢!',u'刚才我和我的朋友在讨论一些事情,我们想知道女人到底是怎么看到这个问题的,女生喜欢一个有女友的男生,应该追吗?/醉酒后的话可以相信吗?',\
u'女生应该生气男友玩真心话大冒险吗?/接吻算是偷情吗?/你们说男人和女人谁更喜欢说谎?',\
u'我的朋友冬瓜(一个有趣的外号)刚和女朋友分手,就是那边穿衬衫的帅哥,你觉得他要等多久才能和别的女生约会'\
u'我需要一些女生观点,如果你跟某人交往了三个月,他不想你跟他的某个朋友太亲近,怎么回应才好,假设这个人只是朋友,不会发生什么事。',\
u'我朋友的女朋友打算去做隆胸手术,作为送给我朋友的生日礼物,我的朋友不知道这回事,我估计他不一定会喜欢,你说我要不要跟他女朋友建议一下、还是把这件事告诉我朋友?',\
u'如果你们对一个人没有兴趣,但是又不想伤害人家, 你们会怎么说?是这样的。我朋友和他的女朋友正在试着撮合我和另外一个女生。好吧,她是很可爱,但就不是我喜欢的类型。 我应该怎么对她说呢?'\
u'你喜欢小马吗?(停顿)我小时候邻居有个女孩常被我欺负,她一见到小马就笑,你就像我以前的邻居小女孩^ ^~',\
u'我叫她做刁蛮小公主,那时候我们经常为一点鸡毛蒜皮的事情吵架,我真的觉得你好像她啊,特别是鼻子。',\
u'你偷看我这么久、你应该过来跟我说话,我不会拒绝你的',\
]
while True:
print u"开始检查时间"
diff = int(time.mktime(datetime.datetime.now().timetuple()))-int(time.mktime(time.strptime(msgReceiveTime,'%Y-%m-%d %H:%M:%S')))
if diff > 1200:
naXienian.send(choice(autoReply))
time.sleep(500)
zhangJiaBuLuo=bot.groups().search(u'张家部落')[0]
@bot.register(zhangJiaBuLuo)
def reply_zhangJiaBuLuo(msg):
tuling.do_reply(msg)
# zhangxiang = bot.friends().search(u'张林祥')[0]
#
# msgReceiveTime=str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# @bot.register(zhangxiang)
# def reply_zhangxiang(msg):
# global msgReceiveTime
# msgReceiveTime=str(msg.receive_time).split('.')[0]
# tuling.do_reply(msg)
# 保存运行测试
checkMessageTime()
embed()
|
Python
|
UTF-8
| 1,074 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
def adapter_array_01(jolts):
differences = [0, 0, 1]
for i in range(len(jolts) - 1):
differences[jolts[i + 1] - jolts[i] - 1] += 1
return differences[0] * differences[2]
def adapter_array_02(jolts):
groups = [True if jolts[i + 2] - jolts[i] <= 3 else False for i in range(len(jolts) - 2)]
group_counts = [0]
for g in groups:
if g:
group_counts[-1] += 1
else:
group_counts += [0] if group_counts[-1] != 0 else []
mult = lambda l : l[0] * mult(l[1:]) if len(l) > 1 else l[0]
valid_subchains = lambda length : len(["{0:b}".format(i) for i in range(pow(2, length)) if '111' not in "{0:b}".format(i)])
return mult(list(map(valid_subchains, group_counts)))
if __name__ == "__main__":
with open('input.txt') as f:
contents = sorted([int(l.strip()) for l in f.readlines()])
with open('output.txt', 'w') as f:
f.write("Part one: {}\n".format(adapter_array_01([0] + contents)))
f.write("Part two: {}\n".format(adapter_array_02([0] + contents + [contents[-1] + 3])))
|
Java
|
UTF-8
| 833 | 2.125 | 2 |
[] |
no_license
|
package org.firstinspires.ftc.teamcode.logging;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.teamcode.framework.subsystems.imu.IMU;
import org.firstinspires.ftc.teamcode.framework.Utility;
import org.firstinspires.ftc.teamcode.logging.DoubleLogger;
import org.firstinspires.ftc.teamcode.framework.enums.DebugMode;
import java.util.List;
public class Debug{
private List<DcMotor> motors;
private List<DcMotor> encoders;
private IMU imu;
private DebugMode debugMode;
private DoubleLogger logger;
public Debug(List<DcMotor> motors, IMU imu, DoubleLogger logger, List<DcMotor> encoders, DebugMode debugMode){
}
public void reset(){
}
public void report(){
}
public void log(){
}
}
|
Java
|
UTF-8
| 2,637 | 1.890625 | 2 |
[] |
no_license
|
package com.peace.ostp.domain;
import java.util.Date;
public class CourseInfo {
private String courseid;
private String coursetitle;
private String courseauthor;
private Date updatetime;
private String content;
private String coverpicture;
private String sporttypeid;
private String clicktimes;
private String keywords;
private String enabled;
private Date createtime;
private String createby;
private String updateby;
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getCreateby() {
return createby;
}
public void setCreateby(String createby) {
this.createby = createby;
}
public String getUpdateby() {
return updateby;
}
public void setUpdateby(String updateby) {
this.updateby = updateby;
}
public String getCourseid() {
return courseid;
}
public void setCourseid(String courseid) {
this.courseid = courseid;
}
public String getCoursetitle() {
return coursetitle;
}
public void setCoursetitle(String coursetitle) {
this.coursetitle = coursetitle;
}
public String getCourseauthor() {
return courseauthor;
}
public void setCourseauthor(String courseauthor) {
this.courseauthor = courseauthor;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCoverpicture() {
return coverpicture;
}
public void setCoverpicture(String coverpicture) {
this.coverpicture = coverpicture;
}
public String getSporttypeid() {
return sporttypeid;
}
public void setSporttypeid(String sporttypeid) {
this.sporttypeid = sporttypeid;
}
public String getClicktimes() {
return clicktimes;
}
public void setClicktimes(String clicktimes) {
this.clicktimes = clicktimes;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
}
|
Java
|
UTF-8
| 6,052 | 2.25 | 2 |
[] |
no_license
|
package clasem.entities.user;
import clasem.config.SecurityUtility;
import clasem.entities.DeletableModel;
import org.hibernate.annotations.ResultCheckStyle;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.hibernate.validator.constraints.Length;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@SQLDelete(sql = "UPDATE user SET enabled = false, deleted_at = SYSDATE() WHERE id = ?", check = ResultCheckStyle.COUNT)
@Where(clause = "deleted_at IS null")
@Table(name = "user")
public class User extends DeletableModel {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
private Long id;
@Column(name = "USERNAME", length = 50, unique = true)
@NotNull
@Size(min = 4, max = 50)
private String username;
@Column(name = "PASSWORD", length = 100)
@NotNull
@Size(min = 4, max = 100)
private String password;
@Column(name = "FIRSTNAME", length = 50)
@NotNull
@Size(min = 4, max = 50)
private String firstname;
@Column(name = "LASTNAME", length = 50)
@NotNull
@Size(min = 4, max = 50)
private String lastname;
@Column(name = "EMAIL", length = 50, unique = true)
@NotNull
@Size(min = 4, max = 50)
private String email;
@Column(name = "CELLPHONE", length = 50, unique = true)
@NotNull
@Size(min = 9, max = 9)
private String cellphone;
@Column(name = "DNI", length = 50, unique = true)
@NotNull
@Size(min = 8, max = 8)
private String dni;
@Column(name = "ENABLED")
@NotNull
private Boolean enabled;
@Column(name = "LASTPASSWORDRESETDATE")
@Temporal(TemporalType.TIMESTAMP)
@NotNull
private Date lastPasswordResetDate;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "USER_AUTHORITY",
joinColumns = {@JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {@JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")})
private List<Authority> authorities;
public User() {
}
public User(String username, String password, String firstname, String lastname, String email, String cellphone, String dni, Boolean enabled, Date lastPasswordResetDate, List<Authority> authorities) {
this.username = username;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.cellphone = cellphone;
this.dni = dni;
this.enabled = enabled;
this.lastPasswordResetDate = lastPasswordResetDate;
this.authorities = authorities;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = SecurityUtility.passwordEncoder().encode(password);
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
public Date getLastPasswordResetDate() {
return lastPasswordResetDate;
}
public void setLastPasswordResetDate(Date lastPasswordResetDate) {
this.lastPasswordResetDate = lastPasswordResetDate;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", email='" + email + '\'' +
", cellphone='" + cellphone + '\'' +
", dni='" + dni + '\'' +
", enabled=" + enabled +
", lastPasswordResetDate=" + lastPasswordResetDate +
", authorities=" + authorities +
'}';
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return id == ((User) obj).id;
}
}
|
Java
|
UTF-8
| 549 | 4.25 | 4 |
[] |
no_license
|
package doit.chap05;
import java.util.Scanner;
//팩토리얼 값을 비재귀적으로 구합니다.
public class FactorialEx_05_01 {
//양의 정수 n의 팩토리얼 값을 반환
static int factorical(int n) {
int fact = 1;
while (n > 1)
fact *= n--;
return fact;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("정수를 입력하세요. : ");
int x = scanner.nextInt();
System.out.println(x + "의 팩토리얼은 " + factorical(x) + "입니다.");
}
}
|
Java
|
UTF-8
| 6,966 | 1.765625 | 2 |
[] |
no_license
|
package com.example.bbook;
import java.io.IOException;
import java.util.List;
import org.w3c.dom.Text;
import com.example.bbook.api.Page;
import com.example.bbook.api.Server;
import com.example.bbook.api.entity.Orders;
import com.example.bbook.api.widgets.GoodsPicture;
import com.example.bbook.api.widgets.OrderStateTabbarFragment;
import com.example.bbook.api.widgets.OrderStateTabbarFragment.OnTabSelectedListener;
import com.example.bbook.api.widgets.TitleBarFragment.OnGoBackListener;
import com.example.bbook.api.widgets.TitleBarFragment.OnGoNextListener;
import com.example.bbook.api.widgets.TitleBarFragment;
import com.example.bbook.fragments.pages.OrdersAllFragment;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Video;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MyOrdersActivity extends Activity {
TitleBarFragment titleBar;
OrderStateTabbarFragment tabbar;
OrdersAllFragment contentAll = new OrdersAllFragment();
OrdersAllFragment contentToBePay = new OrdersAllFragment(2);
OrdersAllFragment contentToBeSend = new OrdersAllFragment(3);
OrdersAllFragment contentToBeCheck = new OrdersAllFragment(4);
OrdersAllFragment contentToBeComment = new OrdersAllFragment(5);
List<Orders> ordersData;
int Page=0;
ListView list;
TextView orderState;
TextView shopName;
ImageView ordersDelete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_orders);
init();
setEvent();
}
private void setEvent() {
titleBar = (TitleBarFragment) getFragmentManager().findFragmentById(R.id.title_bar);
titleBar.setTitleName("我的订单", 18);
titleBar.setBtnNextText("退货/售后", 13);
titleBar.setOnGoNextListener(new OnGoNextListener() {
@Override
public void onGoNext() {
Intent itnt = new Intent(MyOrdersActivity.this, MyRefundOrderActivity.class);
startActivity(itnt);
overridePendingTransition(R.anim.slide_in_right, R.anim.none);
}
});
// 返回
titleBar.setOnGoBackListener(new OnGoBackListener() {
@Override
public void onGoBack() {
finish();
overridePendingTransition(R.anim.none, R.anim.slide_out_right);
}
});
tabbar.setOnTabSelectedListener(new OnTabSelectedListener() {
@Override
public void OnTabSelected(int index) {
changeContentFragment(index);
}
});
}
private void init() {
list = (ListView) findViewById(R.id.list);
tabbar = (OrderStateTabbarFragment) getFragmentManager().findFragmentById(R.id.frag_tabbar);
titleBar = (TitleBarFragment) getFragmentManager().findFragmentById(R.id.title_bar);
}
protected void changeContentFragment(int index) {
Fragment newFrag = null;
switch(index) {
case 0 : newFrag = contentAll;break;
case 1 : newFrag = contentToBePay;break;
case 2 : newFrag = contentToBeSend; break;
case 3 : newFrag = contentToBeCheck; break;
case 4 : newFrag = contentToBeComment; break;
default:
break;
}
if(newFrag == null) return;
getFragmentManager()
.beginTransaction()
.replace(R.id.container, newFrag)
.commit();
}
static void text(Context context) {
Toast.makeText(context, "aaa", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
if (tabbar.getSelectedIndex() < 0) {
tabbar.setSelectedItem(0);
}
// LoadMyOrders();
}
public void LoadMyOrders(){
OkHttpClient client=Server.getSharedClient();
Request request=Server.requestBuilderWithApi("orders/findall")
.get().build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
final String responseStr=arg1.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Page<Orders> data=new ObjectMapper()
.readValue(responseStr, new TypeReference<Page<Orders>>() {});
ordersData=data.getContent();
Page=data.getNumber();
// listAdapter.notifyDataSetInvalidated();
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onFailure(Call arg0, IOException arg1) {
}
});
}
public void goShopActivity(int position){
Intent intent=new Intent(MyOrdersActivity.this,ShopActivity.class);
intent.putExtra("shop",ordersData.get(position).getGoods().getShop());
startActivity(intent);
}
public void goOrderDelete(final int position){
AlertDialog.Builder builder=new Builder(this);
builder.setMessage("是否删除订单?");
builder.setNegativeButton("取消",null);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteOrder(position);
}
});
builder.show();
}
public void deleteOrder(int position){
OkHttpClient client=Server.getSharedClient();
Request request=Server.requestBuilderWithApi("orders/delete/"+ordersData.get(position).getOrdersID())
.get().build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
String responseStr=arg1.body().string();
final Boolean isDeleted=new ObjectMapper().readValue(responseStr, Boolean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
if(isDeleted){
Toast.makeText(MyOrdersActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
LoadMyOrders();
}
}
});
}
@Override
public void onFailure(Call arg0, IOException arg1) {
}
});
}
}
|
C++
|
UTF-8
| 2,788 | 3.296875 | 3 |
[] |
no_license
|
#ifndef OSTIMER_H
#define OSTIMER_H
#include <chrono>
#include <limits>
#include "xolotlPerf/perfConfig.h"
#include "xolotlPerf/ITimer.h"
#include "xolotlCore/Identifiable.h"
namespace xolotlPerf {
/// A timer that measures how long something takes to execute.
/// Uses an operating system/runtime timer interface.
class OSTimer: public ITimer, public xolotlCore::Identifiable {
private:
/// Concise name for type of our time source.
using Clock = std::chrono::system_clock;
/// Concise name for type of a timestamp.
using Timestamp = std::chrono::time_point<Clock>;
/// Concise name for type of a difference between timestamps.
using Duration = std::chrono::duration<ITimer::ValType>;
/// The timestamp value we use to indicate startTime is invalid.
static const Timestamp invalidTimestamp;
/// The timer's value.
ITimer::ValType val;
/// When the timer was started.
/// Will be invalidTimestamp if timer is not running.
Timestamp startTime;
/// Construct a timer.
/// The default constructor is private to force callers to provide a name for the timer object.
OSTimer(void) :
xolotlCore::Identifiable("unused"), val(0) {
}
public:
///
/// Construct a timer.
///
/// @param name The name to associate with the timer.
OSTimer(const std::string& name) :
xolotlCore::Identifiable(name),
val(0),
startTime(invalidTimestamp) {
}
///
/// Destroy the timer.
///
virtual ~OSTimer(void) {
}
///
/// Start the timer.
/// Throws std::runtime_error if starting a timer that was already started.
///
void start(void) override;
///
/// Stop the timer.
/// Throws std::runtime_error if stopping a timer that was not running.
///
void stop(void) override;
///
/// Reset the timer's value.
/// Throws std::runtime_error if resetting a timer that was running.
///
void reset(void) override;
///
/// Determine if the Timer is currently running.
///
/// @return true if the Timer is running, false otherwise.
///
virtual bool isRunning(void) const {
return (startTime != invalidTimestamp);
}
///
/// Retrieve the value of the timer.
/// The value is only valid if the timer is not running.
///
/// @return The elapsed time measured by this timer.
///
ITimer::ValType getValue(void) const override {
return val;
}
///
/// Retrieve the Timer value's units.
/// @return The units in which the timer's value is given.
///
std::string getUnits(void) const override;
/// Add the given Timer's value to my value.
/// @param t The timer whose value should be added to my value.
/// @return Myself after adding the given timer's value.
virtual ITimer& operator+=(const ITimer& t) {
val += t.getValue();
return *this;
}
};
} // namespace xolotlPerf
#endif // OSTIMER_H
|
Java
|
UTF-8
| 7,826 | 2.3125 | 2 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package org.highj.data.num;
import org.highj.data.ratio.Rational;
import org.highj.data.tuple.T2;
import org.highj.typeclass0.num.Integral;
import org.highj.typeclass0.num.Num;
import org.highj.typeclass0.num.Real;
import org.highj.util.ArrayUtils;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import static org.assertj.core.api.Assertions.assertThat;
public class BigIntegersTest {
@Test
public void sqr() {
assertThat(BigIntegers.sqr.apply($(0))).isEqualTo($(0));
assertThat(BigIntegers.sqr.apply($(42))).isEqualTo($(1764));
assertThat(BigIntegers.sqr.apply($(-42))).isEqualTo($(1764));
}
@Test
public void succ() {
assertThat(BigIntegers.succ.apply($(-1))).isEqualTo($(0));
assertThat(BigIntegers.succ.apply($(0))).isEqualTo($(1));
assertThat(BigIntegers.succ.apply($(42))).isEqualTo($(43));
}
@Test
public void pred() {
assertThat(BigIntegers.pred.apply($(0))).isEqualTo($(-1));
assertThat(BigIntegers.pred.apply($(1))).isEqualTo($(0));
assertThat(BigIntegers.pred.apply($(43))).isEqualTo($(42));
}
@Test
public void pow() {
assertThat(BigIntegers.pow.apply($(3)).apply($(4))).isEqualTo($(81));
assertThat(BigIntegers.pow.apply($(10)).apply($(2))).isEqualTo($(100));
assertThat(BigIntegers.pow.apply($(5)).apply($(3))).isEqualTo($(125));
assertThat(BigIntegers.pow.apply($(2)).apply($(8))).isEqualTo($(256));
}
@Test
public void negative() {
assertThat(BigIntegers.negative.test($(0))).isFalse();
assertThat(BigIntegers.negative.test($(42))).isFalse();
assertThat(BigIntegers.negative.test($(-42))).isTrue();
}
@Test
public void positive() {
assertThat(BigIntegers.positive.test($(0))).isFalse();
assertThat(BigIntegers.positive.test($(42))).isTrue();
assertThat(BigIntegers.positive.test($(-42))).isFalse();
}
@Test
public void zero() {
assertThat(BigIntegers.zero.test($(0))).isTrue();
assertThat(BigIntegers.zero.test($(42))).isFalse();
assertThat(BigIntegers.zero.test($(-42))).isFalse();
}
@Test
public void even() {
assertThat(BigIntegers.even.test($(0))).isTrue();
assertThat(BigIntegers.even.test($(42))).isTrue();
assertThat(BigIntegers.even.test($(-42))).isTrue();
assertThat(BigIntegers.even.test($(43))).isFalse();
assertThat(BigIntegers.even.test($(-43))).isFalse();
}
@Test
public void odd() {
assertThat(BigIntegers.odd.test($(0))).isFalse();
assertThat(BigIntegers.odd.test($(42))).isFalse();
assertThat(BigIntegers.odd.test($(-42))).isFalse();
assertThat(BigIntegers.odd.test($(43))).isTrue();
assertThat(BigIntegers.odd.test($(-43))).isTrue();
}
@Test
public void additiveGroup() {
assertThat(BigIntegers.additiveGroup.identity()).isEqualTo($(0));
assertThat(BigIntegers.additiveGroup.apply($(17), $(23))).isEqualTo($(40));
assertThat(BigIntegers.additiveGroup.inverse($(5))).isEqualTo($(-5));
assertThat(BigIntegers.additiveGroup.inverse($(-5))).isEqualTo($(5));
assertThat(BigIntegers.additiveGroup.inverse($(0))).isEqualTo($(0));
}
@Test
public void multiplicativeMonoid() {
assertThat(BigIntegers.multiplicativeMonoid.identity()).isEqualTo($(1));
assertThat(BigIntegers.multiplicativeMonoid.apply($(17), $(23))).isEqualTo($(391));
}
@Test
public void minSemigroup() {
assertThat(BigIntegers.minSemigroup.apply($(17), $(23))).isEqualTo($(17));
assertThat(BigIntegers.minSemigroup.apply($(23), $(17))).isEqualTo($(17));
}
@Test
public void maxSemigroup() {
assertThat(BigIntegers.maxSemigroup.apply($(17), $(23))).isEqualTo($(23));
assertThat(BigIntegers.maxSemigroup.apply($(23), $(17))).isEqualTo($(23));
}
@Test
public void andSemigroup() {
assertThat(BigIntegers.andSemigroup.apply($(17), $(23))).isEqualTo($(17 & 23));
}
@Test
public void xorMonoid() {
assertThat(BigIntegers.xorMonoid.identity()).isEqualTo($(0));
assertThat(BigIntegers.xorMonoid.apply($(17), $(23))).isEqualTo($(6));
}
@Test
public void orMonoid() {
assertThat(BigIntegers.orMonoid.identity()).isEqualTo($(0));
assertThat(BigIntegers.orMonoid.apply($(17), $(23))).isEqualTo($(17 | 23));
}
@Test
public void enumeration() {
org.highj.typeclass0.num.Enum<BigInteger> enumeration = BigIntegers.enumeration;
assertThat(enumeration.toEnum(42)).isEqualTo($(42));
assertThat(enumeration.fromEnum($(42))).isEqualTo(42);
assertThat(enumeration.pred($(10))).isEqualTo($(9));
assertThat(enumeration.pred($(-10))).isEqualTo($(-11));
assertThat(enumeration.succ($(10))).isEqualTo($(11));
assertThat(enumeration.succ($(-10))).isEqualTo($(-9));
assertThat(enumeration.enumFrom($(10))).startsWith($$(10, 11, 12, 13));
assertThat(enumeration.enumFromThen($(10), $(12))).startsWith($$(10, 12, 14, 16));
assertThat(enumeration.enumFromThen($(10), $(8))).startsWith($$(10, 8, 6, 4));
assertThat(enumeration.enumFromTo($(10), $(15))).containsExactly($$(10, 11, 12, 13, 14, 15));
assertThat(enumeration.enumFromTo($(10), $(10))).containsExactly($(10));
assertThat(enumeration.enumFromTo($(10), $(5))).isEmpty();
assertThat(enumeration.enumFromThenTo($(10), $(12), $(16))).containsExactly($$(10, 12, 14, 16));
assertThat(enumeration.enumFromThenTo($(10), $(12), $(17))).containsExactly($$(10, 12, 14, 16));
assertThat(enumeration.enumFromThenTo($(-10), $(-12), $(-16))).containsExactly($$(-10, -12, -14, -16));
assertThat(enumeration.enumFromThenTo($(-10), $(-12), $(-17))).containsExactly($$(-10, -12, -14, -16));
assertThat(enumeration.enumFromThenTo($(10), $(8), $(15))).isEmpty();
assertThat(enumeration.enumFromThenTo($(10), $(10), $(10))).startsWith($$(10, 10, 10, 10));
}
@Test
public void num() {
Num<BigInteger> num = BigIntegers.num;
assertThat(num.abs($(-10))).isEqualTo($(10));
assertThat(num.abs($(0))).isEqualTo($(0));
assertThat(num.abs($(10))).isEqualTo($(10));
assertThat(num.negate($(-10))).isEqualTo($(10));
assertThat(num.negate($(0))).isEqualTo($(0));
assertThat(num.negate($(10))).isEqualTo($(-10));
assertThat(num.signum($(-10))).isEqualTo($(-1));
assertThat(num.signum($(0))).isEqualTo($(0));
assertThat(num.signum($(10))).isEqualTo($(1));
assertThat(num.add($(7), $(3))).isEqualTo($(10));
assertThat(num.subtract($(7), $(3))).isEqualTo($(4));
assertThat(num.times($(7), $(3))).isEqualTo($(21));
assertThat(num.fromBigInteger($(10))).isEqualTo($(10));
}
@Test
public void real() {
Real<BigInteger> real = BigIntegers.real;
assertThat(real.toRational($(23))).isEqualTo(
Rational.rational($(23), $(1)));
}
@Test
public void integral() {
Integral<BigInteger> integral = BigIntegers.integral;
assertThat(integral.quotRem($(23), $(7))).isEqualTo(T2.of($(3), $(2)));
assertThat(integral.quotRem($(-23), $(7))).isEqualTo(T2.of($(-3), $(-2)));
assertThat(integral.quotRem($(23), $(-7))).isEqualTo(T2.of($(-3), $(2)));
assertThat(integral.quotRem($(-23), $(-7))).isEqualTo(T2.of($(3), $(-2)));
}
private static BigInteger $(int i) {
return BigInteger.valueOf(i);
}
private static BigInteger[] $$(Integer... is) {
return ArrayUtils.map(is, BigIntegersTest::$, new BigInteger[is.length]);
}
}
|
Java
|
UTF-8
| 1,609 | 2.328125 | 2 |
[] |
no_license
|
package com.example.jinming.gamestopdemo.util;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.jinming.gamestopdemo.R;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Jinming on 11/25/17.
*/
public class Fragment3Adapter extends ArrayAdapter<Sentence> {
List<Sentence> list;
TextView tv1, tv2;
public Fragment3Adapter(@NonNull Context context, int resource, List<Sentence> list) {
super(context, resource, list);
this.list = list;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Sentence s = list.get(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.fragment3_list_item, parent, false);
}
tv1 = convertView.findViewById(R.id.textView1);
tv2 = convertView.findViewById(R.id.textView2);
tv1.setText(s.getTitle());
tv2.setText(s.getContent());
if (position == 0) {
tv1.setTextColor(Color.WHITE);
tv1.setTextSize(27);
tv2.setVisibility(View.INVISIBLE);
convertView.setBackgroundColor(Color.parseColor("#e74c3c"));
}
return convertView;
}
}
|
Java
|
UTF-8
| 10,267 | 2.46875 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package project;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
/**
*
* @author amjad
*/
public class FirstPanel extends javax.swing.JPanel {
/**
* Creates new form FirstPanel
*/
public static settingFrame sp;
public FirstPanel() {
initComponents();
setLayout(new BorderLayout());
add(jLabel1,BorderLayout.CENTER);
setSize(jLabel1.getSize());
jButton4.setOpaque(false);
jButton4.setContentAreaFilled(false); //to make the content area transparent
jButton4.setBorderPainted(false);
jButton3.setOpaque(false);
jButton3.setContentAreaFilled(false); //to make the content area transparent
jButton3.setBorderPainted(false);
aa1.setLocation(1250, 50);
aa2.setLocation(1250, 150);
aa3.setLocation(1250, 250);
aa4.setLocation(1250, 350);
aa5.setLocation(1250, 450);
aa4.setOpaque(false);
aa4.setContentAreaFilled(false); //to make the content area transparent
aa4.setBorderPainted(false);
aa5.setOpaque(false);
aa5.setContentAreaFilled(false); //to make the content area transparent
aa5.setBorderPainted(false);
aa3.setOpaque(false);
aa3.setContentAreaFilled(false); //to make the content area transparent
aa3.setBorderPainted(false);
aa2.setOpaque(false);
aa2.setContentAreaFilled(false); //to make the content area transparent
aa2.setBorderPainted(false);
aa1.setOpaque(false);
aa1.setContentAreaFilled(false); //to make the content area transparent
aa1.setBorderPainted(false);
}
public class shi extends Thread
{
public void run()
{
while(true)
{
if( aa1.getX()<1000)
return;
try
{
Thread.sleep(1);
} catch (InterruptedException ex)
{}
aa1.setLocation(aa1.getX()-1, aa1.getY());
}
}
}
public class shi1 extends Thread
{
public void run()
{
while(true)
{
if( aa2.getX()<1000)
return;
try
{
Thread.sleep(2);
} catch (InterruptedException ex)
{}
aa2.setLocation(aa2.getX()-1, aa2.getY());
}
}
}
public class shi2 extends Thread
{
public void run()
{
while(true)
{
if( aa3.getX()<1000)
return;
try
{
Thread.sleep(3);
} catch (InterruptedException ex)
{}
aa3.setLocation(aa3.getX()-1, aa3.getY());
}
}
}
public class shi3 extends Thread
{
public void run()
{
while(true)
{
if( aa4.getX()<1000)
return;
try
{
Thread.sleep(4);
} catch (InterruptedException ex)
{}
aa4.setLocation(aa4.getX()-1, aa4.getY());
}
}
}
public class shi4 extends Thread
{
public void run()
{
while(true)
{
if( aa5.getX()<1000)
return;
try
{
Thread.sleep(5);
} catch (InterruptedException ex)
{}
aa5.setLocation(aa5.getX()-1, aa5.getY());
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
aa3 = new javax.swing.JButton();
aa2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
aa1 = new javax.swing.JButton();
aa4 = new javax.swing.JButton();
aa5 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/mclaren_720s_coupe_2017_4k-HD.jpg")); // NOI18N
setSize(new java.awt.Dimension(15, 15));
setLayout(null);
aa3.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/speedometer_service_car_tachometer_traffic-256.png")); // NOI18N
aa3.setRolloverIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/rol img/sss1.png")); // NOI18N
aa3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aa3ActionPerformed(evt);
}
});
add(aa3);
aa3.setBounds(520, 190, 80, 90);
aa2.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/ssssss5.png")); // NOI18N
aa2.setRolloverIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/rol img/aaa.png")); // NOI18N
aa2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aa2ActionPerformed(evt);
}
});
add(aa2);
aa2.setBounds(520, 120, 80, 80);
jButton3.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/282467-256.png")); // NOI18N
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
add(jButton3);
jButton3.setBounds(20, 450, 150, 140);
jButton4.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/f-right_256-128.png")); // NOI18N
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
add(jButton4);
jButton4.setBounds(170, 450, 140, 140);
aa1.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/ssssss3.png")); // NOI18N
aa1.setRolloverIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/rol img/a.png")); // NOI18N
aa1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aa1ActionPerformed(evt);
}
});
add(aa1);
aa1.setBounds(510, 10, 100, 100);
aa4.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/ss.png")); // NOI18N
aa4.setRolloverIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/rol img/ssss2.png")); // NOI18N
aa4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aa4ActionPerformed(evt);
}
});
add(aa4);
aa4.setBounds(520, 280, 80, 90);
aa5.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/sssss4.png")); // NOI18N
aa5.setRolloverIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/rol img/sssss4.png")); // NOI18N
add(aa5);
aa5.setBounds(520, 350, 80, 100);
jLabel1.setIcon(new javax.swing.ImageIcon("/Users/mbp/NetBeansProjects/project/main img/fa61c8c4243772d412bea7a119c6e056.jpg")); // NOI18N
jLabel1.setText("");
add(jLabel1);
jLabel1.setBounds(-20, 0, 710, 590);
}// </editor-fold>//GEN-END:initComponents
private void aa3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aa3ActionPerformed
}//GEN-LAST:event_aa3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
shi s=new shi();
s.start();
shi1 s1=new shi1();
s1.start();
shi2 s2=new shi2();
s2.start();
shi3 s3=new shi3();
s3.start();
shi4 s4=new shi4();
s4.start();
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
UP.ff.setVisible(false);
Project.f.setVisible(true);
aa1.setLocation(1250, 50);
aa2.setLocation(1250, 150);
aa3.setLocation(1250, 250);
aa4.setLocation(1250, 350);
aa5.setLocation(1250, 450);
}//GEN-LAST:event_jButton3ActionPerformed
private void aa2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aa2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_aa2ActionPerformed
private void aa4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aa4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_aa4ActionPerformed
private void aa1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aa1ActionPerformed
sp=new settingFrame();
sp.setLocation(350, 350);
sp.setVisible(true);
}//GEN-LAST:event_aa1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton aa1;
private javax.swing.JButton aa2;
private javax.swing.JButton aa3;
private javax.swing.JButton aa4;
private javax.swing.JButton aa5;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
|
Markdown
|
UTF-8
| 1,948 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
Themed LayoutGrid from <a href="https://github.com/material-components/material-components-web-react/tree/master/packages/layout-grid" target="_blank">material-components-web-react</a>
### Installation
```bash
yarn add @fv-components/layout-grid;
```
### Usage
```js static
import Grid, {
Cell,
Row,
} from '@fv-components/layout-grid';
```
### [Props](https://github.com/material-components/material-components-web-react/tree/master/packages/layout-grid#props)
### Examples
#### Default
```js
import Grid, {
Cell,
Row,
} from '@fv-components/layout-grid';
<div>
<Grid>
<Row>
<Cell columns={4}>Tennis</Cell>
<Cell columns={4}>Cricket</Cell>
<Cell columns={4}>StarCraft</Cell>
</Row>
</Grid>
</div>
```
#### Order
```js
import Grid, {
Cell,
Row,
} from '@fv-components/layout-grid';
<div>
<Grid>
<Row>
<Cell desktopColumns={4} order={2} phoneColumns={4} tabletColumns={4}>Tennis</Cell>
<Cell desktopColumns={4} order={3} phoneColumns={4} tabletColumns={4}>Cricket</Cell>
<Cell desktopColumns={4} order={1} phoneColumns={4} tabletColumns={4}>StarCraft</Cell>
</Row>
</Grid>
</div>
```
#### Nested
```js
import Grid, {
Cell,
Row,
} from '@fv-components/layout-grid';
<div>
<Grid>
<Row>
<Cell columns={4}>
<Row>
<Cell desktopColumns={8} phoneColumns={2} tabletColumns={5}>Tennis</Cell>
<Cell desktopColumns={4} phoneColumns={2} tabletColumns={3}>Tennis2</Cell>
</Row>
</Cell>
<Cell columns={4}>Cricket</Cell>
<Cell columns={4}>Starcraft</Cell>
</Row>
</Grid>
</div>
```
#### Alignment
```js
import Grid, {
Cell,
Row,
} from '@fv-components/layout-grid';
<div>
<Grid align="right">
<Row>
<Cell align="top">Tennis<br /><br /><br /><br /><br /></Cell>
<Cell align="middle">Cricket</Cell>
<Cell align="bottom">StarCraft</Cell>
</Row>
</Grid>
</div>
```
|
PHP
|
UTF-8
| 258 | 2.8125 | 3 |
[] |
no_license
|
<?php
namespace StudentManagementSystem;
class Grade
{
// Properties
public $grade_id;
public $grade_name;
public function getGradeId(){
return $this->grade_id;
}
public function getGradeName(){
return $this->grade_name;
}
}
|
C++
|
GB18030
| 3,149 | 3.703125 | 4 |
[] |
no_license
|
/****************************************************************************************************/
/*
ܣӦC++ʵֵĸ
ĽڵLinkNodeװһSListཫЧڵ
ijԱ
캯캯ֵء
**
**ľ
** 1βڵ
** 2ӡ
** 3ÿ
** 4ββڵ
** 5ͷ
** 6ɾڵ
** 7̶λòһڵ
** 8ɾijһڵ
** 9ijڵ㲢ڵλ
** 10ڵĿ
** 11ijڵ㲢ɾ
** 12ɾеx
** 13ȥ
** 14ϲ
** 15ð
** 16ת
**
** By Lynn-Zhang
**
*/
/*****************************************************************************************************
typedef int DataType;
//ڵ̬ࣨ
//struct LinkNode
//{
// friend class SList; //SListΪԪSListԷʽڵ˽гԱ
//public:
// LinkNode(const DataType x);
//private:
// DataType _data; //ڵ
// LinkNode* _next; //ָýڵһڵ
//};
//ֱstructLinkNode࣬ΪstructijԱĬΪݳԱԿֱӷ
struct LinkNode //ڵ(д)
{
LinkNode(const DataType x);
DataType _data; //ڵ
LinkNode* _next; //ָýڵһڵ
};
class SList
{
public:
SList(); //캯
SList(const SList& s); //
SList &operator=(SList& s); //ֵ
~SList();
public:
//ľ
void Uniqe(); //ȥ
void Merge(SList &s); //ϲ
void Sort(); //ð
void Reverse(); //ת
void Swap(SList& s); //
void PrintSList(); //ӡ
void PushBack(const DataType& x); //βһڵ
void Clear(); //ÿ
void PopBack(); //ɾβڵ
void PushFront(DataType x); //ͷ
void PopFront(); //ɾڵ
void Insert(LinkNode* pos, DataType x);//̶λòһڵ
void Erase(LinkNode* pos); //ɾijһڵ
LinkNode* Find(DataType x); //ҽڵ㲢ڵĵַ
int Amount(); //ڵĿ
void Remove(DataType x); //ijڵ㲢ɾ
void RemoveAll(DataType x); //ɾеx
private:
LinkNode* _head; //ָͷڵ
LinkNode* _tail; //ָβڵ
};
//*********************//
|
C++
|
UTF-8
| 775 | 3.46875 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution
{
public:
vector<int> sieveOfEratosthenes(int N)
{
// Write Your Code here
vector<int> prime(N + 1, 1);
prime[0] = prime[1] = 0;
for (int i = 2; i <= N; i++)
{
if (prime[i])
{
for (int j = i * i; j <= N; j += i)
{
prime[j] = 0;
}
}
}
vector<int> res;
for (int i = 2; i <= N; i++)
if (prime[i])
res.push_back(i);
return res;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int N;
cin >> N;
Solution ob;
vector<int> primes = ob.sieveOfEratosthenes(N);
for (auto prime : primes) {
cout << prime << " ";
}
cout << endl;
}
return 0;
} // } Driver Code Ends
|
Python
|
UTF-8
| 398 | 3.265625 | 3 |
[] |
no_license
|
import json
clientes_dict = {'maria': 27, 'Pedro': 22, 'João': 14, 'Ana': 17}
# Criando e Salvando Arquivo Json convertendo dicionário
with open('clientes.json', 'a+') as arquivo:
json.dump(clientes_dict, arquivo)
# # Abrindo arquivo Json e convertendo o objeto em dicionario python
# with open('clientes.json', 'r') as arquivo:
# dados = json.load(arquivo)
# print(dados)
|
C#
|
UTF-8
| 1,364 | 2.546875 | 3 |
[] |
no_license
|
// **************************************************************************************
// ** **
// ** (C) FOOSBOT - Final Software Engineering Project, 2015 - 2016 **
// ** (C) Authors: M.Toubian, M.Shimon, E.Kleinman, O.Sasson, J.Gleyzer **
// ** Advisors: Mr.Resh Amit & Dr.Hoffner Yigal **
// ** The information and source code here belongs to Foosbot project **
// ** and may not be reproduced or used without authors explicit permission. **
// ** **
// **************************************************************************************
using System;
namespace Foosbot
{
/// <summary>
/// Exception Thrown in case configuration error appeared
/// </summary>
public class ConfigurationException : Exception
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="message">Message</param>
public ConfigurationException(string message) : base(message) { }
/// <summary>
/// Constructor
/// </summary>
/// <param name="message">Message</param>
/// <param name="innerException">Inner Exception</param>
public ConfigurationException(string message, Exception innerException)
: base(message, innerException) { }
}
}
|
Python
|
UTF-8
| 1,778 | 3.890625 | 4 |
[] |
no_license
|
"""
Date:27/04/2021
1622. Fancy Sequence - Leetcode Hard
The following problem is solved using maths logic..+ modular inverse multiplication.
The concept used are:
1)modular arithetic assumes normal rules of arithmetic under modular operation,so operations are lossless..
2)Whenver (N/D)%mod is to performed,then always do N*mulinv(D)%mod,so that ans is lossless ,as many information are lost using N/D and ans is in float whereas %operation under N/D should always give interger.
3)We use the offset technique.While inserting we modify the input by first subtracting by addition upto that point and then result val is divided by product to be multiplied,This modified value is stored in Seq list.
Hint:https://www.youtube.com/watch?v=Z0ymtF4dExU .. by erricto go to 39 mins
"""
class Fancy:
def __init__(self):
self.seq=[]
self.add=0
self.prod=1
self.mod = 10**9 + 7
def append(self, val: int) -> None:
val=val-self.add
mulinv=pow(self.prod,self.mod-2,self.mod)#Using fermet little theorem for primality test.
val=val*mulinv #basically (val/prod)%mod
self.seq.append(val%self.mod)
def addAll(self, inc: int) -> None:
self.add+=inc
self.add%=self.mod
def multAll(self, m: int) -> None:
self.prod*=m
self.prod%=self.mod
self.add*=m
self.add%=self.mod
def getIndex(self, idx: int) -> int:
if idx>=len(self.seq):
return -1
val=self.seq[idx]
ans=val*self.prod + self.add
return ans%self.mod
# Your Fancy object will be instantiated and called as such:
# obj = Fancy()
# obj.append(val)
# obj.addAll(inc)
# obj.multAll(m)
# param_4 = obj.getIndex(idx)
|
C++
|
UTF-8
| 7,606 | 2.625 | 3 |
[] |
no_license
|
#include "Distances.h"
#include "DirectXLib\D3DVECTORHelper.h"
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceFromShape(CShapeImm* pcShape, D3DVECTOR* pcPoint)
{
int iType;
void* pvShape;
float fDistance;
float fTemp;
fDistance = 1e30f;
pvShape = pcShape->GetFirst(&iType);
while (pvShape)
{
switch(iType)
{
case ST_Sphere:
fTemp = PointDistanceFromSphere((CSphereImm*)pvShape, pcPoint);
break;
case ST_Plane:
fTemp = PointDistanceFromPlane((CPlaneImm*)pvShape, pcPoint);
break;
//case ST_Capsule:
// fTemp = PointDistanceFromCapsule((CPlaneImm*)pvShape, pcPoint);
// break;
//case ST_ConvexHull:
// fTemp = PointDistanceFromConvexHull((CPlaneImm*)pvShape, pcPoint);
// break;
}
if (fTemp < fDistance)
{
fDistance = fTemp;
}
pvShape = pcShape->GetNext(pvShape, &iType);
}
return fDistance;
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDirectedDistanceFromShape(CShapeImm* pcShape, D3DVECTOR* psPoint, D3DVECTOR* psDirection)
{
int iType;
void* pvShape;
float fDistance;
float fTemp;
D3DVECTOR sTemp;
fDistance = 1e30f;
pvShape = pcShape->GetFirst(&iType);
while (pvShape)
{
switch(iType)
{
case ST_Sphere:
fTemp = PointDirectedDistanceFromSphere((CSphereImm*)pvShape, psPoint, &sTemp);
break;
case ST_Plane:
fTemp = PointDirectedDistanceFromPlane((CPlaneImm*)pvShape, psPoint, &sTemp);
break;
}
if (fTemp < fDistance)
{
fDistance = fTemp;
D3DXVec3Assign((D3DXVECTOR3*)psDirection, (D3DXVECTOR3*)&sTemp);
}
pvShape = pcShape->GetNext(pvShape, &iType);
}
return fDistance;
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceFromSphere(CSphereImm* pcSphere, D3DVECTOR* point)
{
D3DXVECTOR3 temp;
float f;
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)&pcSphere->msPosition, (D3DXVECTOR3*)point);
f = D3DXVec3Length(&temp) - pcSphere->mfRadius;
return f;
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceFromPoint(D3DVECTOR* point1, D3DVECTOR* point2)
{
D3DXVECTOR3 temp;
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)point1, (D3DXVECTOR3*)point2);
return D3DXVec3Length(&temp);
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceSquaredFromPoint(D3DVECTOR* point1, D3DVECTOR* point2)
{
D3DXVECTOR3 temp;
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)point1, (D3DXVECTOR3*)point2);
return D3DXVec3Dot(&temp, &temp);
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceFromLineInfinite(CLineInfinite* pcLine, D3DVECTOR* point)
{
D3DXVECTOR3 v1;
D3DXVECTOR3 v2;
D3DXVec3Subtract(&v1, (D3DXVECTOR3*)point, (D3DXVECTOR3*)&pcLine->msStart);
D3DXVec3Cross(&v2, &v1, (D3DXVECTOR3*)&pcLine->msDirection);
return D3DXVec3Length(&v2);
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceAlongLineInfinite(CLineInfinite* pcLine, D3DVECTOR* point)
{
D3DXVECTOR3 temp;
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)point, (D3DXVECTOR3*)&pcLine->msStart);
return D3DXVec3Dot(&temp, (D3DXVECTOR3*)&pcLine->msDirection);
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceFromLineSegment(CLineSegmentImm* pcLine, D3DVECTOR* point)
{
D3DXVECTOR3 temp;
D3DXVECTOR3 v2;
float d;
//Perpendicular distance along pcLine
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)point, (D3DXVECTOR3*)&pcLine->msStart);
d = D3DXVec3Dot(&temp, (D3DXVECTOR3*)&pcLine->msDirection);
//If d lies between 0 and length then shortest distance to point from pcLine is perpendicular to it.
if ((d >= 0) && (d <= pcLine->mfLength))
{
D3DXVec3Cross(&v2, &temp, (D3DXVECTOR3*)&pcLine->msDirection);
return D3DXVec3Length(&v2);
}
//If d is less than 0 then shortest distance is from start to point.
else if (d < 0)
{
return D3DXVec3Length(&temp);
}
//If d is greater than length then shortest distance is from msEnd to point.
else
{
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)point, (D3DXVECTOR3*)&pcLine->msEnd);
return D3DXVec3Length(&temp);
}
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceSquaredFromLineSegment(CLineSegmentImm* pcLine, D3DVECTOR* point)
{
D3DXVECTOR3 temp;
D3DXVECTOR3 v2;
float d;
//Perpendicular distance along pcLine
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)point, (D3DXVECTOR3*)&pcLine->msStart);
d = D3DXVec3Dot(&temp, (D3DXVECTOR3*)&pcLine->msDirection);
//If d lies between 0 and length then shortest distance to point from pcLine is perpendicular to it.
if ((d >= 0) && (d <= pcLine->mfLength))
{
D3DXVec3Cross(&v2, &temp, (D3DXVECTOR3*)&pcLine->msDirection);
return D3DXVec3Dot(&v2, &v2);
}
//If d is less than 0 then shortest distance is from start to point.
else if (d < 0)
{
return D3DXVec3Dot(&temp, &temp);
}
//If d is greater than length then shortest distance is from msEnd to point.
else
{
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)point, (D3DXVECTOR3*)&pcLine->msEnd);
return D3DXVec3Dot(&temp, &temp);
}
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDistanceFromPlane(CPlaneImm* pcPlane, D3DVECTOR* psPoint)
{
return D3DXVec3Dot((D3DXVECTOR3*)&pcPlane->sNormal, (D3DXVECTOR3*)psPoint);
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDirectedDistanceFromPlane(CPlaneImm* pcPlane, D3DVECTOR* psPoint, D3DVECTOR* psDirection)
{
D3DXVECTOR3 temp;
D3DXVec3Assign((D3DXVECTOR3*)psDirection, (D3DXVECTOR3*)&pcPlane->sNormal);
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)psPoint, (D3DXVECTOR3*)&pcPlane->sPosition);
return D3DXVec3Dot((D3DXVECTOR3*)&pcPlane->sNormal, &temp);
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
float PointDirectedDistanceFromSphere(CSphereImm* pcSphere, D3DVECTOR* psPoint, D3DVECTOR* psDirection)
{
D3DXVECTOR3 temp;
float f;
float fInv;
D3DXVec3Subtract(&temp, (D3DXVECTOR3*)psPoint, (D3DXVECTOR3*)&pcSphere->msPosition);
f = D3DXVec3Length(&temp) - pcSphere->mfRadius;
if (f > 0.0f)
{
fInv = 1.0f / f;
D3DXVec3Assign((D3DXVECTOR3*)psDirection, temp.x*fInv, temp.y*fInv, temp.z*fInv);
}
else
{
D3DXVec3Assign((D3DXVECTOR3*)psDirection, 0.0f, 0.0f, 0.0f);
}
return f;
}
|
C#
|
UTF-8
| 440 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
using System;
namespace Proxy.AOP
{
public class RealFightManager : IFightManager
{
public void DoFight(string username)
{
Console.WriteLine(username + " 帶領冒險者們與無辜的怪物戰鬥");
Console.WriteLine("......正在戰鬥中.....");
Console.WriteLine(username + " 帶領冒險者們洗劫怪物的家,結束一場慘無妖道的屠殺!!");
}
}
}
|
Python
|
UTF-8
| 2,719 | 2.9375 | 3 |
[
"Apache-2.0"
] |
permissive
|
'''
Usage: {hods} SUBCOMMAND [ARGUMENTS]
{hods} help SUBCOMMAND
Manage structured data stored in plain text files with YAML or JSON formatting.
Available subcommands:
{subcommands}
To view help message for a specific subcommand use:
{hods} help SUBCOMMAND
Copyright 2018 Vitaly Potyarkin
https://github.com/sio/hods
This program is Free Software and comes with ABSOLUTELY NO WARRANTY,
to the extent permitted by applicable law. For more information see:
http://www.apache.org/licenses/LICENSE-2.0
'''
import os.path
import pkgutil
import sys
import textwrap
from importlib import import_module
EXECUTABLE = os.path.basename(sys.argv[0])
def main():
'''
Main entry point for CLI commands
Subcommands are defined in other modules of this package. Each module has
to provide the main() function.
If help() function is provided, it will be used to display usage message
for that subcommand, otherwise the usage message will be generated from the
`main()` docstring or the module docstring.
'''
arguments = sys.argv + [None, None]
show_help = arguments[1] in {'help', '--help', '--usage', '-h'}
if show_help:
subcommand = arguments[2]
else:
subcommand = arguments[1]
if not subcommand:
return usage()
try:
submodule = import_module('.' + subcommand, __package__)
if show_help or arguments[2] == '--help':
try:
submodule.help()
except AttributeError:
message = submodule.main.__doc__
if not message or not message.strip():
message = submodule.__doc__
show_help_message(message.format(
hods=EXECUTABLE,
subcommand=subcommand,
))
else:
submodule.main()
except ImportError:
# TODO: add handler for third-party subcommands, like `hods-subcommand`
print(
'Unsupported subcommand: {}\n'.format(subcommand),
file=sys.stderr,
flush=True
)
usage()
sys.exit(1)
def usage():
'''Show usage message'''
path = os.path.dirname(__file__)
subcommands = []
for _, name, is_package in pkgutil.iter_modules([path,]):
if not is_package and not name.startswith('_'):
subcommands.append(name)
show_help_message(__doc__.format(
hods=EXECUTABLE,
subcommands='\n'.join(' %s' % sub for sub in sorted(subcommands))
))
def show_help_message(message):
'''
Fix indentation and trailing whitespace in the message before printing
it to stdout
'''
print(textwrap.dedent(message).strip())
|
C++
|
UTF-8
| 898 | 3.203125 | 3 |
[] |
no_license
|
/*
* Complexidade:
* Pior Caso: O(n^2)
* Caso medio: O()
* Melhor Caso: O(n+k)
*
* Memoria usada:
* O(n) para vetor
* O(n.k) para auxiliar
*
* Estavel: Sim
*/
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
#include "../utils.h"
using namespace std;
const int MAX = 8;
void bucketSort(vector<float> &vet){
int tam = vet.size();
vector<float> temp[tam];
for(int i=0; i<tam; i++){
int index = tam*vet[i];
temp[index].push_back(vet[i]);
}
for(int i=0; i<tam; i++)
sort(temp[i].begin(), temp[i].end());
int k = 0;
for(int i=0; i<tam; i++)
for(int j=0; j<(int) temp[i].size(); j++)
vet[k++] = temp[i][j];
}
int main(){
srand(time(NULL));
vector<float> vet;
for(int i=0; i<MAX; i++){
float x = ((rand()%100)+1)/100.0;
vet.push_back(x);
}
printVector(vet);
bucketSort(vet);
printVector(vet);
return 0;
}
|
Java
|
UTF-8
| 1,085 | 2.40625 | 2 |
[] |
no_license
|
package org.pitest.pitclipse.pitrunner.client;
import java.io.Closeable;
import java.io.IOException;
import org.pitest.pitclipse.pitrunner.PitRequest;
import org.pitest.pitclipse.pitrunner.PitResults;
import org.pitest.pitclipse.pitrunner.io.ObjectStreamSocket;
import org.pitest.pitclipse.pitrunner.io.SocketProvider;
import org.pitest.pitclipse.reloc.guava.annotations.VisibleForTesting;
public class PitClient implements Closeable {
private final int portNumber;
private final SocketProvider socketProvider;
private ObjectStreamSocket socket;
public PitClient(int portNumber) {
this(portNumber, new SocketProvider());
}
@VisibleForTesting
PitClient(int portNumber, SocketProvider socketProvider) {
this.portNumber = portNumber;
this.socketProvider = socketProvider;
}
public void connect() {
socket = socketProvider.connectTo(portNumber);
}
public void sendResults(PitResults results) {
socket.write(results);
}
public PitRequest readRequest() {
return socket.read();
}
@Override
public void close() throws IOException {
socket.close();
}
}
|
Java
|
UTF-8
| 589 | 2.390625 | 2 |
[] |
no_license
|
package com.javaweb.michaelkai.common.enums;
/**
* @ClassName MsgActionEnum
* @Description TODO
* @Author YuKai Fan
* @Date 2019/8/22 23:07
* @Version 1.0
**/
public enum MsgActionEnum {
CONNECT(1, "第一次(或重连)初始化连接"),
CHAT(2, "聊天消息"),
SIGNED(3, "消息签收"),
KEEPLIVE(4, "客户端保持心跳");
public final Integer type;
public final String content;
MsgActionEnum(Integer type, String content) {
this.type = type;
this.content = content;
}
public Integer getType() {
return type;
}
}
|
Java
|
UTF-8
| 413 | 3.546875 | 4 |
[] |
no_license
|
package com.tyss.javaprogram.inheritance;
public class PrimeNumber {
public static void main(String[] args) {
int a=9;
int count=0;
for (int i =2; i <=a/2; i++)
{
if(a%i==0)
{
count++;
break;
}
}
if(count==0)
{
System.out.println("It is prime number");
}
else
{
System.out.println("not a prime number");
}
}
}
|
C
|
UTF-8
| 1,080 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
#include "./stb_image_custom.h"
typedef struct data_t {
unsigned char* data;
size_t capacity;
size_t size;
} data;
data* data_init() {
data* d = malloc(sizeof(data));
d->capacity = 1024;
d->size = 0;
d->data = malloc(sizeof(unsigned char) * d->capacity);
return d;
}
void data_free(data* d) {
free(d->data);
free(d);
}
void data_concat(data* d, void* new, int size) {
if (d->size + size > d->capacity) {
d->capacity *= 2;
d->data = realloc(d->data, sizeof(unsigned char) * d->capacity);
}
memcpy(d->data + d->size, new, sizeof(unsigned char) * size);
d->size += size;
}
void callback(void* ctx, void* ptr, int size) {
data* d = (data*)ctx;
data_concat(d, ptr, size);
}
size_t stbi_write_jpg_memory(int width, int height, int comp, unsigned char* ptr, float quality, unsigned char** output) {
data* d = data_init();
stbi_write_jpg_to_func(&callback, d, width, height, comp, ptr, quality);
size_t size = d->size;
*output = malloc(sizeof(unsigned char) * size);
memcpy(*output, d->data, sizeof(unsigned char) * size);
data_free(d);
return size;
}
|
Markdown
|
UTF-8
| 2,466 | 3.21875 | 3 |
[] |
no_license
|
# Unscented_Kalman_Filter_Project
I built this Unscented Kalman filter using C++ to estimate the state of a moving object of interest with noisy lidar and radar measurements
A standard Kalman filter can only handle linear equations. Both the Extended Kalman filter and the Unscented Kalman filter allow you to use non-linear equations; the difference between EKF and UKF is how they handle non-linear equations.
Instead of using linearization to predict the behavior of the system under investigation in the Extended Kalman filter, I used the Unscented Transformation. This filter has some advantages when compared to the EKF, because the Unscented transformation describes the nonlinear system better than the linearization, hence this filter converges to the right solution more rapidly. However, like the EKF, this filter may become unstable and results may be biased.
All Kalman filters have the same three steps:
1. Initialization
2. Prediction
3. Update
***
### Files in the GitHub src Folder
**main.cpp** - reads in data, calls a function to run the Kalman filter, calls a function to calculate RMSE
**ukf.cpp** - initializes the filter, calls the predict and update function, defines the predict and update functions
**tools.cpp** - function to calculate RMSE
***
### Data
The data file information is provided by the simulator and is the same data files from EKF. Again each line in the data file represents either a lidar or radar measurement marked by "L" or "R" on the starting line. The next columns are either the two lidar position measurements (x,y) or the three radar position measurements (rho, phi, rho_dot). Then comes the time stamp and finally the ground truth values for x, y, vx, vy, yaw, yawrate.
Although the data set contains values for yaw and yawrate ground truth, there is no need to use these values. main.cpp does not use these values, and you are only expected to calculate RMSE for x, y vx and vy. You can compare your vx and vy RMSE values from the UKF project and the EKF project. For UKF, vx and vy RMSE should be lower than for EKF; this is because we are using a more detailed motion model and UKF is also known for handling non-linear equations better than EKF.
***
### To Run The Code:
1. cd build
2. cmake ..
3. make
4. ./UnscentedKF ../data/obj_pose-laser-radar-synthetic-input.txt output.txt
#### Make sure you have the following dependencies installed:
- cmake >= v3.5
- make >= v4.1
- gcc/g++ >= v5.4
|
C#
|
UTF-8
| 2,995 | 3.03125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WiseBet.Models
{
public class LottoNumbers
{
public int num1 { get; set; }
public int num2 { get; set; }
public int num3 { get; set; }
public int num4 { get; set; }
public int num5 { get; set; }
public int num6 { get; set; }
public int strongNumber { get; set; }
public static int[] FindKBiggestNumbers(int[] testArray, int k)
{
int[] result = new int[k];
int[] common = new int[k];
for (int i = 0; i < testArray.Length; i++)
{
//if bigger than the smallest node
if (testArray[i] <= result[0])
{
continue;
}
else
{
//if bigger than all?
if (testArray[i] > result[k - 1])
{
for (int l = 0; l < k - 1; l++)
{
result[l] = result[l + 1];
}
result[k - 1] = testArray[i];
common[k - 1] = i;
}
else
{
//binary search
int indexLeft = 0;
int indexRight = k - 1;
int currIndex = (indexRight + indexLeft) / 2; ;
//10 20 30 40 50 - > place 33
while (indexRight - indexLeft > 1)
{
if (testArray[i] >= result[currIndex])
{
indexLeft = currIndex;
}
else
{
indexRight = currIndex;
}
currIndex = (indexRight + indexLeft) / 2;
}
for (int l = 0; l < currIndex; l++)
{
result[l] = result[l + 1];
common[l] = common[l + 1];
}
result[currIndex] = testArray[i];
common[currIndex] = i;
}
}
}
return common;
}
public static int FindStrongNumber(int[] strongArr)
{
int strong = 0, min, max = 0;
for (int i = 1; i < strongArr.Length; i++)
{
min = strongArr[i];
if (max < min)
{
max = min;
strong = i;
}
}
return strong;
}
}
}
|
Java
|
UTF-8
| 394 | 1.9375 | 2 |
[] |
no_license
|
package org.company.erp.core.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.company.erp.core.model.Template;
import org.company.erp.core.model.TemplatesGroup;
import java.util.List;
@Mapper
public interface TemplateMapper {
List<Template> getTemplateList();
List<TemplatesGroup> getTemplatesGroupList();
List<Template> getTemplateListByGroup(long groupId);
}
|
PHP
|
UTF-8
| 635 | 2.765625 | 3 |
[] |
no_license
|
<?php
/**
* Interfaz que define los metodos que realizaran
* consultas sobre la base de datos relacionado con la entidad
* correspondiente.
* @author Miguel Callon
*/
interface IEstadoUsuarioDAO extends IDAO {
/**
* Metodo que obtiene un EstadoUsuario de base de datos pasandole
* un EstadoUsuarioBean con el idEstadoUsuario.
* @param $idEstadoUsuario Identificador del estado de usuario
* @param $estadoUsuarioBean objeto de la base de datos que tiene los
* datos de un estado usuario.
* @author Miguel Callon
*/
public function consultarEstadoUsuario($idEstadoUsuario,
EstadoUsuarioBean $estadoUsuarioBean);
}
?>
|
Java
|
UTF-8
| 1,600 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ggj16.officeobjects;
import bropals.lib.simplegame.animation.Animation;
import bropals.lib.simplegame.entity.GameWorld;
import ggj16.Camera;
import ggj16.OfficeObject;
import ggj16.Task;
import ggj16.tasks.HitImpTask;
import ggj16.tasks.InterviewTask;
import java.awt.image.BufferedImage;
/**
*
* @author Jonathon
*/
public class OfficeTaskObject extends OfficeObject {
private Task associatedTask;
public OfficeTaskObject(GameWorld par, float x, BufferedImage image, Camera camera, Task associatedTask) {
super(par, x, image, camera);
this.associatedTask = associatedTask;
}
public OfficeTaskObject(GameWorld par, float x, Animation animation, Camera camera, Task associatedTask) {
super(par, x, animation, camera);
this.associatedTask = associatedTask;
}
public Task getAssociatedTask() {
return associatedTask;
}
@Override
public void update(int delta) {
super.update(delta);
if (associatedTask != null) {
if (associatedTask instanceof HitImpTask ||
associatedTask instanceof InterviewTask) {
associatedTask.update(delta);
}
}
}
public boolean collidesWith(PlayerDemon player) {
float half = player.getX() + (player.getWidth()/2);
return half > getX() && half < getX() + getWidth();
}
}
|
Markdown
|
UTF-8
| 1,403 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
skypper
=======
Converts an image into Skype emoticons using the HTML5 Canvas element. Because, well, it's possible.
- Input: an image element with data (mario.png!)
- Output: a text block with a lot of Skype emoticons
Creates a one-to-one mapping between each image pixel and the predefined colors,
so pretty much the only image that currently makes sense is mario.png.
tl;dr
-----
(e)(e)(e)(e)(devil)(devil)(devil)(devil)(devil)(e)(e)(y)(y)(y)(e)
(e)(e)(e)(devil)(devil)(devil)(devil)(devil)(devil)(devil)(devil)(devil)(y)(y)(e)
(e)(e)(e)(hug)(hug)(hug)(y)(y)(emo)(y)(devil)(devil)(devil)(devil)(e)
(e)(e)(hug)(y)(hug)(y)(y)(y)(emo)(y)(y)(y)(devil)(devil)(e)
(e)(e)(hug)(y)(hug)(hug)(y)(y)(y)(emo)(y)(y)(y)(e)(e)
(e)(e)(hug)(hug)(y)(y)(y)(y)(emo)(emo)(emo)(emo)(devil)(e)(e)
(e)(e)(e)(y)(y)(y)(y)(y)(y)(y)(y)(devil)(devil)(e)(e)
(e)(devil)(devil)(devil)(devil)(skype)(devil)(devil)(devil)(skype)(devil)(devil)(e)(e)(hug)
(e)(devil)(devil)(devil)(devil)(devil)(skype)(devil)(devil)(devil)(skype)(e)(e)(hug)(hug)
(e)(e)(devil)(devil)(devil)(devil)(skype)(skype)(skype)(skype)(sun)(skype)(skype)(hug)(hug)
(e)(e)(e)(skype)(skype)(skype)(skype)(sun)(skype)(skype)(skype)(skype)(skype)(hug)(hug)
(e)(hug)(hug)(skype)(skype)(skype)(skype)(skype)(skype)(e)(e)(e)(e)(e)(e)
(hug)(hug)(hug)(e)(e)(e)(e)(e)(e)(e)(e)(e)(e)(e)(e)
(hug)(hug)(e)(e)(e)(e)(e)(e)(e)(e)(e)(e)(e)(e)(e)
License: MIT
|
Java
|
UTF-8
| 21,323 | 2.34375 | 2 |
[] |
no_license
|
package com.dk.pojo;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class CarExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public CarExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
protected void addCriterionForJDBCDate(String condition, Date value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value.getTime()), property);
}
protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
Iterator<Date> iter = values.iterator();
while (iter.hasNext()) {
dateList.add(new java.sql.Date(iter.next().getTime()));
}
addCriterion(condition, dateList, property);
}
protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
}
public Criteria andCarIdIsNull() {
addCriterion("car_id is null");
return (Criteria) this;
}
public Criteria andCarIdIsNotNull() {
addCriterion("car_id is not null");
return (Criteria) this;
}
public Criteria andCarIdEqualTo(Integer value) {
addCriterion("car_id =", value, "carId");
return (Criteria) this;
}
public Criteria andCarIdNotEqualTo(Integer value) {
addCriterion("car_id <>", value, "carId");
return (Criteria) this;
}
public Criteria andCarIdGreaterThan(Integer value) {
addCriterion("car_id >", value, "carId");
return (Criteria) this;
}
public Criteria andCarIdGreaterThanOrEqualTo(Integer value) {
addCriterion("car_id >=", value, "carId");
return (Criteria) this;
}
public Criteria andCarIdLessThan(Integer value) {
addCriterion("car_id <", value, "carId");
return (Criteria) this;
}
public Criteria andCarIdLessThanOrEqualTo(Integer value) {
addCriterion("car_id <=", value, "carId");
return (Criteria) this;
}
public Criteria andCarIdIn(List<Integer> values) {
addCriterion("car_id in", values, "carId");
return (Criteria) this;
}
public Criteria andCarIdNotIn(List<Integer> values) {
addCriterion("car_id not in", values, "carId");
return (Criteria) this;
}
public Criteria andCarIdBetween(Integer value1, Integer value2) {
addCriterion("car_id between", value1, value2, "carId");
return (Criteria) this;
}
public Criteria andCarIdNotBetween(Integer value1, Integer value2) {
addCriterion("car_id not between", value1, value2, "carId");
return (Criteria) this;
}
public Criteria andCarNameIsNull() {
addCriterion("car_name is null");
return (Criteria) this;
}
public Criteria andCarNameIsNotNull() {
addCriterion("car_name is not null");
return (Criteria) this;
}
public Criteria andCarNameEqualTo(String value) {
addCriterion("car_name =", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameNotEqualTo(String value) {
addCriterion("car_name <>", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameGreaterThan(String value) {
addCriterion("car_name >", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameGreaterThanOrEqualTo(String value) {
addCriterion("car_name >=", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameLessThan(String value) {
addCriterion("car_name <", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameLessThanOrEqualTo(String value) {
addCriterion("car_name <=", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameLike(String value) {
addCriterion("car_name like", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameNotLike(String value) {
addCriterion("car_name not like", value, "carName");
return (Criteria) this;
}
public Criteria andCarNameIn(List<String> values) {
addCriterion("car_name in", values, "carName");
return (Criteria) this;
}
public Criteria andCarNameNotIn(List<String> values) {
addCriterion("car_name not in", values, "carName");
return (Criteria) this;
}
public Criteria andCarNameBetween(String value1, String value2) {
addCriterion("car_name between", value1, value2, "carName");
return (Criteria) this;
}
public Criteria andCarNameNotBetween(String value1, String value2) {
addCriterion("car_name not between", value1, value2, "carName");
return (Criteria) this;
}
public Criteria andCarPriceIsNull() {
addCriterion("car_price is null");
return (Criteria) this;
}
public Criteria andCarPriceIsNotNull() {
addCriterion("car_price is not null");
return (Criteria) this;
}
public Criteria andCarPriceEqualTo(Integer value) {
addCriterion("car_price =", value, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceNotEqualTo(Integer value) {
addCriterion("car_price <>", value, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceGreaterThan(Integer value) {
addCriterion("car_price >", value, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceGreaterThanOrEqualTo(Integer value) {
addCriterion("car_price >=", value, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceLessThan(Integer value) {
addCriterion("car_price <", value, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceLessThanOrEqualTo(Integer value) {
addCriterion("car_price <=", value, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceIn(List<Integer> values) {
addCriterion("car_price in", values, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceNotIn(List<Integer> values) {
addCriterion("car_price not in", values, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceBetween(Integer value1, Integer value2) {
addCriterion("car_price between", value1, value2, "carPrice");
return (Criteria) this;
}
public Criteria andCarPriceNotBetween(Integer value1, Integer value2) {
addCriterion("car_price not between", value1, value2, "carPrice");
return (Criteria) this;
}
public Criteria andCarTypeIsNull() {
addCriterion("car_type is null");
return (Criteria) this;
}
public Criteria andCarTypeIsNotNull() {
addCriterion("car_type is not null");
return (Criteria) this;
}
public Criteria andCarTypeEqualTo(Integer value) {
addCriterion("car_type =", value, "carType");
return (Criteria) this;
}
public Criteria andCarTypeNotEqualTo(Integer value) {
addCriterion("car_type <>", value, "carType");
return (Criteria) this;
}
public Criteria andCarTypeGreaterThan(Integer value) {
addCriterion("car_type >", value, "carType");
return (Criteria) this;
}
public Criteria andCarTypeGreaterThanOrEqualTo(Integer value) {
addCriterion("car_type >=", value, "carType");
return (Criteria) this;
}
public Criteria andCarTypeLessThan(Integer value) {
addCriterion("car_type <", value, "carType");
return (Criteria) this;
}
public Criteria andCarTypeLessThanOrEqualTo(Integer value) {
addCriterion("car_type <=", value, "carType");
return (Criteria) this;
}
public Criteria andCarTypeIn(List<Integer> values) {
addCriterion("car_type in", values, "carType");
return (Criteria) this;
}
public Criteria andCarTypeNotIn(List<Integer> values) {
addCriterion("car_type not in", values, "carType");
return (Criteria) this;
}
public Criteria andCarTypeBetween(Integer value1, Integer value2) {
addCriterion("car_type between", value1, value2, "carType");
return (Criteria) this;
}
public Criteria andCarTypeNotBetween(Integer value1, Integer value2) {
addCriterion("car_type not between", value1, value2, "carType");
return (Criteria) this;
}
public Criteria andManuTimeIsNull() {
addCriterion("manu_time is null");
return (Criteria) this;
}
public Criteria andManuTimeIsNotNull() {
addCriterion("manu_time is not null");
return (Criteria) this;
}
public Criteria andManuTimeEqualTo(Date value) {
addCriterionForJDBCDate("manu_time =", value, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeNotEqualTo(Date value) {
addCriterionForJDBCDate("manu_time <>", value, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeGreaterThan(Date value) {
addCriterionForJDBCDate("manu_time >", value, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeGreaterThanOrEqualTo(Date value) {
addCriterionForJDBCDate("manu_time >=", value, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeLessThan(Date value) {
addCriterionForJDBCDate("manu_time <", value, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeLessThanOrEqualTo(Date value) {
addCriterionForJDBCDate("manu_time <=", value, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeIn(List<Date> values) {
addCriterionForJDBCDate("manu_time in", values, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeNotIn(List<Date> values) {
addCriterionForJDBCDate("manu_time not in", values, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeBetween(Date value1, Date value2) {
addCriterionForJDBCDate("manu_time between", value1, value2, "manuTime");
return (Criteria) this;
}
public Criteria andManuTimeNotBetween(Date value1, Date value2) {
addCriterionForJDBCDate("manu_time not between", value1, value2, "manuTime");
return (Criteria) this;
}
public Criteria andExpireTimeIsNull() {
addCriterion("expire_time is null");
return (Criteria) this;
}
public Criteria andExpireTimeIsNotNull() {
addCriterion("expire_time is not null");
return (Criteria) this;
}
public Criteria andExpireTimeEqualTo(Date value) {
addCriterionForJDBCDate("expire_time =", value, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeNotEqualTo(Date value) {
addCriterionForJDBCDate("expire_time <>", value, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeGreaterThan(Date value) {
addCriterionForJDBCDate("expire_time >", value, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeGreaterThanOrEqualTo(Date value) {
addCriterionForJDBCDate("expire_time >=", value, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeLessThan(Date value) {
addCriterionForJDBCDate("expire_time <", value, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeLessThanOrEqualTo(Date value) {
addCriterionForJDBCDate("expire_time <=", value, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeIn(List<Date> values) {
addCriterionForJDBCDate("expire_time in", values, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeNotIn(List<Date> values) {
addCriterionForJDBCDate("expire_time not in", values, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeBetween(Date value1, Date value2) {
addCriterionForJDBCDate("expire_time between", value1, value2, "expireTime");
return (Criteria) this;
}
public Criteria andExpireTimeNotBetween(Date value1, Date value2) {
addCriterionForJDBCDate("expire_time not between", value1, value2, "expireTime");
return (Criteria) this;
}
public Criteria andIsLowerIsNull() {
addCriterion("is_lower is null");
return (Criteria) this;
}
public Criteria andIsLowerIsNotNull() {
addCriterion("is_lower is not null");
return (Criteria) this;
}
public Criteria andIsLowerEqualTo(Integer value) {
addCriterion("is_lower =", value, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerNotEqualTo(Integer value) {
addCriterion("is_lower <>", value, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerGreaterThan(Integer value) {
addCriterion("is_lower >", value, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerGreaterThanOrEqualTo(Integer value) {
addCriterion("is_lower >=", value, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerLessThan(Integer value) {
addCriterion("is_lower <", value, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerLessThanOrEqualTo(Integer value) {
addCriterion("is_lower <=", value, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerIn(List<Integer> values) {
addCriterion("is_lower in", values, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerNotIn(List<Integer> values) {
addCriterion("is_lower not in", values, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerBetween(Integer value1, Integer value2) {
addCriterion("is_lower between", value1, value2, "isLower");
return (Criteria) this;
}
public Criteria andIsLowerNotBetween(Integer value1, Integer value2) {
addCriterion("is_lower not between", value1, value2, "isLower");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
Ruby
|
UTF-8
| 764 | 3.71875 | 4 |
[] |
no_license
|
# Helper Method
def position_taken?(board, location)
!(board[location].nil? || board[location] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
def won?(board)
WIN_COMBINATIONS.detect do |winner|
winner.all? {|token| board[token] == "X"} || winner.all?{|token| board[token] == "O"}
end
end
def full?(board)
board.all?{|token| token == "X" || token == "O"}
end
def draw?(board)
if !won?(board) && full?(board)
return true
else
return false
end
end
def over?(board)
if won?(board) || full?(board) || draw?(board)
return true
end
end
def winner(board)
if the_index_win = won?(board)
board[the_index_win.first]
end
end
|
Java
|
UTF-8
| 2,531 | 2.515625 | 3 |
[] |
no_license
|
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.domain.Shop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Reader;
public class Executor {
private static final Logger log = LoggerFactory.getLogger(Executor.class);
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 마이바티스 환경 설정 XML 파일 경로
String resource = "mybatis/config-mybatis.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 세션 및 트랜잭션 시작
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 파라미터 객체 생성 및 파라미터 등록
Shop shop = new Shop();
shop.setShopNo(4);
shop.setShopName("Dad Store");
shop.setShopLocation("D Tower Secho dong");
shop.setShopStatus("Y");
// 등록 매핑 구문 실행
sqlSession.insert("org.mybatis.persistence.ShopMapper.insert", shop);
// 파라미터 객체 생성 및 파라미터 등록
shop = new Shop();
shop.setShopNo(4);
shop.setShopStatus("N");
sqlSession.update("org.mybatis.persistence.ShopMapper.update", shop);
// 파라미터 객체 생성 및 파라미터 등록
shop = new Shop();
shop.setShopNo(4);
// 조회 매핑 구문 실행
shop = sqlSession.selectOne("org.mybatis.persistence.ShopMapper.select", shop);
log.debug(shop.getShopName());
// 파라미터 객체 생성 및 파라미터 삭제
shop = new Shop();
shop.setShopNo(4);
sqlSession.delete("org.mybatis.persistence.ShopMapper.delete", shop);
// 트랜잭션 커밋
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
// 트랜잭션 커밋
sqlSession.rollback();
} finally {
// 세션 및 트랜잭션 종료
sqlSession.close();
}
}
}
|
Java
|
UTF-8
| 1,205 | 2.1875 | 2 |
[] |
no_license
|
package com.example.pedro.greateranglia.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.example.pedro.greateranglia.services.CheckLocation;
/**
* Created by Pedro on 23/04/2018.
*/
public class ServiceLocation extends Service {
CheckLocation h1;
@Override
public void onCreate() {
/** Servicio creado... */
System.out.println("Servicio creado... +++++++++++++++++++++++++++++++++++++++++++++");
h1=new CheckLocation(getApplicationContext());
h1.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/** Servicio iniciado... */
System.out.println("Servicio iniciado... +++++++++++++++++++++++++++++++++++++++++++++");
if(!h1.isAlive()){
h1=new CheckLocation(getApplicationContext());
h1.start();
}
return START_STICKY;
}
@Override
public void onDestroy() {
// Log.d(TAG, "Servicio destruido...");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
|
Python
|
UTF-8
| 25,591 | 2.59375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
"""Module to provide main autocas functions.
All functions here, provide basic autocas workflows for groundstates and excited states
in combination with standard and large cas protocols.
"""
# -*- coding: utf-8 -*-
__copyright__ = """ This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details. """
import os
from typing import Any, Dict, List, Tuple, cast
import numpy as np
from scine_autocas import Autocas
from scine_autocas.autocas_utils.input_handler import InputHandler
from scine_autocas.autocas_utils.molecule import Molecule
from scine_autocas.interfaces import Interface
from scine_autocas.interfaces.molcas import Molcas
from scine_autocas.plots.entanglement_plot import EntanglementPlot
from scine_autocas.plots.threshold_plot import ThresholdPlot
class MainFunctions:
"""Class for autocas main.
Provides some utility functions.
Attributes
----------
results : Dict[str, Any]
stores all results
"""
def __init__(self):
"""Init."""
self.results: Dict[str, Any] = {}
def _large_cas_loop(self, interface: Interface):
partial_s1_list = []
partial_s2_list = []
partial_mutual_information_list = []
large_cas_occupations = self.results["partial_occupations"]
large_cas_indices = self.results["partial_indices"]
print("")
print(f"Number of Sub-CAS: {len(large_cas_occupations)}")
for i, occupation in enumerate(large_cas_occupations):
print("")
print(f"Evaluating CAS: {i} / {len(large_cas_occupations)}")
print(f"Current CAS(e,o): ({sum(occupation)}, {len(occupation)})")
print(f"Current orbital indices: {large_cas_indices[i]}")
print(f"Current orbital occupation: {occupation}")
(
partial_energy,
s1_partial,
s2_partial,
mutual_informaion_partial,
) = interface.calculate(occupation, large_cas_indices[i])
# energy is meaningless
_ = partial_energy
# we know we have excited states
s1_partial = cast(List[np.ndarray], s1_partial)
s2_partial = cast(List[np.ndarray], s2_partial)
mutual_informaion_partial = cast(List[np.ndarray], mutual_informaion_partial)
partial_s1_list.append(s1_partial)
partial_s2_list.append(s2_partial)
partial_mutual_information_list.append(mutual_informaion_partial)
# FOR CAST
# no excited states, so we know its a ndarray not List[ndarray]
# s1_partial = cast(np.ndarray, s1_partial)
# s2_partial = cast(np.ndarray, s2_partial)
# mutual_information_partial = cast(np.ndarray, mutual_information_partial)
self.results["partial_s1"] = partial_s1_list
self.results["partial_s2"] = partial_s2_list
self.results["partial_mutual_information_list"] = partial_mutual_information_list
def large_cas_excited_states(self, autocas: Autocas, interface: Interface):
"""Evaluate initial cas with excited states and large cas protocol.
Parameters
----------
autocas : Autocas
the autocas object to search for the active space
interface : Interface
an interface to a suitable electronic structure program
"""
print("Running large active spaces with excited states algorithm.")
# raise NotImplementedError("large cas with excited states")
if interface.dumper:
interface.dumper.large_cas = True
try:
initial_occupation = self.results["initial_occupation"]
initial_orbital_indices = self.results["initial_orbital_indices"]
except KeyError:
initial_occupation, initial_orbital_indices = autocas.make_initial_active_space()
self.results["initial_occupation"] = initial_occupation
self.results["initial_orbital_indices"] = initial_orbital_indices
large_cas_occupations, large_cas_indices = autocas.get_large_active_spaces()
self.results["partial_occupations"] = large_cas_occupations
self.results["partial_indices"] = large_cas_indices
# interface.calculate()
self._large_cas_loop(interface)
# for i, occupation in enumerate(large_cas_occupations):
# (
# partial_energy,
# s1_partial,
# s2_partial,
# mutual_informaion_partial,
# ) = interface.calculate(occupation, large_cas_indices[i])
# # energy is meaningless
# _ = partial_energy
# # we know we have excited states
# s1_partial = cast(List[np.ndarray], s1_partial)
# s2_partial = cast(List[np.ndarray], s2_partial)
# mutual_informaion_partial = cast(List[np.ndarray], mutual_informaion_partial)
# partial_s1_list.append(s1_partial)
# partial_s2_list.append(s2_partial)
# partial_mutual_information_list.append(mutual_informaion_partial)
partial_s1_list = self.results["partial_s1"]
partial_s2_list = self.results["partial_s2"]
partial_mutual_information_list = self.results["partial_mutual_information_list"]
partial_s1_per_state: List[List[np.ndarray]] = []
partial_s2_per_state: List[List[np.ndarray]] = []
partial_mut_inf_per_state: List[List[np.ndarray]] = []
for i in range(len(partial_s1_list[0])):
partial_s1_per_state.append([])
partial_s2_per_state.append([])
partial_mut_inf_per_state.append([])
for i, part_s1 in enumerate(partial_s1_list):
for j, part_s1_j in enumerate(part_s1):
partial_s1_per_state[j].append(part_s1_j)
partial_s2_per_state[j].append(partial_s2_list[i][j])
partial_mut_inf_per_state[j].append(partial_mutual_information_list[i][j])
# only for storage not for autocas
autocas_results = autocas.collect_entropies(
large_cas_indices,
large_cas_occupations,
partial_s1_per_state[0],
partial_s2_per_state[0],
partial_mut_inf_per_state[0],
)
if len(autocas_results) == 4:
autocas_results = cast(Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], autocas_results)
initial_occupation = autocas_results[0].tolist()
initial_s1 = autocas_results[1]
initial_s2 = autocas_results[2]
initial_mut_inf = autocas_results[3]
self.results["initial_occupation"] = initial_occupation
self.results["initial_s1"] = initial_s1
self.results["initial_s2"] = initial_s2
self.results["initial_mutual_information"] = initial_mut_inf
final_occupation, final_orbital_indices = autocas.get_cas_from_large_cas_excited_states(
large_cas_indices,
large_cas_occupations,
partial_s1_list,
partial_s2_list,
partial_mutual_information_list,
)
self.results["final_occupation"] = final_occupation
self.results["final_orbital_indices"] = final_orbital_indices
interface.dumper.large_cas = False
return final_occupation, final_orbital_indices
def large_cas(self, autocas: Autocas, interface: Interface):
"""Evaluate initial cas with large cas protocol.
Parameters
----------
autocas : Autocas
the autocas object to search for the active space
interface : Interface
an interface to a suitable electronic structure program
"""
print("Running large active spaces algorithm.")
if interface.dumper:
interface.dumper.large_cas = True
try:
initial_occupation = self.results["initial_occupation"]
initial_orbital_indices = self.results["initial_orbital_indices"]
except KeyError:
initial_occupation, initial_orbital_indices = autocas.make_initial_active_space()
self.results["initial_occupation"] = initial_occupation
self.results["initial_orbital_indices"] = initial_orbital_indices
large_cas_occupations, large_cas_indices = autocas.get_large_active_spaces()
self.results["partial_occupations"] = large_cas_occupations
self.results["partial_indices"] = large_cas_indices
self._large_cas_loop(interface)
# for i, occupation in enumerate(large_cas_occupations):
# (
# partial_energy,
# s1_partial,
# s2_partial,
# mutual_information_partial,
# ) = interface.calculate(occupation, large_cas_indices[i])
# # energy is meaningless
# _ = partial_energy
# # no excited states, so we know its a ndarray not List[ndarray]
# s1_partial = cast(np.ndarray, s1_partial)
# s2_partial = cast(np.ndarray, s2_partial)
# mutual_information_partial = cast(np.ndarray, mutual_information_partial)
# partial_s1_list.append(s1_partial)
# partial_s2_list.append(s2_partial)
# partial_mutual_information_list.append(mutual_information_partial)
partial_s1_list = self.results["partial_s1"]
partial_s2_list = self.results["partial_s2"]
partial_mutual_information_list = self.results["partial_mutual_information_list"]
autocas_results = autocas.collect_entropies(
large_cas_indices,
large_cas_occupations,
partial_s1_list,
partial_s2_list,
partial_mutual_information_list
)
if len(autocas_results) == 4:
autocas_results = cast(Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], autocas_results)
initial_occupation = autocas_results[0].tolist()
initial_s1 = autocas_results[1]
initial_s2 = autocas_results[2]
initial_mut_inf = autocas_results[3]
self.results["initial_occupation"] = initial_occupation
self.results["initial_s1"] = initial_s1
self.results["initial_s2"] = initial_s2
self.results["initial_mutual_information"] = initial_mut_inf
final_occupation, final_orbital_indices = autocas.get_cas_from_large_cas(
large_cas_indices,
large_cas_occupations,
partial_s1_list,
partial_s2_list,
partial_mutual_information_list,
)
self.results["final_occupation"] = final_occupation
self.results["final_orbital_indices"] = final_orbital_indices
interface.dumper.large_cas = False
return final_occupation, final_orbital_indices
def excited_states(self, autocas: Autocas, interface: Interface):
"""Evaluate initial cas with excited states.
Parameters
----------
autocas : Autocas
the autocas object to search for the active space
interface : Interface
an interface to a suitable electronic structure program
"""
print("Running excited states algorithm.")
try:
initial_occupation = self.results["initial_occupation"]
initial_orbital_indices = self.results["initial_orbital_indices"]
except KeyError:
initial_occupation, initial_orbital_indices = autocas.make_initial_active_space()
self.results["initial_occupation"] = initial_occupation
self.results["initial_orbital_indices"] = initial_orbital_indices
energy, initial_s1, initial_s2, initial_mutual_information = interface.calculate(
initial_occupation, initial_orbital_indices
)
# energy is meaningless
_ = energy
# we know we calculate excited states
initial_s1 = cast(List[np.ndarray], initial_s1)
initial_s2 = cast(List[np.ndarray], initial_s2)
initial_mutual_information = cast(List[np.ndarray], initial_mutual_information)
self.results["initial_s1"] = initial_s1[0]
self.results["initial_s2"] = initial_s2[0]
self.results["initial_mutual_information"] = initial_mutual_information[0]
final_occupation, final_orbital_indices = autocas.get_cas_from_excited_states(
initial_occupation,
initial_s1,
mutual_information_list=initial_mutual_information,
force_cas=False,
)
self.results["final_occupation"] = final_occupation
self.results["final_orbital_indices"] = final_orbital_indices
return final_occupation, final_orbital_indices
def conventional(self, autocas: Autocas, interface: Interface):
"""Evaluate initial cas.
Parameters
----------
autocas : Autocas
the autocas object to search for the active space
interface : Interface
an interface to a suitable electronic structure program
"""
try:
initial_occupation = self.results["initial_occupation"]
initial_orbital_indices = self.results["initial_orbital_indices"]
except KeyError:
initial_occupation, initial_orbital_indices = autocas.make_initial_active_space()
self.results["initial_occupation"] = initial_occupation
self.results["initial_orbital_indices"] = initial_orbital_indices
# interface.calculate()
energy, initial_s1, initial_s2, initial_mutual_information = interface.calculate(
initial_occupation, initial_orbital_indices
)
# energy is meaningless
_ = energy
# we know we do not calculate excited states
initial_s1 = cast(np.ndarray, initial_s1)
initial_s2 = cast(np.ndarray, initial_s2)
initial_mutual_information = cast(np.ndarray, initial_mutual_information)
self.results["initial_s1"] = initial_s1
self.results["initial_s2"] = initial_s2
self.results["initial_mutual_information"] = initial_mutual_information
final_occupation, final_orbital_indices = autocas.get_active_space(
initial_occupation,
initial_s1,
mutual_information=initial_mutual_information,
force_cas=False,
)
self.results["final_occupation"] = final_occupation
self.results["final_orbital_indices"] = final_orbital_indices
return final_occupation, final_orbital_indices
# flake8: noqa: C901
def main(self, settings_dict: Dict):
"""Provide main function of autocas.
Parameters
----------
settings_dict : Dict
provide yaml settings
"""
# looks better in output (escape \)
print(" _ _____ _____ ")
print(" | | / ____| /\\ / ____| ")
print(" __ _ _ _ | |_ ___ | | / \\ | (___ ")
print(" / _` || | | || __| / _ \\ | | / /\\ \\ \\___ \\ ")
print(" | (_| || |_| || |_ | (_) || |____ / ____ \\ ____) | ")
print(" \\__,_| \\__,_| \\__| \\___/ \\_____|/_/ \\_\\|_____/ ")
print(" ")
print("*******************************************************************************************")
print("* *")
print("* Settings *")
print("* *")
print("*******************************************************************************************")
# if "yaml_input" in settings_dict:
if settings_dict["yaml_input"] is not None:
input_handler = InputHandler(settings_dict["yaml_input"])
input_handler.print_settings()
settings = input_handler.settings_dir
molecule = input_handler.get_molecule()
autocas = input_handler.get_autocas()
interface = input_handler.get_interface()
elif "xyz_file" in settings_dict:
for key in settings_dict:
print(f" {key}: {settings_dict[key]}")
settings = settings_dict
molecule = Molecule(xyz_file=settings_dict["xyz_file"])
autocas = Autocas(molecule=molecule)
if settings_dict["xyz_file"][0] != "/":
settings_dict["xyz_file"] = os.getcwd() + "/" + settings_dict["xyz_file"]
interface = Molcas(molecules=[molecule])
interface.settings.basis_set = settings_dict["basis_set"]
interface.settings.xyz_file = settings_dict["xyz_file"]
interface.environment.molcas_scratch_dir = os.getcwd() + "/molcas_scratch"
else:
raise ValueError("Provide yaml input or an xyz-file.")
self.results["settings"] = settings
self.results["autocas"] = autocas
self.results["molecule"] = molecule
self.results["interface"] = interface
use_large_cas = False
if "large_cas" in settings and settings["large_cas"] is True:
use_large_cas = True
print("The Large active space protocol is enabled!")
interface.settings.method = "dmrg_ci"
interface.settings.dmrg_sweeps = 5
interface.settings.dmrg_bond_dimension = 250
interface.settings.post_cas_method = ""
print("")
print("*******************************************************************************************")
print("* *")
print("* Initial HF Calculation *")
print("* *")
print("*******************************************************************************************")
# make initial hf calculation
interface.calculate()
print("")
print("*******************************************************************************************")
print("* *")
print("* DMRG Calculation *")
print("* *")
print("*******************************************************************************************")
print("Settings for autoCAS DMRG calculation:")
print("method: 'dmrg_ci'")
print("dmrg_sweeps: 5")
print("dmrg_bond_dimension: 250")
print("Switching back to original settings for the final calculation.")
print("")
(
initial_occupation,
initial_orbital_indices,
) = autocas.make_initial_active_space()
self.results["initial_occupation"] = initial_occupation
self.results["initial_orbital_indices"] = initial_orbital_indices
print(f"Initial active space CAS(e, o): ({sum(initial_occupation)}, {len(initial_occupation)})")
print(f"Orbital indices: {initial_orbital_indices}")
print(f"Orbital occupations: {initial_occupation}")
print("")
# large cas and excited states
if interface.settings.n_excited_states > 0 and use_large_cas:
final_occupation, final_orbital_indices = self.large_cas_excited_states(autocas, interface)
# large active space protocol groundstate only
elif use_large_cas:
final_occupation, final_orbital_indices = self.large_cas(autocas, interface)
# conventional excited states
elif interface.settings.n_excited_states > 0:
final_occupation, final_orbital_indices = self.excited_states(autocas, interface)
# conventional groundstate only
else:
final_occupation, final_orbital_indices = self.conventional(autocas, interface)
if "entanglement_diagram" in settings or "plot" in settings:
print("Creating entanglement diagram.")
entanglement_plot = EntanglementPlot()
plt = entanglement_plot.plot(
self.results["initial_s1"],
self.results["initial_mutual_information"],
self.results["initial_orbital_indices"],
)
if "entanglement_diagram" in settings:
plt.savefig(str(settings["entanglement_diagram"])) # type: ignore[attr-defined]
else:
plt.show() # type: ignore[attr-defined]
# if "full_entanglement_diagram" in settings:
# entanglement_plot = EntanglementPlot()
# plt = entanglement_plot.plot_in_plot(
# self.results["initial_s1"],
# self.results["initial_mutual_information"],
# self.results["final_s1"],
# self.results["final_mutual_information"],
# self.results["initial_orbital_indices"],
# self.results["final_orbital_indices"],
# )
# plt.savefig(settings["full_entanglement_diagram"], dpi=300)
if "threshold_diagram" in settings:
print("Creating threshold diagram.")
threshold_plot = ThresholdPlot()
plt = threshold_plot.plot(self.results["initial_s1"])
plt.savefig(str(settings["threshold_diagram"])) # type: ignore[attr-defined]
if settings_dict["yaml_input"] is not None:
try:
interface.settings.method = settings["interface"]["settings"]["method"]
except KeyError:
pass
try:
interface.settings.post_cas_method = settings["interface"]["settings"]["post_cas_method"]
except KeyError:
pass
try:
interface.settings.dmrg_sweeps = settings["interface"]["settings"]["dmrg_sweeps"]
except KeyError:
pass
try:
interface.settings.dmrg_bond_dimension = settings["interface"]["settings"]["dmrg_bond_dimension"]
except KeyError:
pass
else:
try:
interface.settings.method = settings["method"]
except KeyError:
pass
try:
interface.settings.post_cas_method = settings["post_cas_method"]
except KeyError:
pass
try:
interface.settings.dmrg_bond_dimension = settings["dmrg_bond_dimension"]
except KeyError:
pass
try:
interface.settings.dmrg_sweeps = settings["dmrg_sweeps"]
except KeyError:
pass
print("")
print("*******************************************************************************************")
print("* *")
print("* Final Calculation *")
print("* *")
print("*******************************************************************************************")
print("Starting final calculation with optimized CAS.")
print(f"Final active space CAS(e, o): ({sum(final_occupation)}, {len(final_occupation)})")
print(f"Final orbital indices: {final_orbital_indices}")
print(f"Final orbital occupation: {final_occupation}")
print("")
energy, s1_entropy, s2_entropy, mutual_information = interface.calculate(
final_occupation, final_orbital_indices
)
self.results["energy"] = energy
print(f"Final energy: {energy}")
try:
self.results["s1"] = s1_entropy
self.results["s2"] = s2_entropy
self.results["mutual_information"] = mutual_information
if "full_entanglement_diagram" in settings:
print("Creating full entanglement diagram.")
entanglement_plot = EntanglementPlot()
plt = entanglement_plot.plot_in_plot(
self.results["initial_s1"],
self.results["initial_mutual_information"],
self.results["final_s1"],
self.results["final_mutual_information"],
self.results["initial_orbital_indices"],
self.results["final_orbital_indices"],
)
plt.savefig(settings["full_entanglement_diagram"], dpi=600) # type: ignore[attr-defined]
except KeyError:
pass
|
Java
|
UTF-8
| 5,632 | 2.25 | 2 |
[] |
no_license
|
package com.haitago.business.baseandcommon;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.haitago.factory.bean.base.OpenResponse;
import com.haitago.presenter.RxPresenter;
import com.haitago.utils.ACache;
import com.haitago.utils.StrUtils;
import org.json.JSONObject;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Action2;
import rx.functions.Func0;
import rx.schedulers.Schedulers;
/**
* Created by onion on 2016/5/10.
* for cache
* <View> type View's className and restartableId for cache key
* <T> T's Gsonformate is cache value
*/
public class MPresenter<View> extends RxPresenter<View> {
private String mPresenterName = getClass().getName();
@Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
}
@Override
protected void onTakeView(View view) {
super.onTakeView(view);
}
/**
* 联网在后台,回调在UI 添加缓存
*
* @param restartableId an id of the restartable.
* @param observableFactory a factory that should return an Observable when the restartable should run.
* @param onNext a callback that will be called when received data should be delivered to view.
* @param onError a callback that will be called if the source observable emits onError.
* @param <T>
*/
public <T> void restartableLatestCache(final int restartableId, final Func0<Observable<T>> observableFactory, final CacheAble<View, T> onNext, @Nullable final CacheAble<View, Throwable> onError, CacheAble.CacheType type, Action2<View, OpenResponse> onCache) {
initCache(restartableId, onNext, onError, type, onCache);
restartable(restartableId, new Func0<Subscription>() {
@Override
public Subscription call() {
return observableFactory.call()
.compose(MPresenter.this.<T>deliverLatestCache()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(split(onNext, onError));
}
});
}
/**
* 不带缓存的 联网在后台 展示在UI线程
*
* @param restartableId an id of the restartable.
* @param observableFactory a factory that should return an Observable when the restartable should run.
* @param onNext a callback that will be called when received data should be delivered to view.
* @param onError a callback that will be called if the source observable emits onError.
* @param <T>
*/
@Override
public <T> void restartableFirst(int restartableId, final Func0<Observable<T>> observableFactory,
final Action2<View, T> onNext, @Nullable final Action2<View, Throwable> onError) {
restartable(restartableId, new Func0<Subscription>() {
@Override
public Subscription call() {
return observableFactory.call()
.compose(MPresenter.this.<T>deliverFirst()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(split(onNext, onError));
}
});
}
/**
* @param restartableId
* @param observableFactory
* @param onNext
* @param onError
* @param type
* @param onCache
* @param <T>
*/
public <T> void restartableFirst(int restartableId, final Func0<Observable<T>> observableFactory,
final CacheAble<View, T> onNext, @Nullable final CacheAble<View, Throwable> onError, CacheAble.CacheType type, Action2<View, OpenResponse> onCache) {
initCache(restartableId, onNext, onError, type, onCache);
restartable(restartableId, new Func0<Subscription>() {
@Override
public Subscription call() {
return observableFactory.call()
.compose(MPresenter.this.<T>deliverFirst()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(split(onNext, onError));
}
});
}
/**
* 缓存模块
*/
private <T> void initCache(int restartableId, final CacheAble<View, T> onNext, @Nullable final CacheAble<View, Throwable> onError, CacheAble.CacheType type, @Nullable final Action2<View, OpenResponse> onCache) {
if (onCache == null || type == CacheAble.CacheType.None) return;
final String key = mPresenterName + restartableId;
if (type == CacheAble.CacheType.Before) {
doInView(new Action1<View>() {
@Override
public void call(View view) {
OpenResponse response = getCache(key);
if (response != null)
onCache.call(view, response);
}
});
}
onNext.setTypeAndKey(type, key, onCache);
onError.setTypeAndKey(type, key, onCache);
}
/**
* 获取cache的时候
*
* @param restartableId
*/
public OpenResponse getCache(String cacheKey) {
//get cache
JSONObject cache = ACache.get(TApplication.getInstance()).getAsJSONObject(StrUtils.string2md5(cacheKey));
if (cache == null) return null;
return TApplication.gson.fromJson(cache.toString(), OpenResponse.class);
}
protected void doInView(Action1<View> action1) {
view().take(1).subscribe(action1);
}
}
|
Python
|
UTF-8
| 11,688 | 2.875 | 3 |
[] |
no_license
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# model averaging ensemble for the blobs dataset
from sklearn.datasets import make_blobs
from sklearn.metrics import accuracy_score
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense
from matplotlib import pyplot
from numpy import mean
from numpy import std
import numpy
from numpy import array
from numpy import argmax
# fit model on dataset
def fit_model(trainX, trainy):
trainy_enc = to_categorical(trainy)
# define model
model = Sequential()
model.add(Dense(25, input_dim=2, activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit model
model.fit(trainX, trainy_enc, epochs=500, verbose=0)
return model
# make an ensemble prediction for multi-class classification
def ensemble_predictions(members, testX):
# make predictions
yhats = [model.predict(testX) for model in members]
yhats = array(yhats)
# sum across ensemble members
summed = numpy.sum(yhats, axis=0)
# argmax across classes
result = argmax(summed, axis=1)
return result
# evaluate a specific number of members in an ensemble
def evaluate_n_members(members, n_members, testX, testy):
# select a subset of members
subset = members[:n_members]
# make prediction
yhat = ensemble_predictions(subset, testX)
# calculate accuracy
return accuracy_score(testy, yhat)
# generate 2d classification dataset
X, y = make_blobs(n_samples=1100, centers=3, n_features=2, cluster_std=2, random_state=2)
# split into train and test
n_train = 100
trainX, testX = X[:n_train, :], X[n_train:, :]
trainy, testy = y[:n_train], y[n_train:]
print(trainX.shape, testX.shape)
# fit all models
n_members = 10
members = [fit_model(trainX, trainy) for _ in range(n_members)]
# evaluate different numbers of ensembles on hold out set
single_scores, ensemble_scores = list(), list()
for i in range(1, len(members)+1):
# evaluate model with i members
ensemble_score = evaluate_n_members(members, i, testX, testy)
# evaluate the i'th model standalone
testy_enc = to_categorical(testy)
_, single_score = members[i-1].evaluate(testX, testy_enc, verbose=0)
# summarize this step
print('> %d: single=%.3f, ensemble=%.3f' % (i, single_score, ensemble_score))
ensemble_scores.append(ensemble_score)
single_scores.append(single_score)
# summarize average accuracy of a single final model
print('Accuracy %.3f (%.3f)' % (mean(single_scores), std(single_scores)))
# plot score vs number of ensemble members
x_axis = [i for i in range(1, len(members)+1)]
pyplot.plot(x_axis, single_scores, marker='o', linestyle='None')
pyplot.plot(x_axis, ensemble_scores, marker='o')
pyplot.show()
'''
Running the example first reports the performance of each single model as well as the model averaging ensemble of a given size with 1, 2, 3, etc. members.
Your results will vary given the stochastic nature of the training algorithm.
On this run, the average performance of the single models is reported at about 80.4% and we can see that an ensemble with between five and nine members will achieve a performance between 80.8% and 81%. As expected, the performance of a modest-sized model averaging ensemble out-performs the performance of a randomly selected single model on average.
> 1: single=0.803, ensemble=0.803
> 2: single=0.805, ensemble=0.808
> 3: single=0.798, ensemble=0.805
> 4: single=0.809, ensemble=0.809
> 5: single=0.808, ensemble=0.811
> 6: single=0.805, ensemble=0.808
> 7: single=0.805, ensemble=0.808
> 8: single=0.804, ensemble=0.809
> 9: single=0.810, ensemble=0.810
> 10: single=0.794, ensemble=0.808
Accuracy 0.804 (0.005)
Next, a graph is created comparing the accuracy of single models (blue dots) to the model averaging ensemble of increasing size (orange line).
On this run, the orange line of the ensembles clearly shows better or comparable performance (if dots are hidden) than the single models.
'''
'''Weighted Average MLP Ensemble
An alternative to searching for weight values is to use a directed optimization process.
Optimization is a search process, but instead of sampling the space of possible solutions randomly or exhaustively, the search process uses any available information to make the next step in the search, such as toward a set of weights that has lower error.
The SciPy library offers many excellent optimization algorithms, including local and global search methods.
SciPy provides an implementation of the Differential Evolution method. This is one of the few stochastic global search algorithms that “just works” for function optimization with continuous inputs, and it works well.
The differential_evolution() SciPy function requires that function is specified to evaluate a set of weights and return a score to be minimized. We can minimize the classification error (1 – accuracy).
As with the grid search, we most normalize the weight vector before we evaluate it. The loss_function() function below will be used as the evaluation function during the optimization process.
'''
# loss function for optimization process, designed to be minimized
def loss_function(weights, members, testX, testy):
# normalize weights
normalized = normalize(weights)
# calculate error rate
return 1.0 - evaluate_ensemble(members, normalized, testX, testy)
'''Our loss function requires three parameters in addition to the weights, which we will provide as a tuple to then be passed along to the call to the loss_function() each time a set of weights is evaluated.'''
# arguments to the loss function
search_arg = (members, testX, testy)
'''
We can now call our optimization process.
We will limit the total number of iterations of the algorithms to 1,000, and use a smaller than default tolerance to detect if the search process has converged.
'''
# global optimization of ensemble weights
result = differential_evolution(loss_function, bound_w, search_arg, maxiter=1000, tol=1e-7)
'''The result of the call to differential_evolution() is a dictionary that contains all kinds of information about the search.
Importantly, the ‘x‘ key contains the optimal set of weights found during the search. We can retrieve the best set of weights, then report them and their performance on the test set when used in a weighted ensemble.
'''
# get the chosen weights
weights = normalize(result['x'])
print('Optimized Weights: %s' % weights)
# evaluate chosen weights
score = evaluate_ensemble(members, weights, testX, testy)
print('Optimized Weights Score: %.3f' % score)
'''
Tying all of this together, the complete example is listed below.
'''
# global optimization to find coefficients for weighted ensemble on blobs problem
from sklearn.datasets import make_blobs
from sklearn.metrics import accuracy_score
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense
from matplotlib import pyplot
from numpy import mean
from numpy import std
from numpy import array
from numpy import argmax
from numpy import tensordot
from numpy.linalg import norm
from scipy.optimize import differential_evolution
# fit model on dataset
def fit_model(trainX, trainy):
trainy_enc = to_categorical(trainy)
# define model
model = Sequential()
model.add(Dense(25, input_dim=2, activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit model
model.fit(trainX, trainy_enc, epochs=500, verbose=0)
return model
# make an ensemble prediction for multi-class classification
def ensemble_predictions(members, weights, testX):
# make predictions
yhats = [model.predict(testX) for model in members]
yhats = array(yhats)
# weighted sum across ensemble members
summed = tensordot(yhats, weights, axes=((0),(0)))
# argmax across classes
result = argmax(summed, axis=1)
return result
# # evaluate a specific number of members in an ensemble
def evaluate_ensemble(members, weights, testX, testy):
# make prediction
yhat = ensemble_predictions(members, weights, testX)
# calculate accuracy
return accuracy_score(testy, yhat)
# normalize a vector to have unit norm
def normalize(weights):
# calculate l1 vector norm
result = norm(weights, 1)
# check for a vector of all zeros
if result == 0.0:
return weights
# return normalized vector (unit norm)
return weights / result
# loss function for optimization process, designed to be minimized
def loss_function(weights, members, testX, testy):
# normalize weights
normalized = normalize(weights)
# calculate error rate
return 1.0 - evaluate_ensemble(members, normalized, testX, testy)
# generate 2d classification dataset
X, y = make_blobs(n_samples=1100, centers=3, n_features=2, cluster_std=2, random_state=2)
# split into train and test
n_train = 100
trainX, testX = X[:n_train, :], X[n_train:, :]
trainy, testy = y[:n_train], y[n_train:]
print(trainX.shape, testX.shape)
# fit all models
n_members = 5
members = [fit_model(trainX, trainy) for _ in range(n_members)]
# evaluate each single model on the test set
testy_enc = to_categorical(testy)
for i in range(n_members):
_, test_acc = members[i].evaluate(testX, testy_enc, verbose=0)
print('Model %d: %.3f' % (i+1, test_acc))
# evaluate averaging ensemble (equal weights)
weights = [1.0/n_members for _ in range(n_members)]
score = evaluate_ensemble(members, weights, testX, testy)
print('Equal Weights Score: %.3f' % score)
# define bounds on each weight
bound_w = [(0.0, 1.0) for _ in range(n_members)]
# arguments to the loss function
search_arg = (members, testX, testy)
# global optimization of ensemble weights
result = differential_evolution(loss_function, bound_w, search_arg, maxiter=1000, tol=1e-7)
# get the chosen weights
weights = normalize(result['x'])
print('Optimized Weights: %s' % weights)
# evaluate chosen weights
score = evaluate_ensemble(members, weights, testX, testy)
print('Optimized Weights Score: %.3f' % score)
'''
Running the example first creates five single models and evaluates the performance of each on the test dataset.
Your specific results will vary given the stochastic nature of the learning algorithm.
We can see on this run that models 3 and 4 both perform best with an accuracy of about 82.2%.
Next, a model averaging ensemble with all five members is evaluated on the test set reporting an accuracy of 81.8%, which is better than some, but not all, single models.
(100, 2) (1000, 2)
Model 1: 0.814
Model 2: 0.811
Model 3: 0.822
Model 4: 0.822
Model 5: 0.809
Equal Weights Score: 0.818
The optimization process is relatively quick.
We can see that the process found a set of weights that pays most attention to models 3 and 4, and spreads the remaining attention out among the other models, achieving an accuracy of about 82.4%, out-performing the model averaging ensemble and individual models.
Optimized Weights: [0.1660322 0.09652591 0.33991854 0.34540932 0.05211403]
Optimized Weights Score: 0.824
It is important to note that in these examples, we have treated the test dataset as though it were a validation dataset. This was done to keep the examples focused and technically simpler. In practice, the choice and tuning of the weights for the ensemble would be chosen by a validation dataset, and single models, model averaging ensembles, and weighted ensembles would be compared on a separate test set
'''
|
C++
|
UTF-8
| 361 | 2.6875 | 3 |
[] |
no_license
|
#include "wordlist.h"
#include "freqlist.h"
using namespace std;
int main()
{
int size;
WordList L;
L.read("input.txt");
FreqList F1;
FreqList F2;
F1.frequency(L,L.head);
size = F2.frequency_unsorted(L);
F2.sort(size);
cout << "F1 is:" << endl;
F1.print();
cout << "F2 is:" << endl;
F2.print();
return 0;
}
|
Shell
|
UTF-8
| 268 | 2.953125 | 3 |
[] |
no_license
|
#!/bin/bash
source platform
source prettyecho
source dots
case $PLATFORM in
Debian*)
# sudo apt-get install git -y
;;
Darwin*)
brew install git
;;
*)
log_error "Platform not supported"
exit 1
;;
esac
setup_dotfile git/gitconfig
|
TypeScript
|
UTF-8
| 2,024 | 3.609375 | 4 |
[] |
no_license
|
let initialPrimeNumbers = [2];
export const isPrime = (num: number) => {
if (num < 3) {
return true;
}
const maxPossible = Math.floor(Math.sqrt(num));
for(let i = 3; i <= maxPossible; i += 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
export const getPrimeNumbersBy = (max: number): number[] => {
const primeNumbers = initialPrimeNumbers.filter(number => number <= max);
let number = primeNumbers[primeNumbers.length - 1] + 1;
do {
let isPrime = true;
for(let i = 0; i < primeNumbers.length; i++) {
if (number % primeNumbers[i] === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeNumbers.push(number);
}
number += 1;
} while (number <= max);
if (primeNumbers[primeNumbers.length - 1] > initialPrimeNumbers[initialPrimeNumbers.length - 1]) {
initialPrimeNumbers = primeNumbers;
}
return primeNumbers;
}
export const getRandomPrimeNumber = (min: number, max: number) => {
const primeNumbers = getPrimeNumbersBy(max);
const primeNumbersInRange = primeNumbers.filter(number => number >= min && number <= max);
const randomIndex = Math.floor(Math.random() * primeNumbersInRange.length)
return primeNumbersInRange[randomIndex]
}
export const getCoprimeIntegersFor = (num: number) => {
const coprimeIntegers = [];
const divisors = getPrimeNumbersBy(num).filter(divisor => num % divisor === 0);
for(let i = 1; i < num; i += 1) {
let hasCommonDivisors = false;
let divisorIndex = 0;
while (i >= divisors[divisorIndex] && !hasCommonDivisors && divisorIndex < divisors.length) {
if (i % divisors[divisorIndex] === 0) {
hasCommonDivisors = true;
}
divisorIndex += 1;
}
if (!hasCommonDivisors) {
coprimeIntegers.push(i);
}
}
return coprimeIntegers;
}
|
Markdown
|
UTF-8
| 1,352 | 2.875 | 3 |
[] |
no_license
|
---
title: DNSimple Services
excerpt:
categories:
- DNSimple
---
# DNSimple Services
DNSimple provides several services that every system connected to the Internet needs: domain registration, hosted DNS and SSL certificates.
## DNS Hosting
DNSimple DNS hosting is billed as a monthly service. We currently offer three pricing tiers:
- **Bronze** $3/month for up to 2 managed domains
- **Silver** $8/month for up to 10 managed domains
- **Gold**: $18/month for up to 50 managed domains
- **Platinum**: $50/month for up to 500 managed domains
## Domain Registration
DNSimple domain registrations and transfers are billed on a yearly basis. Pricing varies depending on the domain name. For more information view the [domain pricing list](https://dnsimple.com/tld-pricing).
As a DNSimple customer you do not need to use our domain registration services in order to take advantage of our hosted DNS. If you want to use another registrar you may do so and just change your name servers to our name servers for domains that you want us to provide hosted DNS for.
## SSL Certificates
SSL certificates are available in two flavors:
- Standard single host SSL certificates from RapidSSL ($20 per year)
- Wildcard certificates from Comodo ($100 per year)
Learn more about [DNSimple certificates](/articles/ssl-certificates).
|
PHP
|
UTF-8
| 1,779 | 2.546875 | 3 |
[] |
no_license
|
<?php
@include("objects/page.class.php");
@include("../objects/page.class.php");
$page = new Page();
$page->loadMeta("Protocollen website");
$page->loadHeader();
$user = new User();
$MySql = new MySql();
if(isset($_SESSION["loggedin"])){
$user = $_SESSION["loggedin"];
}
else{
$user = new User();
}
if($user->getPermission() != null && $user->getPermission() == 2){
if(!empty($_GET)){
if(isset($_GET["category"])){
$category = $MySql->getCategory($_GET["category"]);
?>
<div id="editCategory" class="panel">
<form method="post" action="">
<h1> Bewerk Categorie </h1>
<p> <b>Aan het bewerken:</b> <?php echo $category->getName(); ?> </p>
<label for="editCategoryInput"> Naam: </label>
<input type="text" id="editCategoryInput" name="editCategoryInput" class="form-control" value="<?php echo $category->getName(); ?>">
<input type="hidden" name="categoryid" value="<?php echo $_GET["category"]; ?>">
<br><input type="submit" name="editCategorySubmit" id="editCategorySubmit" class="btn btn-danger" Value="Opslaan">
</form>
</div>
<?php
}
}
if(isset($_POST["editCategorySubmit"]) || !empty($_POST["editCategoryInput"])){
$category = new Category();
$category->setId($_POST["categoryid"]);
$category->setName($_POST["editCategoryInput"]);
if($MySql->editCategory($category)){
?> <script> window.location.href = "http://<?php echo getenv('HTTP_HOST'); ?>/protocols/"</script><?php
}
};
}
else{
header("Location: http://".getenv('HTTP_HOST')." ");
}
$page->showFooter();
?>
|
JavaScript
|
UTF-8
| 713 | 2.953125 | 3 |
[] |
no_license
|
/**
* Created by cuss on 2016/7/8.
*/
let slice = Array.prototype.slice,
toString = Object.prototype.toString;
let utils = {
isArray(obj){
let type = utils.checkType(obj);
if(type == 'Array'){
return true;
}
return false;
},
//判断是否是函数
isFunction(obj){
let type = utils.checkType(obj);
if(type == 'Function'){
return true;
}
return false;
},
isNumber(obj){
return !utils.isArray( obj ) && ( obj - parseFloat( obj ) + 1 ) >= 0;
},
checkType(obj){
let str = toString.call(obj);
return str.substring(8,str.length-1);
}
};
export default utils;
|
C++
|
UTF-8
| 25,917 | 2.796875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Contains runtime matrix implementation
*/
#pragma once
#include "etl/dyn_base.hpp" //The base class and utilities
namespace etl {
/*!
* \brief Matrix with run-time fixed dimensions.
*
* The matrix support an arbitrary number of dimensions.
*/
template <typename T, order SO, std::size_t D>
struct dyn_matrix_impl final : dense_dyn_base<dyn_matrix_impl<T, SO, D>, T, SO, D>,
inplace_assignable<dyn_matrix_impl<T, SO, D>>,
comparable<dyn_matrix_impl<T, SO, D>>,
expression_able<dyn_matrix_impl<T, SO, D>>,
value_testable<dyn_matrix_impl<T, SO, D>>,
dim_testable<dyn_matrix_impl<T, SO, D>> {
static constexpr std::size_t n_dimensions = D; ///< The number of dimensions
static constexpr order storage_order = SO; ///< The storage order
static constexpr std::size_t alignment = intrinsic_traits<T>::alignment; ///< The memory alignment
using base_type = dense_dyn_base<dyn_matrix_impl<T, SO, D>, T, SO, D>; ///< The base type
using value_type = T; ///< The value type
using dimension_storage_impl = std::array<std::size_t, n_dimensions>; ///< The type used to store the dimensions
using memory_type = value_type*; ///< The memory type
using const_memory_type = const value_type*; ///< The const memory type
using iterator = memory_type; ///< The type of iterator
using const_iterator = const_memory_type; ///< The type of const iterator
/*!
* \brief The vectorization type for V
*/
template<typename V = default_vec>
using vec_type = typename V::template vec_type<T>;
private:
using base_type::_size;
using base_type::_dimensions;
using base_type::_memory;
mutable gpu_handler<T> _gpu_memory_handler; ///< The GPU memory handler
using base_type::release;
using base_type::allocate;
using base_type::check_invariants;
using base_type::index;
public:
using base_type::dim;
using base_type::memory_start;
using base_type::memory_end;
using base_type::begin;
using base_type::end;
// Construction
/*!
* \brief Construct an empty matrix
*
* This matrix don't have any memory nor dimensionsand most
* operations will likely fail on it
*/
dyn_matrix_impl() noexcept : base_type() {
//Nothing else to init
}
/*!
* \brief Copy construct a matrix
* \param rhs The matrix to copy
*/
dyn_matrix_impl(const dyn_matrix_impl& rhs) noexcept : base_type(rhs) {
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
direct_copy(rhs.memory_start(), rhs.memory_end(), memory_start());
}
/*!
* \brief Move construct a matrix
* \param rhs The matrix to move
*/
dyn_matrix_impl(dyn_matrix_impl&& rhs) noexcept : base_type(std::move(rhs)), _gpu_memory_handler(std::move(rhs._gpu_memory_handler)) {
_memory = rhs._memory;
rhs._memory = nullptr;
}
/*!
* \brief Copy construct a matrix
* \param rhs The matrix to copy
*/
template <typename T2, order SO2, std::size_t D2, cpp_enable_if(SO2 == SO)>
explicit dyn_matrix_impl(const dyn_matrix_impl<T2, SO2, D2>& rhs) noexcept : base_type(rhs){
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
direct_copy(rhs.memory_start(), rhs.memory_end(), memory_start());
}
/*!
* \brief Copy construct a matrix
* \param rhs The matrix to copy
*/
template <typename T2, order SO2, std::size_t D2, cpp_disable_if(SO2 == SO)>
explicit dyn_matrix_impl(const dyn_matrix_impl<T2, SO2, D2>& rhs) noexcept : base_type(rhs){
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
//The type is different, so we must use assign
assign_evaluate(rhs, *this);
}
/*!
* \brief Construct a matrix from an expression
* \param e The expression to initialize the matrix with
*/
template <typename E, cpp_enable_if(
std::is_convertible<value_t<E>, value_type>::value,
is_etl_expr<E>::value,
!is_dyn_matrix<E>::value)>
explicit dyn_matrix_impl(E&& e) noexcept
: base_type(e){
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
assign_evaluate(e, *this);
}
/*!
* \brief Construct a vector with the given values
* \param list Initializer list containing all the values of the vector
*/
dyn_matrix_impl(std::initializer_list<value_type> list) noexcept : base_type(list.size(), {{list.size()}}) {
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
static_assert(n_dimensions == 1, "This constructor can only be used for 1D matrix");
std::copy(list.begin(), list.end(), begin());
}
/*!
* \brief Construct a matrix with the given dimensions
* \param sizes The dimensions of the matrix
*
* The number of dimesnions must be the same as the D template
* parameter of the matrix.
*/
template <typename... S, cpp_enable_if(
(sizeof...(S) == D),
cpp::all_convertible_to<std::size_t, S...>::value,
cpp::is_homogeneous<typename cpp::first_type<S...>::type, S...>::value)>
explicit dyn_matrix_impl(S... sizes) noexcept : base_type(dyn_detail::size(sizes...), {{static_cast<std::size_t>(sizes)...}}) {
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
}
/*!
* \brief Construct a matrix with the given dimensions and values
* \param sizes The dimensions of the matrix followed by an initializer_list
*/
template <typename... S, cpp_enable_if(dyn_detail::is_initializer_list_constructor<S...>::value)>
explicit dyn_matrix_impl(S... sizes) noexcept : base_type(dyn_detail::size(std::make_index_sequence<(sizeof...(S)-1)>(), sizes...),
dyn_detail::sizes(std::make_index_sequence<(sizeof...(S)-1)>(), sizes...)) {
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
static_assert(sizeof...(S) == D + 1, "Invalid number of dimensions");
auto list = cpp::last_value(sizes...);
std::copy(list.begin(), list.end(), begin());
}
/*!
* \brief Construct a matrix with the given dimensions and values
* \param sizes The dimensions of the matrix followed by a values_t
*/
template <typename... S, cpp_enable_if(
(sizeof...(S) == D),
cpp::is_specialization_of<values_t, typename cpp::last_type<std::size_t, S...>::type>::value)>
explicit dyn_matrix_impl(std::size_t s1, S... sizes) noexcept : base_type(dyn_detail::size(std::make_index_sequence<(sizeof...(S))>(), s1, sizes...),
dyn_detail::sizes(std::make_index_sequence<(sizeof...(S))>(), s1, sizes...)) {
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
auto list = cpp::last_value(sizes...).template list<value_type>();
std::copy(list.begin(), list.end(), begin());
}
/*!
* \brief Construct a matrix with the given dimensions and a value
* \param sizes The dimensions of the matrix followed by a values
*
* Every element of the matrix will be set to this value.
*/
template <typename S1, typename... S, cpp_enable_if(
(sizeof...(S) == D),
std::is_convertible<std::size_t, S1>::value, //The first type must be convertible to size_t
cpp::is_sub_homogeneous<S1, S...>::value, //The first N-1 types must homegeneous
(std::is_arithmetic<typename cpp::last_type<S1, S...>::type>::value
? std::is_convertible<value_type, typename cpp::last_type<S1, S...>::type>::value //The last type must be convertible to value_type
: std::is_same<value_type, typename cpp::last_type<S1, S...>::type>::value //The last type must be exactly value_type
))>
explicit dyn_matrix_impl(S1 s1, S... sizes) noexcept : base_type(
dyn_detail::size(std::make_index_sequence<(sizeof...(S))>(), s1, sizes...),
dyn_detail::sizes(std::make_index_sequence<(sizeof...(S))>(), s1, sizes...)
){
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
intel_decltype_auto value = cpp::last_value(s1, sizes...);
std::fill(begin(), end(), value);
}
/*!
* \brief Construct a matrix with the given dimensions and a generator expression
* \param sizes The dimensions of the matrix followed by a values
*
* The generator expression will be used to initialize the
* elements of the matrix, in order.
*/
template <typename S1, typename... S, cpp_enable_if(
(sizeof...(S) == D),
std::is_convertible<std::size_t, S1>::value, //The first type must be convertible to size_t
cpp::is_sub_homogeneous<S1, S...>::value, //The first N-1 types must homegeneous
cpp::is_specialization_of<generator_expr, typename cpp::last_type<S1, S...>::type>::value //The last type must be a generator expr
)>
explicit dyn_matrix_impl(S1 s1, S... sizes) noexcept : base_type(dyn_detail::size(std::make_index_sequence<(sizeof...(S))>(), s1, sizes...),
dyn_detail::sizes(std::make_index_sequence<(sizeof...(S))>(), s1, sizes...)) {
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
intel_decltype_auto e = cpp::last_value(sizes...);
assign_evaluate(e, *this);
}
/*!
* \brief Construct a matrix with the given dimensions and a generator expression
* \param sizes The dimensions of the matrix followed by an init_flag and a value
*
* Every element of the matrix will be set to this value.
*
* This constructor is necessary when the type of the matrix is
* std::size_t
*/
template <typename... S, cpp_enable_if(dyn_detail::is_init_constructor<S...>::value)>
explicit dyn_matrix_impl(S... sizes) noexcept : base_type(dyn_detail::size(std::make_index_sequence<(sizeof...(S)-2)>(), sizes...),
dyn_detail::sizes(std::make_index_sequence<(sizeof...(S)-2)>(), sizes...)) {
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
static_assert(sizeof...(S) == D + 2, "Invalid number of dimensions");
std::fill(begin(), end(), cpp::last_value(sizes...));
}
/*!
* \brief Construct a vector from a Container
* \param container A STL container
*
* Only possible for 1D matrices
*/
template <typename Container, cpp_enable_if(
cpp::not_c<is_etl_expr<Container>>::value,
std::is_convertible<typename Container::value_type, value_type>::value)>
explicit dyn_matrix_impl(const Container& container)
: base_type(container.size(), {{container.size()}}){
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
static_assert(D == 1, "Only 1D matrix can be constructed from containers");
// Copy the container directly inside the allocated memory
std::copy_n(container.begin(), _size, _memory);
}
/*!
* \brief Copy assign from another matrix
*
* This operator can change the dimensions of the matrix
*
* \param rhs The matrix to copy from
* \return A reference to the matrix
*/
dyn_matrix_impl& operator=(const dyn_matrix_impl& rhs) noexcept {
if (this != &rhs) {
if (!_size) {
_size = rhs._size;
_dimensions = rhs._dimensions;
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
} else {
validate_assign(*this, rhs);
}
direct_copy(rhs.memory_start(), rhs.memory_end(), memory_start());
}
check_invariants();
return *this;
}
/*!
* \brief Move assign from another matrix
*
* The other matrix won't be usable after the move operation
*
* \param rhs The matrix to move from
* \return A reference to the matrix
*/
dyn_matrix_impl& operator=(dyn_matrix_impl&& rhs) noexcept {
if (this != &rhs) {
if(_memory){
release(_memory, _size);
}
_size = rhs._size;
_dimensions = std::move(rhs._dimensions);
_memory = rhs._memory;
_gpu_memory_handler = std::move(rhs._gpu_memory_handler);
rhs._size = 0;
rhs._memory = nullptr;
}
check_invariants();
return *this;
}
/*!
* \brief Resize with the new dimensions in the given array
* \param dimensions The new dimensions
*/
void resize_arr(const dimension_storage_impl& dimensions){
auto new_size = std::accumulate(dimensions.begin(), dimensions.end(), std::size_t(1), std::multiplies<std::size_t>());
if(_memory){
auto new_memory = allocate(alloc_size_mat<T>(new_size, (dimensions.back())));
for (std::size_t i = 0; i < std::min(_size, new_size); ++i) {
new_memory[i] = _memory[i];
}
release(_memory, _size);
_memory = new_memory;
} else {
_memory = allocate(alloc_size_mat<T>(new_size, (dimensions.back())));
}
_size = new_size;
_dimensions = dimensions;
}
/*!
* \brief Resize with the new given dimensions
* \param sizes The new dimensions
*/
template<typename... Sizes>
void resize(Sizes... sizes){
static_assert(sizeof...(Sizes), "Cannot change number of dimensions");
auto new_size = dyn_detail::size(sizes...);
if(_memory){
auto new_memory = allocate(alloc_size_mat<T>(new_size, cpp::last_value(sizes...)));
for (std::size_t i = 0; i < std::min(_size, new_size); ++i) {
new_memory[i] = _memory[i];
}
release(_memory, _size);
_memory = new_memory;
} else {
_memory = allocate(alloc_size_mat<T>(new_size, cpp::last_value(sizes...)));
}
_size = new_size;
_dimensions = dyn_detail::sizes(std::make_index_sequence<D>(), sizes...);
}
/*!
* \brief Assign from an ETL expression.
* \param e The expression containing the values to assign to the matrix
* \return A reference to the matrix
*/
template <typename E, cpp_enable_if(!std::is_same<std::decay_t<E>, dyn_matrix_impl<T, SO, D>>::value, std::is_convertible<value_t<E>, value_type>::value, is_etl_expr<E>::value)>
dyn_matrix_impl& operator=(E&& e) noexcept {
// It is possible that the matrix was not initialized before
// In the case, get the the dimensions from the expression and
// initialize the matrix
if(!_memory){
inherit(e);
} else {
validate_assign(*this, e);
}
assign_evaluate(e, *this);
check_invariants();
return *this;
}
/*!
* \brief Assign from an STL container.
* \param vec The container containing the values to assign to the matrix
* \return A reference to the matrix
*/
template <typename Container, cpp_enable_if(!is_etl_expr<Container>::value, std::is_convertible<typename Container::value_type, value_type>::value)>
dyn_matrix_impl& operator=(const Container& vec) {
validate_assign(*this, vec);
std::copy(vec.begin(), vec.end(), begin());
check_invariants();
return *this;
}
/*!
* \brief Assign the same value to each element of the matrix
* \param value The value to assign to each element of the matrix
* \return A reference to the matrix
*/
dyn_matrix_impl& operator=(const value_type& value) noexcept {
std::fill(begin(), end(), value);
check_invariants();
return *this;
}
/*!
* \brief Destruct the matrix and release all its memory
*/
~dyn_matrix_impl() noexcept {
if(_memory){
release(_memory, _size);
}
}
/*!
* \brief Swap the content of the matrix with the content of the given matrix
* \param other The other matrix to swap content with
*/
void swap(dyn_matrix_impl& other) {
using std::swap;
swap(_size, other._size);
swap(_dimensions, other._dimensions);
swap(_memory, other._memory);
//TODO swap is likely screwing up GPU memory!
check_invariants();
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
ETL_STRONG_INLINE(void) store(const vec_type<V> in, std::size_t i) noexcept {
V::store(_memory + i, in);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
ETL_STRONG_INLINE(void) storeu(const vec_type<V> in, std::size_t i) noexcept {
V::storeu(_memory + i, in);
}
/*!
* \brief Store several elements in the matrix at once, using non-temporal store
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
ETL_STRONG_INLINE(void) stream(const vec_type<V> in, std::size_t i) noexcept {
V::stream(_memory + i, in);
}
/*!
* \brief Load several elements of the matrix at once
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the matrix
*/
template<typename V = default_vec>
ETL_STRONG_INLINE(vec_type<V>) load(std::size_t i) const noexcept {
return V::load(_memory + i);
}
/*!
* \brief Load several elements of the matrix at once
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the matrix
*/
template<typename V = default_vec>
ETL_STRONG_INLINE(vec_type<V>) loadu(std::size_t i) const noexcept {
return V::loadu(_memory + i);
}
/*!
* \brief Returns a reference to the ith dimension value.
*
* This should only be used internally and with care
*
* \return a refernece to the ith dimension value.
*/
std::size_t& unsafe_dimension_access(std::size_t i) {
cpp_assert(i < n_dimensions, "Out of bounds");
return _dimensions[i];
}
/*!
* \brief Return an opaque (type-erased) access to the memory of the matrix
* \return a structure containing the dimensions, the storage order and the memory pointers of the matrix
*/
opaque_memory<T, n_dimensions> direct() const {
return opaque_memory<T, n_dimensions>(memory_start(), _size, _dimensions, _gpu_memory_handler, SO);
}
/*!
* \brief Inherit the dimensions of an ETL expressions, if the matrix has no
* dimensions.
* \param e The expression to get the dimensions from.
*/
template <typename E>
void inherit_if_null(const E& e){
static_assert(n_dimensions == etl::dimensions(e), "Cannot inherit from an expression with different number of dimensions");
static_assert(!etl::decay_traits<E>::is_generator, "Cannot inherit dimensions from a generator expression");
if(!_memory){
inherit(e);
}
}
private:
/*!
* \brief Inherit the dimensions of an ETL expressions.
* This must only be called when the matrix has no dimensions
* \param e The expression to get the dimensions from.
*/
template <typename E, cpp_enable_if(etl::decay_traits<E>::is_generator)>
void inherit(const E& e){
cpp_assert(false, "Impossible to inherit dimensions from generators");
cpp_unused(e);
}
/*!
* \brief Inherit the dimensions of an ETL expressions.
* This must only be called when the matrix has no dimensions
* \param e The expression to get the dimensions from.
*/
template <typename E, cpp_disable_if(etl::decay_traits<E>::is_generator)>
void inherit(const E& e){
cpp_assert(n_dimensions == etl::dimensions(e), "Invalid number of dimensions");
// Compute the size and new dimensions
_size = 1;
for (std::size_t d = 0; d < n_dimensions; ++d) {
_dimensions[d] = etl::dim(e, d);
_size *= _dimensions[d];
}
// Allocate the new memory
_memory = allocate(alloc_size_mat<T>(_size, dim(n_dimensions - 1)));
}
};
static_assert(std::is_nothrow_default_constructible<dyn_vector<double>>::value, "dyn_vector should be nothrow default constructible");
static_assert(std::is_nothrow_copy_constructible<dyn_vector<double>>::value, "dyn_vector should be nothrow copy constructible");
static_assert(std::is_nothrow_move_constructible<dyn_vector<double>>::value, "dyn_vector should be nothrow move constructible");
static_assert(std::is_nothrow_copy_assignable<dyn_vector<double>>::value, "dyn_vector should be nothrow copy assignable");
static_assert(std::is_nothrow_move_assignable<dyn_vector<double>>::value, "dyn_vector should be nothrow move assignable");
static_assert(std::is_nothrow_destructible<dyn_vector<double>>::value, "dyn_vector should be nothrow destructible");
/*!
* \brief Swap two dyn matrix
* \param lhs The first matrix
* \param rhs The second matrix
*/
template <typename T, order SO, std::size_t D>
void swap(dyn_matrix_impl<T, SO, D>& lhs, dyn_matrix_impl<T, SO, D>& rhs) {
lhs.swap(rhs);
}
/*!
* \brief Serialize the given matrix using the given serializer
* \param os The serializer
* \param matrix The matrix to serialize
*/
template <typename Stream, typename T, order SO, std::size_t D>
void serialize(serializer<Stream>& os, const dyn_matrix_impl<T, SO, D>& matrix){
for(std::size_t i = 0; i < etl::dimensions(matrix); ++i){
os << matrix.dim(i);
}
for(const auto& value : matrix){
os << value;
}
}
/*!
* \brief Deserialize the given matrix using the given serializer
* \param is The deserializer
* \param matrix The matrix to deserialize
*/
template <typename Stream, typename T, order SO, std::size_t D>
void deserialize(deserializer<Stream>& is, dyn_matrix_impl<T, SO, D>& matrix){
typename std::decay_t<decltype(matrix)>::dimension_storage_impl new_dimensions;
for(auto& value : new_dimensions){
is >> value;
}
matrix.resize_arr(new_dimensions);
for(auto& value : matrix){
is >> value;
}
}
/*!
* \brief Print the description of the matrix to the given stream
* \param os The output stream
* \param mat The matrix to output the description to the stream
* \return The given output stream
*/
template <typename T, order SO, std::size_t D>
std::ostream& operator<<(std::ostream& os, const dyn_matrix_impl<T, SO, D>& mat) {
if (D == 1) {
return os << "V[" << mat.size() << "]";
}
os << "M[" << mat.dim(0);
for (std::size_t i = 1; i < D; ++i) {
os << "," << mat.dim(i);
}
return os << "]";
}
} //end of namespace etl
|
C#
|
UTF-8
| 649 | 2.96875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PooCalculaIdade
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("programa para calcular a idade da pessoa.");
Console.WriteLine("Digite seu nome: ");
string nome = (Console.ReadLine());
Console.WriteLine("Digite o ano em que nasceu: ");
int ano = int.Parse(Console.ReadLine());
Pessoa pessoa = new Pessoa(nome,ano);
pessoa.ExibirDados();
Console.ReadKey();
}
}
}
|
C#
|
UTF-8
| 8,692 | 3.03125 | 3 |
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DominionCards
{
public abstract class Player
{
private int number;
private Stack<Card> deck = new Stack<Card>();
private List<Card> hand = new List<Card>();
private List<Card> discard = new List<Card>();
private Queue<AttackCard> attacks = new Queue<AttackCard>();
public int actions, buys, money;
public Player()
{
resetStats();
populateStartingDeck();
System.Threading.Thread.Sleep(new Random().Next(100));
deck = ShuffleDiscard();
drawHand();
}
private void resetStats()
{
actions = 1;
buys = 1;
money = 0;
}
private void populateStartingDeck()
{
for (int i = 0; i < 3; i++)
{
discard.Add(new KingdomCards.Estate());
}
for (int i = 0; i < 7; i++)
{
discard.Add(new KingdomCards.Copper());
}
}
public void setNumber(int numb)
{
number = numb;
}
public int getNumber()
{
return number;
}
public Card GetNextCard()
{
if (deck.Count == 0)
{
deck = ShuffleDiscard();
}
return deck.Pop();
}
public void drawHand()
{
// discard old hand
for (int i = 0; i < hand.Count; i++)
{
discard.Add((Card)hand[i]);
}
hand.Clear();
// draw five new cards
for (int i = 0; i < 5; i++)
{
hand.Add(GetNextCard());
}
}
public abstract void actionPhase();
public abstract void buyPhase();
public abstract List<Card> MakeDecision(IDecision decision);
public List<Card> getHand()
{
return hand;
}
public void setHand(List<Card> h)
{
hand = h; // THIS METHOD IS FOR TESTING USE
}
public void setDiscard(List<Card> dis)
{
discard = dis; // THIS METHOD IS USED FOR TESTING
}
public void setDeck(Stack<Card> d)
{
deck = d; // THIS METHOD IS FOR TESTING USE
}
public Stack<Card> getDeck()
{
return deck;
}
public List<Card> getDiscard()
{
return discard;
}
public Queue<AttackCard> getAttacks()
{
return attacks;
}
public int actionsLeft()
{
return actions;
}
public int buysLeft()
{
return buys;
}
public int moneyLeft()
{
return moneyInHand() + this.money;
}
public int moneyInHand()
{
int moneyInHand = 0;
for (int i = 0; i < hand.Count; i++)
{
Card card = (Card)hand[i];
if (card.IsTreasure())
{
moneyInHand += ((TreasureCard)card).value;
}
}
return moneyInHand;
}
public bool IsBuyPhase()
{
if (GameBoard.AbortPhase || GameBoard.AbortGame)
{
GameBoard.AbortPhase = false;
return false;
}
if (buysLeft() == 0)
{
return false;
}
return true;
}
public bool buyCard(Card card)
{
if (this.moneyLeft() < card.getPrice())
{
return false;
}
if (GameBoard.getInstance().getCardsLeft(card) == 0)
{
return false;
}
discard.Add(card);
GameBoard.getInstance().GetCards()[card] -= 1;
buys--;
this.money -= card.getPrice();
return true;
}
public void addCardToHand(Card card)
{
hand.Add(card);
}
public int playCard(Card c)
{
EnsureCardIsPlayable(c);
RemoveCardFromHand(c);
ActionCard card = (ActionCard) c;
actions--;
for (int i = 0; i < card.cards; i++)
{
hand.Add(GetNextCard());
}
actions += card.actions;
buys += card.buys;
money += card.money;
card.Play(this);
return actions;
}
public void EnsureCardIsPlayable(Card c)
{
if (c.IsVictory())
{
throw new CardCannotBePlayedException("you cannot play victory cards!!");
}
if (c.IsTreasure())
{
throw new CardCannotBePlayedException("You cannot play treasure cards!!");
}
}
public void RemoveCardFromHand(Card c)
{
int handSize = hand.Count;
for (int i = 0; i < hand.Count; i++)
{
if (hand[i].Equals(c))
{
hand.Remove(c);
discard.Add(c);
break;
}
}
if (handSize - 1 != hand.Count)
{
throw new Exception("Tried to play a card not in your hand!!!");
}
}
public static Stack<Card> ConvertStackToCardStack(Stack s)
{
Stack<Card> deck = new Stack<Card>();
while (s.Count > 0)
{
deck.Push((Card)s.Pop());
}
return deck;
}
public virtual void TakeTurn()
{
Console.WriteLine("beginning turn for player " + getNumber());
ProcessAttacks();
if (!IsActionPhase())
{
GameBoard.setGamePhase(2);
}
else { Console.WriteLine("begin action phase"); }
GameBoard.getInstance().Update();
while (IsActionPhase())
{
actionPhase();
GameBoard.getInstance().Update();
}
bool buyPhaseTemp = IsBuyPhase();
Console.WriteLine("Begin buy phase");
while (buyPhaseTemp)
{
buyPhase();
buyPhaseTemp = IsBuyPhase();
// If it's still the buy phase, immediately update graphics,
// otherwise, wait for the next player to load.
if (buyPhaseTemp)
{
GameBoard.getInstance().Update();
}
}
Console.WriteLine("ending turn for player " + getNumber());
Console.WriteLine();
EndTurn();
}
public override string ToString()
{
return "Player " + number;
}
public void ProcessAttacks()
{
while (attacks.Count > 0)
{
AttackCard card = attacks.Dequeue();
card.MakeDelayedAttack(this);
}
}
public void EndTurn()
{
resetStats();
drawHand();
}
public bool IsActionPhase()
{
if (GameBoard.AbortPhase || GameBoard.AbortGame)
{
GameBoard.AbortPhase = false;
return false;
}
if (actions == 0)
{
return false;
}
for (int i = 0; i < this.getHand().Count; i++)
{
Card card = (Card)this.getHand()[i];
if (card.IsAction())
{
return true; // if you still have action cards, it's still the action phase.
}
}
return false;
}
public Stack<Card> ShuffleDiscard()
{
Random random = new Random();
int n = discard.Count;
while (n > 1)
{
n--;
int k = random.Next(n + 1);
Card val = discard[k];
discard[k] = discard[n];
discard[n] = val;
}
Stack<Card> toReturn = new Stack<Card>(discard);
discard.Clear();
return toReturn;
}
}
}
|
C++
|
UTF-8
| 392 | 2.75 | 3 |
[] |
no_license
|
#include <fstream>
using namespace std;
int main()
{
ifstream in("input.txt");
ofstream out("output.txt");
int n, m;
int i, j;
int *k;
int c;
in >> n >> m;
k = new int[n];
for(c = 0; c < n; ++c)
k[c] = 0;
for(c = 0; c < m; ++c)
{
in >> i >> j;
++k[i-1];
++k[j-1];
}
for(c = 0; c < n; ++c)
out << k[c] << ' ';
return 0;
}
|
JavaScript
|
UTF-8
| 7,155 | 2.9375 | 3 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
function getNormalizationFactorByInvertingMaxValue(max){
if (max == 0) {
factor = 1;
}
else{
factor = 1/ max;
}
return factor;
}
function getMaxFromCellsLists(cellsLists){
var max = 0.0;
for (var i in cellsLists){
var cellsList = cellsLists[i];
var curMax = getMaxValueForLayer(cellsList);
if (curMax > max){
max = curMax;
}
}
return max;
}
// returns an array of cell arrays, one for each layer
function getCellsForAllLayersOfSaliencyId(saliencyId){
result = [];
var layerMessage = saliencyLookupMap.get(saliencyId);
if (layerMessage == undefined){
console.log("ERROR - no Layer message for saliencyID " + saliencyId);
}
else {
var expLayers = layerMessage.getLayersList();
for (var i in expLayers){
var expLayer = expLayers[i];
var name = expLayer.getName();
console.log("Layer name:", name);
var cellList = expLayer.getCellsList();
result.push(cellList);
}
}
return result;
}
function getCellsForSingleLayerForSaliencyId(saliencyId, desiredLayerName){
var layerMessage = saliencyLookupMap.get(saliencyId);
if (layerMessage == undefined){
console.log("ERROR - no Layer message for saliencyID " + saliencyId);
}
else {
var expLayers = layerMessage.getLayersList();
for (var i in expLayers){
var expLayer = expLayers[i];
var name = expLayer.getName();
if (name == desiredLayerName){
cellList = expLayer.getCellsList();
return cellList;
}
}
}
return undefined;
}
function addLayersToYieldSingleLayer(cellLists){
var result = [];
var length = cellLists[0].length;
for (var i = 0; i < length; i++){
var value = 0.0;
for (var j in cellLists){
value = value + cellLists[j][i];
}
result[i] = value;
}
return result;
}
function getNormalizationFactorForAllBarGroupSaliencies(barGroups){
var temp = [];
// gather up the cellList from each layer of all groups
for (var i in barGroups){
var group = barGroups[i];
var saliencyId = group.saliencyId;
var cellsLists = getCellsForAllLayersOfSaliencyId(saliencyId);
for (var j in cellsLists){
var cellsList = cellsLists[j];
temp.push(cellsList);
}
}
// now allthe cells lists are in temp. Get the max of the max of each
var max = getMaxFromCellsLists(temp);
// now get the normalizationFactor
var normFactor = getNormalizationFactorByInvertingMaxValue(max);
return normFactor;
}
function getNormalizationFactorForAllBarSaliencies(barGroups){
var temp = [];
// gather up the cellList from each layer of all bars
for (var i in barGroups){
var group = barGroups[i];
var bars = group.bars;
for (var j in bars){
var bar = bars[j];
var saliencyId = bar.saliencyId;
var cellsLists = getCellsForAllLayersOfSaliencyId(saliencyId);
for (var j in cellsLists){
var cellsList = cellsLists[j];
temp.push(cellsList);
}
}
}
// now all the cells lists are in temp. Get the max of the max of each
var max = getMaxFromCellsLists(temp);
// now get the normalizationFactor
var normFactor = getNormalizationFactorByInvertingMaxValue(max);
return normFactor;
}
function getNormalizationFactorForAllBarSalienciesNew(barGroups){
var out = [];
// gather up the cellList from each layer of all bars
for (var i in barGroups){
var group = barGroups[i];
var bars = group.bars;
for (var j in bars){
var bar = bars[j];
var saliencyId = bar.saliencyId;
console.log( "saliencyID: " + saliencyId );
var layerMessage = saliencyLookupMap.get(saliencyId);
if (layerMessage == undefined){
console.log("ERROR - no Layer message for saliencyID " + saliencyId);
continue;
}
var expLayers = layerMessage.getLayersList();
var name;
for (var i in expLayers){
var expLayer = expLayers[i];
name = expLayer.getName();
console.log("Layer name:", name);
}
out.push(1.0 / norm_dict[saliencyId][name]);
}
}
return out;
}
function getNormalizationFactorForCombinedBarGroupSaliencies(barGroups) {
var temp = [];
// gather up the cellList from each layer of all groups
for (var i in barGroups){
var group = barGroups[i];
var saliencyId = group.saliencyId;
var cellsLists = getCellsForAllLayersOfSaliencyId(saliencyId);
// add each pixel value from all layers together to get a flattened-combined single layer
var flattentedCombinedCellList = addLayersToYieldSingleLayer(cellsLists);
temp.push(flattentedCombinedCellList);
}
// now allthe cells lists are in temp. Get the max of the max of each
var max = getMaxFromCellsLists(temp);
// now get the normalizationFactor
var normFactor = getNormalizationFactorByInvertingMaxValue(max);
return normFactor;
}
function getNormalizationFactorForCombinedBarSaliencies(barGroups) {
var temp = [];
// gather up the cellList from each layer of all groups
for (var i in barGroups){
var group = barGroups[i];
var bars = group.bars;
for (var j in bars) {
var bar = bars[j];
var saliencyId = bar.saliencyId;
var cellsLists = getCellsForAllLayersOfSaliencyId(saliencyId);
// add each pixel value from all layers together to get a flattened-combined single layer
var flattentedCombinedCellList = addLayersToYieldSingleLayer(cellsLists);
temp.push(flattentedCombinedCellList);
}
}
// now allthe cells lists are in temp. Get the max of the max of each
var max = getMaxFromCellsLists(temp);
// now get the normalizationFactor
var normFactor = getNormalizationFactorByInvertingMaxValue(max);
return normFactor;
}
var normalizationFunctionMap = {};
normalizationFunctionMap["action.detailed"] = getNormalizationFactorForAllBarGroupSaliencies;
normalizationFunctionMap["action.combined"] = getNormalizationFactorForCombinedBarGroupSaliencies;
normalizationFunctionMap["reward.detailed"] = getNormalizationFactorForAllBarSaliencies;
normalizationFunctionMap["reward.combined"] = getNormalizationFactorForCombinedBarSaliencies;
function getNormalizationKey(displayGranularity, dataGranularity){
// dataGranularity == "action" | "reward"
// dispplayGranularity = "detailed" | "combined"
return dataGranularity + "." + displayGranularity;
}
function getNormalizationFactorForDisplayStyleAndResolution(style, resolution, actions) {
var key =getNormalizationKey(style, resolution);
var f = normalizationFunctionMap[key];
return f(actions);
}
|
Python
|
UTF-8
| 4,741 | 4.53125 | 5 |
[] |
no_license
|
#XOR decryption
#Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
#A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
#For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.
#Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
#Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
#DON'T NEED FOR PROBLEM
def num_to_bin(num_list):
#takes in a list of numbers and converts them to binary
bin_list = []
for i in num_list:
#converts each number to binary, adds to list
bin_list.append( bin( i ) )
return bin_list
#built in functions:
#ord('A') (returns 65) converts A to a (base 10) number
#chr(65) = chr(0b1000001) (returns A) - converts 65 to an ascii character
#bin(65) (returns 0b1000001) - converts 65 to a binary number (has leading 0b to identify as binary)
#a ^ b returns a XOR b (Ex: 65 ^ 42 = 107)
def str_to_num( str ):
#converts a string to a list of numbers
str = list( str )
#converts str to a list of single digit strings divided by commas
num_list = []
for i in str:
#converts each entry in string to number and appends to num_list
num_list.append( ord( i ) )
return num_list
def num_to_str( num_list ):
#reverse operation of str_to_num. converts list of numbers to a string
str = ''
#str starts as empty string
for i in num_list:
#for each number in list, finds the character corresponding to it and concatenates with string
str += chr( i )
return str
def XOR_with_key( num_str, key_str ):
#takes a number string and XORs it with a key of arbitrary length
#key is assumed to be string
key = str_to_num( key_str )
keylen = len( key )
#converts key to a number list and gets its length to use later
output = []
for i in range( 0, len( num_str ) ):
#goes through every index of number string
output.append( num_str[ i ] ^ key[ i % keylen ] )
#appends number[index] XOR key[index corresponding to next character in key - loops around if key too short
return output
def decrypt( num_str, key_str ):
#takes in a string of numbers, outputs text
numbers = XOR_with_key( num_str, key_str )
#XORs number string with key
output = num_to_str( numbers )
#converts numbers to string
return output
def encrypt( str, key_str ):
#takes in string and key, outputs number string
#not necessary for problem
num_str = str_to_num( str )
#converts string to numbers
output = XOR_with_key( num_str, key_str )
#XORs numbers with key
return output
def problem():
#solves defined problem
low_let = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#list of all lowercase letters
cipher_file = open( 'cipher.txt' )
#opens file
cipher_text = cipher_file.read().replace('\n','').split(',')
#reads data, copies to cipher_text, removes line breaks, splits into list
for i in range( 0, len( cipher_text )):
#converts entries in cipher_text to numbers
cipher_text[ i ] = int( cipher_text[ i ] )
cipher_file.close()
#closes file
for i in low_let:
for j in low_let:
for k in low_let:
key_str = i + j + k
#creates 3 character keystring from all lowercase latters
#TEST
print('keystring=',key_str)
#TEST
decrypt_text = decrypt( cipher_text, key_str )
#tries decrypting the text using the keystring
if 'the' in decrypt_text and 'to' in decrypt_text and 'be' in decrypt_text and 'and' in decrypt_text:
#simple criteria to test if output is English
print('key =',key_str)
return decrypt_text
|
JavaScript
|
UTF-8
| 1,480 | 2.890625 | 3 |
[] |
no_license
|
// using our types for action types on reducers
import {
LOGIN_USER,
LOGIN_USER_ERROR,
REGISTER_USER,
REGISTER_USER_ERROR,
LOG_USER_OUT,
FETCH_USER,
FETCH_USER_ERROR
} from "../actions/Types";
// our initial state
const initialState = {
isAuthenticated: false,
login: {},
register: {},
user: {}
};
// reducer method that handles user login and user logout
export function authenticateReducer(state = initialState, action) {
switch (action.type) {
case LOGIN_USER:
return {
...state,
isAuthenticated: true,
login: {
success: action.payload.success,
message: action.payload.message
}
};
case LOGIN_USER_ERROR:
return { ...state, isAuthenticated: false, login: action.payload };
case LOG_USER_OUT:
return { ...state, isAuthenticated: false, login: {} };
case REGISTER_USER:
return {
...state,
register: {
success: action.payload.success,
message: action.payload.message
}
};
case REGISTER_USER_ERROR:
return {
...state,
register: action.payload
};
case FETCH_USER:
return { ...state, user: action.payload };
case FETCH_USER_ERROR:
return {
...state,
user: {
success: false,
message:
"Your account info was not fetched. Log Out and Log back in please"
}
};
default:
return state;
}
}
|
PHP
|
UTF-8
| 142 | 2.609375 | 3 |
[] |
no_license
|
<?php
if ($_GET) {
if ($_GET["name"] == "Brandi") {
echo "Hi, Brandi!";
} else {
echo "Sorry, You're Not Welcome";
}
}
?>
|
Java
|
UTF-8
| 1,075 | 3.75 | 4 |
[] |
no_license
|
/**
* Ejercicio 19
* Realiza un programa que pinte una pirámide por pantalla. La altura se debe pedir
* por teclado. El carácter con el que se pinta la pirámide también se debe pedir
* por teclado.
*
* @author Alejandro Zambrana Naranjo
*/
public class Ejercicio19 {
public static void main(String[] args) {
System.out.println("ESTE PROGRAMA PINTA UNA PIRAMIDE POR PANTALLA");
System.out.print("Introduzca la altura de la piramide : ");
int altura = Integer.parseInt(System.console().readLine());
System.out.print("Introduzca con que caracter quieres pintar la piramide : ");
String caracter = System.console().readLine();
int alto = 1;
int espacios = altura-1;
while (alto <= altura){
//meter espacios
for (int i = 1; i <= espacios; i++){
System.out.print(" ");
}
// pinta la línea
for (int i = 1; i < alto * 2; i++){
System.out.print(caracter);
}
System.out.println();
alto++;
espacios--;
}
}
}
|
Java
|
UTF-8
| 2,066 | 3.015625 | 3 |
[] |
no_license
|
package Dictionary;
import java.util.Scanner;
public class DictionaryCommandline {
private DictionaryManagement manager = new DictionaryManagement();
public void showAllWords() {
manager.showDictionary();
}
public void dictionaryBasic() {
manager.insertFromCommandLine();
}
public void dictionaryAdvanced() {
System.out.println("1. Hiển thị từ điển ");
System.out.println("2. Tìm kiếm từ ");
System.out.println("3. Tìm kiếm từ bắt đầu với kí tự ");
System.out.println("4. Thêm từ ");
System.out.println("5. Xóa từ ");
System.out.println("6. Sửa từ");
System.out.println("7. Sửa nghĩa");
System.out.println("8. Xuất ra file");
System.out.println("9. Thoát ra");
System.out.print("Chọn yêu cầu: ");
Scanner scanner = new Scanner(System.in);
int command = scanner.nextInt();
while (true) {
if (command == 1) {
manager.showDictionary();
}
if (command == 2) {
manager.dictionaryLookup();
}
if (command == 3) {
manager.dictionarySearcher();
}
if (command == 4) {
manager.insertFromCommandLine();
}
if (command == 5) {
manager.deleteWordFromDictionary();
}
if (command == 6) {
manager.modifyWord();
}
if (command == 7) {
manager.modifyMeaning();
}
if (command == 8) {
manager.exportToFile();
}
if (command == 9) {
break;
}
}
// manager.insertFromFile();
// showAllWords();
// manager.dictionarySearcher();
// manager.deleteWordFromDictionary();
// manager.exportToFile();
// String output = manager.dictionaryLookup();
// System.out.println(output);
}
}
|
PHP
|
UTF-8
| 1,829 | 3.3125 | 3 |
[] |
no_license
|
<?php
class Truck extends Vehicle {
protected $maxSpeed = 90;
protected $capacity;
protected $items = [];
protected $trailer = false;
public function __construct($brand, $price, $capacity, $wheels) {
parent::__construct($brand, $price);
$this->capacity = $capacity;
$this->wheels = $wheels;
}
/**
* Ajoute un élément dans le camion
*/
public function addItem($item) {
// Je vérifie la capacité du camion
// On compare la taille du tableau $items avec $capacity
if (count($this->items) >= $this->capacity) {
echo 'Vous avez dépassé la capacité du camion...';
return $this;
}
$this->items[] = $item;
return $this;
}
/**
* Renvoie la cargaison en array
*/
public function getItems() {
return $this->items;
}
/**
* Attache la remorque
*/
public function attachTrailer() {
// On ajoute la remorque si possible
if (!$this->trailer) {
$this->trailer = true;
$this->capacity *= 2;
}
}
/**
* Détache la remorque
*/
public function detachTrailer() {
// On retire la remorque si possible
if ($this->trailer) {
$this->trailer = false;
$this->capacity /= 2;
// Si on veut récupérer les X derniers (Hors capacité)
// ['A', 'B', 'C', 'D', 'E', 'F'] devient ['D', 'E', 'F']
$lastItems = array_slice($this->items, $this->capacity, $this->capacity);
// Retirer les items qui sont en trop dans le chargement ($this->items)
// Le tableau ['A', 'B', 'C', 'D', 'E', 'F'] devient ['A', 'B', 'C']
$this->items = array_slice($this->items, 0, $this->capacity);
}
}
}
|
Java
|
UTF-8
| 11,746 | 2.28125 | 2 |
[
"Apache-2.0"
] |
permissive
|
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.io;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ConcurrencyUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.VisibleForTesting;
import java.io.IOException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static com.intellij.util.SystemProperties.getIntProperty;
/**
* A class intended to overcome interruptibility of {@link FileChannel} by repeating passed operation
* until it will be successfully applied.
* <p>
* If underlying {@link FileChannel} throws {@link ClosedByInterruptException} -> we close and reopen the
* channel, and try the operation again.
* <p>
* Basically, this class tries to provide something similar to Atomicity (Transaction) -- i.e. ensure
* {@link FileChannelIdempotentOperation} is either applied successfully, or not at all (if Retryer is
* closed before the operation starts) -- but operation can't be 'partially applied'.
* This is important because 'partially applied' operation usually means that either on-disk (in case of
* write-ops) or in-memory (in case of read-ops) data structure is left in inconsistent (=corrupted) state,
* and we want to prevent that. So we repeatedly re-open underlying FileChannel, and apply operation
* on the top of it, until either the operation succeeds, or until heat death of the universe -- whatever
* comes first.
* <p>
* WARNING: class API doesn't prevent incorrect usage, so needs caution: to be safely repeatable
* {@link FileChannelIdempotentOperation} implementation must be free of side effects (except for
* FileChannel modifications), and must not rely on FileChannel position from previous operations
* (because position will be lost during channel re-opening). For simpler API consider use of
* {@link ResilientFileChannel}. {@link ResilientFileChannel} could be seen as a counterpart of this
* class: this class implements kind-of-atomicity for logical units of work ({@link FileChannelIdempotentOperation}),
* while {@link ResilientFileChannel} implements same kind of atomicity for elementary operations,
* like read & write. It is easier to use, but has slightly more overhead.
* <p/>
* TODO RC: current implementation catches-and-retries not only {@link ClosedByInterruptException},
* but any {@link ClosedChannelException}. This (likely) serves same goal of keeping data structures in a
* consistent state -- if Channel is closed from another thread in the middle of an operation, this
* also most probably leads to corrupted data structure. But this violates description above, and
* the class name itself is misleading then -- class actually does a more general task than claims. If
* we insist to keep 'retry on anything' then class name and description should be adjusted accordingly.
* Also we could use already existing libs (e.g. <a href="https://github.com/failsafe-lib/failsafe">FailSafe</a>)
* for that.
*/
@ApiStatus.Internal
public final class FileChannelInterruptsRetryer implements AutoCloseable {
private static final Logger LOG = Logger.getInstance(FileChannelInterruptsRetryer.class);
/** If a single IO operation still not succeeds after that many retries -- fail */
@VisibleForTesting
static final int MAX_RETRIES = getIntProperty("idea.vfs.FileChannelInterruptsRetryer.MAX_RETRIES", 64);
/**
* If value > 0: add stacktrace to each Nth in a row retry warning log message
* If value <=0: never add stacktrace to a retry warning log message
*/
private static final int LOG_STACKTRACE_IF_RETRY_CHAIN_LONGER = getIntProperty("idea.vfs.LOG_STACKTRACE_IF_RETRY_CHAIN_LONGER", 32);
private final @NotNull Lock openCloseLock = new ReentrantLock();
private final @NotNull Path path;
private final Set<? extends @NotNull OpenOption> openOptions;
/** null if retryer has been closed */
private volatile FileChannel channel;
/**
* Total number of retries across all instances of this class. Only retries count -- a first
* successful attempt doesn't.
*/
private final static AtomicLong totalRetriedAttempts = new AtomicLong();
public static long totalRetriedAttempts(){
return totalRetriedAttempts.get();
}
public FileChannelInterruptsRetryer(final @NotNull Path path,
final Set<? extends @NotNull OpenOption> openOptions) throws IOException {
this.path = path;
this.openOptions = openOptions;
reopenChannel();
}
public <T> T retryIfInterrupted(final @NotNull FileChannelIdempotentOperation<T> operation) throws IOException {
boolean interruptedStatusWasCleared = false;
try {
for (int attempt = 0; ; attempt++) {
final FileChannel channelLocalCopy = channel;
if (channelLocalCopy == null && attempt == 0) {
//we haven't tried yet -> just reject
throw new ClosedChannelException();
}
try {
if (channelLocalCopy == null && attempt >= 0) {
//we have tried already, and failed, so now we can't just reject, since previous unsuccessful
// attempts may corrupt the data -> throw CCException (which will be caught and re-tried)
throw new ClosedChannelException();
}
return operation.execute(channelLocalCopy);
}
catch (ClosedChannelException e) {
totalRetriedAttempts.incrementAndGet();
if (attempt >= MAX_RETRIES) {
IOException ioe = new IOException(
"Channel[" + path + "][@" + System.identityHashCode(channelLocalCopy) + "] " +
"is interrupted/closed in the middle of operation " + MAX_RETRIES + " times in the row: surrender");
ioe.addSuppressed(e);
throw ioe;
}
//TODO RC: this catches _all_ close causes, not only thread interruptions!
// (for the latter only ClosedByInterruptException should be caught)
// ...Actually, catching all ClosedXXXExceptions make sense for the primary
// purpose of the class -- avoid corrupted IO-ops by making them 'atomic'
// (kind-of) i.e. all-or-nothing. From the PoV of keeping data structures
// in a consistent state -- async .close() is the same kind of danger as
// Thread.interrupt(): both could interrupt IO-op mid-flight giving corrupted
// result or leaving data structure in a corrupted state. Hence it is pretty
// reasonable to work around both issues same way.
// There are 2 issues here, though:
// 1) That behavior is inconsistent with that class javadocs (and even class
// name) promises -- docs promise the class deals with Thread.interrupt(),
// while really it does more than that, which could come as surprise for
// somebody naive enough to trust the docs.
// 2) Class currently handles async .close() in an inconsistent way: inconsistent
// with how .interrupt() is handled, and internally-inconsistent. I.e. async .close()
// could make Retryer 'closed' forever -- or could be silently ignored, depending
// on exact timing of the calls.
// This is not how .interrupt() is handled: interrupt()-ed IO-op is repeated until
// succeed, but Thread.interrupted status is remembered, and restored after op is
// succeed -- so interrupt() is not 'swallowed' silently, it is just 'postponed'
// until op currently in-flight finishes.
// But for async .close() it is different: if 'closed' status observed _before_
// IOps started -> ChannelClosedException is thrown, and Retryer remains closed
// forever, all following IOps will fail with the same exception. But if closed
// status observed in the middle of an operation -> channel is reopened, and
// closed status just silently disappears. This is hardly the 'least surprise'
// behavior, so must be fixed: either we handle async .close() same ways as
// .interrupt() -- i.e. postpone actual closing until current IOps finishes,
// but restore the 'closed' status afterwards -- or we explicitly state in the
// docs that 'closed' state is reversible, and remove 'if (!isOpen())' branch
// from the method start.
// (See @Ignored test ResilientFileChannel_MultiThreaded_Test.onceClosed_FileChannelInterruptsRetryer_RemainsClosedForever
// which fails now)
boolean logStackTrace = LOG_STACKTRACE_IF_RETRY_CHAIN_LONGER > 0
&& (attempt % LOG_STACKTRACE_IF_RETRY_CHAIN_LONGER == (LOG_STACKTRACE_IF_RETRY_CHAIN_LONGER - 1));
if (logStackTrace) {
LOG.warn("Channel[" + path + "][@" + System.identityHashCode(channelLocalCopy) + "] is closed during " + operation
+ " " + LOG_STACKTRACE_IF_RETRY_CHAIN_LONGER + " times in a row -- suspicious, log stacktrace", e);
}
else {
LOG.warn("Channel[" + path + "][@" + System.identityHashCode(channelLocalCopy) + "] is closed during " + operation
+ " => trying to reopen it again. Reason: " + e);
}
if (Thread.currentThread().isInterrupted()) {
Thread.interrupted();//must clear interrupted status, otherwise newly opened channel throws ClosedByInterrupt again
interruptedStatusWasCleared = true;
}
//TODO RC: should we remember 'close' status also, and apply it after the loop?
reopenChannel();
}
}
}
finally {
if (interruptedStatusWasCleared) {
Thread.currentThread().interrupt();
}
}
}
public boolean isOpen() {
return channel != null;
}
@Override
public void close() throws IOException {
ConcurrencyUtil.withLock(openCloseLock, this::tryClose);
}
private void reopenChannel() throws IOException {
ConcurrencyUtil.withLock(openCloseLock, () -> {
try {
tryClose();
}
catch (IOException e) {//RC: Why swallow this exception?
LOG.info("Can't close channel[" + path + "]: " + e.getMessage());
}
channel = FileChannel.open(path, openOptions);
});
}
private void tryClose() throws IOException {
try {
FileChannel channel = this.channel;
if (channel != null && channel.isOpen()) {
channel.close();
}
}
finally {
channel = null;
}
}
public interface FileChannelIdempotentOperation<T> {
/**
* Implementation must be idempotent: i.e. has no other side effects except for desirable changes
* in fileChannel. Also, implementation shouldn't rely on FileChannel.position from previous calls:
* if you want to read or write bytes at some offset -- either use absolute-positioned read-write
* methods, or position fileChannel explicitly inside the lambda.
*/
T execute(@NotNull FileChannel fileChannel) throws IOException;
}
}
|
C#
|
UTF-8
| 1,136 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using PublicHolidays.Au.Internal.PublicHolidays;
using Shouldly;
using Xunit;
namespace PublicHolidays.Au.UnitTests.Internal.PublicHolidays
{
public class NewYearsDayTests
{
private readonly NewYearsDay _newYearsDay;
public NewYearsDayTests()
{
_newYearsDay = new NewYearsDay();
}
[Fact]
public void In_YearWhereNewYearsDayIsNotOnWeekend_ReturnsJanurary1stOfThatYear()
{
const int year = 2018;
var result = _newYearsDay.In(year);
result.ShouldContain(new DateTime(year, 1, 1));
}
[Fact]
public void In_YearWhereNewYearsDayIsOnWeekend_ReturnsMondayFollowingJanurary1stOfThatYear()
{
const int year = 2017;
var result = _newYearsDay.In(year);
result.ShouldContain(new DateTime(year, 1, 2));
}
[Fact]
public void GetNameOfPublicHolidayIn_Any_ReturnsCorrectName()
{
var name = _newYearsDay.GetNameOfPublicHolidayIn(State.National);
name.ShouldBe("New Years Day");
}
}
}
|
Java
|
UTF-8
| 299 | 3.0625 | 3 |
[] |
no_license
|
package com.vishwa.lld.designpattern.structuraldesignpattern;
/**
* Base Car decorator
*/
public class CarDecorator implements Car{
protected Car car ;
public CarDecorator(Car car) {
this.car = car;
}
@Override
public void manufactureCar() {
this.car.manufactureCar();
}
}
|
Markdown
|
UTF-8
| 393 | 3.078125 | 3 |
[] |
no_license
|
520. Detect Capital
**Easy**
[Original Page](https://leetcode.com/problems/largest-triangle-area/)
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
```
Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
```
|
JavaScript
|
UTF-8
| 619 | 3.875 | 4 |
[] |
no_license
|
// for(i = 0; i < 10; i++){
// console.log(i);
// if(i === 9){
// break;
// }
// }
// console.log ("end of loop");
// var links = document.getElementsByTagName("a");
// for (i = 0; i < links.length; i++){
// links[i].className = "link-" + i ;
// }
// function getAverage (a,b){
// var average = (a + b)/ 2;
// console.log (average);
// return average;
// }
// var Result = getAverage(21,13);
// console.log ("Average is = " + Result);
var a = 15;
var b = 13;
if (isNaN(a)){
console.log ("Not a number");
}
else {
console.log("Use a calculator nxt time anyways here's your answer " + (a * b ));
}
|
Java
|
UTF-8
| 203 | 2.328125 | 2 |
[] |
no_license
|
package absFactory;
/**
* @author tjk
* @date 2019/8/3 17:30
*
* 抽象工厂
*/
public abstract class AbstractFactory {
abstract Product1 ProductA();
abstract Product2 ProductB();
}
|
Java
|
UTF-8
| 1,516 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package org.drools.analytics.components;
import java.util.HashSet;
import java.util.Set;
import org.drools.analytics.result.Cause;
/**
* Instance of this class represents a possible combination of Constraints under
* one Pattern. Each possibility returns true if all the Constraints in the
* combination are true.
*
* @author Toni Rikkola
*/
public class PatternPossibility extends AnalyticsComponent implements
Possibility {
private static final long serialVersionUID = 8871361928380977116L;
private static int index = 0;
private int patternId;
private int ruleId;
private Set<Cause> items = new HashSet<Cause>();
public PatternPossibility() {
super(index++);
}
@Override
public AnalyticsComponentType getComponentType() {
return AnalyticsComponentType.PATTERN_POSSIBILITY;
}
public CauseType getCauseType() {
return Cause.CauseType.POSSIBILITY;
}
public Set<Cause> getItems() {
return items;
}
public int getAmountOfItems() {
return items.size();
}
public int getPatternId() {
return patternId;
}
public int getRuleId() {
return ruleId;
}
public void setRuleId(int ruleId) {
this.ruleId = ruleId;
}
public void setPatternId(int patternId) {
this.patternId = patternId;
}
public void add(Restriction restriction) {
items.add(restriction);
}
@Override
public String toString() {
return "PatternPossibility from rule: " + ruleName
+ ", amount of items:" + items.size();
}
}
|
Java
|
UTF-8
| 965 | 2 | 2 |
[] |
no_license
|
package com.zszd.ai.service.resource;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.zszd.ai.dao.resource.ResourceDao;
import com.zszd.ai.pojo.Resources;
@Service
public class ResourceServiceImpl implements ResourceService {
@Resource
private ResourceDao resourceDao;
@Override
public List<Resources> queryPassedResourceInfoByType(int type) {
return resourceDao.queryPassedResourceInfoByType(type);
}
@Override
public List<Resources> queryAllResourceInfoByType(int type) {
return resourceDao.queryAllResourceInfoByType(type);
}
@Override
public int insertResourceRecord(Resources resource) {
return resourceDao.insertResourceRecord(resource);
}
@Override
public Resources getResourceById(String id) {
return resourceDao.getResourceById(id);
}
@Override
public int updateResourceInfo(Resources resource) {
return resourceDao.updateResourceInfo(resource);
}
}
|
Ruby
|
UTF-8
| 1,420 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
def matrix_addition_reloaded(*matrices)
matrix = matrices.first
height = matrix.length
width = matrix[0].length
empty_matrix = Array.new(height) { [0] * width }
matrices.inject(empty_matrix) do |m1, m2|
return nil if m2.length != height or m2[0].length != width
matrix_addition(m1, m2)
end
end
def squarocol?(arrays)
# Better way
# return true if grid.any? { |row| row.uniq.length == 1 }
# return true if grid.transpose.any? { |col| col.uniq.length == 1 }
# false
(0...arrays.length).each do |i|
return true if arrays[i].uniq.length == 1
temp = []
(0...arrays.length).each do |j|
temp << arrays[j][i]
end
return true if temp.uniq.length == 1
end
false
end
def squaragonal?(arrays)
left_to_right = []
right_to_left = []
(0...arrays.length).each do |index|
left_to_right << arrays[index][index]
right_to_left << arrays[index][-1 * (index+ 1)]
end
if (left_to_right.uniq.length == 1 || right_to_left.uniq.length == 1)
true
else
false
end
end
def adjacent_sums(arr)
sums = []
(0...arr.length-1).each do |i|
sums << arr[i] + arr[i + 1]
end
sums
end
def pascals_triangle(number)
triangle = [[1]]
while triangle.length < number
level_above = triangle.last
next_level = [1]
next_level += adjacent_sums(level_above)
next_level << 1
triangle << next_level
end
triangle
end
|
Shell
|
UTF-8
| 343 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
cd /opt/streamer
# check and copy configuration files from secrets
if [ -f $STREAMER_SERVICE_CONFIG ]; then
cp $STREAMER_SERVICE_CONFIG config/default.json
fi
if [ -f $STREAMER_MAILER_CONFIG ]; then
cp $STREAMER_MAILER_CONFIG config/mailer.json
fi
/opt/nodejs/bin/node --expose-gc --max-old-space-size=2048 streamer.js
|
JavaScript
|
UTF-8
| 687 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/** @jsx React.DOM */
var React = require('react');
var requireStylesheet = require('stylesheets').requireStylesheet;
var MyComponent = React.createClass({
componentWillMount: function() {
// this call can be put outside of `componentWillMount`. Reason why it's
// here:
// - lazy loading
// - makes server rendering work, as the style sheet should be injected for
// every request rather than at import time
// - ^ consequently, makes tests work
requireStylesheet(process.env.STATIC_ROOT + 'MyComponent.css');
},
render: function() {
return <span className="MyComponent">Hello, {this.props.name}!</span>;
}
});
module.exports = MyComponent;
|
Python
|
UTF-8
| 2,114 | 4.21875 | 4 |
[] |
no_license
|
# multiple versions of the algorithm
# this version will pick the 'middle' element of the 'array'
# quicksort requires a partition function as well as the sort function
import random
import time
def quicksort(arr, left, right):
# print(f"Current left value: {left}")
# print(f"Current right value: {right}")
# base case to exit the recursive lookup
if left >= right:
return
pivot = arr[(left + (right - left) // 2)]
# print(f"Current pivot value: {pivot}")
# partition array around this pivot point - value of left is updated with each recursion
index = partition(arr, left, right, pivot)
# recursive quicksort call on the array with the lower (left) and upper (mid -1)
quicksort(arr, left, index - 1)
# recursive quicksort call on the array with the index (pivot) and end of array (len - 1)
quicksort(arr, index, right)
def partition(arr, left, right, pivot):
# while left (lower) is less than right (upper) continue the loop
while left <= right:
# while the value at index left of the array is less than pivot continue moving 'right'
while arr[left] < pivot:
left += 1
# contraflow to above
while arr[right] > pivot:
right -= 1
# if both while loops have been escaped it is time to swap values at the specific array indexes
# value of left & right are swapped and left & right are incre/decremented appropriately
if left <= right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
# if outer while loop has escaped then the left value needs to be returned
return left
if __name__ == "__main__":
arr1 = [32, 73, 71, 78, 93, 30, 0, 53, 1, 74]
arr2 = []
for i in range(2500000):
arr2.append(random.randrange(0, 50000000))
start_time = time.time()
# print(f"The list before Quicksort is applied: {arr1}")
quicksort(arr2, 0, len(arr2) - 1)
# print(f"The list after Quicksort is applied: {arr2}")
print(f"Program took {time.time() - start_time} seconds. ")
|
C#
|
UTF-8
| 2,978 | 2.828125 | 3 |
[] |
no_license
|
using ClearSkies.Prefabs.Bullets;
using Microsoft.DirectX;
using ClearSkies.Prefabs.Enemies.Tanks;
namespace ClearSkies.Prefabs.Turrets
{
/// <summary>
/// A Turret the player will control in the game.
/// </summary>
abstract class Turret : Prefab
{
#region Fields
protected TurretHead head;
protected float colliderSize;
protected float health;
#endregion
#region Initializer Methods
/// <summary>
/// Creates a Turret at the given location, facing the given rotation,
/// scaled to the given amount, with the given TurretHead mounted on
/// top, and with a collision sphere of the given size.
/// </summary>
/// <param name="location">Location of the Turret</param>
/// <param name="rotation">Rotation the Turret is facing</param>
/// <param name="scale">Scale of the Turret</param>
/// <param name="head">TurretHead to be placed on top</param>
/// <param name="colliderSize">Size of the collison Sphere</param>
public Turret(Vector3 location, Vector3 rotation, Vector3 scale, TurretHead head, float colliderSize)
: base(location, rotation, scale)
{
this.head = head;
this.colliderSize = colliderSize;
this.children.Add(head);
this.health = 100f;
}
#endregion
#region Getters and Setters
/// <summary>
/// The Head mounted on the Turret.
/// </summary>
public TurretHead Head
{
get { return this.head; }
}
/// <summary>
/// The size of the collider sphere.
/// </summary>
public float ColliderSize
{
get { return this.colliderSize; }
}
/// <summary>
/// The Turrets current health value.
/// </summary>
public float Health
{
get { return this.health; }
}
#endregion
#region Public Methods
/// <summary>
/// Detects collisions from incoming Bullets.
/// </summary>
/// <param name="collider"></param>
public override void detectCollision(Prefab collider)
{
base.detectCollision(collider);
float damage = 0f;
if (collider is Bullet)
{
Bullet collidingBullet = (Bullet)collider;
if (collidingBullet.Owner != this)
{
damage = collidingBullet.Damage;
}
}
else if (collider is Tank)
{
damage = Settings.TANK_COLLIDE_DAMAGE;
}
health -= damage;
if (health <= 0)
{
this.health = 0;
this.alive = false;
// TODO: Add death animation script
}
}
#endregion
}
}
|
JavaScript
|
UTF-8
| 878 | 2.640625 | 3 |
[] |
no_license
|
import 'fetch'
import { HttpClient } from 'aurelia-fetch-client';
export class WeatherApi {
constructor() {
this.http = new HttpClient().configure(config => {
config
.withBaseUrl('https://crossorigin.me/http://api.openweathermap.org/')
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response;
}
})
})
}
getCurrentWeather(latitude, longitude) {
console.log("Fetching weather");
let key = "d1c70a6726e70b55ac3c105ee5a29d4c";
return this.http.fetch('data/2.5/weather?APPID=' + key + `&lat=${latitude}&lon=${longitude}&units=metric`)
.then(response => response.json())
}
}
|
Java
|
UTF-8
| 402 | 2.125 | 2 |
[] |
no_license
|
package cn.edu.sdut.dao;
import java.util.List;
import cn.edu.sdut.domain.Staff;
public interface StaffMapper {
public List<Staff> selectAll();
public Staff selectStaff(int s_id);
public int add(Staff staff);
public int update(Staff staff);
public int delete(int s_id);
public int getSum();
public int avgAge();
public float avgWage();
public int[] getAge();
public float[] getWage();
}
|
Java
|
UTF-8
| 311 | 2.5 | 2 |
[] |
no_license
|
package com.notesapp.models;
import java.sql.SQLException;
public class NoteTest {
public static void main(String []args) throws SQLException {
Note note1 = Note.insertNoteToDB("Hello", "Hello world from our notes app", 2);
System.out.printf("%s\n%s", note1.title, note1.content);
}
}
|
Python
|
UTF-8
| 1,190 | 3.296875 | 3 |
[] |
no_license
|
import random
print("__________ Dice Stimulator __________")
while True:
number = random.randint(1,6)
if number == 1:
print("----------")
print("| |")
print("| O |")
print("| |")
print("----------")
elif number == 2:
print("----------")
print("| O |")
print("| |")
print("| O |")
print("----------")
elif number == 3:
print("----------")
print("| O |")
print("| O |")
print("| O |")
print("----------")
elif number == 4:
print("----------")
print("| O O |")
print("| |")
print("| O O |")
print("----------")
elif number == 5:
print("----------")
print("| O O |")
print("| O |")
print("| O O |")
print("----------")
elif number == 6:
print("----------")
print("| O O |")
print("| O O |")
print("| O O |")
print("----------")
print("\n")
stop = input("Press y for continue or q for quite : ")
if stop == 'q':
break
|
Java
|
GB18030
| 1,285 | 2.484375 | 2 |
[] |
no_license
|
package com.icss.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.icss.util.DbInfo;
public class BaseDao implements IBaseDao{
protected Connection conn;
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public void openConnection() throws ClassNotFoundException,SQLException,Exception {
if(conn == null || conn.isClosed()) {
DbInfo dbinfo = DbInfo.newInstance();
Class.forName(dbinfo.getDbdriver());
conn = DriverManager.getConnection(dbinfo.getDburl(),dbinfo.getUsername(),dbinfo.getPassword());
}
}
public void closeConnection() {
if(this.conn != null) {
try {
this.conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void beginTransaction() throws Exception {
this.openConnection();
this.conn.setAutoCommit(false);
}
public void commit() throws Exception{
if(this.conn != null) {
this.conn.commit();
}else {
throw new Exception("ûдݿҪύ");
}
}
public void rollback() throws Exception {
if(this.conn != null) {
this.conn.rollback();
}else {
throw new Exception("ûдݿҪύ");
}
}
}
|
C++
|
UTF-8
| 1,819 | 3.578125 | 4 |
[] |
no_license
|
/*
* @lc app=leetcode id=166 lang=cpp
*
* [166] Fraction to Recurring Decimal
*
* https://leetcode.com/problems/fraction-to-recurring-decimal/description/
*
* algorithms
* Medium (19.28%)
* Total Accepted: 84.7K
* Total Submissions: 439.4K
* Testcase Example: '1\n2'
*
* Given two integers representing the numerator and denominator of a fraction,
* return the fraction in string format.
*
* If the fractional part is repeating, enclose the repeating part in
* parentheses.
*
* Example 1:
*
*
* Input: numerator = 1, denominator = 2
* Output: "0.5"
*
*
* Example 2:
*
*
* Input: numerator = 2, denominator = 1
* Output: "2"
*
* Example 3:
*
*
* Input: numerator = 2, denominator = 3
* Output: "0.(6)"
*
*
*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string fractionToDecimal(int numerator, int denominator)
{
if (numerator == 0) return "0";
bool sign = true;
int64_t n = numerator, d = denominator;
if (n < 0) {
sign = !sign;
n = -n;
}
if (d < 0) {
sign = !sign;
d = -d;
}
string result;
if (!sign) result += "-";
int64_t q = n / d;
int64_t r = n % d;
result += to_string( q );
if (r != 0) result += ".";
vector<int64_t> r_history = { r };
while (r != 0) {
n = r * 10;
q = n / d;
r = n % d;
result += to_string( q );
auto it = find( r_history.begin(), r_history.end(), r );
if (it != r_history.end()) {
const int repeat_size = distance( it, r_history.end() );
result.insert( result.end() - repeat_size, '(' );
result += ")";
break;
}
r_history.push_back( r );
}
return result;
}
int main()
{
cout << fractionToDecimal( 1, 1 ) << endl;
return 0;
}
|
Markdown
|
UTF-8
| 3,850 | 2.765625 | 3 |
[] |
no_license
|
---
description: "Steps to Make Favorite Microwaved Bread Pudding for One"
title: "Steps to Make Favorite Microwaved Bread Pudding for One"
slug: 2131-steps-to-make-favorite-microwaved-bread-pudding-for-one
date: 2021-06-25T06:25:25.486Z
image: https://img-global.cpcdn.com/recipes/6233633403699200/680x482cq70/microwaved-bread-pudding-for-one-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/6233633403699200/680x482cq70/microwaved-bread-pudding-for-one-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/6233633403699200/680x482cq70/microwaved-bread-pudding-for-one-recipe-main-photo.jpg
author: Rebecca Lawrence
ratingvalue: 4.5
reviewcount: 17921
recipeingredient:
- " Egg"
- " Sugar"
- " half the mug Milk"
- " if a loaf of sandwich bread 1 slice Bread of your choice"
- " Honey or jam etc"
recipeinstructions:
- "Break the egg into the mug and beat. Add the sugar and mix."
- "Fill the mug with milk until about 2/3 filled. Stir."
- "Chop the bread into pieces and sink into the bread mixture. Lightly cover with plastic wrap."
- "Microwave while keeping an eye on it. When it seems like it will boil over, let it rest a bit. Once it has calmed, microwave again. The total microwaved time should be 3-5 minutes."
- "Once the egg mixture becomes jelly-like, it's done Optionally top with honey or jam and enjoy."
- "It was delicious. This was the only thing I had to wash."
categories:
- Recipe
tags:
- microwaved
- bread
- pudding
katakunci: microwaved bread pudding
nutrition: 102 calories
recipecuisine: American
preptime: "PT39M"
cooktime: "PT50M"
recipeyield: "1"
recipecategory: Dinner
---

Hello everybody, hope you're having an amazing day today. Today, we're going to make a special dish, microwaved bread pudding for one. One of my favorites food recipes. For mine, I am going to make it a little bit tasty. This will be really delicious.
Microwaved Bread Pudding for One is one of the most popular of current trending meals in the world. It is appreciated by millions daily. It is simple, it's quick, it tastes yummy. They're fine and they look fantastic. Microwaved Bread Pudding for One is something which I have loved my entire life.
To begin with this particular recipe, we must first prepare a few ingredients. You can cook microwaved bread pudding for one using 5 ingredients and 6 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Microwaved Bread Pudding for One:
1. Make ready Egg
1. Make ready Sugar
1. Take half the mug Milk
1. Prepare if a loaf of sandwich bread, 1 slice Bread of your choice
1. Take Honey or jam, etc.
<!--inarticleads2-->
##### Instructions to make Microwaved Bread Pudding for One:
1. Break the egg into the mug and beat. Add the sugar and mix.
1. Fill the mug with milk until about 2/3 filled. Stir.
1. Chop the bread into pieces and sink into the bread mixture. Lightly cover with plastic wrap.
1. Microwave while keeping an eye on it. When it seems like it will boil over, let it rest a bit. Once it has calmed, microwave again. The total microwaved time should be 3-5 minutes.
1. Once the egg mixture becomes jelly-like, it's done Optionally top with honey or jam and enjoy.
1. It was delicious. This was the only thing I had to wash.
So that is going to wrap this up with this special food microwaved bread pudding for one recipe. Thank you very much for your time. I am confident that you can make this at home. There is gonna be more interesting food in home recipes coming up. Don't forget to bookmark this page in your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
|
Java
|
GB18030
| 808 | 2.234375 | 2 |
[] |
no_license
|
package mr.flowcount;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
public class ProvincePartitioner extends Partitioner<Text, FlowBean>{
@Override
public int getPartition(Text key, FlowBean value, int numPartitions) {
// TODO Auto-generated method stub
//дgetpartition
//keyֻ
//flowbeanϢ
String prePhonenum = key.toString().substring(0,3);
int partition = 5;
if ("130".equals(prePhonenum))
partition = 0;
else if ("131".equals(prePhonenum))
partition = 1;
else if ("132".equals(prePhonenum))
partition = 2;
else if ("133".equals(prePhonenum))
partition = 3;
else
partition = 4;
return partition;
}
}
|
TypeScript
|
UTF-8
| 2,439 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
import database from '../../services/database';
import execution from '../../services/execution';
import LogManager from '../../services/logManager';
import cacheTTL from 'map-cache-ttl';
import {IncomingMessage, ServerResponse} from 'http';
const idCache = new cacheTTL('8s', '30s');
/**
* Gets the function ID of the refferer URL.
* @param {IncomingMessage} req - The request object.
* @param {ServerResponse} res - The response object.
* @return {null | string} - The function ID or null if not in the referer.
*/
function getRefferalFunctionID(req: IncomingMessage, res: ServerResponse): null | string {
if (!req.headers.referer) return null;
const functionID = req.headers.referer.split('/')[3];
if (functionID === '' || !functionID) return null;
return functionID;
}
/**
* Lets a function respond to the request
* @param {Request} req the request
* @param {Response} res the response
*/
export default async function executeFunction(req: IncomingMessage, res: ServerResponse) {
if (!req.url) return;
let functionID = req.url.split('/')[1];
const referrerFuncID = getRefferalFunctionID(req, res);
if ((functionID !== referrerFuncID) && referrerFuncID) {
req.url = '/' + referrerFuncID + req.url;
functionID = referrerFuncID;
}
if (!functionID) {
res.statusCode = 403;
res.end('Invalid URL!');
return;
}
let instance;
if (idCache.has(functionID)) {
instance = idCache.get(functionID);
} else {
instance = await database.getInstanceByIdOrName(functionID).catch((error) => {
const logs = new LogManager();
logs.updateContext('api', ['execute', functionID]);
logs.logError(`Failed to get instance of called function ${functionID}, ${error}`);
res.statusCode = 200;
res.end();
return;
});
idCache.set(functionID, instance);
}
if (!instance) {
const logs = new LogManager();
logs.updateContext('api', ['execute', functionID]);
logs.logError(`Failed to get instance of called function ${functionID}, instance not found`);
res.statusCode = 404;
res.end();
return;
}
await execution.execute(instance, req, res).catch((error: Error) => {
const logs = new LogManager();
logs.updateContext('api', ['execute', functionID]);
logs.logError(`Failed to execute function ${functionID}, ${error}. STACK: ${error.stack}`);
res.statusCode = 500;
res.end();
return;
});
}
|
Shell
|
UTF-8
| 1,254 | 2.59375 | 3 |
[] |
no_license
|
# vim:ft=sh
alias be='bundle exec'
alias gerp='grep -rs --include=*.{js,coffee,hbs,json,rb,py} --exclude-dir={bower_components,node_modules,tmp,dist}'
alias all_vars='(set -o posix; set) | less -R'
alias cm='cd '$DOTFILE_DIR
alias cdg='cd $(git root)'
alias gemdir='cd $(gem environment gemdir)'
alias tree='tree -Ca --noreport -I ".sass-cache|.git|node_modules|bower_components|tmp|__pycache__|.virtualenv"'
alias ll='ls -la'
alias la='ls -A'
alias l='ls -CF'
alias src='. $HOME/.bashrc'
alias spf='. $HOME/.bash_profile'
alias stripescapes='sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"'
alias vi='vim'
alias path='echo $PATH | tr ":" "\n"'
alias pythonpath='echo $PYTHONPATH | tr ":" "\n"'
alias :q='logout'
alias :e='vim'
alias ,e='vim $HOME/.vimrc'
alias which='type -a'
alias wget='wget --content-disposition'
alias loc="find . -type f -iname \"*.rb\" -exec cat {} \; | sed '/^\s*#/d;/^\s*$/d' | wc -l"
alias rbdoc="cd ~/my-ruby/src/ruby-2.1.2 && yard server -m core .yardoc-core stdlib-2.1.2 .yardoc-stdlib"
alias curriculum='cd $HOME/src/nycda/nycda-curriculum && tree curriculums/web-development-intensive'
alias ecurriculum='cd $HOME/src/nycda/nycda-curriculum && vim curriculums/web-development-intensive/web-development-intensive.md'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.