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 |
|---|---|---|---|---|---|---|---|
TypeScript | UTF-8 | 3,131 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | import * as crypto from "crypto";
import * as something from "whatsit";
import * as eccrypto from "eccrypto";
import * as secp256k1 from "secp256k1";
export function rand_hex(length: number): string {
let byte_sz = Math.floor(length / 2);
return crypto.randomBytes(byte_sz).toString("hex");
}
export class PrivateKey {
inner!: Buffer;
constructor() {
this.inner = eccrypto.generatePrivate();
}
static from(buffer: Buffer): PrivateKey {
let key = Object.create(this.prototype);
key.inner = buffer;
return key;
}
static fromHex(hex: string): PublicKey {
let inner = Buffer.from(hex, "hex");
return PublicKey.from(inner);
}
publicKey(compressed: boolean = true): PublicKey {
let buffer = compressed
? eccrypto.getPublicCompressed(this.inner)
: eccrypto.getPublic(this.inner);
return PublicKey.from(buffer);
}
async derive(publicKey: PublicKey): Promise<Buffer> {
return await eccrypto.derive(this.inner, publicKey.inner);
}
async sign(msg: Buffer) {
return await eccrypto.sign(this.inner, msg);
}
toString(): string {
return this.inner.toString("hex");
}
}
export class PublicKey {
inner!: Buffer;
private constructor() {}
static from(buffer: Buffer): PublicKey {
let key = Object.create(this.prototype);
key.inner = buffer;
return key;
}
static fromHex(hex: string): PublicKey {
let inner = Buffer.from(hex, "hex");
return PublicKey.from(inner);
}
toString(): string {
return this.inner.toString("hex");
}
}
export class CryptoCtx {
priv_key!: PrivateKey;
ephem_key!: Buffer;
static async from(pub_key: PublicKey, priv_key?: PrivateKey): Promise<CryptoCtx> {
priv_key = priv_key ? priv_key : new PrivateKey();
let ephem_key = Buffer.from(secp256k1.ecdh(pub_key.inner, priv_key.inner));
return new CryptoCtx(priv_key, ephem_key);
}
private constructor(priv_key: PrivateKey, ephem_key: Buffer) {
this.priv_key = priv_key;
this.ephem_key = ephem_key;
}
encrypt(data: Buffer): Buffer {
let iv = crypto.randomBytes(12);
let cipher = crypto.createCipheriv("aes-256-gcm", this.ephem_key, iv);
let chunk_1 = cipher.update(data);
let chunk_2 = cipher.final();
let tag = cipher.getAuthTag();
let buffer = Buffer.alloc(1 + iv.length + 1 + tag.length, 0, 'binary');
let off = 0;
buffer.writeUInt8(iv.length, off);
off += 1;
iv.copy(buffer, off);
off += iv.length;
buffer.writeUInt8(tag.length, off);
off += 1;
tag.copy(buffer, off);
return Buffer.concat([buffer, chunk_1, chunk_2]);
}
decrypt(data: Buffer): Buffer {
let off = 0;
let iv_length = data.readUInt8(off);
off += 1;
let iv = data.slice(off, off + iv_length);
off += iv_length;
let tag_length = data.readUInt8(off);
off += 1;
let tag = data.slice(off, off + tag_length);
off += tag_length;
let enc = data.slice(off);
var cipher = crypto.createDecipheriv("aes-256-gcm", this.ephem_key, iv);
cipher.setAuthTag(tag);
return Buffer.concat([cipher.update(enc), cipher.final()]);
}
}
|
C# | UTF-8 | 2,557 | 3.375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AvengersUtd.Odyssey.Geometry
{
public partial class Polygon
{
public static double ComputeSignedArea(Polygon polygon)
{
int i;
double area = 0;
Vertices vertices = polygon.Vertices;
for (i = 0; i < vertices.Count; i++)
{
int j = (i + 1)%vertices.Count;
area += vertices[i].X*vertices[j].Y;
area -= vertices[i].Y*vertices[j].X;
}
area /= 2.0;
return area;
}
/// <summary>
/// Winding number test for a point in a polygon.
/// </summary>
/// See more info about the algorithm here: http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm
/// <param name="point">The point to be tested.</param>
/// <returns>-1 if the winding number is zero and the point is outside
/// the polygon, 1 if the point is inside the polygon, and 0 if the point
/// is on the polygons edge.</returns>
public static int PointInPolygon(Polygon polygon, Vector2D point)
{
// Winding number
int wn = 0;
Vertices polyVertices = polygon.Vertices;
// Iterate through polygon's edges
for (int i = 0; i < polyVertices.Count; i++)
{
// Get points
Vector2D p1 = polyVertices[i];
Vector2D p2 = polyVertices[polyVertices.NextIndex(i)];
// Test if a point is directly on the edge
Vector2D edge = p2 - p1;
double area = MathHelper.Area(ref p1, ref p2, ref point);
if (Math.Abs(area - 0f) < MathHelper.EpsilonD && Vector2D.Dot(point - p1, edge) >= 0 && Vector2D.Dot(point - p2, edge) <= 0)
{
return 0;
}
// Test edge for intersection with ray from point
if (p1.Y <= point.Y)
{
if (p2.Y > point.Y && area > 0)
{
++wn;
}
}
else
{
if (p2.Y <= point.Y && area < 0)
{
--wn;
}
}
}
return wn;
}
}
}
|
C | UTF-8 | 925 | 3.1875 | 3 | [] | no_license | #include <stdio.h> // printf.
#include <math.h> // pow()
#include <stdlib.h> // malloc.
#include "sum.h" // All our functions + common.h ( MPI, omp, WallTime() ).
int main(int argc,char** argv){
int iterations = 30;
long long N[iterations]; // Numer of elements to sum.
int i;
int rank = 0; // MPI rank.
double S = (M_PI*M_PI)/6; // The limit of the series.
double* SnOrdi = (double*)malloc(iterations*sizeof(double));
double* SnForw = (double*)malloc(iterations*sizeof(double));
MPI_Init(&argc,&argv);
N[0] = 8;
for(i=1; i<iterations; ++i)
N[i] = 2*N[i-1];
// Do calculations.
for(i=0; i<iterations; ++i)
{
SnOrdi[i] = sum(N[i]);
SnForw[i] = sumF(N[i]);
}
// Output results.
if(rank==0)
{
printf("n \terror\n");
for(i=0; i<iterations; ++i)
printf("%lld \t%.17e \t%.17e \n", N[i], S-SnOrdi[i], S-SnForw[i]);
}
// Clean up.
free(SnOrdi); free(SnForw);
MPI_Finalize();
return 0;
}
|
Markdown | UTF-8 | 5,497 | 2.578125 | 3 | [
"MIT"
] | permissive | # BFT
[](https://travis-ci.com/KaoImin/bft-core)
[](https://crates.io/crates/bft-core)
An efficient and stable Rust library of BFT protocol for distributed system.
## What is BFT?
BFT(Byzantine Fault Tolerance) comprise a class of consensus algorithms that achieve byzantine fault tolerance. BFT can guarantee liveness and safety for a distributed system where there are not more than 33% malicious byzantine nodes, and thus BFT is often used in the blockchain network.
## BFT Protocol
### Protocol
BFT is a State Machine Replication algorithm, and some states are shown below:
1. The three states protocol
```
NewHeight -> (Propose -> Prevote -> Precommit)+ -> Commit -> NewHeight -> ...
```
2. The three states protocol in a height
```
+-------------------------------------+
| | (Wait new block)
v |
+-----------+ +-----+-----+
+----------> | Propose +--------------+ | NewHeight |
| +-----------+ | +-----------+
| | ^
| (Else) | |
| v |
+-----+-----+ +-----------+ |
| Precommit | <------------------------+ Prevote | | (Wait RichStatus)
+-----+-----+ +-----------+ |
| |
| (When +2/3 Precommits for the block found) |
v |
+--------------------------------------------------------------+-----+
| Commit |
| |
| * Generate Proof; |
| * Set CommitTime = now; |
+--------------------------------------------------------------------+
```
### Architecture
A complete BFT model consists of 4 essential parts:
1. Consensus Module, the consensus algorithm module includes signature verification, proof generation, version check, etc.;
2. State Machine, the BFT state machine is focused on consensus proposal;
3. Transport Module, the network for consensus module to communicate with other modules;
4. Wal Module, the place saving BFT logs.
**NOTICE**: The bft-core only provides a basic BFT state machine and does not support the advanced functions such as signature verification, proof generation, compact block, etc. These functions are in consensus module rather than bft-core library.
## Feature
The bft-core provides `async_verify` feature to verify transcation after received a proposal. BFT state machine will check the verify result of the proposal before `Precommit` step. If it has not received the result of the proposal yet, it will wait for an extra 1/2 of the consensus duration.
## Interface
If bft-core works correctly, it needs to receive 4 types of message: `Proposal`, `Vote`, `Feed`, `Status`. And bft-core can send 4 types of message: `Proposal`, `Vote`, `Commit` and `GetProposalRequest`. Besides, bft-core also provides `Stop` and `Start` message that can control state machine stop or go on. These types of messages consist in the enum `CoreInput` and `CoreOutput`:
```rust
enum CoreInput {
Proposal(Proposal),
Vote(Vote),
Feed(Feed),
Status(Status),
Commit(Commit),
#[cfg(feature = "async_verify")]
VerifyResp(VerifyResp),
Pause,
Start,
}
enum CoreOutput {
Proposal(Proposal),
Vote(Vote),
Commit(Commit),
GetProposalRequest(u64),
}
```
For detailed introduction, click [here](src/types.rs).
## Usage
First, add bft-core to your `Cargo.toml`:
```rust
[dependencies]
bft-core = { git = "https://github.com/KaoImin/bft-core.git", branch = "develop" }
```
If you want to use `async_verify` feature, needs to add following codes:
```rust
[features]
async_verify = ["bft-core/async_verify"]
```
Second, add BFT and channel to your crate as following:
```rust
extern crate bft_core as bft;
use bft::{types::*, Core, FromCore};
```
Third, initialize a BFT core:
```rust
let bft = BFT::new(address);
```
*The `address` here is the address of this node with type `Vec<u8>`.*
What needs to illustrate is that the BFT machine is in stop step by default, therefore, the first thing is send `CoreInput::Start` message. Use `send_bft_msg()` function to send a message to BFT state machine as following:
```rust
bft.send_bft_msg(CoreInput::Start).map_err();
bft.send_bft_msg(CoreInput::Status(status)).map_err();
// only in feature async_verify
bft.send_bft_msg(CoreInput::VerifyResq(result)).map_err();
```
And implement the trait `FromCore` to receive messages from BFT core.
If you want to use the BFT height to do some verify, use `get_height` function as following:
```rust
let height: u64 = bft.get_height();
```
## License
This an open source project under the [MIT License](https://github.com/KaoImin/bft-core/blob/develop/LICENSE).
|
Python | UTF-8 | 4,188 | 2.75 | 3 | [] | no_license | import re
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 30 09:20:46 2017
@author: rjr
"""
# Creating a web scraper for r/dailyprogrammer
# Step 1: Import the scraper (scrapy, BS4?, requests?)
# Step 2: Have it scrape the first page of dailyprogrammer
#2A: Commit the text that is scraped to a file
# Step 3: Have it scrape additional pages
#3A: Grab the next link, pass it to the urllib
#
"""
TODO: An interesting project I came across: https://github.com/stanfordjournalism/search-script-scrape
Ok doing some quick research it looks like Scrapy is what I need, judging by:
https://stackoverflow.com/questions/19687421/difference-between-beautifulsoup-and-scrapy-crawler
https://stackoverflow.com/questions/27652543/how-to-use-python-requests-to-fake-a-browser-visit/27652558
Grabbing all the title links
https://stackoverflow.com/questions/1080411/retrieve-links-from-web-page-using-python-and-beautifulsoup (3rd answer: or the Python 3 version:)
Helping me grab the next link:
https://stackoverflow.com/questions/41908426/extracting-deeply-nested-href-in-python-with-beautiful-soup
finding string partials:
https://stackoverflow.com/questions/14849293/python-find-index-position-in-list-based-of-partial-string
Super helpful for associating the correct URL with the correct post:
https://stackoverflow.com/questions/2407398/how-to-merge-lists-into-a-list-of-tuples
https://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python
Helpful for zipping everything together:
https://www.reddit.com/r/learnpython/comments/10kuw5/why_is_using_zip_giving_me_zip_object_at/?st=jbu5r8sm&sh=d4aa5692
Now finding stuff in the tuple:
https://www.w3resource.com/python-exercises/tuple/python-tuple-exercise-14.php
I really need to use in and not in more:
https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method
data validation/scrubbing is certainly a thing...I just lost a half hour because
the right prepend wasn't in place, so it was making the zip off by one
These numbers are annoying the crap out of me right now:
print(len(dateList)) # 144
print(len(difficultyList)) # 142
print(len(idList)) # 144
print(len(titleList)) # 144
That's because the difficulty list is off by two for some reason....ugh
...Turns out I had to remove the weekly, monthly, and mini challenges...sorry :(
Finally got everything sorted out and put into a final list
"""
import requests
from bs4 import BeautifulSoup
import random as rand
import time
def getPage(url, headers):
r = requests.get(url, headers = headers)
soup = BeautifulSoup(r.content)
f = open("dailyprogrammerOutput.txt", "a")
dataList = ["share", "javascript: void 0;", "save", "#", "hide", "report"]
for title in soup.find_all("div", class_ = "top-matter"):
for link in title.find_all("a", href = True):
linkText = link.get_text()
linkHref = link["href"]
if linkText in dataList:
pass
elif linkHref in dataList:
pass
else:
f.write(linkText)
f.write("\n")
f.write(linkHref)
f.write("\n")
for link in soup.find_all("span", class_ = "next-button"):
url = link.find("a")["href"]
f.close()
print(url)
return(url)
url = "https://www.reddit.com/r/dailyprogrammer/"
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"}
for x in range(0, 9):
url = getPage(url, headers)
randomInteger = rand.randint(10, 31)
print(randomInteger)
time.sleep(randomInteger)
#print(soup.get_text())
#print(titles.get_text())
""""
url2 = "https://news.ycombinator.com/news?p=2"
r = requests.get(url2)
soup = BeautifulSoup(r.content)
titles = soup.find_all(class_ = "title")
selectors = soup.select("td.title")
#print(soup)
print(selectors)
print(soup.get_text())
"""
|
Ruby | UTF-8 | 117 | 2.546875 | 3 | [] | no_license | # p060usemodule.rb
require 'p058mytrig'
require 'p059mymoral'
Trig.sin(Trig::PI/4)
Moral.sin(Moral::VERY_BAD)
|
C# | UTF-8 | 8,046 | 2.6875 | 3 | [] | no_license | #region 文件描述
/******************************************************************************
* 创建: Daoting
* 摘要:
* 日志: 2014-07-02 创建
******************************************************************************/
#endregion
#region 引用命名
using System;
using System.ComponentModel;
using System.Globalization;
#endregion
namespace Dt.Cells.Data
{
/// <summary>
/// Represents a locale format.
/// </summary>
/// <remarks>
/// The user can add a locale format to a formatter, for example "[$$-1009]".
/// For example,
/// NFPartLocaleID = ASCII-LEFT-SQUARE-BRACKET ASCII-DOLLAR-SIGN 1*UTF16-ANY [ASCII-HYPHEN-MINUS 3*8ASCII-DIGIT-HEXADECIMAL] ASCII-RIGHT-SQUARE-BRACKET
/// </remarks>
internal sealed class LocaleIDFormatPart : FormatPartBase
{
/// <summary>
/// the content.
/// </summary>
string content;
/// <summary>
/// culture info.
/// </summary>
System.Globalization.CultureInfo cultureInfo;
/// <summary>
/// the utf16any
/// </summary>
string currencySymbol;
/// <summary>
/// the locate id.
/// </summary>
int locateID;
/// <summary>
/// Creates a new locale format with the specified token.
/// </summary>
/// <param name="token">The string expression for the format.</param>
public LocaleIDFormatPart(string token) : base(token)
{
this.locateID = -1;
if (token == null)
{
throw new ArgumentNullException("token");
}
if (token == string.Empty)
{
throw new FormatException(ResourceStrings.FormatterIllegaTokenError);
}
this.content = DefaultTokens.TrimSquareBracket(token);
string content = this.content;
if ((content == null) || (content == string.Empty))
{
throw new FormatException(ResourceStrings.FormatterIllegaTokenError);
}
if (!DefaultTokens.IsEquals(content[0], DefaultTokens.Dollar, false))
{
throw new FormatException(ResourceStrings.FormatterIllegaTokenError);
}
content = content.Remove(0, 1);
int index = content.IndexOf(DefaultTokens.HyphenMinus);
if (index > -1)
{
this.currencySymbol = content.Substring(0, index);
content = content.Remove(0, index);
}
else
{
this.currencySymbol = content;
return;
}
if (!DefaultTokens.IsEquals(content[0], DefaultTokens.HyphenMinus, false))
{
throw new FormatException(ResourceStrings.FormatterIllegaTokenError);
}
content = content.Remove(0, 1);
if (content.Length <= 0)
{
throw new FormatException(ResourceStrings.FormatterIllegaTokenError);
}
this.locateID = NumberHelper.ParseHexString(content);
}
/// <summary>
/// Encodes the symbol.
/// </summary>
/// <param name="symbol">The format string to encode</param>
/// <returns>Returns the encoded format string.</returns>
string EncodeSymbol(string symbol)
{
return symbol.Replace(".", "'.'");
}
/// <summary>
/// Determines whether the format string is valid.
/// </summary>
/// <param name="token">The token to evaluate.</param>
/// <returns>
/// <c>true</c> if the specified format contains the text; otherwise, <c>false</c>.
/// </returns>
internal static bool EvaluateFormat(string token)
{
if ((token == null) || (token == string.Empty))
{
return false;
}
string str = DefaultTokens.TrimSquareBracket(token);
return (((str != null) && !(str == string.Empty)) && DefaultTokens.IsEquals(str[0], DefaultTokens.Dollar, false));
}
/// <summary>
/// Gets a <see cref="T:Dt.Cells.Data.DBNumber" /> object by the number letter type and culture information for this format.
/// </summary>
/// <param name="type">The number letter type.</param>
/// <returns>
/// Returns a <see cref="T:Dt.Cells.Data.DBNumber" /> object that indicates how the number is formatted.
/// </returns>
public DBNumber GetDBNumber(int type)
{
switch ((this.locateID & 0xff))
{
case 4:
switch (type)
{
case 1:
return DBNumber.ChineseDBNum1;
case 2:
return DBNumber.ChineseDBNum2;
case 3:
return DBNumber.ChineseDBNum3;
}
break;
case 0x11:
switch (type)
{
case 1:
return DBNumber.JapaneseDBNum1;
case 2:
return DBNumber.JapaneseDBNum2;
case 3:
return DBNumber.JapaneseDBNum3;
}
break;
}
return null;
}
/// <summary>
/// Returns a <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// A <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
/// </returns>
public override string ToString()
{
if (this.content != null)
{
return DefaultTokens.AddSquareBracket(this.content);
}
return string.Empty;
}
/// <summary>
/// Indicates whether the current culture supports scientific number display.
/// </summary>
[DefaultValue(true)]
public bool AllowScience
{
get { return CultureHelper.AllowScience(this.cultureInfo); }
}
/// <summary>
/// Gets the culture information for the format.
/// </summary>
/// <value>The culture information for the format.</value>
public System.Globalization.CultureInfo CultureInfo
{
get
{
if (this.cultureInfo == null)
{
this.cultureInfo = CultureHelper.CreateCultureInfo(this.locateID);
if (((this.currencySymbol != null) && (this.currencySymbol != string.Empty)) && !this.cultureInfo.NumberFormat.IsReadOnly)
{
this.cultureInfo.NumberFormat.CurrencySymbol = this.currencySymbol;
}
if (((CultureHelper.CreateCalendar(this.locateID) != null) && ((this.cultureInfo.Name == "ja-JP") || (this.cultureInfo.Name == "ja"))) && (this.cultureInfo.OptionalCalendars.Length > 1))
{
this.cultureInfo.DateTimeFormat.Calendar = this.cultureInfo.OptionalCalendars[1];
}
}
return this.cultureInfo;
}
}
/// <summary>
/// Gets the currency symbol for the format.
/// </summary>
/// <value>The currency symbol for the format. The default value is a dollar sign ($).</value>
[DefaultValue("$")]
public string CurrencySymbol
{
get
{
if (this.currencySymbol != null)
{
return this.EncodeSymbol(this.currencySymbol);
}
return string.Empty;
}
}
}
}
|
Python | UTF-8 | 3,166 | 3.0625 | 3 | [
"Apache-2.0"
] | permissive | import sys
from PyQt4 import QtGui, QtCore
#how do we integrate different widgets into a single GUI?
#able to create different classes for the GUI itself (need to know how to get it to work with PyEmotiv)
class Example2(QtGui.QMainWindow):
def __init__(self):
super(Example2, self).__init__()
self.initUI()
def initUI(self):
exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(QtGui.qApp.quit)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
self.show()
class Example (QtGui.QWidget): #inherits from QtGUI and QWidget Classes
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.resize(500, 500)
self.center()
#printing out pictures on the pretty GUI.
hbox= QtGui.QHBoxLayout(self)
pixmap= QtGui.QPixmap("trollWifi.png") #allows the printing of the image
lbl= QtGui.QLabel(self)
lbl.setPixmap(pixmap)
hbox.addWidget(lbl)
self.setLayout(hbox)
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10 ))
#self.setToolTip('This is a <b> QWidget</b> widget')
#define all buttons
btn= QtGui.QPushButton('Start',self) #declaration of buttons
btn.setToolTip('Start collecting data') #what it shows when we hover
btn.resize(btn.sizeHint()) #button gets resized and moved
btn.move(10, 400) #positioning of the button
#need to figure out how to connect this with the trial.py -> collect the data
#a button which lets you quit the window itself
qbtn= QtGui.QPushButton('Quit', self)
#when button is clicked, it sends a signal 'Clicked'
#instance gives you the current instance
qbtn.clicked.connect(QtCore.QCoreApplication. instance().quit)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50,50)
self.setGeometry(300, 300, 500,500) #detects the location and sets the size
self.setWindowTitle('GUI')
#self.setWindowIcon(QtGui.QIcon('web.png'))
self.show()
def keyPressEvent(self, e):
if e.key()== QtCore.Qt.Key_Escape:
self.close()
def center(self):
qr= self.frameGeometry()
cp= QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def closeEvent(self, event):
#when you close a QT wiedge, it generates a QT Close Event
reply= QtGui.QMessageBox.question(self, 'Message', "are you sure you want to quit? "
,QtGui.QMessageBox.Yes| QtGui.QMessageBox.No, QtGui.QMessageBox.No)
#last one is the default option
if reply== QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
def main():
app = QtGui.QApplication(sys.argv)
ex= Example()
#ex1= Example2()
#w = QtGui.QWidget()
#w.resize(250, 150) #allows us to resize the size of the window
#w.move(300, 300) #allows movement of the screen
#w.setWindowTitle('GUI')
#w.show()
sys.exit(app.exec_()) #exec is a python keyword; use exec_ instead. Quits main
if __name__== '__main__':
main() |
C++ | UTF-8 | 661 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <rlib/functional.hpp>
#include <rlib/stdio.hpp>
#include <iostream>
using namespace rlib;
#include <cstdio>
#define test_str "This is some test string."
#define test_times 1000000
int main() {
rlib::sync_with_stdio(false);
println(std::cerr, timeof(repeat(test_times, []{
print(test_str "\n");
})));
std::cerr << (timeof(repeat(test_times, []{
std::cout << test_str << "\n";
}))) << std::endl;
std::cerr << (timeof(repeat(test_times, []{
std::printf(test_str);
std::printf("\n");
}))) << std::endl;
}
|
Python | UTF-8 | 911 | 3.953125 | 4 | [
"MIT"
] | permissive | #desafio36. Escreva um progama para aprovar o empréstimo bancario para a compra de uma casa. O progama vai perguntar,
# o valor da casa, o salario do comprador e em quantos anos ele vai pagar.
#calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salario ou então o empréstimo será negado.
v_casa = float(input('O valor da casa R$'))
salario = float(input('Salario do comprador R$'))
anos = int(input('Em quantos anos vai pagar?'))
parcela = v_casa / (anos * 12)
limite = salario * 30 / 100
if parcela > limite:
print('Para pagar uma casa de R${:.2f} em {} anos a prestação será de R${:.2f}'.format(v_casa, anos, parcela))
print('Empréstimo NEGADO!')
elif parcela <= limite:
liberado = parcela
print('Para pagar uma casa de R${:.2f} em {} anos a prestação será de R${:.2f}'.format(v_casa, anos, liberado))
print('Empréstimo pode ser CONCEDIDO!')
|
Markdown | UTF-8 | 3,632 | 2.859375 | 3 | [] | no_license | ###### Old town road
# An Inca highway still benefits people living nearby
##### A new study finds that wages, nutrition and schooling levels along a pre-Columbian road are all unusually high
> Jul 31st 2021
SPAIN’S CONQUEST of the Inca empire in the 16th century was catastrophic for the Incas. Within four decades the native population fell by 75-90%. Old-world diseases were mostly to blame, but forced labour played a part. Missionaries coerced Spain’s new subjects to convert to Catholicism, while viceroys razed Inca buildings.
Yet Inca culture proved persistent. Some 10m people in Peru and nearby countries speak Quechua, the Incas’ language of empire, whose use the Spaniards discouraged. Peruvians still hand-weave textiles with bright patterns. A new paper, by Ana Paula Franco of Harvard, Sebastian Galiani of the University of Maryland and Pablo Lavado of the University of the Pacific in Lima, unearths another example of the Incas’ durable achievements: Peruvians still benefit from 15th-century infrastructure.
The Incas ruled over 10m square km (3.8m square miles). To collect taxes, deploy troops and exchange messages with remote lands, they built 30,000km of stone roads, dotted with warehouses to store food and water. The biggest cities in modern Peru are on or near the coast, far from the Incas’ most important routes. This makes it possible to study the effects of pre-Columbian infrastructure with little distortion from later urbanisation.
To test if the Inca road, the Incas’ main thoroughfare, has boosted modern living standards, the authors split the map into small squares. For four indicators of welfare—wages, nutrition, maths-test scores and years of schooling—they compared levels from 2007-17 in squares crossed by the road with those in neighbouring squares not on its route. On every measure, residents of roadside squares fared better than those in adjacent ones, even after controlling for differences in such factors as the slope of terrain and the presence of rivers. Women gained more than men.
How did the road grant such long-lived blessings? The Spaniards used it to ship silver and turned the warehouses into profitmaking shops, often staffed by women (possibly inculcating more equal gender roles). This made land near the road unusually valuable, encouraging colonisers to settle there. The authors argue that Spaniards who moved in claimed legal title to their landholdings and built schools and new roads in the vicinity, creating enduring property rights and public goods. Today, the presence of the Inca road alone accounts for a third of the observed difference in levels of formal land ownership between dwellers on the road and those in nearby areas. It explains half the difference in the number of schools.
Might modern roads along the corridor explain more of that uplift in welfare than the ancient one? The scholars investigated that, too. The Inca-road squares do have twice as many kilometres of road as adjacent ones do. However, on average, even when comparing squares with similar densities of road, people living in those along the old route earned more money and had more years of schooling.
The builders of the Inca road might be pleased that the areas they improved remain relatively prosperous (though they are poorer than the coast). They would be less happy that one reason is the usefulness of their handiwork to colonisers. But today, the Incas’ descendants are also among the beneficiaries of their labour. ■
Source: “Long-term effects of the Inca road” by A. P. Franco, S. Galiani and P. Lavado, National Bureau of Economic Research, 2021
|
C# | UTF-8 | 1,129 | 2.578125 | 3 | [] | no_license | using Microsoft.VisualStudio.TestTools.UnitTesting;
using PHP_Generator.Generators;
using PHP_Generator.Structures;
namespace PHP_Generator_Test.Tests
{
[TestClass]
public class ArithmeticOperatorGeneratorTest
{
private ArithmeticOperatorGenerator _generator;
[TestInitialize]
public void TestInitialize()
{
_generator = new ArithmeticOperatorGenerator();
}
[TestMethod]
public void TestGenerateAddition()
{
Assert.AreEqual("+", _generator.Generate(ArithmeticOperator.Addition));
}
[TestMethod]
public void TestGenerateSubtraction()
{
Assert.AreEqual("-", _generator.Generate(ArithmeticOperator.Subtraction));
}
[TestMethod]
public void TestGenerateMultiplication()
{
Assert.AreEqual("*", _generator.Generate(ArithmeticOperator.Multiplication));
}
[TestMethod]
public void TestGenerateDivision()
{
Assert.AreEqual("/", _generator.Generate(ArithmeticOperator.Division));
}
}
}
|
Java | UTF-8 | 1,147 | 2.15625 | 2 | [] | no_license | package com.privateclass.privateClasses.api;
import com.privateclass.privateClasses.model.Izbira;
import com.privateclass.privateClasses.model.Predmet;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequestMapping("views")
@RestController
public class IzbiraController
{
private final JdbcTemplate jdbcTemplate;
public IzbiraController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@GetMapping("/izbirasql")
public List<Izbira> getIzbira()
{
final String sql="SELECT id_izbira,id_korisnik, id_predmet FROM izbira";
return jdbcTemplate.query(sql,(resultSet, i) ->
{
int id=Integer.parseInt(resultSet.getString("id_izbira"));
int id_k=Integer.parseInt(resultSet.getString("id_korisnik"));
int id_p=Integer.parseInt(resultSet.getString("id_predmet"));
return new Izbira(id,id_k,id_p);
});
}
}
|
Java | UTF-8 | 1,668 | 1.960938 | 2 | [] | no_license | package weikun.mydiary.Fragment;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import weikun.mydiary.Activity.user_drafts;
import weikun.mydiary.R;
/**
* Created by Weikun on 2017/9/30.
*/
public class UserFragment extends Fragment{
protected Activity mActivity;
@Bind(R.id.draft_layout)
RelativeLayout draftLayout;
public UserFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user, container, false);
ButterKnife.bind(this, view);
return view;
}
public static UserFragment newInstance() {
UserFragment fragment = new UserFragment();
return fragment;
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mActivity = (Activity) context;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@OnClick(R.id.draft_layout)
public void onViewClicked() {
startActivity(new Intent(getContext(),user_drafts.class));
}
}
|
JavaScript | UTF-8 | 907 | 2.625 | 3 | [] | no_license | /*
* @Description:释放error事件,需要注意的是如果错误被try...catch捕获,就不会触发error事件,这时,必须调用ctx.app.emit(),
手动释放error事件,才能监听函数生效
* @Author: yuli
* @Date: 2021-01-22 13:52:35
* @LastEditors: yuli
* @LastEditTime: 2021-01-22 14:31:01
*/
const Koa = require('koa')
const app = new Koa()
const handler = async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.response.status = err.statusCode || err.status || 500
ctx.response.type = 'html'
ctx.response.body = '<p>Something wrong, please contact administrator.</p>'
ctx.app.emit('error', err, ctx)
}
}
const main = ctx => {
ctx.throw(500)
}
app.on('error', function (err) {
console.log('logging error', err.message)
console.log(err)
})
app.use(handler)
app.use(main)
app.listen(3000) |
C++ | UTF-8 | 21,095 | 2.78125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Font generated by stb_font_inl_generator.c (4/1 bpp)
//
// Following instructions show how to use the only included font, whatever it is, in
// a generic way so you can replace it with any other font by changing the include.
// To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_consolas_10_latin1_*,
// and separately install each font. Note that the CREATE function call has a
// totally different name; it's just 'stb_font_consolas_10_latin1'.
//
/* // Example usage:
static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS];
static void init(void)
{
// optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2
static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH];
STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT);
... create texture ...
// for best results rendering 1:1 pixels texels, use nearest-neighbor sampling
// if allowed to scale up, use bilerp
}
// This function positions characters on integer coordinates, and assumes 1:1 texels to pixels
// Appropriate if nearest-neighbor sampling is used
static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0);
glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0);
glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1);
glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance_int;
}
glEnd();
}
// This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels
// Appropriate if bilinear filtering is used
static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f);
glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance;
}
glEnd();
}
*/
#ifndef STB_FONTCHAR__TYPEDEF
#define STB_FONTCHAR__TYPEDEF
typedef struct
{
// coordinates if using integer positioning
float s0,t0,s1,t1;
signed short x0,y0,x1,y1;
int advance_int;
// coordinates if using floating positioning
float s0f,t0f,s1f,t1f;
float x0f,y0f,x1f,y1f;
float advance;
} stb_fontchar;
#endif
#define STB_FONT_consolas_10_latin1_BITMAP_WIDTH 256
#define STB_FONT_consolas_10_latin1_BITMAP_HEIGHT 46
#define STB_FONT_consolas_10_latin1_BITMAP_HEIGHT_POW2 64
#define STB_FONT_consolas_10_latin1_FIRST_CHAR 32
#define STB_FONT_consolas_10_latin1_NUM_CHARS 224
#define STB_FONT_consolas_10_latin1_LINE_SPACING 7
static unsigned int stb__consolas_10_latin1_pixels[]={
0xc8010320,0x03880000,0x32604074,0x40dc642c,0x4400c0c8,0x00020080,
0x2200c088,0x80400040,0x29804c08,0x00a80004,0x090d4c01,0x0100c088,
0x0dd980c0,0xb8aa2088,0x64b10642,0x56ca8644,0x263b509d,0x22581404,
0x20108325,0x2a059808,0xcc84ca84,0x20e4641d,0x82cc0da8,0x3226544a,
0x036e21c8,0x904b9895,0x320ee641,0x425c41c8,0x3abd84ca,0x4c254032,
0x4644ca85,0x0361661c,0x995d1254,0x1641906c,0xab40c872,0xecd98b03,
0x441fdd12,0x555371ec,0x8ee68ee5,0x54415446,0xa882a882,0x7442a882,
0x128223fa,0x44a08941,0x0e6744a0,0x82b83555,0x1500a858,0x20540720,
0x42893049,0xa86aaa09,0x46aaa1aa,0x3b61aaa8,0x5c6aaa22,0x1924c3a2,
0x0c8ae162,0x98b03ab4,0x10d8688e,0x3276195d,0x926d12ad,0x57449368,
0x932ba24c,0x3a24cae8,0x32ba24ca,0xb9ae6ae4,0x2ed15da2,0x2ad15da2,
0x0d5741bc,0x41b83ddb,0x84e884e8,0x44e884e8,0x4771602b,0xe86aba0e,
0x46aba1aa,0x1931bea8,0x46faa27b,0x3268761c,0x01930750,0x45983ab4,
0x54361a49,0x367362ab,0xb072762a,0x1d15c393,0x4570e8ae,0xb874570e,
0x4dce43a2,0x2bb4570d,0x8aed15da,0x80d0bf26,0x355c2c49,0x355c355c,
0x812a355c,0x21dc743a,0xd81a0d06,0x362c3a20,0x9a0d8720,0x5b10570c,
0x6443ab40,0xd858a4c3,0x66c37b10,0x1b2a0bd9,0x6c391b2a,0x1c86c390,
0x21b0e436,0xace4361c,0x2bb4570d,0x8aed15da,0x99f266c6,0x752e65c3,
0x8d8391b0,0x20e46c1c,0x03a21c8d,0x7c365458,0x8733e1cc,0x206c1ccf,
0x706c2dd8,0x32689a27,0x64550930,0x8b03ab40,0x0d81dcf9,0x64e4b3b2,
0x7d03e83a,0x0e4361c8,0x90d8721b,0x361c86c3,0x5cd19950,0x2ed15da2,
0xd8d15da2,0x4d261a68,0x73d10365,0x125cf449,0x4f44973d,0x4277544b,
0x8341741b,0x806c0d06,0x37606c1c,0x20c92a1e,0xd0322b86,0x126340ea,
0x0dc1b0d0,0x21a20d10,0x89dcd13b,0x77344ee6,0x8d13b9a2,0x44ea1edd,
0x9d5a2756,0x55a27568,0x221a1dfd,0x70935cce,0x66dcd99b,0x9b336e6c,
0x0c86ccdb,0x680d8b10,0x0d81a0d0,0x1b037322,0x83a22590,0x4390ee0c,
0xb03ab40c,0x76cc24c1,0x665c4582,0x3b207b20,0xd83dbb01,0x0f6ec1ed,
0xdbb07b76,0x3b760583,0xdd87b761,0x887b761e,0x003eef84,0x0d8e41b0,
0x23906c72,0x0030720d,0x3eef80d8,0xeef8fbbe,0x447dfd13,0x21f7f440,
0x641b8dc8,0x645c8640,0x13aad950,0x10000766,0x00000000,0x00000000,
0x10000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x45ceb800,0x22000180,0x1b8c8080,0xc88325b5,
0x0ea0c883,0x664c376e,0x6440ea2e,0x7990f220,0xb10dc643,0x10dc6437,
0x81555055,0x6640c44a,0x9376e0ef,0x203a82da,0x40d440c8,0x1bcc81a8,
0x2aa24526,0x22055541,0xda8aa21a,0xa981e442,0xd3ff33b1,0x41662654,
0x42541c8c,0xb0421dcc,0x20210eb6,0xaac40808,0x08d11d33,0x20108110,
0x2e5c0841,0x995d1042,0x0441daa8,0x8eab10ea,0x75a2b159,0x30220080,
0xcae8973b,0x91498303,0x2ba1d9a8,0x446b6e0a,0x10ec4c9e,0x84eaf602,
0x55169ffa,0x5440a835,0x220541aa,0x71ddb8a2,0x3bb70b7b,0xbb70eedc,
0x4c367263,0x21eed9a4,0x3bb61eed,0xed87bb61,0x4c7b6e1e,0x0e8aeb14,
0xd91cc1c8,0x367a29dd,0x3d2c4ea2,0xc83bb90b,0x2f6321dd,0x91a6751c,
0x48a4c3bb,0x2c42c570,0x15c49ac4,0x424c3bb9,0x169fe88c,0x274437d5,
0xe886faa2,0x93687d44,0x49839162,0x9ac526b1,0x8af26b14,0x0930b149,
0x93093093,0xacd26930,0xd872b149,0x0b661c80,0x41ac9875,0x2b6cb73a,
0x2953452a,0x9546f668,0x52a6dbab,0x22556668,0x866ec5c9,0x3ae2dcea,
0xa543360e,0x8320ae68,0x55c0d8d0,0x6ab81b06,0x9b56a654,0x52664cb9,
0x336ab99b,0x2b99b55c,0x9f32e8c9,0x72e65c3d,0x2e65cb99,0x665cb997,
0x149b4575,0xc80d872b,0x221d41a1,0x5e743ecf,0x5cd79575,0xd9a2b9a2,
0x7d72a9ba,0xf99a2b9a,0x25c40ecd,0x45a3aa5c,0x57164c9d,0x03b09534,
0x646c0d8d,0x646c0d81,0x4da3aaa1,0x23773b05,0x59859859,0x424da498,
0x4d26b349,0xa4d66935,0x55669359,0xacd62b13,0x8760d13b,0x1dc4981e,
0xe8e5620d,0x75344ea4,0xd999c9a2,0x3a962930,0x4c024cd1,0xb4934985,
0x9d419a3a,0x3b03a268,0xd106c588,0x441b0973,0x2aaa4b9e,0x64f3b26b,
0x3b20dd89,0xc8f3b23c,0x9b5933ce,0x333a2126,0x22b99d15,0x99d15cce,
0xd9733a2b,0x973761ed,0x3ba21edd,0x6ec36c44,0x207b9d33,0x1dbbd358,
0x3760f6ec,0x216e641e,0x76ec1edc,0x6e441261,0x41bb910d,0xb9b11ddc,
0x3b761e25,0x1da76d41,0x20d85d99,0x0d86ccdb,0x2a9b336e,0x000000dd,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x9f7f4408,0x7f44720d,0xa8e41b3e,0x00000f72,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x52206aa0,0x21551038,0x07911a3b,0x64190191,0x71914111,0x5c003a83,
0x64415303,0x32e0c883,0x1b30311b,0x31b8c832,0x80351141,0x64d70aa9,
0x35cf7660,0x8aaaa619,0x0d441aa8,0x88090772,0x41c43b02,0x6d42aaa8,
0x8309850d,0x7b141109,0x126b1075,0xb442aba2,0x08808449,0x23b0fee4,
0x20109a2b,0x42cce4c0,0x4229cb81,0x44300881,0x263a61ad,0x45660843,
0x40b2b665,0x439ac2de,0x5473580e,0x2b6228b8,0x7076b24d,0x07640583,
0x2a21220c,0x0ec2c5ca,0x2a37161b,0xdb81d5a2,0x25d9b35e,0x4393b05a,
0x4526b149,0x6cd73755,0xbb934571,0x3a58a4c3,0x20f6c2ec,0x6c1ed80d,
0x4777221e,0x3b54c9d8,0x9c83db0b,0xa858e60d,0x588b484b,0x32251690,
0x3a869222,0x225d60dc,0x0f6c0dc9,0x1d03bbb1,0x4a867a62,0x21908c96,
0x644e5a2a,0x74d62b34,0x50bb2688,0x2b1498d9,0x32aeb149,0xd15c3668,
0x2933452a,0x5c1d5a58,0x702f3a61,0x9b443703,0x07234914,0xb0fa20dc,
0x3a36167d,0x0340e40c,0x45972839,0x83909748,0xac256c1b,0x5a21b80d,
0xf7515c49,0x64756877,0x9b50c9d8,0xab4c72d9,0x46926b13,0x261f44c8,
0xac526b14,0xb864d5ba,0x4cd15da2,0x15c74b14,0x033d10dc,0xa4437037,
0x992a9158,0x221b84ab,0x792a3dec,0x2606c644,0x1ef544bb,0x52949573,
0x1dc1ef44,0x703b60dc,0x43703b15,0x82ccb148,0x5c191b06,0x22aa4cc9,
0x4ab4b568,0x42c526b7,0x5621a258,0xd966b159,0x13a861ee,0xb1344ead,
0x1eeec566,0x1b8160dc,0xac5221b8,0x646c3de8,0x5ed41b85,0x2e2d4e61,
0x216584cc,0x52e46c0c,0x2e09114e,0x59d83703,0x2067665c,0xb2c5221b,
0x2e541a01,0x2a97676e,0x3a6deb9a,0x3b9d15bd,0x7647b7aa,0x6cb9bb01,
0x3a0325cd,0xdd87b761,0x9ae6ec1e,0x4eed88e1,0x3629bbf5,0x9ddb14ee,
0x848ac522,0xb10eb89b,0x0ded49dd,0x1581bdd3,0x6ec6e39d,0x2e26e140,
0x4977770e,0x5eef9848,0xaac9ddb1,0x76c41b05,0x5562914e,0x88345eef,
0x26bb543f,0x00001a2a,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x43100000,
0x328a20a2,0x01505555,0x0aa88355,0x806a2098,0x5c3db900,0x4f7661dd,
0x6edc9148,0xda8776e1,0x006a25dd,0x35174190,0x45128528,0x261c0bbb,
0x18988b35,0x36a3bb91,0x54555514,0x86aaa1aa,0x0d440888,0xa80820ba,
0x309851aa,0x71431141,0xfa869aad,0x0af6a2b0,0xdad889d1,0x44b2b622,
0x32b2a2ed,0x52601e82,0x2074b148,0x4c34b148,0x37190d14,0x20321662,
0x321508d8,0x872321da,0x59530dbc,0x7715ee49,0x11c8d81b,0x515a926d,
0x0ded4b75,0x5554355d,0xa8b27621,0x44b86cc0,0x34771aae,0xb49926b3,
0xd2e4e5c3,0x19169950,0x5488d550,0x2249a449,0x0048aa2b,0x66d5372e,
0x2910b15c,0x5c33aa58,0xddeda9a2,0x8190d771,0x5684deca,0xf124dcc5,
0x51d6c547,0x443e819d,0x2c52258d,0x642b81d3,0x76f54340,0x8162570d,
0x0d2d40da,0xb590ae3a,0x2e1de4c1,0x2a1a5bd9,0x406458da,0x33a21c8d,
0x03b7a20d,0x5cb15457,0x4d265ddd,0x221a0b34,0x2a950b35,0xb83959a3,
0x177b6e5c,0xbb509832,0x2360d8d8,0x4773912c,0x06ddc339,0x8a44ae6e,
0x90d0bb75,0x322ccf81,0x2a3660c8,0x807442a6,0x54399f3c,0xe987f05c,
0x0c8d8c85,0x8b75550d,0x25cf440c,0x8c88b3b1,0x45515c5a,0xcce88187,
0xda8f3724,0xd973763d,0x877761dc,0x550cdbdb,0x1500c815,0x20aaa974,
0xb8820810,0x59acc081,0x2c522108,0xd0320ae0,0x16ded411,0x23d96ae6,
0x1d1e41d8,0xbb305d01,0x0640dc98,0x74aa1a19,0x336a0645,0x115d226c,
0x54571a29,0x003b0b52,0x00200000,0x204ccc00,0x26eecc0b,0x00004ccc,
0x00000000,0x0d0320d0,0x2e03b3b1,0x64760722,0xd0190341,0x2c64c591,
0xbbd0c836,0x3235caa9,0x223906c0,0x6ef44d14,0x2a9ddd11,0x00000cee,
0x00000000,0x00000000,0x00000000,0x221d4000,0x377e3ded,0x37622d63,
0x34000ae3,0xd13b8190,0x00255261,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x6c400000,0x71b8b3ed,
0xb15c97b7,0x0982dbd8,0x2ed4376a,0x83d50b80,0x22132a0a,0x49bbb30c,
0x642e1b8c,0x77065911,0x41106ce4,0x192ddddd,0x00000000,0x00000000,
0x00000000,0x40000000,0x1917190d,0x589672ae,0x88d1f893,0x9a15564c,
0x4fa5ddd9,0x8017c1c9,0x104ccc08,0x64765d02,0x32185cc9,0x01bb70d9,
0x00000050,0x00000000,0x00000000,0x00000000,0x5d370ec0,0x22c645cb,
0x90341c8d,0x436b6391,0x1d9602d8,0x8800006e,0x4c003bbb,0x44c00980,
0x00000001,0x00000000,0x00000000,0x00000000,0x543b8000,0x322e5dac,
0x34365458,0x04c71288,0x5c203bdb,0x0003bae1,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0xdf880000,0x4b91f33d,0x3f858c8b,
0x00000068,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,
};
static signed short stb__consolas_10_latin1_x[224]={ 0,2,1,0,0,0,0,2,1,1,0,0,1,1,
1,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,
2,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,0,1,2,1,1,0,0,0,0,0,0,0,0,0,
0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
static signed short stb__consolas_10_latin1_y[224]={ 7,0,0,0,-1,0,0,0,-1,-1,0,1,5,3,
5,0,0,0,0,0,0,0,0,0,0,0,2,2,1,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,-1,0,8,0,2,0,2,0,2,0,2,0,0,
0,0,0,2,2,2,2,2,2,2,0,2,2,2,2,2,2,-1,-1,-1,3,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,2,-1,0,0,0,
-1,0,0,0,0,2,3,3,0,0,0,1,0,0,0,2,0,3,7,0,0,2,0,0,0,2,-2,-2,-2,-2,
-2,-2,0,0,-2,-2,-2,-2,-2,-2,-2,-2,0,-2,-2,-2,-2,-2,-2,2,-1,-2,-2,-2,-2,-2,0,0,0,0,
0,0,0,-1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,
};
static unsigned short stb__consolas_10_latin1_w[224]={ 0,2,4,6,5,6,6,2,4,4,5,6,3,4,
3,5,6,5,5,5,6,5,5,5,5,5,2,3,5,5,4,4,6,6,5,5,6,5,4,5,5,5,5,6,
4,6,5,6,5,6,6,5,6,5,6,6,6,6,5,4,5,3,5,6,4,5,5,5,5,5,6,6,5,5,
5,6,5,6,5,6,5,5,6,5,5,5,6,6,6,6,5,5,2,4,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,0,2,5,5,6,6,
2,5,5,6,4,5,5,4,5,5,4,5,4,4,5,6,5,3,2,4,4,5,6,6,6,5,6,6,6,6,
6,6,7,5,5,5,5,5,5,5,5,5,6,5,6,6,6,6,6,5,6,5,5,5,5,6,5,5,5,5,
5,5,5,5,6,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,5,5,5,5,6,5,6,
};
static unsigned short stb__consolas_10_latin1_h[224]={ 0,8,3,7,10,8,8,3,11,11,5,6,4,2,
3,9,8,7,7,8,7,8,8,7,8,7,6,7,7,3,7,8,10,7,7,8,7,7,7,8,7,7,8,7,
7,7,7,8,7,9,7,8,7,8,7,7,7,7,7,11,9,11,4,2,3,6,8,6,8,6,7,8,7,7,
10,7,7,5,5,6,8,8,5,6,8,6,5,5,5,8,5,11,11,11,3,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,0,8,10,7,7,7,
11,9,3,8,6,5,4,2,5,3,4,6,4,4,3,8,9,3,2,4,6,5,7,7,7,8,9,9,9,9,
9,9,7,9,9,9,9,9,9,9,9,9,7,9,10,10,10,10,10,5,10,10,10,10,10,9,7,8,8,8,
8,8,8,9,6,7,8,8,8,8,7,7,7,7,8,7,8,8,8,8,8,6,8,8,8,8,8,10,10,10,
};
static unsigned short stb__consolas_10_latin1_s[224]={ 148,51,185,19,142,45,162,170,9,1,226,
187,129,190,138,160,190,118,184,211,203,217,223,1,229,26,200,32,36,154,42,
235,55,98,112,247,124,13,47,1,249,7,131,66,80,73,85,124,178,249,105,
19,91,54,235,242,59,52,222,26,200,22,107,195,180,138,13,150,7,144,228,
149,216,210,43,196,190,86,245,168,76,156,100,162,143,156,93,79,232,25,73,
31,6,14,173,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,
171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,148,253,49,
86,73,129,19,237,160,183,182,239,123,190,220,142,113,194,118,251,148,204,1,
166,202,133,203,208,164,151,116,137,13,26,187,166,173,180,143,194,213,148,219,
225,231,243,7,20,136,33,76,83,90,97,104,214,111,118,124,130,136,206,110,
70,82,88,94,100,106,154,175,158,64,58,52,39,80,98,92,123,112,104,169,
176,240,197,60,131,44,67,38,32,118,69,37,62, };
static unsigned short stb__consolas_10_latin1_t[224]={ 11,23,39,32,1,13,13,39,1,1,31,
31,39,39,39,1,13,31,23,13,23,13,13,32,13,32,31,32,32,39,32,
13,1,31,31,13,31,32,32,23,23,32,13,32,31,31,31,13,23,1,31,
23,31,23,23,23,32,32,23,1,1,1,39,39,39,31,23,31,23,31,23,
13,23,23,1,23,23,39,31,31,13,13,39,31,13,31,39,39,31,23,39,
1,1,1,39,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,
23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,11,13,1,
23,23,23,1,1,39,13,31,31,39,39,31,39,39,31,39,31,39,13,13,
39,39,39,31,31,23,23,23,13,13,13,1,1,1,1,23,1,1,1,1,
1,1,1,13,13,23,13,1,1,1,1,1,31,1,1,1,1,1,1,23,
13,13,13,13,13,13,1,31,23,13,13,13,13,23,23,23,23,13,23,13,
13,13,13,23,31,23,23,23,23,13,1,1,1, };
static unsigned short stb__consolas_10_latin1_a[224]={ 88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,88,
88,88,88,88,88,88,88,88, };
// Call this function with
// font: NULL or array length
// data: NULL or specified size
// height: STB_FONT_consolas_10_latin1_BITMAP_HEIGHT or STB_FONT_consolas_10_latin1_BITMAP_HEIGHT_POW2
// return value: spacing between lines
static void stb_font_consolas_10_latin1(stb_fontchar font[STB_FONT_consolas_10_latin1_NUM_CHARS],
unsigned char data[STB_FONT_consolas_10_latin1_BITMAP_HEIGHT][STB_FONT_consolas_10_latin1_BITMAP_WIDTH],
int height)
{
int i,j;
if (data != 0) {
unsigned int *bits = stb__consolas_10_latin1_pixels;
unsigned int bitpack = *bits++, numbits = 32;
for (i=0; i < STB_FONT_consolas_10_latin1_BITMAP_WIDTH*height; ++i)
data[0][i] = 0; // zero entire bitmap
for (j=1; j < STB_FONT_consolas_10_latin1_BITMAP_HEIGHT-1; ++j) {
for (i=1; i < STB_FONT_consolas_10_latin1_BITMAP_WIDTH-1; ++i) {
unsigned int value;
if (numbits==0) bitpack = *bits++, numbits=32;
value = bitpack & 1;
bitpack >>= 1, --numbits;
if (value) {
if (numbits < 3) bitpack = *bits++, numbits = 32;
data[j][i] = (bitpack & 7) * 0x20 + 0x1f;
bitpack >>= 3, numbits -= 3;
} else {
data[j][i] = 0;
}
}
}
}
// build font description
if (font != 0) {
float recip_width = 1.0f / STB_FONT_consolas_10_latin1_BITMAP_WIDTH;
float recip_height = 1.0f / height;
for (i=0; i < STB_FONT_consolas_10_latin1_NUM_CHARS; ++i) {
// pad characters so they bilerp from empty space around each character
font[i].s0 = (stb__consolas_10_latin1_s[i]) * recip_width;
font[i].t0 = (stb__consolas_10_latin1_t[i]) * recip_height;
font[i].s1 = (stb__consolas_10_latin1_s[i] + stb__consolas_10_latin1_w[i]) * recip_width;
font[i].t1 = (stb__consolas_10_latin1_t[i] + stb__consolas_10_latin1_h[i]) * recip_height;
font[i].x0 = stb__consolas_10_latin1_x[i];
font[i].y0 = stb__consolas_10_latin1_y[i];
font[i].x1 = stb__consolas_10_latin1_x[i] + stb__consolas_10_latin1_w[i];
font[i].y1 = stb__consolas_10_latin1_y[i] + stb__consolas_10_latin1_h[i];
font[i].advance_int = (stb__consolas_10_latin1_a[i]+8)>>4;
font[i].s0f = (stb__consolas_10_latin1_s[i] - 0.5f) * recip_width;
font[i].t0f = (stb__consolas_10_latin1_t[i] - 0.5f) * recip_height;
font[i].s1f = (stb__consolas_10_latin1_s[i] + stb__consolas_10_latin1_w[i] + 0.5f) * recip_width;
font[i].t1f = (stb__consolas_10_latin1_t[i] + stb__consolas_10_latin1_h[i] + 0.5f) * recip_height;
font[i].x0f = stb__consolas_10_latin1_x[i] - 0.5f;
font[i].y0f = stb__consolas_10_latin1_y[i] - 0.5f;
font[i].x1f = stb__consolas_10_latin1_x[i] + stb__consolas_10_latin1_w[i] + 0.5f;
font[i].y1f = stb__consolas_10_latin1_y[i] + stb__consolas_10_latin1_h[i] + 0.5f;
font[i].advance = stb__consolas_10_latin1_a[i]/16.0f;
}
}
}
#ifndef STB_SOMEFONT_CREATE
#define STB_SOMEFONT_CREATE stb_font_consolas_10_latin1
#define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_consolas_10_latin1_BITMAP_WIDTH
#define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_consolas_10_latin1_BITMAP_HEIGHT
#define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_consolas_10_latin1_BITMAP_HEIGHT_POW2
#define STB_SOMEFONT_FIRST_CHAR STB_FONT_consolas_10_latin1_FIRST_CHAR
#define STB_SOMEFONT_NUM_CHARS STB_FONT_consolas_10_latin1_NUM_CHARS
#define STB_SOMEFONT_LINE_SPACING STB_FONT_consolas_10_latin1_LINE_SPACING
#endif
|
JavaScript | UTF-8 | 1,762 | 3.0625 | 3 | [] | no_license | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './props.css';
// React 數據傳遞: 子傳父
// 調用父元素的函數從而操作父元素的數據,實現數據從子元素傳到父元素
class ParentComponent extends React.Component{
constructor(props){
super(props)
this.state={
parentData:null
}
}
render(){
return(
<div>
<h2>子元素傳遞給父元素的數據: {this.state.parentData}</h2>
<ChildComponent updateParentData={this.updateParentData}/>
</div>
)
}
// updateParentData方法會將 this.state.parentData修改為形參傳進來的值
// 將此方法透過props傳遞給子元素,子元素就可以將子元素的數據作為形參調用此方法,修改父元素的state
updateParentData=(childData)=>{
this.setState({
parentData:childData
})
}
}
class ChildComponent extends React.Component{
constructor(props){
super(props)
this.state={
childData:'this is from ChildComponent'
}
}
render(){
return(
<div>
<button onClick={this.sendDataToParent}>傳遞數據給父元素 數據: {this.state.childData}</button>
<button onClick={()=>{this.props.updateParentData('使用箭頭函數直接調用props函數')}}>傳遞數據給父元素 數據: 使用箭頭函數直接調用props函數</button>
</div>
)
}
sendDataToParent=()=>{
console.log(this.props)
// 子元素傳遞數據給父元素,是透過調用父元素傳遞進來的方法修改父元素的state
this.props.updateParentData(this.state.childData)
}
}
ReactDOM.render(
<ParentComponent />,
document.querySelector('#root')
) |
Java | UTF-8 | 4,836 | 2.84375 | 3 | [] | no_license | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class MainFrame extends JFrame {
private JButton jbtrun = new JButton("Run");
private JButton jbtre = new JButton("Reset");
private JButton jbtexit = new JButton("EXIT");
private JButton jbt [] [ ] = new JButton [3][3];
private Container cp ;
private JPanel jpnc = new JPanel(new GridLayout(3,3,3,3));
private JPanel jpnr = new JPanel(new GridLayout(3,1,3,3));
private boolean flag = true;
public MainFrame(){
init();
}
public void init(){
setBounds(100,100,600,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
cp = this.getContentPane();
jpnr.add(jbtrun);
jpnr.add(jbtre);
jpnr.add(jbtexit);
cp.add(jpnc,BorderLayout.CENTER);
cp.add(jpnr, BorderLayout.EAST);
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
jbt[i][j] = new JButton();
jbt[i][j].setBackground(new Color(91, 255, 209));
jbt[i][j].setFont(new Font(null, Font.BOLD, 72));
jpnc.add(jbt[i][j]);
jbt[i][j].addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JButton tmpbon = (JButton) e.getSource();
if (tmpbon.getText().equals("")){
if (flag){
tmpbon.setText("O");
}else{
tmpbon.setText("X");
}
win();
flag = !flag;
}
}
});
}
}
jbtexit.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
jbtrun.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
jbt[i][j].setEnabled(true);
}
}
}
});
jbtre.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
jbt[i][j].setText("");
jbt[i][j].setEnabled(false);
jbt[i][j].setFont(new Font(null, Font.BOLD, 72));
}
}
}
});
}
public void win () {
if (jbt[0][0].getText().equals(jbt[0][1].getText()) && jbt[0][0].getText().equals(jbt[0][2].getText()) && !jbt[0][0].getText().equals("")) {
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
else if (jbt[1][0].getText().equals(jbt[1][1].getText()) && jbt[1][0].getText().equals(jbt[1][2].getText()) && !jbt[1][0].getText().equals("")){
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
else if (jbt[2][0].getText().equals(jbt[2][1].getText()) && jbt[2][0].getText().equals(jbt[2][2].getText()) && !jbt[2][0].getText().equals("")){
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
else if (jbt[0][0].getText().equals(jbt[1][0].getText()) && jbt[0][0].getText().equals(jbt[2][0].getText()) && !jbt[0][0].getText().equals("")){
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
else if (jbt[0][1].getText().equals(jbt[1][1].getText()) && jbt[0][1].getText().equals(jbt[2][1].getText()) && !jbt[0][1].getText().equals("")){
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
else if (jbt[0][2].getText().equals(jbt[1][2].getText()) && jbt[0][2].getText().equals(jbt[2][2].getText()) && !jbt[0][2].getText().equals("")){
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
else if (jbt[0][0].getText().equals(jbt[1][1].getText()) && jbt[0][0].getText().equals(jbt[2][2].getText()) && !jbt[0][0].getText().equals("")){
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
else if (jbt[0][2].getText().equals(jbt[1][1].getText()) && jbt[0][2].getText().equals(jbt[2][0].getText()) && !jbt[0][2].getText().equals("")){
JOptionPane.showMessageDialog(MainFrame.this,"~~win~~");
}
}
}
|
Markdown | UTF-8 | 1,453 | 2.671875 | 3 | [
"MIT"
] | permissive | # Resolution Changer
Fast and easy way to change test resolution of your game with only 2 clicks!
This addon is tested with Godot 3.1
## Description
Resolution Changer is the fastest way to test you game with different resolutions.
You have simply to click the menu button and pick one resolution.
There are almost all common resolution available but you can also add you custon resolution with the "Add custom..." voice menu.
All the resolution are stored in category and are full reorganizable.
## Getting Started
### Installation
In your project's root copy "addons" folder (if "addons" folder already exist copy the "addons" content in it)
Open your project in Godot, go to Project Settings, click the Plugins tab and enable Resolution Changer.
### How to use
Click on the "Resolutions" menu button and pick one of the available resolutions.

If you need custom resolution click on the "Resolutions" menu button and pick the last item "Add custom...". A popup will appear:

Compile data with device, label and screen width and height, after that click save.
Now you have your custom resolution listed with the other.
### Documentation
All the resolution are store in Resolutions.txt file, if you want to delete some resolutions you have to do it manually deleting the corrisponded record from this file. |
Java | UTF-8 | 3,956 | 2.265625 | 2 | [] | no_license | package tradersdiary.lukapplication.tradersdiary;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
public class Login extends AppCompatActivity {
EditText usernameEditText;
EditText passwordEditText;
Button loginButton;
Button createAccountButton;
//Firebase authentication field
FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener authStateListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameEditText = (EditText) findViewById(R.id.loginEditText);
passwordEditText = (EditText) findViewById(R.id.passwordEditText);
loginButton = (Button) findViewById(R.id.loginButton);
createAccountButton = (Button) findViewById(R.id.createAccountButton);
//Assign instance
firebaseAuth = FirebaseAuth.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
} else {
startActivity(new Intent(Login.this, MainActivity.class));
}
}
};
//on click Listener
createAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String usernameString, passwordString;
usernameString = usernameEditText.getText().toString().trim();
passwordString = passwordEditText.getText().toString().trim();
if(TextUtils.isEmpty(usernameString) && TextUtils.isEmpty(passwordString)){
firebaseAuth.createUserWithEmailAndPassword(usernameString, passwordString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(Login.this, "User Account Created", Toast.LENGTH_LONG).show();
startActivity(new Intent(Login.this, MainActivity.class));
}else{
}
}
});
}
}
});
//Move to Login
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
@Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
@Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(authStateListener);
}
ImageView resultImage = (ImageView) findViewById(R.id.wallstreet);
Bitmap resultBmp = BlurBitmap.blur(this, BitmapFactory.decodeResource(getResources(), R.drawable.wallstreet));
resultImage.setImageBitmap(resultBmp);
}
}
|
JavaScript | UTF-8 | 2,024 | 3.484375 | 3 | [] | no_license | let input;
let buton;
let video;
let classisfier;
let user;
function preload() {
classifier = ml5.imageClassifier('https://teachablemachine.withgoogle.com/models/mG4CuF5N/model.json');
}
function setup() {
createCanvas(400, 400);
input = createInput('');
button = createButton('ENTER!');
button.mousePressed(myfunction);
background(0);
video = createCapture(VIDEO);
video.hide();
}
function draw() {
image(video, 0, 0);
classifyVideo();
}
function myfunction() {
// var user = getInput()
var computer, ran
ran = Math.ceil(Math.random() * 3)
if (ran == 1) {
computer = 'rock'
} else if (ran == 2) {
computer = 'paper'
} else {
computer = 'scissors'
}
check(computer, user)
}
// Function to find out wheather you win/lose/draw.
function check(computer, user) {
var result
if (computer == 'rock' && user == 'rock') {
result = 'draw'
}
else if(computer == 'rock'&& user == 'paper') {
result = 'win'
}
else if(computer == 'rock' && user == 'scissors') {
result = 'lose'
}
else if (computer == 'paper' && user == 'rock') {
result = 'lose'
}
else if(computer =='paper' && user == 'paper') {
result = 'draw'
}
else if(computer == 'paper' && user == 'scissors') {
result = 'win'
}
else if (computer == 'scissors' && user == 'rock') {
result = 'win'
}
else if(computer =='scissors' && user == 'paper') {
result = 'lose'
}
else {
result = 'draw'
}
console.log('Computer choose ' + computer + '. You chose ' + user)
console.log('You ' + result)
showResult(computer, user, result);
}
function getInput() {
return input.elt.value.trimRight();
}
function showResult(computer, user, result) {
background(0);
textSize(32);
fill(255);
text('Computer chose '+ computer , 10, 300);
text('You chose '+ user , 10, 335);
fill(0, 102, 153);
text('You '+ result , 10, 380);
}
function classifyVideo() {
classifier.classify(video, (err, res) => user = res[0].label);
}
|
Java | UTF-8 | 1,878 | 2.25 | 2 | [] | no_license | package com.emotion.ecm.controller;
import com.emotion.ecm.model.dto.UserDto;
import com.emotion.ecm.service.AppUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
@Controller
@RequestMapping(value = "/register")
public class RegisterController {
private AppUserService userService;
@Autowired
public RegisterController(AppUserService userService) {
this.userService = userService;
}
private final static Logger LOG = LoggerFactory.getLogger(RegisterController.class);
@GetMapping
public String showForm(Model model) {
model.addAttribute("user", new UserDto());
return "register";
}
@PostMapping
public String register(@ModelAttribute("user") @Valid UserDto userDto,
BindingResult result, Model model) {
model.addAttribute("user", userDto);
if (userService.getByUsername(userDto.getUsername()).isPresent()) {
result.rejectValue("username", "username.error", "Username is not unique!");
}
if (userService.getByEmail(userDto.getEmail()).isPresent()) {
result.rejectValue("email", "email.error", "E-mail is not unique!");
}
if (result.hasErrors()) {
return "redirect:/register?error";
}
userService.registerNewUser(userDto);
return "redirect:/register?success";
}
}
|
Python | UTF-8 | 1,613 | 3.046875 | 3 | [] | no_license | from ..helpers import is_constant
from .index import Index
class AxesIterator:
def __init__(self, axes):
self.axes = axes
@property
def is_empty(self):
return not bool(self.axes)
@property
def axes_count(self):
return len(self.axes)
@property
def axis_lengths(self):
# TODO: handle str, other consts, iterables, indexables here
lengths = []
for values in self.axes_values:
if is_constant(values):
lengths.append(1)
else:
lengths.append(len(values))
return lengths
@property
def axis_names(self):
return list(self.axes.keys())
@property
def axes_values(self):
return list(self.axes.values())
def point_at(self, index):
# TODO: handle str, other consts, iterables, indexables here
index_values = index.index_values if type(index) == Index else index
point_values = []
for pos, i in enumerate(index_values):
values = self.axes_values[pos]
if is_constant(values):
point_values.append(values)
else:
point_values.append(values[i])
point = dict(zip(self.axis_names, point_values))
return point
def __iter__(self):
index = Index(self.axis_lengths)
def generator():
if self.is_empty:
return
while not index.is_last:
yield self.point_at(index)
index.increment()
yield self.point_at(index)
return generator()
|
Ruby | UTF-8 | 2,490 | 2.84375 | 3 | [
"Zlib"
] | permissive | # sexp-ruby - A simple Ruby library for parsing and validating s-expressions
# Copyright (c) 2007-2015 Ingo Ruhnke <grumbel@gmail.com>
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
require "test/unit"
require "sexp-ruby/parser"
require "sexp-ruby"
class TestParser < Test::Unit::TestCase
def test_parser
sx_str = "(section (var1 5) (var2 10))"
lexer = SExp::Lexer.new(sx_str)
tokens = lexer.tokenize()
# puts ">>>>>>>>>>", tokens.inspect
end
def test_boolean
sxs = SExp::parse(" #f #t ")
assert_true(sxs[0].is_a?(SExp::Boolean))
assert_true(sxs[1].is_a?(SExp::Boolean))
assert_equal(false, sxs[0].value)
assert_equal(true, sxs[1].value)
end
def test_integer
sxs = SExp::parse(" 12 43")
assert_true(sxs[0].is_a?(SExp::Integer))
assert_equal(12, sxs[0].value)
assert_true(sxs[1].is_a?(SExp::Integer))
assert_equal(43, sxs[1].value)
end
def test_real
sxs = SExp::parse("1.125")
assert_true(sxs[0].is_a?(SExp::Real))
assert_equal(1.125, sxs[0].value)
end
def test_string
sxs = SExp::parse(" \"Hello World\" ")
assert_true(sxs[0].is_a?(SExp::String))
assert_equal("Hello World", sxs[0].value)
end
def test_symbol
sxs = SExp::parse(" HelloWorld ")
assert_true(sxs[0].is_a?(SExp::Symbol))
assert_equal("HelloWorld", sxs[0].value)
end
def test_list
sxs = SExp::parse(" (1 2 3) ")
assert_true(sxs[0].is_a?(SExp::List))
assert_equal(3, sxs[0].length)
end
def test_roundtrip
content = File.new("test/level-syntax.scm").read()
sx = SExp::parse(content, true, true)
result = sx.map{|s| s.to_s}.join
assert_equal(content, result)
end
end
# EOF #
|
Markdown | UTF-8 | 1,538 | 2.734375 | 3 | [
"MIT"
] | permissive | > A perfect resume did not exi...
<p align="center">
<img width="192" height="192" src="https://tufan.ee/images/icon_domain.svg">
</p>
---
# Single Page Printable Resume Website
[**`tufan.ee`**](https://tufan.ee) is my resume website that is hosted on Github Pages.
## Rules
- Single page
- Printable
- Must represent whole career, experience and skills
- Clear & minimal
## Installation
Fork and complete [Github Pages setup](https://help.github.com/en/articles/configuring-a-publishing-source-for-github-pages).
## Usage
Change information as yours: `/index.html`
Change website icon: `/images/icon.png`
Change resume photo: `/images/me.jpeg`
---
##### The order and Bootstrap colors of tech stack tags adding
1. `-warning` Industry, domain
2. `-primary` Programming languages
3. `-success` Frameworks, libraries, etc. that are related with those programming languages
4. `-danger` Development terms like *RESTful API*
5. `-info` Databases
6. `-secondary` Version control tools
7. `-secondary` Container tools
8. `-secondary` Other CI/CD tools
9. `-secondary` Servers like *Tomcat*
10. `-secondary` Third party services like *Admob* or *Google Play Game Services*
- *The order of the same types should be according to importance & experience.*
- *Typing of the all terms must be the same with title of its Wikipedia article. (For example, it should be Apache Ant, not Ant.)*
## Contributing
Pull requests are welcome without changing personal information.
## License
[MIT](https://choosealicense.com/licenses/mit/) |
JavaScript | UTF-8 | 1,171 | 3.046875 | 3 | [
"MIT"
] | permissive | var fs = require('fs');
var EventEmitter = require('events');
var util = require('util');
function LineReader(path){
this._rs = fs.createReadStream(path);
}
var RETURN = 0x0d;
var NEWLINE = 0x0a;
util.inherits(LineReader,EventEmitter);
LineReader.prototype.on('newListener',function(eventName,callback){
if(eventName == 'newLine'){
var row = [];
var self = this;
this._rs.on('readable',function(){
var buff;
while(null != (buff = this.read(1))){
var ch = buff[0];
if(ch == RETURN) {
this.read(1);
self.emit('newLine',new Buffer(row));
row.length = 0;
}else{
row.push(ch);
}
}
});
this._rs.on('end',function(){
if(row.length>0){
self.emit('newLine',new Buffer(row));
}
self.emit('end');
})
}
});
var lineReader = new LineReader('./index.txt');
lineReader.on('newLine',function(row){
console.log(row.toString());
});
lineReader.on('end',function(){
console.log('end');
}); |
Java | UTF-8 | 336 | 1.914063 | 2 | [] | no_license | package com.android.tallybook.base;
import android.app.Dialog;
import android.content.Context;
public interface BaseView<P>{
void setPresenter(P presenter);
Dialog showloading(Context context, String msg) ;
/**
* 关闭dialog
*
* @param mDialogUtils
*/
void closeDialog(Dialog mDialogUtils);
}
|
Java | UTF-8 | 1,167 | 2.4375 | 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 bomberman.tile;
import bomberman.camera.Camera;
import bomberman.controllers.ImageResourceController;
import bomberman.gameobj.GameObject;
import bomberman.util.Global;
import bomberman.util.ImagePath;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/**
*
* @author user
*/
public class River extends GameObject {
private BufferedImage img;
private BufferedImage img2;
private int id;
public River(int x, int y, int id) {
super(x, y, Global.UNIT_X, Global.UNIT_Y, true);
this.id = id;
this.img = ImageResourceController.getInstance().tryGeyImage(ImagePath.WATERTILE + String.valueOf(this.id) + ".png");
}
@Override
public void update() {
}
@Override
public void paintComponent(Graphics g, Camera camera, int startX) {
g.drawImage(img, super.getLeft() + startX - camera.getCameraX(), super.getTop() - camera.getCameraY(), super.getWidth(), super.getHeight(), null);
}
}
|
C# | UTF-8 | 1,638 | 3.359375 | 3 | [] | no_license | namespace PasswordGenerator
{
public class CharacterSet
{
public CharacterSet(string name, char[] chars)
{
Name = name;
Chars = chars;
}
public string Name { get; }
public char[] Chars { get; }
public string GetDefinition()
{
return $"Name:\t{Name}\r\nSet:\t{string.Join("", Chars)}";
}
public override string ToString()
{
return Name;
}
public static CharacterSet Default_UpperCaseLetters = new CharacterSet("Default_UpperCaseLetters",
new char[]
{
'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'
});
public static CharacterSet Default_LowerCaseLetters = new CharacterSet("Default_LowerCaseLetters",
new char[]
{
'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'
});
public static CharacterSet Default_Numbers = new CharacterSet("Default_Numbers",
new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'});
public static CharacterSet Default_SpecialCharacters = new CharacterSet("Default_SpecialCharacters",
new char[]
{
'+', '-', '=', '_', '@', '#', '$', '%', '^', '&', ';', ':', ',', '.', '<', '>', '/', '~', '\\', '[', ']',
'(', ')', '{', '}', '?', '!', '|'
});
}
} |
Python | UTF-8 | 2,728 | 2.796875 | 3 | [
"MIT"
] | permissive | from typing import Tuple
import psycopg2
from psycopg2.extensions import connection, cursor
from configparser import ConfigParser
from datetime import datetime
class Tracker:
def __init__(self, name: str, config: ConfigParser) -> None:
self._name = name
self._config = config
self._trade_date = config.get('PRODUCTION', 'ProcessingDate')
self._connection: connection = self._get_db_connection()
def update_job_status(self, status: str) -> None:
job_id = self._assign_job_id()
update_time = datetime.now()
if self._connection is not None:
insert_string = f"INSERT into {self._config.get('PRODUCTION', 'TrackingTableName')}" + \
" (job_id, update_time, status) VALUES (%s,%s,%s);"
try:
cur: cursor = self._connection.cursor()
cur.execute(insert_string, (job_id, update_time, status))
self._connection.commit()
cur.close()
except psycopg2.Error as e:
print("Error inserting status record: ", e.pgerror)
else:
print(f"Error: Connection unavailable for status record: {job_id} {update_time} {status}")
def _assign_job_id(self) -> str:
return self._name + '_' + self._trade_date
def get_job_status(self, job_id: str) -> Tuple:
if self._connection is not None:
query_string = f"SELECT job_id, update_time, status FROM {self._config.get('PRODUCTION', 'TrackingTableName')}" + \
" WHERE job_id = %s;"
try:
cur: cursor = self._connection.cursor()
cur.execute(query_string, (job_id,))
result = cur.fetchone()
self._connection.commit()
cur.close()
return result
except psycopg2.Error as e:
print("Error reading tracking table: ", e.pgerror)
return None
else:
print("Error: Connection to tracking table not available")
return None
def _get_db_connection(self):
try:
conn: connection = psycopg2.connect(database=self._config.get('PRODUCTION', 'Database'),
host=self._config.get('PRODUCTION', 'Host'),
user=self._config.get('PRODUCTION', 'User'),
password=self._config.get('PRODUCTION', 'Password')
)
return conn
except psycopg2.Error as e:
print("Error creating connection: ", e.pgerror)
return None
|
C++ | UTF-8 | 780 | 2.71875 | 3 | [] | no_license | #ifndef _PATCH_H_
#define _PATCH_H_
#include <vector>
#include <string>
#include "Primitives.h"
#include "Point.h"
#include "MyMath.h"
using namespace std;
/*
Patch
*/
class Patch : public Primitive {
public:
Patch(int order, int partsU, int partsV, vector<Point3d *> controlPts, string drawingMode);
Patch(int order, int partsU, int partsV, string drawingMode);
void setControlPoints(float* ctrlPoints);
void setNormals(float* n);
void setColors(float* c);
void setTexCoords(float* v);
string Type();
void draw();
protected:
int order, partsU, partsV;
string drawingMode;
float* ctrlPoints;
float* normals;
float* colors;
float* texCoords;
};
/*
Plane
*/
class Plane : public Patch {
public:
Plane(int parts);
string Type();
void draw();
};
#endif |
JavaScript | UTF-8 | 2,756 | 4.40625 | 4 | [] | no_license | /*
//game goes here
var words = [
"a"
];
// Pick a random word
var word = words[Math.floor(Math.random() * words.length)];
// Set up the answer array
var answerArray = [];
for (var i = 0; i <word.length; i++){
answerArray[i] = "_";
}
var remainingLetters = word.length;
// The game loop
while (remainingLetters > 0) {
// Show the player their progress
alert(answerArray.join(" "));
document.write("<p id='scriptoutput'>")
document.write(answerArray.join(" "));
document.write("</p>")
// Get a guess from the player
var guess = prompt("Guess a letter, or click Cancel to stop playing.");
if (guess === null) {
// Exit the game loop
break;
} else if (guess.length !==1){
alert("Please enter a single letter.");
} else{
// Update the game state with the guess
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters --;
}
}
}
// The end of the game loop
}
// Show the answer and congratulate the player
alert(answerArray.join(" "))
alert("Good job! The answer was " + word);
document.write("<p id='scriptoutput'>")
document.write(answerArray.join(" "));
document.write("</p>")
document.write("<p id='displayAnswer'>")
document.write("Good job! The answer was " + word);
document.write("</p>")
*/
// OLD CODE ENDS HERE
// NEW CODE GOES HERE
// Write you functions here
var pickWord = function(){
// Return a random word
var words = [
"a",
];
// Pick a random word
var word = words[Math.floor(Math.random() * words.length)];
return word;
};
var setupAnswer = function (word) {
// Return the answer array
var answerArray = [];
for (var i = 0; i <word.length; i++){
answerArray[i] = "_";
};
var showPlayerProgress = function(answerArray){
// Use alert to show the player their progress
alert(answerArray.join(" "));
document.write("<p id='scriptoutput'>")
document.write(answerArray.join(" "));
document.write("</p>")
};
var getGuess = function() {
// Use prompt to get a guess
};
//
var word = pickWord();
var answerArray = setupAnswerArray(word);
var remainingLetters = word.length;
while (remainingLetters > 0) {
showPlayerProgress(answerArray);
var guess = getGuess();
if (guess === null){
break;
} else if (guess.length !== 1){
alert("Please enter a single letter.");
} else {
var correctGuesses = updateGameState(guess, word, answerArray);
remainingLetters -= correctGuesses;
}
}
showAnswerAndCongratulatePlayer(answerArray);
|
JavaScript | UTF-8 | 1,086 | 3.265625 | 3 | [] | no_license |
var inp = document.getElementById('inp');
var socket = io.connect();
var result = document.getElementById('result');
var nam = '';
inputName();
function inputName() {
nam = window.prompt("What's your name?")
}
function send() {
socket.emit('sendMsg', {name: nam, key: inp.value})
}
socket.on('join', function(data){
socket.emit('name', {name: nam});
});
socket.on('joined', function(data){
let line = `${data.name} has JOINED`;
let pi = document.createElement('p');
let text = document.createTextNode(line);
pi.appendChild(text);
result.appendChild(pi);
})
socket.on('everybody', function(data){
createNodes(data);
})
function createNodes(data){
var p = document.createElement('p');
var namBox = document.createElement('span');
var msgBox = document.createElement('span');
var namtext = document.createTextNode(data.name + ": ");
var msgtext = document.createTextNode(data.key);
namBox.appendChild(namtext);
msgBox.appendChild(msgtext);
p.appendChild(namBox);
p.appendChild(msgBox);
result.appendChild(p);
} |
Java | UTF-8 | 849 | 2.390625 | 2 | [] | no_license | package main;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class CRUDClient {
private WebResource webResource;
private Client client;
private static final String BASE_URI = "http://localhost:8080/CRUDAssignGradeBookService/gradebook";
public CRUDClient() {
super();
ClientConfig config = new DefaultClientConfig();
client = Client.create(config);
}
public ClientResponse viewGrade(String id, String itemname){
webResource = client.resource(BASE_URI).path("viewgrade");
ClientResponse response = webResource.path(id).path(itemname).get(ClientResponse.class);
return response;
}
}
|
Java | UTF-8 | 467 | 2.171875 | 2 | [] | no_license | package mashup.backend.tich.category.dto;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class CategorySaveRequestDto {
private String name;
private Integer averageCycle;
@Builder
public CategorySaveRequestDto(String name, Integer averageCycle) {
this.name = name;
this.averageCycle = averageCycle;
}
}
|
Java | UTF-8 | 1,250 | 2.984375 | 3 | [] | no_license | package mckenna.colin.hw3;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.shapes.Shape;
/**
* Created by cmckenna on 10/22/2015.
*/
public class Diamond extends Shape {
private Context context;
private int strokeWidth;
public Diamond(Context context){
this.context = context;
strokeWidth = (int)context.getResources().getDimension(R.dimen.diamond_stroke);
}
@Override
public void draw(Canvas canvas, Paint paint){
float width = getWidth();
float height = getHeight();
Path path = new Path();
//create path
path.moveTo(0,height/2);
path.lineTo(width / 2, height);
path.lineTo(width ,height/2);
path.lineTo(width / 2 , 0);
path.close();
//fill
paint.setColor(context.getResources().getColor(R.color.green));
paint.setStyle(Paint.Style.FILL);
canvas.drawPath(path, paint);
//stroke
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(strokeWidth);
canvas.drawPath(path, paint);
}
}
|
Shell | UTF-8 | 640 | 2.578125 | 3 | [] | no_license | if [ ! -d "~/shareG" ]; then
mkdir ~/shareG
fi
if [ ! -d "~/shareE" ]; then
mkdir ~/shareE
fi
if [ ! -d "~/shareH" ]; then
mkdir ~/shareH
fi
if [ ! -d "~/shareD" ]; then
mkdir ~/shareD
fi
sudo mount -t cifs -o username=admin,password=123456,dir_mode=0777,file_mode=0777 //10.10.1.220/g ~/shareG
sudo mount -t cifs -o username=admin,password=123456,dir_mode=0777,file_mode=0777 //10.10.1.220/e ~/shareE
sudo mount -t cifs -o username=admin,password=123456,dir_mode=0777,file_mode=0777 //10.10.1.220/h ~/shareH
sudo mount -t cifs -o username=admin,password=123456,dir_mode=0777,file_mode=0777 //10.10.1.220/d ~/shareD
|
Swift | UTF-8 | 3,831 | 3.421875 | 3 | [] | no_license | //
// Sorter.swift
// Session3
//
// Created by Lan on 17/2/20.
// Copyright © 2017年 TL. All rights reserved.
//
import Foundation
/*
插入排序
*/
func insertionSort<T: Comparable>(_ arr: [T]) -> [T] {
var result = arr
for i in 1 ..< arr.count {
let insertValue = arr[i]
if (insertValue >= result[i-1]) {
continue
}
for j in stride(from: i, through: 0, by: -1) {
if j == 0 || insertValue > result[j-1] {
result[j] = insertValue
break
} else {
result[j] = result[j-1]
}
}
}
return result
}
/*
归并排序法
*/
func mergeSorted<T: Comparable>(_ arr: [T]) -> [T]{
var result = arr
mergeSort(&result, l: arr.startIndex, r: arr.endIndex-1)
return result
}
func mergeSort<T: Comparable>(_ arr: inout [T], l: Int, r: Int){
let mid = (l+r)/2
if r - l <= 15 {
arr[l...r] = ArraySlice(insertionSort(Array(arr[l...r])))
return
}
mergeSort(&arr, l: l, r: mid)
mergeSort(&arr, l: mid+1, r: r)
if arr[mid] > arr[mid+1] {
merge(&arr, l: l, mid: mid, r: r)
}
}
func merge<T: Comparable>(_ arr: inout [T], l: Int, mid: Int, r: Int) {
let aux = arr
var i = l
var j = mid + 1
for k in l ... r {
if i > mid {
arr[k] = aux[j-l]
j += 1
} else if j > r {
arr[k] = aux[i-l]
i += 1
} else if aux[i-l] <= aux[j-l] {
arr[k] = aux[i-l]
i += 1
} else {
arr[k] = aux[j-l]
j += 1
}
}
}
/*
快速排序
*/
func quickSorted<T: Comparable>(_ arr: [T]) -> [T] {
if arr.count <= 1 {
return arr
}
var result = arr
let j = partition(&result)
if j > 1 {
result[0...j-1] = ArraySlice(quickSorted(Array(result[0...j-1])))
}
if j+1 < result.count {
result[j+1...result.endIndex-1] = ArraySlice(quickSorted(Array(result[j+1...result.endIndex-1])))
}
return result
}
func partition<T: Comparable>(_ arr: inout [T]) -> Int {
let l = arr[0]
var j = 0
for i in 1 ..< arr.count {
if arr[i] < l {
if j+1 != i {
swap(&arr[j+1], &arr[i])
}
j += 1
}
}
if j != 0 {
swap(&arr[0], &arr[j])
}
return j
}
/*
三路快速排序
*/
func quickSortThreeWays<T: Comparable>(_ arr: [T]) -> [T] {
if arr.count <= 1 {
return arr
}
if arr.count < 16 {
return insertionSort(arr)
}
var result = arr
let (lt, rt) = partitionThreeWays(&result)
if lt > 1 {
result[0...lt] = ArraySlice(quickSortThreeWays(Array(result[0...lt])))
}
if rt+1 < result.count {
result[rt...result.endIndex-1] = ArraySlice(quickSortThreeWays(Array(result[rt...result.endIndex-1])))
}
return result
}
func partitionThreeWays<T: Comparable>(_ arr: inout [T]) -> (Int, Int) {
let randomValue = Int(arc4random()%UInt32(arr.count))
if randomValue != 0 {
swap(&arr[0], &arr[randomValue])
}
let l = arr[0]
var i = 1
var lt = 0
var rt = arr.count
while i < rt {
if arr[i] > l {
rt -= 1
if i != rt {
swap(&arr[i], &arr[rt])
}
} else if arr[i] < l {
if i != lt+1 {
swap(&arr[i], &arr[lt+1])
}
lt += 1
i += 1
} else {
i += 1
}
}
if lt != 0 {
swap(&arr[lt], &arr[0])
}
return (lt, rt)
}
|
PHP | UTF-8 | 1,189 | 2.734375 | 3 | [] | no_license | <?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class NewProductRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|string|min:5|unique:products,title',
'qty' => 'required|numeric',
'price' => 'required|numeric',
'description' => 'required',
'image' => ''
];
}
public function messages()
{
return [
'title.required' => 'Judul wajib diisi',
'title.min' => 'Judul minimal 5 karakter',
'title.unique' => 'Judul harus unik',
'qty.required' => 'Qty harus diisi',
'qty.number' => 'Qty harus berupa angka',
'price.required' => 'Harga harus diisi',
'price.number' => 'Harga harus berupa angka',
'description.required' => 'Deskripsi wajib diisi'
];
}
}
|
C++ | UTF-8 | 3,746 | 2.8125 | 3 | [] | no_license | #include <ESP8266WiFi.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <Servo.h>
// Replace with your network credentials
const char* ssid = "Southbound 35";
const char* password = "aggiesss";
ESP8266WebServer server(80);
Servo servoPortOne;
Servo servoPortTwo;
Servo servoPortThree;
String page = "";
int portOnePinTrans = D0;
int portOnePinSignal = D3;
int portTwoPinTrans = D1;
int portTwoPinSignal = D4;
int portThreePinTrans = D2;
int portThreePinSignal = D5;
void setup(void){
servoPortOne.attach(portOnePinSignal);
servoPortTwo.attach(portTwoPinSignal);
servoPortThree.attach(portThreePinSignal);
page = "<h1>You have reached a Tiger Blind Peripheral</h1>";
pinMode(portOnePinTrans, OUTPUT);
pinMode(portOnePinSignal, OUTPUT);
pinMode(portTwoPinTrans, OUTPUT);
pinMode(portTwoPinSignal, OUTPUT);
pinMode(portThreePinTrans, OUTPUT);
pinMode(portThreePinSignal, OUTPUT);
digitalWrite(portOnePinTrans, LOW);
digitalWrite(portTwoPinTrans, LOW);
digitalWrite(portThreePinTrans, LOW);
delay(500);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", [](){
server.send(200, "text/html", page);
});
server.on("/setPositionForServoAtPort", HTTP_POST, setPositionForServoAtPort);
server.begin();
Serial.println("Web server started!");
}
void loop(void){
server.handleClient();
}
void setPositionForServoAtPort() {
Serial.println("Setting Servo Positions...");
delay(100);
int pos = 0;
int currentPosition = server.arg("currentPosition").toInt();
int targetPosition = server.arg("targetPosition").toInt();
int servoDelay = server.arg("delay").toInt();
int port = server.arg("port").toInt();
// Serial.println(currentPosition);
// Serial.println(targetPosition);
// Serial.println(servoDelay);
server.send(200);
Serial.println("Turn on Servos...");
turnOnServo(port);
if (currentPosition < targetPosition) {
Serial.println("Less than");
for(pos = currentPosition; pos <= targetPosition; pos += 1) {
switch (port) {
case 1:
servoPortOne.write(pos);
break;
case 2:
servoPortTwo.write(pos);
break;
case 3:
servoPortThree.write(pos);
break;
default:
break;
}
delay(servoDelay);
}
} else if (currentPosition > targetPosition) {
for(pos = currentPosition; pos >= targetPosition; pos -= 1) {
switch (port) {
case 1:
servoPortOne.write(pos);
break;
case 2:
servoPortTwo.write(pos);
break;
case 3:
servoPortThree.write(pos);
break;
default:
break;
}
delay(servoDelay);
}
}
Serial.println("Turn off Servos...");
turnOffServos();
}
void turnOnServo(int port) {
switch (port) {
case 1:
digitalWrite(portOnePinTrans, HIGH);
break;
case 2:
digitalWrite(portTwoPinTrans, HIGH);
break;
case 3:
digitalWrite(portThreePinTrans, HIGH);
break;
default:
break;
}
delay(100);
}
void turnOffServos() {
digitalWrite(portOnePinTrans, LOW);
digitalWrite(portTwoPinTrans, LOW);
digitalWrite(portThreePinTrans, LOW);
delay(100);
}
|
C++ | UTF-8 | 2,501 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <algorithm>
#include <cstdlib>
using namespace std;
class Point
{
public:
float x, y;
public:
Point(float x, float y)
{
this->x = x;
this->y = y;
}
float getx()
{
return x;
}
float gety()
{
return y;
}
};
bool Witam(Point x, Point y)
{
if(x.x != y.x) return x.x < y.x;
return y.y > x.y;
}
vector <Point> Fun(vector <Point> const & v1, Point x, Point y)
{
vector <Point> v2;
for(int i=0; i<v1.size(); i++)
{
if(v1[i].x>=x.x&&v1[i].x<=y.x&&v1[i].y<=x.y&&v1[i].y>=y.y) v2.push_back(v1[i]);
}
return v2;
}
void Funkcja(list <string>::iterator it1, list<string>::iterator it2)
{
for(it1; it1 != it2; it1++)
cout<<*it1<<" ";
}
int main()
{
srand(time(NULL));
/*vector <int> witam;
witam.push_back(0);
witam.push_back(5);
witam.push_back(99);
witam.push_back(3);
witam.push_back(4);
for(int i=0; i<witam.size(); i++)
cout<<witam[i]<<" ";
list <int> lista;
for(int i=0; i<15; i++)
lista.push_front(i);
for(list <int>::iterator it = lista.begin(); it!=lista.end(); it++)
cout<<*it<<" ";
map <string, int> mapa;
mapa["test"] = 6;
mapa["inna"] = 8;
cout<<mapa["test"]<<endl;
set <string> s;
s.insert("Witam");
s.insert("www");
set <string>::iterator it = s.find("Witam");
if(it != s.end())
cout<<"Witam"<<endl;*/
/*vector <Point> v1;
//sort(v1.begin(), v1.end());
for(int i=0; i<10; i++)
v1.push_back(Point(i*rand()%10, i*rand()%10));
//for(int i=0; i<v1.size(); i++)
//cout<<v1[i].getx()<<" "<<v1[i].gety()<<endl;
sort(v1.begin(), v1.end(), Witam);
for(int i=0; i<v1.size(); i++)
cout<<v1[i].getx()<<" "<<v1[i].gety()<<endl;
Point x(-5, 5);
Point y(5, -5);
vector <Point> v2 = Fun(v1, x, y);
cout<<endl<<"_______________"<<endl;
for(int i=0; i<v2.size(); i++)
cout<<v2[i].getx()<<" "<<v2[i].gety()<<endl;*/
list <string> lista;
lista.push_back("Witam");
lista.push_back("Witam1");
lista.push_back("Witam2");
lista.push_back("Witam3");
lista.push_back("Witam4");
lista.push_back("Witam5");
lista.push_back("Witam6");
list <string>::iterator it1 = lista.begin();
list <string>::iterator it2 = lista.end();
Funkcja(it1, it2);
return 0;
}
|
Python | UTF-8 | 1,529 | 2.78125 | 3 | [] | no_license |
# coding: utf-8
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
path = "F:/for learn/Python_MachineLearning/"
df = pd.read_csv(path + "wdbc.data", header=None)
X = df.iloc[:, 2:].values
y = df.iloc[:, 1].values
le = LabelEncoder()
y = le.fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
pipe_lr = Pipeline([("scaler", StandardScaler()),
('pca', PCA(n_components=2)),
('lr', LogisticRegression(random_state=1))])
pipe_lr.fit(X_train, y_train)
print("the Test ACC is: %.3f" % pipe_lr.score(X_test, y_test))
kfold = StratifiedKFold(n_splits=10, random_state=1)
scores = []
for k, (train, test) in enumerate(kfold.split(X_train, y_train)):
pipe_lr.fit(X_train[train], y_train[train])
score = pipe_lr.score(X_train[test], y_train[test])
scores.append(score)
print("Fold: %d, Class dist: %s, ACC: %.3f" % (k+1, np.bincount(y_train[train]), score))
print("CV ACC: %.3f +/- %.3f" % (np.mean(scores), np.std(scores)))
# 采用sklearn中的集成方法做cv
scores = cross_val_score(estimator=pipe_lr, X=X_train, y=y_train, cv=10, n_jobs=-1)
print("CV ACC scores: %s" % scores)
print("CV ACC: %.3f +/- %.3f" % (np.mean(scores), np.std(scores)))
|
Python | UTF-8 | 924 | 3.046875 | 3 | [] | no_license |
#inheriting stuf
import speech_recognition as sr
import os
import webbrowser
import subprocess
#making r meaningful
r = sr.Recognizer()
#getting the microphone and printing "Say Something" after getting it
with sr.Microphone() as source:
print("Say Something")
#making audio the thing we said (in sound)
audio = r.listen(source)
#makind said the thing we said (in text)
said = r.recognize_google(audio)
said = said.lower()
#what will happen if said is a certain thing
print("You have said " + said)
if "search" in said:
if "google" in said:
said = said.replace("search in google for", "")
said = said.replace("search google", "")
said = said.replace("search in google", "")
said = said.replace("search google for", "")
said = said.replace(" ", "+")
webbrowser.open("https://www.google.com/search?q=" + said) |
Java | UTF-8 | 340 | 1.53125 | 2 | [] | no_license | package com.deity.echidna;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EchidnaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EchidnaConsumerApplication.class, args);
}
}
|
Java | UTF-8 | 161 | 1.515625 | 2 | [] | no_license | package com.runescape.media;
public final class Vertex {
public int anInt602;
public int anInt603;
public int anInt604;
public int anInt605;
}
|
JavaScript | UTF-8 | 583 | 3.140625 | 3 | [] | no_license | //the spec file
// example below
var flattener = require('../index.js');
// describe("Hello world", function() {
// it("says hello", function() {
// expect(helloWorld()).toEqual("Hello world!");
// });
// });
describe("Flatten a nested array", function() {
it("takes a nexted array and flattens it", function() {
expect(flattener.nestedArray).toEqual([ 1, [2], [ 3, [[4]] ] , 7, [[8]], 9 ]);
expect(flattener.flatten(nestedArray)).toEqual([ 1,2,3,4,7,8,9 ]);
expect(flattener.flatten(testArray1)).toEqual([ 1,2,3,4,5,'g','h','d' ]);
});
});
|
C# | UTF-8 | 1,337 | 3.171875 | 3 | [
"MIT"
] | permissive | using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace ObjectsComparer.Tests
{
[TestFixture]
public class ParentInterfacePropertiesTests
{
interface IParent
{
string Property1 { get; set; }
}
interface IChild : IParent
{
string Property2 { get; set; }
}
class Child : IChild
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
[Test]
public void ComparePropertyOfParentInterface()
{
var a1 = new Child {Property1 = "str11", Property2 = "str12"};
var a2 = new Child {Property1 = "str21", Property2 = "str22"};
var comparer = new Comparer<IChild>();
var differences = comparer.CalculateDifferences(a1, a2).ToList();
Assert.AreEqual(2, differences.Count);
Assert.AreEqual("Property1", differences[1].MemberPath);
Assert.AreEqual("str11", differences[1].Value1);
Assert.AreEqual("str21", differences[1].Value2);
Assert.AreEqual("Property2", differences[0].MemberPath);
Assert.AreEqual("str12", differences[0].Value1);
Assert.AreEqual("str22", differences[0].Value2);
}
}
} |
Markdown | UTF-8 | 1,385 | 2.875 | 3 | [] | no_license | ---
layout: post
title: Talk
description: python skill
tag: 杂谈
---
Talk 记录
+ 写在最前面:魏老师是个爱面子的人呀,以后不要再傻逼的当面diss了
+ 情绪调节:情绪不好的时候如何调节呢,情绪的大喜大悲的波动。越高兴的人可能在不开心的时候波动越大。平时要准备好几个让自己高兴的内容,这样在不开心的时候就比较容易能开心起来。我自己也是在不开心的时候就会倾向于凤爪,奶茶小蛋糕之类的食物,这样就会让我心情舒缓一些。
周老师说,有一个针对对于悲观人群的建议,那就是去医院的癌症科等做义工。看到有人的日子比自己惨很多,就会觉得自己没有那么惨了。从而可以找到生活的信心。“比惨”也是自我安慰的一种方式。
+ 成功定义
每个人对于成功的定义都不一样,这源于我们的每个人的个性都不太一样。大多数是实现个人价值吧。
+ 成功要素
我们对于成功的要素都不太一样。大多数选择了毅力,坚持,努力,勤奋等,周老师说“体力好”,当然体力好更像是前提的一件事。当然,也有运气。
+ 价值观
+ 其实真正决定一个企业或者一个人能走多远的,是价值观。
+ 合作
+ 吃亏是福。
|
JavaScript | UTF-8 | 40,954 | 2.84375 | 3 | [
"MIT"
] | permissive | function BranchData() {
this.position = -1;
this.nodeLength = -1;
this.src = null;
this.evalFalse = 0;
this.evalTrue = 0;
this.init = function(position, nodeLength, src) {
this.position = position;
this.nodeLength = nodeLength;
this.src = src;
return this;
}
this.ranCondition = function(result) {
if (result)
this.evalTrue++;
else
this.evalFalse++;
};
this.pathsCovered = function() {
var paths = 0;
if (this.evalTrue > 0)
paths++;
if (this.evalFalse > 0)
paths++;
return paths;
};
this.covered = function() {
return this.evalTrue > 0 && this.evalFalse > 0;
};
this.toJSON = function() {
return '{"position":' + this.position
+ ',"nodeLength":' + this.nodeLength
+ ',"src":' + jscoverage_quote(this.src)
+ ',"evalFalse":' + this.evalFalse
+ ',"evalTrue":' + this.evalTrue + '}';
};
this.message = function() {
if (this.evalTrue === 0 && this.evalFalse === 0)
return 'Condition never evaluated :\t' + this.src;
else if (this.evalTrue === 0)
return 'Condition never evaluated to true :\t' + this.src;
else if (this.evalFalse === 0)
return 'Condition never evaluated to false:\t' + this.src;
else
return 'Condition covered';
};
}
BranchData.fromJson = function(jsonString) {
var json = eval('(' + jsonString + ')');
var branchData = new BranchData();
branchData.init(json.position, json.nodeLength, json.src);
branchData.evalFalse = json.evalFalse;
branchData.evalTrue = json.evalTrue;
return branchData;
};
BranchData.fromJsonObject = function(json) {
var branchData = new BranchData();
branchData.init(json.position, json.nodeLength, json.src);
branchData.evalFalse = json.evalFalse;
branchData.evalTrue = json.evalTrue;
return branchData;
};
function buildBranchMessage(conditions) {
var message = 'The following was not covered:';
for (var i = 0; i < conditions.length; i++) {
if (conditions[i] !== undefined && conditions[i] !== null && !conditions[i].covered())
message += '\n- '+ conditions[i].message();
}
return message;
};
function convertBranchDataConditionArrayToJSON(branchDataConditionArray) {
var array = [];
var length = branchDataConditionArray.length;
for (var condition = 0; condition < length; condition++) {
var branchDataObject = branchDataConditionArray[condition];
if (branchDataObject === undefined || branchDataObject === null) {
value = 'null';
} else {
value = branchDataObject.toJSON();
}
array.push(value);
}
return '[' + array.join(',') + ']';
}
function convertBranchDataLinesToJSON(branchData) {
if (branchData === undefined) {
return '{}'
}
var json = '';
for (var line in branchData) {
if (json !== '')
json += ','
json += '"' + line + '":' + convertBranchDataConditionArrayToJSON(branchData[line]);
}
return '{' + json + '}';
}
function convertBranchDataLinesFromJSON(jsonObject) {
if (jsonObject === undefined) {
return {};
}
for (var line in jsonObject) {
var branchDataJSON = jsonObject[line];
if (branchDataJSON !== null) {
for (var conditionIndex = 0; conditionIndex < branchDataJSON.length; conditionIndex ++) {
var condition = branchDataJSON[conditionIndex];
if (condition !== null) {
branchDataJSON[conditionIndex] = BranchData.fromJsonObject(condition);
}
}
}
}
return jsonObject;
}
function jscoverage_quote(s) {
return '"' + s.replace(/[\u0000-\u001f"\\\u007f-\uffff]/g, function (c) {
switch (c) {
case '\b':
return '\\b';
case '\f':
return '\\f';
case '\n':
return '\\n';
case '\r':
return '\\r';
case '\t':
return '\\t';
// IE doesn't support this
/*
case '\v':
return '\\v';
*/
case '"':
return '\\"';
case '\\':
return '\\\\';
default:
return '\\u' + jscoverage_pad(c.charCodeAt(0).toString(16));
}
}) + '"';
}
function getArrayJSON(coverage) {
var array = [];
if (coverage === undefined)
return array;
var length = coverage.length;
for (var line = 0; line < length; line++) {
var value = coverage[line];
if (value === undefined || value === null) {
value = 'null';
}
array.push(value);
}
return array;
}
function jscoverage_serializeCoverageToJSON() {
var json = [];
for (var file in _$jscoverage) {
var lineArray = getArrayJSON(_$jscoverage[file].lineData);
var fnArray = getArrayJSON(_$jscoverage[file].functionData);
json.push(jscoverage_quote(file) + ':{"lineData":[' + lineArray.join(',') + '],"functionData":[' + fnArray.join(',') + '],"branchData":' + convertBranchDataLinesToJSON(_$jscoverage[file].branchData) + '}');
}
return '{' + json.join(',') + '}';
}
function jscoverage_pad(s) {
return '0000'.substr(s.length) + s;
}
function jscoverage_html_escape(s) {
return s.replace(/[<>\&\"\']/g, function (c) {
return '&#' + c.charCodeAt(0) + ';';
});
}
try {
if (typeof top === 'object' && top !== null && typeof top.opener === 'object' && top.opener !== null) {
// this is a browser window that was opened from another window
if (! top.opener._$jscoverage) {
top.opener._$jscoverage = {};
}
}
}
catch (e) {}
try {
if (typeof top === 'object' && top !== null) {
// this is a browser window
try {
if (typeof top.opener === 'object' && top.opener !== null && top.opener._$jscoverage) {
top._$jscoverage = top.opener._$jscoverage;
}
}
catch (e) {}
if (! top._$jscoverage) {
top._$jscoverage = {};
}
}
}
catch (e) {}
try {
if (typeof top === 'object' && top !== null && top._$jscoverage) {
this._$jscoverage = top._$jscoverage;
}
}
catch (e) {}
if (! this._$jscoverage) {
this._$jscoverage = {};
}
if (! _$jscoverage['/color.js']) {
_$jscoverage['/color.js'] = {};
_$jscoverage['/color.js'].lineData = [];
_$jscoverage['/color.js'].lineData[6] = 0;
_$jscoverage['/color.js'].lineData[7] = 0;
_$jscoverage['/color.js'].lineData[14] = 0;
_$jscoverage['/color.js'].lineData[20] = 0;
_$jscoverage['/color.js'].lineData[21] = 0;
_$jscoverage['/color.js'].lineData[28] = 0;
_$jscoverage['/color.js'].lineData[29] = 0;
_$jscoverage['/color.js'].lineData[38] = 0;
_$jscoverage['/color.js'].lineData[39] = 0;
_$jscoverage['/color.js'].lineData[46] = 0;
_$jscoverage['/color.js'].lineData[47] = 0;
_$jscoverage['/color.js'].lineData[55] = 0;
_$jscoverage['/color.js'].lineData[56] = 0;
_$jscoverage['/color.js'].lineData[64] = 0;
_$jscoverage['/color.js'].lineData[71] = 0;
_$jscoverage['/color.js'].lineData[83] = 0;
_$jscoverage['/color.js'].lineData[84] = 0;
_$jscoverage['/color.js'].lineData[85] = 0;
_$jscoverage['/color.js'].lineData[86] = 0;
_$jscoverage['/color.js'].lineData[87] = 0;
_$jscoverage['/color.js'].lineData[88] = 0;
_$jscoverage['/color.js'].lineData[90] = 0;
_$jscoverage['/color.js'].lineData[93] = 0;
_$jscoverage['/color.js'].lineData[95] = 0;
_$jscoverage['/color.js'].lineData[107] = 0;
_$jscoverage['/color.js'].lineData[122] = 0;
_$jscoverage['/color.js'].lineData[124] = 0;
_$jscoverage['/color.js'].lineData[126] = 0;
_$jscoverage['/color.js'].lineData[127] = 0;
_$jscoverage['/color.js'].lineData[128] = 0;
_$jscoverage['/color.js'].lineData[129] = 0;
_$jscoverage['/color.js'].lineData[132] = 0;
_$jscoverage['/color.js'].lineData[134] = 0;
_$jscoverage['/color.js'].lineData[146] = 0;
_$jscoverage['/color.js'].lineData[148] = 0;
_$jscoverage['/color.js'].lineData[150] = 0;
_$jscoverage['/color.js'].lineData[151] = 0;
_$jscoverage['/color.js'].lineData[152] = 0;
_$jscoverage['/color.js'].lineData[153] = 0;
_$jscoverage['/color.js'].lineData[156] = 0;
_$jscoverage['/color.js'].lineData[160] = 0;
_$jscoverage['/color.js'].lineData[178] = 0;
_$jscoverage['/color.js'].lineData[181] = 0;
_$jscoverage['/color.js'].lineData[198] = 0;
_$jscoverage['/color.js'].lineData[201] = 0;
_$jscoverage['/color.js'].lineData[218] = 0;
_$jscoverage['/color.js'].lineData[221] = 0;
_$jscoverage['/color.js'].lineData[240] = 0;
_$jscoverage['/color.js'].lineData[252] = 0;
_$jscoverage['/color.js'].lineData[257] = 0;
_$jscoverage['/color.js'].lineData[258] = 0;
_$jscoverage['/color.js'].lineData[259] = 0;
_$jscoverage['/color.js'].lineData[260] = 0;
_$jscoverage['/color.js'].lineData[261] = 0;
_$jscoverage['/color.js'].lineData[262] = 0;
_$jscoverage['/color.js'].lineData[263] = 0;
_$jscoverage['/color.js'].lineData[264] = 0;
_$jscoverage['/color.js'].lineData[265] = 0;
_$jscoverage['/color.js'].lineData[266] = 0;
_$jscoverage['/color.js'].lineData[271] = 0;
_$jscoverage['/color.js'].lineData[272] = 0;
_$jscoverage['/color.js'].lineData[273] = 0;
_$jscoverage['/color.js'].lineData[274] = 0;
_$jscoverage['/color.js'].lineData[275] = 0;
_$jscoverage['/color.js'].lineData[276] = 0;
_$jscoverage['/color.js'].lineData[280] = 0;
_$jscoverage['/color.js'].lineData[298] = 0;
_$jscoverage['/color.js'].lineData[299] = 0;
_$jscoverage['/color.js'].lineData[300] = 0;
_$jscoverage['/color.js'].lineData[312] = 0;
_$jscoverage['/color.js'].lineData[313] = 0;
_$jscoverage['/color.js'].lineData[314] = 0;
_$jscoverage['/color.js'].lineData[320] = 0;
_$jscoverage['/color.js'].lineData[321] = 0;
_$jscoverage['/color.js'].lineData[325] = 0;
_$jscoverage['/color.js'].lineData[326] = 0;
_$jscoverage['/color.js'].lineData[336] = 0;
_$jscoverage['/color.js'].lineData[338] = 0;
_$jscoverage['/color.js'].lineData[339] = 0;
_$jscoverage['/color.js'].lineData[340] = 0;
_$jscoverage['/color.js'].lineData[341] = 0;
_$jscoverage['/color.js'].lineData[343] = 0;
_$jscoverage['/color.js'].lineData[344] = 0;
_$jscoverage['/color.js'].lineData[345] = 0;
_$jscoverage['/color.js'].lineData[346] = 0;
_$jscoverage['/color.js'].lineData[348] = 0;
_$jscoverage['/color.js'].lineData[349] = 0;
_$jscoverage['/color.js'].lineData[350] = 0;
_$jscoverage['/color.js'].lineData[351] = 0;
_$jscoverage['/color.js'].lineData[353] = 0;
_$jscoverage['/color.js'].lineData[354] = 0;
_$jscoverage['/color.js'].lineData[355] = 0;
_$jscoverage['/color.js'].lineData[356] = 0;
_$jscoverage['/color.js'].lineData[358] = 0;
_$jscoverage['/color.js'].lineData[359] = 0;
_$jscoverage['/color.js'].lineData[360] = 0;
_$jscoverage['/color.js'].lineData[361] = 0;
_$jscoverage['/color.js'].lineData[363] = 0;
_$jscoverage['/color.js'].lineData[364] = 0;
_$jscoverage['/color.js'].lineData[365] = 0;
_$jscoverage['/color.js'].lineData[366] = 0;
_$jscoverage['/color.js'].lineData[369] = 0;
_$jscoverage['/color.js'].lineData[372] = 0;
_$jscoverage['/color.js'].lineData[373] = 0;
_$jscoverage['/color.js'].lineData[377] = 0;
_$jscoverage['/color.js'].lineData[383] = 0;
_$jscoverage['/color.js'].lineData[385] = 0;
_$jscoverage['/color.js'].lineData[386] = 0;
_$jscoverage['/color.js'].lineData[388] = 0;
_$jscoverage['/color.js'].lineData[389] = 0;
_$jscoverage['/color.js'].lineData[390] = 0;
_$jscoverage['/color.js'].lineData[392] = 0;
_$jscoverage['/color.js'].lineData[394] = 0;
_$jscoverage['/color.js'].lineData[395] = 0;
_$jscoverage['/color.js'].lineData[397] = 0;
_$jscoverage['/color.js'].lineData[398] = 0;
_$jscoverage['/color.js'].lineData[401] = 0;
_$jscoverage['/color.js'].lineData[403] = 0;
_$jscoverage['/color.js'].lineData[409] = 0;
_$jscoverage['/color.js'].lineData[412] = 0;
_$jscoverage['/color.js'].lineData[413] = 0;
_$jscoverage['/color.js'].lineData[420] = 0;
_$jscoverage['/color.js'].lineData[422] = 0;
_$jscoverage['/color.js'].lineData[428] = 0;
_$jscoverage['/color.js'].lineData[429] = 0;
_$jscoverage['/color.js'].lineData[430] = 0;
_$jscoverage['/color.js'].lineData[431] = 0;
_$jscoverage['/color.js'].lineData[432] = 0;
_$jscoverage['/color.js'].lineData[434] = 0;
_$jscoverage['/color.js'].lineData[435] = 0;
_$jscoverage['/color.js'].lineData[437] = 0;
_$jscoverage['/color.js'].lineData[438] = 0;
_$jscoverage['/color.js'].lineData[440] = 0;
_$jscoverage['/color.js'].lineData[441] = 0;
_$jscoverage['/color.js'].lineData[443] = 0;
_$jscoverage['/color.js'].lineData[444] = 0;
_$jscoverage['/color.js'].lineData[446] = 0;
_$jscoverage['/color.js'].lineData[447] = 0;
_$jscoverage['/color.js'].lineData[449] = 0;
_$jscoverage['/color.js'].lineData[450] = 0;
_$jscoverage['/color.js'].lineData[452] = 0;
_$jscoverage['/color.js'].lineData[454] = 0;
_$jscoverage['/color.js'].lineData[455] = 0;
_$jscoverage['/color.js'].lineData[457] = 0;
_$jscoverage['/color.js'].lineData[464] = 0;
_$jscoverage['/color.js'].lineData[465] = 0;
_$jscoverage['/color.js'].lineData[468] = 0;
_$jscoverage['/color.js'].lineData[469] = 0;
_$jscoverage['/color.js'].lineData[472] = 0;
_$jscoverage['/color.js'].lineData[473] = 0;
_$jscoverage['/color.js'].lineData[474] = 0;
_$jscoverage['/color.js'].lineData[476] = 0;
_$jscoverage['/color.js'].lineData[479] = 0;
_$jscoverage['/color.js'].lineData[480] = 0;
_$jscoverage['/color.js'].lineData[483] = 0;
_$jscoverage['/color.js'].lineData[484] = 0;
_$jscoverage['/color.js'].lineData[487] = 0;
_$jscoverage['/color.js'].lineData[488] = 0;
_$jscoverage['/color.js'].lineData[493] = 0;
}
if (! _$jscoverage['/color.js'].functionData) {
_$jscoverage['/color.js'].functionData = [];
_$jscoverage['/color.js'].functionData[0] = 0;
_$jscoverage['/color.js'].functionData[1] = 0;
_$jscoverage['/color.js'].functionData[2] = 0;
_$jscoverage['/color.js'].functionData[3] = 0;
_$jscoverage['/color.js'].functionData[4] = 0;
_$jscoverage['/color.js'].functionData[5] = 0;
_$jscoverage['/color.js'].functionData[6] = 0;
_$jscoverage['/color.js'].functionData[7] = 0;
_$jscoverage['/color.js'].functionData[8] = 0;
_$jscoverage['/color.js'].functionData[9] = 0;
_$jscoverage['/color.js'].functionData[10] = 0;
_$jscoverage['/color.js'].functionData[11] = 0;
_$jscoverage['/color.js'].functionData[12] = 0;
_$jscoverage['/color.js'].functionData[13] = 0;
_$jscoverage['/color.js'].functionData[14] = 0;
_$jscoverage['/color.js'].functionData[15] = 0;
_$jscoverage['/color.js'].functionData[16] = 0;
_$jscoverage['/color.js'].functionData[17] = 0;
_$jscoverage['/color.js'].functionData[18] = 0;
_$jscoverage['/color.js'].functionData[19] = 0;
_$jscoverage['/color.js'].functionData[20] = 0;
_$jscoverage['/color.js'].functionData[21] = 0;
_$jscoverage['/color.js'].functionData[22] = 0;
_$jscoverage['/color.js'].functionData[23] = 0;
_$jscoverage['/color.js'].functionData[24] = 0;
_$jscoverage['/color.js'].functionData[25] = 0;
_$jscoverage['/color.js'].functionData[26] = 0;
_$jscoverage['/color.js'].functionData[27] = 0;
_$jscoverage['/color.js'].functionData[28] = 0;
_$jscoverage['/color.js'].functionData[29] = 0;
_$jscoverage['/color.js'].functionData[30] = 0;
_$jscoverage['/color.js'].functionData[31] = 0;
_$jscoverage['/color.js'].functionData[32] = 0;
_$jscoverage['/color.js'].functionData[33] = 0;
}
if (! _$jscoverage['/color.js'].branchData) {
_$jscoverage['/color.js'].branchData = {};
_$jscoverage['/color.js'].branchData['21'] = [];
_$jscoverage['/color.js'].branchData['21'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['29'] = [];
_$jscoverage['/color.js'].branchData['29'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['83'] = [];
_$jscoverage['/color.js'].branchData['83'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['84'] = [];
_$jscoverage['/color.js'].branchData['84'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['85'] = [];
_$jscoverage['/color.js'].branchData['85'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['87'] = [];
_$jscoverage['/color.js'].branchData['87'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['124'] = [];
_$jscoverage['/color.js'].branchData['124'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['124'][2] = new BranchData();
_$jscoverage['/color.js'].branchData['128'] = [];
_$jscoverage['/color.js'].branchData['128'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['148'] = [];
_$jscoverage['/color.js'].branchData['148'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['148'][2] = new BranchData();
_$jscoverage['/color.js'].branchData['152'] = [];
_$jscoverage['/color.js'].branchData['152'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['257'] = [];
_$jscoverage['/color.js'].branchData['257'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['257'][2] = new BranchData();
_$jscoverage['/color.js'].branchData['257'][3] = new BranchData();
_$jscoverage['/color.js'].branchData['257'][4] = new BranchData();
_$jscoverage['/color.js'].branchData['257'][5] = new BranchData();
_$jscoverage['/color.js'].branchData['259'] = [];
_$jscoverage['/color.js'].branchData['259'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['263'] = [];
_$jscoverage['/color.js'].branchData['263'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['272'] = [];
_$jscoverage['/color.js'].branchData['272'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['276'] = [];
_$jscoverage['/color.js'].branchData['276'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['280'] = [];
_$jscoverage['/color.js'].branchData['280'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['389'] = [];
_$jscoverage['/color.js'].branchData['389'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['401'] = [];
_$jscoverage['/color.js'].branchData['401'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['420'] = [];
_$jscoverage['/color.js'].branchData['420'][1] = new BranchData();
_$jscoverage['/color.js'].branchData['420'][2] = new BranchData();
_$jscoverage['/color.js'].branchData['420'][3] = new BranchData();
_$jscoverage['/color.js'].branchData['473'] = [];
_$jscoverage['/color.js'].branchData['473'][1] = new BranchData();
}
_$jscoverage['/color.js'].branchData['473'][1].init(14, 13, 'v.length != 2');
function visit28_473_1(result) {
_$jscoverage['/color.js'].branchData['473'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['420'][3].init(271, 9, 'h == null');
function visit27_420_3(result) {
_$jscoverage['/color.js'].branchData['420'][3].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['420'][2].init(261, 6, 's == 0');
function visit26_420_2(result) {
_$jscoverage['/color.js'].branchData['420'][2].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['420'][1].init(261, 19, 's == 0 || h == null');
function visit25_420_1(result) {
_$jscoverage['/color.js'].branchData['420'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['401'][1].init(742, 9, 'max === 0');
function visit24_401_1(result) {
_$jscoverage['/color.js'].branchData['401'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['389'][1].init(71, 5, 'g < b');
function visit23_389_1(result) {
_$jscoverage['/color.js'].branchData['389'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['280'][1].init(970, 23, 'typeof r == \'undefined\'');
function visit22_280_1(result) {
_$jscoverage['/color.js'].branchData['280'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['276'][1].init(164, 26, 'parseFloat(values[4]) || 1');
function visit21_276_1(result) {
_$jscoverage['/color.js'].branchData['276'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['272'][1].init(67, 6, 'values');
function visit20_272_1(result) {
_$jscoverage['/color.js'].branchData['272'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['263'][1].init(164, 15, 'str.length == 4');
function visit19_263_1(result) {
_$jscoverage['/color.js'].branchData['263'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['259'][1].init(66, 6, 'values');
function visit18_259_1(result) {
_$jscoverage['/color.js'].branchData['259'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['257'][5].init(152, 24, 'str.substr(0, 1) === \'#\'');
function visit17_257_5(result) {
_$jscoverage['/color.js'].branchData['257'][5].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['257'][4].init(132, 15, 'str.length == 7');
function visit16_257_4(result) {
_$jscoverage['/color.js'].branchData['257'][4].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['257'][3].init(113, 15, 'str.length == 4');
function visit15_257_3(result) {
_$jscoverage['/color.js'].branchData['257'][3].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['257'][2].init(113, 34, 'str.length == 4 || str.length == 7');
function visit14_257_2(result) {
_$jscoverage['/color.js'].branchData['257'][2].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['257'][1].init(113, 63, '(str.length == 4 || str.length == 7) && str.substr(0, 1) === \'#\'');
function visit13_257_1(result) {
_$jscoverage['/color.js'].branchData['257'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['152'][1].init(26, 8, 'x in cfg');
function visit12_152_1(result) {
_$jscoverage['/color.js'].branchData['152'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['148'][2].init(88, 24, '"s" in cfg && "l" in cfg');
function visit11_148_2(result) {
_$jscoverage['/color.js'].branchData['148'][2].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['148'][1].init(74, 38, '"h" in cfg && "s" in cfg && "l" in cfg');
function visit10_148_1(result) {
_$jscoverage['/color.js'].branchData['148'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['128'][1].init(26, 8, 'x in cfg');
function visit9_128_1(result) {
_$jscoverage['/color.js'].branchData['128'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['124'][2].init(88, 24, '"s" in cfg && "v" in cfg');
function visit8_124_2(result) {
_$jscoverage['/color.js'].branchData['124'][2].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['124'][1].init(74, 38, '"h" in cfg && "s" in cfg && "v" in cfg');
function visit7_124_1(result) {
_$jscoverage['/color.js'].branchData['124'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['87'][1].init(190, 8, 'g == max');
function visit6_87_1(result) {
_$jscoverage['/color.js'].branchData['87'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['85'][1].init(102, 8, 'r == max');
function visit5_85_1(result) {
_$jscoverage['/color.js'].branchData['85'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['84'][1].init(23, 7, 'l < 0.5');
function visit4_84_1(result) {
_$jscoverage['/color.js'].branchData['84'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['83'][1].init(441, 10, 'min != max');
function visit3_83_1(result) {
_$jscoverage['/color.js'].branchData['83'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['29'][1].init(81, 10, 'hsl.h || 0');
function visit2_29_1(result) {
_$jscoverage['/color.js'].branchData['29'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].branchData['21'][1].init(80, 10, 'hsl.h || 0');
function visit1_21_1(result) {
_$jscoverage['/color.js'].branchData['21'][1].ranCondition(result);
return result;
}_$jscoverage['/color.js'].lineData[6]++;
KISSY.add("color", function(S, Base) {
_$jscoverage['/color.js'].functionData[0]++;
_$jscoverage['/color.js'].lineData[7]++;
var rgbaRe = /\s*rgba?\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*(?:,\s*([\d\.]+))?\)\s*/, hexRe = /\s*#([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)\s*/;
_$jscoverage['/color.js'].lineData[14]++;
var Color = Base.extend({
toHSL: function() {
_$jscoverage['/color.js'].functionData[1]++;
_$jscoverage['/color.js'].lineData[20]++;
var hsl = this.getHSL();
_$jscoverage['/color.js'].lineData[21]++;
return "hsl(" + (Math.round(visit1_21_1(hsl.h || 0))) + ", " + percentage(hsl.s) + ", " + percentage(hsl.l) + ")";
},
'toHSLA': function() {
_$jscoverage['/color.js'].functionData[2]++;
_$jscoverage['/color.js'].lineData[28]++;
var hsl = this.getHSL();
_$jscoverage['/color.js'].lineData[29]++;
return "hsla(" + (Math.round(visit2_29_1(hsl.h || 0))) + ", " + percentage(hsl.s) + ", " + percentage(hsl.l) + ", " + this.get('a') + ")";
},
toRGB: function() {
_$jscoverage['/color.js'].functionData[3]++;
_$jscoverage['/color.js'].lineData[38]++;
var self = this;
_$jscoverage['/color.js'].lineData[39]++;
return "rgb(" + self.get("r") + ", " + self.get("g") + ", " + self.get("b") + ")";
},
toRGBA: function() {
_$jscoverage['/color.js'].functionData[4]++;
_$jscoverage['/color.js'].lineData[46]++;
var self = this;
_$jscoverage['/color.js'].lineData[47]++;
return "rgba(" + self.get("r") + ", " + self.get("g") + ", " + self.get("b") + ", " + self.get("a") + ")";
},
toHex: function() {
_$jscoverage['/color.js'].functionData[5]++;
_$jscoverage['/color.js'].lineData[55]++;
var self = this;
_$jscoverage['/color.js'].lineData[56]++;
return "#" + padding2(Number(self.get("r")).toString(16)) + padding2(Number(self.get("g")).toString(16)) + padding2(Number(self.get("b")).toString(16));
},
toString: function() {
_$jscoverage['/color.js'].functionData[6]++;
_$jscoverage['/color.js'].lineData[64]++;
return this.toRGBA();
},
getHSL: function() {
_$jscoverage['/color.js'].functionData[7]++;
_$jscoverage['/color.js'].lineData[71]++;
var self = this, r = self.get("r") / 255, g = self.get("g") / 255, b = self.get("b") / 255, max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min, h, s = 0, l = 0.5 * (max + min);
_$jscoverage['/color.js'].lineData[83]++;
if (visit3_83_1(min != max)) {
_$jscoverage['/color.js'].lineData[84]++;
s = (visit4_84_1(l < 0.5)) ? delta / (max + min) : delta / (2 - max - min);
_$jscoverage['/color.js'].lineData[85]++;
if (visit5_85_1(r == max)) {
_$jscoverage['/color.js'].lineData[86]++;
h = 60 * (g - b) / delta;
} else {
_$jscoverage['/color.js'].lineData[87]++;
if (visit6_87_1(g == max)) {
_$jscoverage['/color.js'].lineData[88]++;
h = 120 + 60 * (b - r) / delta;
} else {
_$jscoverage['/color.js'].lineData[90]++;
h = 240 + 60 * (r - g) / delta;
}
}
_$jscoverage['/color.js'].lineData[93]++;
h = (h + 360) % 360;
}
_$jscoverage['/color.js'].lineData[95]++;
return {
h: h,
s: s,
l: l};
},
getHSV: function() {
_$jscoverage['/color.js'].functionData[8]++;
_$jscoverage['/color.js'].lineData[107]++;
return rgb2hsv({
r: this.get("r"),
g: this.get("g"),
b: this.get("b")});
},
setHSV: function(cfg) {
_$jscoverage['/color.js'].functionData[9]++;
_$jscoverage['/color.js'].lineData[122]++;
var self = this, current;
_$jscoverage['/color.js'].lineData[124]++;
if (visit7_124_1("h" in cfg && visit8_124_2("s" in cfg && "v" in cfg))) {
} else {
_$jscoverage['/color.js'].lineData[126]++;
current = self.getHSV();
_$jscoverage['/color.js'].lineData[127]++;
S.each(["h", "s", "v"], function(x) {
_$jscoverage['/color.js'].functionData[10]++;
_$jscoverage['/color.js'].lineData[128]++;
if (visit9_128_1(x in cfg)) {
_$jscoverage['/color.js'].lineData[129]++;
current[x] = cfg[x];
}
});
_$jscoverage['/color.js'].lineData[132]++;
cfg = current;
}
_$jscoverage['/color.js'].lineData[134]++;
self.set(hsv2rgb(cfg));
},
'setHSL': function(cfg) {
_$jscoverage['/color.js'].functionData[11]++;
_$jscoverage['/color.js'].lineData[146]++;
var self = this, current;
_$jscoverage['/color.js'].lineData[148]++;
if (visit10_148_1("h" in cfg && visit11_148_2("s" in cfg && "l" in cfg))) {
} else {
_$jscoverage['/color.js'].lineData[150]++;
current = self.getHSL();
_$jscoverage['/color.js'].lineData[151]++;
S.each(["h", "s", "l"], function(x) {
_$jscoverage['/color.js'].functionData[12]++;
_$jscoverage['/color.js'].lineData[152]++;
if (visit12_152_1(x in cfg)) {
_$jscoverage['/color.js'].lineData[153]++;
current[x] = cfg[x];
}
});
_$jscoverage['/color.js'].lineData[156]++;
cfg = current;
}
_$jscoverage['/color.js'].lineData[160]++;
self.set(hsl2rgb(cfg));
}}, {
ATTRS: {
r: {
getter: function(v) {
_$jscoverage['/color.js'].functionData[13]++;
_$jscoverage['/color.js'].lineData[178]++;
return Math.round(v);
},
setter: function(v) {
_$jscoverage['/color.js'].functionData[14]++;
_$jscoverage['/color.js'].lineData[181]++;
return constrain255(v);
}},
g: {
getter: function(v) {
_$jscoverage['/color.js'].functionData[15]++;
_$jscoverage['/color.js'].lineData[198]++;
return Math.round(v);
},
setter: function(v) {
_$jscoverage['/color.js'].functionData[16]++;
_$jscoverage['/color.js'].lineData[201]++;
return constrain255(v);
}},
b: {
getter: function(v) {
_$jscoverage['/color.js'].functionData[17]++;
_$jscoverage['/color.js'].lineData[218]++;
return Math.round(v);
},
setter: function(v) {
_$jscoverage['/color.js'].functionData[18]++;
_$jscoverage['/color.js'].lineData[221]++;
return constrain255(v);
}},
a: {
value: 1,
setter: function(v) {
_$jscoverage['/color.js'].functionData[19]++;
_$jscoverage['/color.js'].lineData[240]++;
return constrain1(v);
}}},
parse: function(str) {
_$jscoverage['/color.js'].functionData[20]++;
_$jscoverage['/color.js'].lineData[252]++;
var values, r, g, b, a = 1;
_$jscoverage['/color.js'].lineData[257]++;
if (visit13_257_1((visit14_257_2(visit15_257_3(str.length == 4) || visit16_257_4(str.length == 7))) && visit17_257_5(str.substr(0, 1) === '#'))) {
_$jscoverage['/color.js'].lineData[258]++;
values = str.match(hexRe);
_$jscoverage['/color.js'].lineData[259]++;
if (visit18_259_1(values)) {
_$jscoverage['/color.js'].lineData[260]++;
r = parseHex(values[1]);
_$jscoverage['/color.js'].lineData[261]++;
g = parseHex(values[2]);
_$jscoverage['/color.js'].lineData[262]++;
b = parseHex(values[3]);
_$jscoverage['/color.js'].lineData[263]++;
if (visit19_263_1(str.length == 4)) {
_$jscoverage['/color.js'].lineData[264]++;
r = paddingHex(r);
_$jscoverage['/color.js'].lineData[265]++;
g = paddingHex(g);
_$jscoverage['/color.js'].lineData[266]++;
b = paddingHex(b);
}
}
} else {
_$jscoverage['/color.js'].lineData[271]++;
values = str.match(rgbaRe);
_$jscoverage['/color.js'].lineData[272]++;
if (visit20_272_1(values)) {
_$jscoverage['/color.js'].lineData[273]++;
r = parseInt(values[1]);
_$jscoverage['/color.js'].lineData[274]++;
g = parseInt(values[2]);
_$jscoverage['/color.js'].lineData[275]++;
b = parseInt(values[3]);
_$jscoverage['/color.js'].lineData[276]++;
a = visit21_276_1(parseFloat(values[4]) || 1);
}
}
_$jscoverage['/color.js'].lineData[280]++;
return (visit22_280_1(typeof r == 'undefined')) ? undefined : new Color({
r: r,
g: g,
b: b,
a: a});
},
'fromHSL': function(cfg) {
_$jscoverage['/color.js'].functionData[21]++;
_$jscoverage['/color.js'].lineData[298]++;
var rgb = hsl2rgb(cfg);
_$jscoverage['/color.js'].lineData[299]++;
rgb.a = cfg.a;
_$jscoverage['/color.js'].lineData[300]++;
return new Color(rgb);
},
fromHSV: function(cfg) {
_$jscoverage['/color.js'].functionData[22]++;
_$jscoverage['/color.js'].lineData[312]++;
var rgb = hsv2rgb(cfg);
_$jscoverage['/color.js'].lineData[313]++;
rgb.a = cfg.a;
_$jscoverage['/color.js'].lineData[314]++;
return new Color(rgb);
}});
_$jscoverage['/color.js'].lineData[320]++;
function to255(v) {
_$jscoverage['/color.js'].functionData[23]++;
_$jscoverage['/color.js'].lineData[321]++;
return v * 255;
}
_$jscoverage['/color.js'].lineData[325]++;
function hsv2rgb(cfg) {
_$jscoverage['/color.js'].functionData[24]++;
_$jscoverage['/color.js'].lineData[326]++;
var h = Math.min(Math.round(cfg.h), 359), s = Math.max(0, Math.min(1, cfg.s)), v = Math.max(0, Math.min(1, cfg.v)), r, g, b, i = Math.floor((h / 60) % 6), f = (h / 60) - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s);
_$jscoverage['/color.js'].lineData[336]++;
switch (i) {
case 0:
_$jscoverage['/color.js'].lineData[338]++;
r = v;
_$jscoverage['/color.js'].lineData[339]++;
g = t;
_$jscoverage['/color.js'].lineData[340]++;
b = p;
_$jscoverage['/color.js'].lineData[341]++;
break;
case 1:
_$jscoverage['/color.js'].lineData[343]++;
r = q;
_$jscoverage['/color.js'].lineData[344]++;
g = v;
_$jscoverage['/color.js'].lineData[345]++;
b = p;
_$jscoverage['/color.js'].lineData[346]++;
break;
case 2:
_$jscoverage['/color.js'].lineData[348]++;
r = p;
_$jscoverage['/color.js'].lineData[349]++;
g = v;
_$jscoverage['/color.js'].lineData[350]++;
b = t;
_$jscoverage['/color.js'].lineData[351]++;
break;
case 3:
_$jscoverage['/color.js'].lineData[353]++;
r = p;
_$jscoverage['/color.js'].lineData[354]++;
g = q;
_$jscoverage['/color.js'].lineData[355]++;
b = v;
_$jscoverage['/color.js'].lineData[356]++;
break;
case 4:
_$jscoverage['/color.js'].lineData[358]++;
r = t;
_$jscoverage['/color.js'].lineData[359]++;
g = p;
_$jscoverage['/color.js'].lineData[360]++;
b = v;
_$jscoverage['/color.js'].lineData[361]++;
break;
case 5:
_$jscoverage['/color.js'].lineData[363]++;
r = v;
_$jscoverage['/color.js'].lineData[364]++;
g = p;
_$jscoverage['/color.js'].lineData[365]++;
b = q;
_$jscoverage['/color.js'].lineData[366]++;
break;
}
_$jscoverage['/color.js'].lineData[369]++;
return {
r: constrain255(to255(r)),
g: constrain255(to255(g)),
b: constrain255(to255(b))};
}
_$jscoverage['/color.js'].lineData[372]++;
function rgb2hsv(cfg) {
_$jscoverage['/color.js'].functionData[25]++;
_$jscoverage['/color.js'].lineData[373]++;
var r = cfg.r / 255, g = cfg.g / 255, b = cfg.b / 255;
_$jscoverage['/color.js'].lineData[377]++;
var h, s, min = Math.min(Math.min(r, g), b), max = Math.max(Math.max(r, g), b), delta = max - min, hsv;
_$jscoverage['/color.js'].lineData[383]++;
switch (max) {
case min:
_$jscoverage['/color.js'].lineData[385]++;
h = 0;
_$jscoverage['/color.js'].lineData[386]++;
break;
case r:
_$jscoverage['/color.js'].lineData[388]++;
h = 60 * (g - b) / delta;
_$jscoverage['/color.js'].lineData[389]++;
if (visit23_389_1(g < b)) {
_$jscoverage['/color.js'].lineData[390]++;
h += 360;
}
_$jscoverage['/color.js'].lineData[392]++;
break;
case g:
_$jscoverage['/color.js'].lineData[394]++;
h = (60 * (b - r) / delta) + 120;
_$jscoverage['/color.js'].lineData[395]++;
break;
case b:
_$jscoverage['/color.js'].lineData[397]++;
h = (60 * (r - g) / delta) + 240;
_$jscoverage['/color.js'].lineData[398]++;
break;
}
_$jscoverage['/color.js'].lineData[401]++;
s = (visit24_401_1(max === 0)) ? 0 : 1 - (min / max);
_$jscoverage['/color.js'].lineData[403]++;
hsv = {
h: Math.round(h),
s: s,
v: max};
_$jscoverage['/color.js'].lineData[409]++;
return hsv;
}
_$jscoverage['/color.js'].lineData[412]++;
function hsl2rgb(cfg) {
_$jscoverage['/color.js'].functionData[26]++;
_$jscoverage['/color.js'].lineData[413]++;
var h = Math.min(Math.round(cfg.h), 359), s = Math.max(0, Math.min(1, cfg.s)), l = Math.max(0, Math.min(1, cfg.l)), C, X, m, rgb = [], abs = Math.abs, floor = Math.floor;
_$jscoverage['/color.js'].lineData[420]++;
if (visit25_420_1(visit26_420_2(s == 0) || visit27_420_3(h == null))) {
_$jscoverage['/color.js'].lineData[422]++;
rgb = [l, l, l];
} else {
_$jscoverage['/color.js'].lineData[428]++;
h /= 60;
_$jscoverage['/color.js'].lineData[429]++;
C = s * (1 - abs(2 * l - 1));
_$jscoverage['/color.js'].lineData[430]++;
X = C * (1 - abs(h - 2 * floor(h / 2) - 1));
_$jscoverage['/color.js'].lineData[431]++;
m = l - C / 2;
_$jscoverage['/color.js'].lineData[432]++;
switch (floor(h)) {
case 0:
_$jscoverage['/color.js'].lineData[434]++;
rgb = [C, X, 0];
_$jscoverage['/color.js'].lineData[435]++;
break;
case 1:
_$jscoverage['/color.js'].lineData[437]++;
rgb = [X, C, 0];
_$jscoverage['/color.js'].lineData[438]++;
break;
case 2:
_$jscoverage['/color.js'].lineData[440]++;
rgb = [0, C, X];
_$jscoverage['/color.js'].lineData[441]++;
break;
case 3:
_$jscoverage['/color.js'].lineData[443]++;
rgb = [0, X, C];
_$jscoverage['/color.js'].lineData[444]++;
break;
case 4:
_$jscoverage['/color.js'].lineData[446]++;
rgb = [X, 0, C];
_$jscoverage['/color.js'].lineData[447]++;
break;
case 5:
_$jscoverage['/color.js'].lineData[449]++;
rgb = [C, 0, X];
_$jscoverage['/color.js'].lineData[450]++;
break;
}
_$jscoverage['/color.js'].lineData[452]++;
rgb = [rgb[0] + m, rgb[1] + m, rgb[2] + m];
}
_$jscoverage['/color.js'].lineData[454]++;
S.each(rgb, function(v, index) {
_$jscoverage['/color.js'].functionData[27]++;
_$jscoverage['/color.js'].lineData[455]++;
rgb[index] = to255(v);
});
_$jscoverage['/color.js'].lineData[457]++;
return {
r: rgb[0],
g: rgb[1],
b: rgb[2]};
}
_$jscoverage['/color.js'].lineData[464]++;
function parseHex(v) {
_$jscoverage['/color.js'].functionData[28]++;
_$jscoverage['/color.js'].lineData[465]++;
return parseInt(v, 16);
}
_$jscoverage['/color.js'].lineData[468]++;
function paddingHex(v) {
_$jscoverage['/color.js'].functionData[29]++;
_$jscoverage['/color.js'].lineData[469]++;
return v + v * 16;
}
_$jscoverage['/color.js'].lineData[472]++;
function padding2(v) {
_$jscoverage['/color.js'].functionData[30]++;
_$jscoverage['/color.js'].lineData[473]++;
if (visit28_473_1(v.length != 2)) {
_$jscoverage['/color.js'].lineData[474]++;
v = "0" + v;
}
_$jscoverage['/color.js'].lineData[476]++;
return v;
}
_$jscoverage['/color.js'].lineData[479]++;
function percentage(v) {
_$jscoverage['/color.js'].functionData[31]++;
_$jscoverage['/color.js'].lineData[480]++;
return Math.round(v * 100) + "%";
}
_$jscoverage['/color.js'].lineData[483]++;
function constrain255(v) {
_$jscoverage['/color.js'].functionData[32]++;
_$jscoverage['/color.js'].lineData[484]++;
return Math.max(0, Math.min(v, 255));
}
_$jscoverage['/color.js'].lineData[487]++;
function constrain1(v) {
_$jscoverage['/color.js'].functionData[33]++;
_$jscoverage['/color.js'].lineData[488]++;
return Math.max(0, Math.min(v, 1));
}
_$jscoverage['/color.js'].lineData[493]++;
return Color;
}, {
requires: ['base']});
|
C# | UTF-8 | 3,193 | 2.515625 | 3 | [] | no_license | using Application.Interfaces;
using Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Application.Commands.Customers
{
public class NewCustomerCommand
{
public async Task RunAsync(IBankDbContext context, NewCustomerCommandModel model)
{
var foundCustomer = context.Customers.SingleOrDefault(c => c.CustomerId == model.CustomerId);
if (foundCustomer == null)
{
var customer = NewCustomer(model);
await context.Customers.AddAsync(customer);
await context.SaveChangesAsync(new System.Threading.CancellationToken());
Account account = new Account()
{
Balance = 0,
Created = DateTime.Now,
Frequency = "Monthly"
};
await context.Accounts.AddAsync(account);
await context.SaveChangesAsync(new System.Threading.CancellationToken());
Disposition disposition = new Disposition()
{
Account = account,
Customer = customer,
Type = "Owner"
};
await context.Dispositions.AddAsync(disposition);
}
else
{
EditCustomer(foundCustomer, model);
}
await context.SaveChangesAsync(new System.Threading.CancellationToken());
}
// Helpers
private void EditCustomer(Customer foundCustomer, NewCustomerCommandModel model)
{
foundCustomer.Birthday = model.Birthday;
foundCustomer.City = model.City;
foundCustomer.Country = model.Country;
foundCustomer.CountryCode = model.CountryCode;
foundCustomer.Emailaddress = model.Emailaddress;
foundCustomer.Gender = model.Gender;
foundCustomer.Givenname = model.Givenname;
foundCustomer.Surname = model.Surname;
foundCustomer.Streetaddress = model.Streetaddress;
foundCustomer.NationalId = model.NationalId;
foundCustomer.Telephonecountrycode = model.Telephonecountrycode;
foundCustomer.Telephonenumber = model.Telephonenumber;
foundCustomer.Zipcode = model.Zipcode;
}
private Customer NewCustomer(NewCustomerCommandModel model)
{
return new Customer()
{
Birthday = model.Birthday,
City = model.City,
Country = model.Country,
CountryCode = model.CountryCode,
Emailaddress = model.Emailaddress,
Gender = model.Gender,
Givenname = model.Givenname,
Surname = model.Surname,
Streetaddress = model.Streetaddress,
NationalId = model.NationalId,
Telephonecountrycode = model.Telephonecountrycode,
Telephonenumber = model.Telephonenumber,
Zipcode = model.Zipcode
};
}
}
} |
C | UTF-8 | 7,363 | 2.921875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <sys/param.h> // For system parameters
#include <sys/errno.h> // For system calls and error numbers
#include <unistd.h> // For getopt universal routines
#include <time.h> // For time functions
#include <stdio.h> // For standard io routines
#include <stdlib.h> // For standard library functions
#include <string.h> // For string functions
#include <signal.h> // For simplified software signal facilities
typedef enum {FALSE, TRUE} Bool;
#define minAmount 256
#define DEFAULT_TMP_FILENAME "0slask0.zro"
#define DEFAULT_BLKSIZE 4096
char *tmpFilename = DEFAULT_TMP_FILENAME;
size_t blockSize = DEFAULT_BLKSIZE; // Amount of zeroes to write at each pass
Bool quiet = FALSE; // No progress report during zeroing, a bit faster
FILE *fid;
//***********************************************************************
//
// showHelp
//
// Description:
// This procedure gives the correct syntax of the input command
//
// Parameters:
// ( char * ) program - This programs name, usually argv[ 0 ]
//
// Returns:
// ( void )
//***********************************************************************/
void showHelp( program )
char *program;
{
system( "clear" );
fprintf( stdout, "%s -q -b < blkdSize > [ tempFile ]\n\n", program );
fprintf( stdout, " Description: \n" );
fprintf( stdout, "\n" );
fprintf( stdout, " A simple command line tool that fills FREE space on a disk with zeroes by\n" );
fprintf( stdout, " filling a temporary file and then removing it.\n" );
fprintf( stdout, "\n" );
fprintf( stdout, " Algorithm: ( kindly taken from: https://github.com/nollan/zerofile with his permission )\n" );
fprintf( stdout, "\n" );
fprintf( stdout, " The file is filled 4096 bytes at the time ( blocksize ), and halves\n" );
fprintf( stdout, " it when disk space is to small for 4096 bytes. So next time it's 2048\n" );
fprintf( stdout, " and so on, until it's less than 256 when it will remove the tempfile and\n" );
fprintf( stdout, " exit. The reason for halving is to really fill up all the free space with\n" );
fprintf( stdout, " zeroes. If the selected block size is larger than the file system block\n" );
fprintf( stdout, " size the halving is not really usefull\n" );
fprintf( stdout, "\n" );
fprintf( stdout, " Note: CTRL-C kills and cleans up automatically\n" );
fprintf( stdout, "\n\n" );
fprintf( stdout, " %s recognizes the following options:\n\n", program );
fprintf( stdout, " -q => No progress report during zeroing, a bit faster\n" );
fprintf( stdout, " -b < blkSize > => Amount of zeroes to write at each pass. Default: %u\n", DEFAULT_BLKSIZE );
fprintf( stdout, " [ tempFilename ] => Temporary file used. Defaults to: %s\n", DEFAULT_TMP_FILENAME );
}
//****************************************************************************
//
// parseCommandLineOptions
//
// Description:
// This procedure takes all the command line options passed to main line.
//
// Parameters:
// ( int * ) argc - The number of command line arguments passed
// to this procedure.
// ( char** ) argv - List of command line options specified by the user.
//
// Updates Globals:
// ( Bool ) quiet - No progress report during zeroing, a bit faster.
// ( size_t ) blockSize - The amount of zeroes to write at each pass.
// ( char* ) tmpFilename - The Temporary file name to use.
//
// Returns:
// ( void )
//*************************************************************************/
void parseCommandLineOptions( int *argc, char *argv[ ] )
{
int opt;
extern char *optarg;
extern int optind;
// Check for options passed in
while ( ( opt = getopt( *argc, argv, "hqb:" ) ) != -1 )
{
switch ( opt )
{
case 'h':
showHelp( argv[ 0 ] );
exit( 0 );
case 'q':
quiet = TRUE;
break;
case 'b':
blockSize = strtoul( argv[ optind ], NULL, 10 ) ;
if ( errno == EINVAL )
{
fprintf( stderr, "Cannot convert %s to unsigned long. error: %d\n", argv[ optind ], errno );
exit( errno );
}
break;
case '?':
default:
showHelp( argv[ 0 ] );
fprintf( stderr, "Error: Unknown option given %c.\n", opt );
exit( 666 );
}
}
// Temp-file selection
if ( *argc > optind )
tmpFilename = argv[ optind ];
}
// Cleanup, remove tempfile
void cleanup( )
{
fprintf( stdout, "Removing temp-file ... " );
fclose( fid );
if ( unlink( tmpFilename ) != 0 )
{
fprintf( stderr, "error: %d\n", errno );
exit( errno );
}
fprintf( stdout, "Done\n" );
}
void intHandler( )
{
if ( ! quiet )
fprintf( stdout, "\n" );
fprintf( stdout, "Cleaning up" );
cleanup( );
exit( 1 );
}
//***********************************************************************
//
// main
//
// Description:
//
// Returns:
// 0 if successfull, otherwise errno.
//***********************************************************************/
int main( int argc, char *argv[ ] )
{
time_t startTime, endTime;
double diff_t;
char* bunchOfZeroes;
// Keep score of bytes written
long bytesWritten = 0;
long totalBytesWritten = 0;
// Keep score of when started
time( &startTime );
// Well, parse the flags! :)
parseCommandLineOptions( &argc, argv );
// Handle ctrl-c and kills
signal( SIGINT, intHandler );
signal( SIGTERM, intHandler );
// Make some zeroes
bunchOfZeroes = ( char * ) calloc( blockSize, sizeof( char * ) );
fid = fopen( tmpFilename, "w" );
if ( fid == NULL )
{
fprintf( stderr, "error: %d\n", errno );
exit ( errno );
}
fprintf( stdout, "Using tempfile: '%s'\n", tmpFilename );
// Amount to write at each pass
size_t amount = blockSize;
for ( ; ; )
{
// Write zeroes up to amount ( which is equal or less than blockSize )
size_t bytesWritten = fwrite( bunchOfZeroes, 1, amount, fid );
if ( bytesWritten != amount )
{
// Check for no more space left on device
if ( errno == ENOSPC )
{
// if not all of the amount is written, halve it and try again
// in case of very large blockSize.
if ( bytesWritten != amount )
amount /= 2;
// Limit of amount size, disk buffer size is normally larger
if ( amount < minAmount )
break;
} else
{
// Other error
cleanup( );
fprintf( stderr, "error: %d\n", errno );
exit( errno );
}
}
// Update stats
totalBytesWritten += bytesWritten;
// Keep quiet if wanted
if ( ! quiet )
fprintf( stdout, "Written: %zu bytes \r", totalBytesWritten );
}
// Print some stats
if ( ! quiet )
fprintf( stdout, "\n" );
time( &endTime );
diff_t = difftime( endTime, startTime );
fprintf( stdout, "Duration: %f ; Performance: %.3f bytes/sec\n",
diff_t,
totalBytesWritten / diff_t );
cleanup( );
exit( 0 );
}
|
Java | UTF-8 | 542 | 2.21875 | 2 | [] | no_license | public class NhanVienDaoTao extends NhanVien{
private String nganh;
public NhanVienDaoTao(String ten, int tuoi, String gioi_tinh, String sdt, String email, double luong, String nganh) {
super(ten, tuoi, gioi_tinh, sdt, email, luong);
this.nganh = nganh;
}
public String getNganh() {
return nganh;
}
public void setNganh(String nganh) {
this.nganh = nganh;
}
@Override
public String toString() {
return super.toString()+','+ nganh ;
}
}
|
Java | UTF-8 | 10,067 | 1.929688 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2020 comp500
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package link.infra.bundle.server;
import link.infra.bundle.server.jimfs.Handler;
import link.infra.bundle.server.jimfs.ShimJimfsFileSystemProvider;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Properties;
public class Main {
private static final String VERSION = Main.class.getPackage().getImplementationVersion();
private static final String USER_AGENT = "bundle-server-launcher/" + VERSION;
private static final String DEF_SERVER_JAR_PATH = ".fabric/bundle-cache/server.jar";
private static final int MAX_DOWNLOAD_TRIES = 3;
public static void main(String[] args) {
Properties launcherProps = new Properties();
// Read properties from own JAR
try (InputStream is = Main.class.getClassLoader().getResourceAsStream("bundle-server-launcher.properties")) {
if (is == null) {
throw new FileNotFoundException("bundle-server-launcher.properties");
}
launcherProps.load(is);
} catch (IOException e) {
System.err.println("Failed to load bundle-server-launcher included properties:");
e.printStackTrace();
System.err.println("The launcher jar is corrupt, please redownload it!");
System.exit(1);
}
// Properties can be overridden; bundle-server-launcher takes priority over fabric-server-launcher
Path bundlePropPath = Paths.get("bundle-server-launcher.properties");
Path fabricPropPath = Paths.get("fabric-server-launcher.properties");
if (Files.exists(bundlePropPath)) {
try (BufferedReader br = Files.newBufferedReader(bundlePropPath)) {
launcherProps.load(br);
} catch (NoSuchFileException ignored) {
// Ignored
} catch (IOException e) {
System.err.println("Failed to read configuration file bundle-server-launcher.properties:");
e.printStackTrace();
System.exit(1);
}
} else if (Files.exists(fabricPropPath)) {
String origServerPath = launcherProps.getProperty("serverJar", DEF_SERVER_JAR_PATH);
// Try to read from fabric-server-launcher, and copy serverJar into bundle-server-launcher to preserve it
try (BufferedReader br = Files.newBufferedReader(fabricPropPath)) {
launcherProps.load(br);
} catch (NoSuchFileException ignored) {
// Ignored
} catch (IOException e) {
System.err.println("Failed to read configuration file fabric-server-launcher.properties:");
e.printStackTrace();
System.exit(1);
}
if (!origServerPath.equals(launcherProps.getProperty("serverJar", origServerPath))) {
try (BufferedWriter bw = Files.newBufferedWriter(bundlePropPath)) {
Properties overrideProps = new Properties();
overrideProps.put("serverJar", launcherProps.getProperty("serverJar"));
overrideProps.store(bw, "Bundle server launcher properties - Delete this file to use the default location");
} catch (IOException e) {
System.err.println("Failed to save configuration file bundle-server-launcher.properties:");
e.printStackTrace();
System.exit(1);
}
}
}
String mainClass = launcherProps.getProperty("launch.mainClass");
URL serverJarUrl = null;
try {
serverJarUrl = new URI(launcherProps.getProperty("serverJarUrl")).toURL();
} catch (MalformedURLException | URISyntaxException e) {
System.err.println("Invalid value of serverJarUrl: " + launcherProps.getProperty("serverJarUrl"));
e.printStackTrace();
System.exit(1);
}
byte[] serverJarHash = hexToBytes(launcherProps.getProperty("serverJarHash"));
// Should work backwards-compatible with fabric-server-launcher
Path serverJar = Paths.get(launcherProps.getProperty("serverJar", DEF_SERVER_JAR_PATH));
boolean valid = false;
try {
verifyMinecraftJar(serverJar, serverJarHash);
valid = true;
} catch (InvalidHashException e) {
System.out.println("Minecraft jar has invalid hash (expected " + e.expectedHash + ", found " + e.hashFound
+ ") attempting to download...");
} catch (NoSuchFileException e) {
System.out.println("Downloading Minecraft jar...");
} catch (IOException e) {
System.out.println("Minecraft jar could not be read, attempting to download...");
}
if (!valid) {
for (int i = 0; i < MAX_DOWNLOAD_TRIES; i++) {
try {
downloadMinecraftJar(serverJarUrl, serverJar);
verifyMinecraftJar(serverJar, serverJarHash);
valid = true;
System.out.println("Successfully downloaded Minecraft jar!");
break;
} catch (InvalidHashException e) {
System.err.println("Downloaded Minecraft jar has invalid hash (expected " + e.expectedHash + ", found "
+ e.hashFound + ")");
} catch (IOException e) {
System.err.println("Download failed!");
e.printStackTrace();
}
if (i < MAX_DOWNLOAD_TRIES - 1) {
System.out.println("Retrying... (" + (i + 1) + "/" + (MAX_DOWNLOAD_TRIES - 1) + ")");
}
}
}
if (!valid) {
System.err.println("Failed to download or validate the Minecraft jar!");
System.err.println("If you are lacking a direct internet connection, you can download it from:");
System.err.println(" " + serverJarUrl);
System.err.println("and place it at " + serverJar);
System.err.println("It should have the following SHA-1 hash: " + bytesToHex(serverJarHash));
System.exit(1);
}
System.setProperty("fabric.gameJarPath", serverJar.toAbsolutePath().toString());
URL serverJarFileUrl = null;
try {
serverJarFileUrl = serverJar.toUri().toURL();
} catch (MalformedURLException e) {
System.err.println("Invalid path for server jar: " + serverJar);
e.printStackTrace();
System.exit(1);
}
// Set the parent classloader to the parent of the AppClassLoader
// This will be ExtClassLoader on Java 8 or older, PlatformClassLoader on Java 9 or newer - ensures extension classes will work
URLClassLoader gameLoader = new URLClassLoader(new URL[] {
serverJarFileUrl,
Main.class.getProtectionDomain().getCodeSource().getLocation()
}, ClassLoader.getSystemClassLoader().getParent());
// Register the jimfs URL handler shim and FileSystemProvider shim
Handler.register(gameLoader);
ShimJimfsFileSystemProvider.initialize(gameLoader);
Thread.currentThread().setContextClassLoader(gameLoader);
try {
Class<?> clazz = gameLoader.loadClass(mainClass);
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, (Object) args);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Failed to load the Fabric class", e);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Failed to load the Fabric main method", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to call the Fabric main method", e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
}
}
private static class InvalidHashException extends IOException {
public final String expectedHash;
public final String hashFound;
InvalidHashException(String expectedHash, String hashFound) {
this.expectedHash = expectedHash;
this.hashFound = hashFound;
}
}
private static void verifyMinecraftJar(Path serverJar, byte[] serverJarHash) throws IOException {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to verify Minecraft server JAR", e);
}
// TODO: change to a stream?
byte[] foundHash = digest.digest(Files.readAllBytes(serverJar));
if (!Arrays.equals(foundHash, serverJarHash)) {
throw new InvalidHashException(bytesToHex(serverJarHash), bytesToHex(foundHash));
}
}
private static void downloadMinecraftJar(URL serverJarUrl, Path serverJar) throws IOException {
Files.createDirectories(serverJar.getParent());
URLConnection conn = serverJarUrl.openConnection();
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept", "application/octet-stream");
// 2 minute read/connect timeouts
conn.setConnectTimeout(2 * 60 * 1000);
conn.setReadTimeout(2 * 60 * 1000);
try (InputStream in = conn.getInputStream()) {
Files.copy(in, serverJar, StandardCopyOption.REPLACE_EXISTING);
}
}
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hexToBytes(String s) {
int len = s.length();
if (len % 2 != 0) throw new RuntimeException("Invalid hash " + s);
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
}
|
Python | UTF-8 | 2,989 | 3.375 | 3 | [] | no_license | #sử dụng một trong các hàm sắp xếp sau:
# nổi bọt
def bubbleSort(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
swapped = True
x = -1
while swapped:
swapped = False
x = x + 1
for i in range(1, n-x):
if arr[i - 1] > arr[i]:
swap(i - 1, i)
swapped = True
return arr
#sắp xếp chọn
def selectionSort(arr):
for i in range(len(arr)):
minimum = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minimum]:
minimum = j
arr[minimum], arr[i] = arr[i], arr[minimum]
return arr
#sắp xếp chèn
def insertionSort(arr):
for i in range(len(arr)):
cursor = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > cursor:
arr[pos] = arr[pos - 1]
pos = pos - 1
arr[pos] = cursor
return arr
#Sắp xếp trộn
def mergeSort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left, right = mergeSort(arr[:mid]), mergeSort(arr[mid:])
return merge(left, right, arr.copy())
def merge(left, right, merged):
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
if left[left_cursor] <= right[right_cursor]:
merged[left_cursor+right_cursor]=left[left_cursor]
left_cursor += 1
else:
merged[left_cursor + right_cursor] = right[right_cursor]
right_cursor += 1
for left_cursor in range(left_cursor, len(left)):
merged[left_cursor + right_cursor] = left[left_cursor]
for right_cursor in range(right_cursor, len(right)):
merged[left_cursor + right_cursor] = right[right_cursor]
return merged
#quick sort
def partition(array, begin, end):
pivot_idx = begin
for i in range(begin+1, end+1):
if array[i] <= array[begin]:
pivot_idx += 1
array[i], array[pivot_idx] = array[pivot_idx], array[i]
array[pivot_idx], array[begin] = array[begin], array[pivot_idx]
return pivot_idx
def quick_sort_recursion(array, begin, end):
if begin >= end:
return
pivot_idx = partition(array, begin, end)
quick_sort_recursion(array, begin, pivot_idx-1)
quick_sort_recursion(array, pivot_idx+1, end)
def quick_sort(array, begin=0, end=None):
if end is None:
end = len(array) - 1
return quick_sort_recursion(array, begin, end)
f=open("b1-anhca.inp")
n=list(map(lambda x:int(x),f.readline().strip()))
f.close()
print(n)
# sắp xếp
bubbleSort(n)
#n.reverse() một là sử dụng cái này để đảo ngược lại thứ tự, hai là sư dụng n[::-1]
print(n)
#ghi file
f=open("b1-anhca.out","w",encoding="UTF8")
f.write("".join(list(map(lambda x:str(x),n[::-1]))))
f.close() |
Rust | UTF-8 | 5,932 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | //! Argument and parameter types used by Network service Commands and Responses
use atat::atat_derive::AtatEnum;
use heapless::String;
/// Is used to chose whether the network selection is automatically done by the
/// MT or is forced by this command to the operator <oper> given in the format
/// <format>
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum OperatorSelectionMode {
/// • 0 (default value and factory-programmed value): automatic (<oper> field is ignored)
Automatic = 0,
/// • 1: manual
Manual = 1,
/// • 2: deregister from network
Deregister = 2,
/// • 3: set only <format>
FormatOnly = 3,
/// • 4: manual/automatic
ManualAutomatic = 4,
/// • 5: extended network search
ExtendedNetworkSearch = 5,
/// • 6: extended network search without the tags (e.g. MCC, RxLev will not be printed,
/// see the syntax and the command example)
ExtendedNetworkSearchWithoutTags = 6,
/// • 8: network timing advance search
NetworkTimingAdvanceSearch = 8,
#[at_arg(default)]
Unknown,
}
/// Indicates the radio access technology
#[derive(Debug, Clone, Copy, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RatAct {
/// • 0: GSM
Gsm = 0,
/// • 1: GSM COMPACT
GsmCompact = 1,
/// • 2: UTRAN
Utran = 2,
/// • 3: GSM/GPRS with EDGE availability
GsmGprsEdge = 3,
/// • 4: UTRAN with HSDPA availability
UtranHspda = 4,
/// • 5: UTRAN with HSUPA availability
UtranHsupa = 5,
/// • 6: UTRAN with HSDPA and HSUPA availability
UtranHspdaHsupa = 6,
/// • 7: LTE
Lte = 7,
/// • 8: EC-GSM-IoT (A/Gb mode)
EcGsmIot = 8,
/// • 9: E-UTRAN (NB-S1 mode)
Eutran = 9,
#[at_arg(default)]
Unknown = 10,
}
#[derive(Clone, PartialEq, Eq, AtatEnum)]
pub enum NetworkRegistrationUrcConfig {
/// • 0 (default value and factory-programmed value): network registration URC disabled
UrcDisabled = 0,
/// • 1: network registration URC +CREG: <stat> enabled
UrcEnabled = 1,
/// • 2: network registration and location information URC +CREG: <stat>[,<lac>,<ci>[,
/// <AcTStatus>]] enabled
UrcVerbose = 2,
}
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum NetworkRegistrationStat {
/// • 0: not registered, the MT is not currently searching a new operator to register to
NotRegistered = 0,
/// • 1: registered, home network
Registered = 1,
/// • 2: not registered, but the MT is currently searching a new operator to register to
NotRegisteredSearching = 2,
/// • 3: registration denied
RegistrationDenied = 3,
/// • 4: unknown (e.g. out of GERAN/UTRAN/E-UTRAN coverage)
Unknown = 4,
/// • 5: registered, roaming
RegisteredRoaming = 5,
/// • 6: registered for "SMS only", home network (applicable only when <AcTStatus>
/// indicates E-UTRAN)
RegisteredSmsOnly = 6,
/// • 7: registered for "SMS only", roaming (applicable only when <AcTStatus> indicates
/// E-UTRAN)
RegisteredSmsOnlyRoaming = 7,
/// • 9: registered for "CSFB not preferred", home network (applicable only when
/// <AcTStatus> indicates E-UTRAN)
RegisteredCsfbNotPerferred = 9,
/// • 10: registered for "CSFB not preferred", roaming (applicable only when <AcTStatus>
/// indicates E-UTRAN)
RegisteredCsfbNotPerferredRoaming = 10,
}
/// Indicates the preferred access technology
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RatPreferred {
/// • 0: GSM / GPRS / eGPRS
GsmGprsEgprs = 0,
/// • 2: UTRAN
Utran = 2,
/// • 3: LTE
Lte = 3,
}
/// Indicates the radio access technology
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RadioAccessTechnologySelected {
/// • 0: GSM / GPRS / eGPRS (single mode)
#[at_arg(value = 0)]
GsmGprsEGprs,
/// • 1: GSM / UMTS (dual mode)
#[at_arg(value = 1)]
GsmUmts(RatPreferred),
/// • 2: UMTS (single mode)
#[at_arg(value = 2)]
Umts,
/// • 3: LTE (single mode)
#[at_arg(value = 3)]
Lte,
/// • 4: GSM / UMTS / LTE (tri mode)
#[at_arg(value = 4)]
GsmUmtsLte(RatPreferred, RatPreferred),
/// • 5: GSM / LTE (dual mode)
#[at_arg(value = 5)]
GsmLte(RatPreferred),
/// • 6: UMTS / LTE (dual mode)
#[at_arg(value = 6)]
UmtsLte(RatPreferred),
}
/// Indicates the radio access technology
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg(feature = "lara-r6")]
pub enum FirstRadioAccessTechnology {
/// • 0: GSM / GPRS / eGPRS (single mode)
#[at_arg(value = 0)]
GsmGprsEGprs,
/// • 2: UMTS (single mode)
#[at_arg(value = 2)]
Umts,
/// • 3: LTE (single mode)
#[at_arg(value = 3)]
Lte,
}
/// Indicates the radio access technology
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg(feature = "lara-r6")]
pub enum SecondRadioAccessTechnology {
/// • 2: UMTS (single mode)
#[at_arg(value = 2)]
Umts,
}
/// Indicates the radio access technology
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg(feature = "lara-r6")]
pub enum ThirdRadioAccessTechnology {
/// • 0: GSM / GPRS / eGPRS (single mode)
#[at_arg(value = 0)]
GsmGprsEGprs,
}
#[derive(Debug, Clone, PartialEq, Eq, AtatEnum)]
pub enum OperatorNameFormat {
#[at_arg(value = 0)]
Long(String<24>),
#[at_arg(value = 1)]
Short(String<10>),
#[at_arg(value = 2)]
Numeric(String<6>),
}
|
C++ | UTF-8 | 1,505 | 3.734375 | 4 | [] | no_license | /* 演習 03-23-02
* list03-16を平均も求めるように書き換え
* 作成日:5月3日
* 作成者:成田修之
* 更新日:5月10日
* 更新者:成田修之
*/
#include<iostream>
using namespace std;
int main()
{
int nCount; //加算する個数の入力で使う変数
//加算する個数の入力を促す表示
cout << "整数を加算します。\n何個加算しますか:";
//キーボードから入力
cin >> nCount;
int nSum; //合計を求めるのに必要な変数
int i = 0; //後で使うのでfor文の中で宣言しないであらかじめ宣言しておく
int nInput; //値の入力に使う変数
//iが最大個数以下かつ合計が1000以下限り繰り返す
for( ; i < nCount && nSum <= 1000; i++) {
//繰り返すたびにに入力に使う変数を0でリセット
nInput = 0;
//整数の入力を促す表示
cout <<"整数:";
//キーボードから入力
cin >> nInput;
//合計に加算して代入する
nSum += nInput;
}
//合計が1000を超えている場合
if(nSum > 1000) {
cout <<"合計が1000を超えました。\n最後の数値は無視します。\n";
//最後に入力した値を引いて代入
nSum -= nInput;
//最後の数は分母に含めないので
i--;
}
//break文によって途中で終わることがあるので数値の個数は繰り返した数(i)
cout << "合計は" << nSum <<"で平均は"<<nSum / i << "です。\n";
//main関数の返却値0
return 0;
}
|
SQL | UTF-8 | 410 | 4.0625 | 4 | [] | no_license | CREATE DEFINER=`root`@`localhost` PROCEDURE `incomesVsExpensesByMonths`(IN Id INT)
BEGIN
SELECT month.month, SUM(month.income) AS incomes, SUM(month.expenses) AS expences
FROM monthlyaccounts AS month
JOIN annualcounts AS year ON month.idannualcounts = year.idannualcounts
JOIN condominium AS cond ON year.idcondom = cond.idcondom
WHERE year.year = year AND cond.idcondom = Id
GROUP BY month.month;
END |
Markdown | UTF-8 | 616 | 2.609375 | 3 | [] | no_license | 3D-Terrain-Visualizer
=====================
_3D Terrain Visualizer_ created using _JavaScript_ and _WebGL_. Takes input in the form of either manual input or a file containing indexes and values on a matrix Grid. After the input is recieved the program interpolates a Height Grid using Laplace's Finitie differential equation with the Neumann boundary condition to create a 3D model from the input.

__N.B.__
The program is created just for __learning purposes__ and may contain bugs or bad practices the owner is not aware of :)
|
Markdown | UTF-8 | 1,226 | 3.703125 | 4 | [] | no_license | # ES 7
## async & await
async 是一个修饰符
async 定义的函数会默认的返回一个Promise对象resolve的值,因此对async函数可以直接进行then操作,返回的值即为then方法的传入函数
await 也是一个修饰符
await 关键字只能放在 async 函数内部, await 关键字的作用就是获取 Promise中返回的内容, 获取的是Promise函数中resolve或者reject的值
如果await 后面并不是一个Promise的返回值,则会按照同步程序返回值处理
关于async & await中的错误捕获
既然.then(..)不用写了,那么.catch(..)也不用写,可以直接用标准的try catch语法捕捉错误
```js
var sleep = function (time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
// 模拟出错了,返回 ‘error’
reject('error');
}, time);
})
};
var start = async function () {
try {
console.log('start');
await sleep(3000); // 这里得到了一个返回错误
// 所以以下代码不会被执行了
console.log('end');
} catch (err) {
console.log(err); // 这里捕捉到错误 `error`
}
};
``` |
Java | UTF-8 | 1,229 | 2.28125 | 2 | [] | no_license | package cinema.main.action;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import cinema.dbaccess.DBAccess;
import cinema.domain.pojo.Movie;
import cinema.util.Constants;
public class SearchProvider implements Constants
{
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(SearchProvider.class);
private static final Gson gson = new Gson();
public SearchProvider()
{
}
public static void GetSearchList(HttpSession sessionObj) throws Exception
{
try
{
logger.info("[Executing::" + SearchProvider.class + "]");
DBAccess dbObj = new DBAccess();
List<Movie> movieList = dbObj.getAllMovie();
String movieNames[] = new String[movieList.size()];
int counter = 0;
Iterator<Movie> mIterator = movieList.iterator();
while (mIterator.hasNext())
{
movieNames[counter] = mIterator.next().getMovieName();
counter++;
}
sessionObj.setAttribute(SEARCH_HANDLE, gson.toJson(movieNames));
}
catch (Exception ex)
{
logger.info("Exception in GetSearchList(HttpSession sessionObj)");
}
}
} |
JavaScript | UTF-8 | 3,996 | 2.875 | 3 | [] | no_license | import React, { useState } from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import Container from "@material-ui/core/Container";
import axios from "axios";
import Header from "./components/Header";
import Country from "./components/Country";
import Loading from "./components/Loading";
import CountrySearch from "./components/CountrySearch";
import Converter from "./components/Converter";
const App = () => {
const [searchInput, setSearchInput] = useState("");
const [country, setCountry] = useState();
const [error, setError] = useState(false);
const [searching, setSearching] = useState(false);
//currencyKey: Variable to hold currency "code" ex, DK (denmark)
//setCurrencyKey: Sets the currencyKey from the API (https://restcountries.eu/rest/v2/name/${searchInput})
const [currencyKey, setCurrencyKey] = useState("");
//fromCurrency: Currency that we convert from, now its always from Sweden (SEK)
const [fromCurrency] = useState("SEK");
//Result: Variable to hold the Converted Result
//setResult: Sets the Result from the response we get from API (https://api.exchangeratesapi.io/latest?base=${fromCurrency}&symbols=${currencyKey})
const [result, setResult] = useState();
//currency: The value that we want to convert (from SEK) default always 0.
//setCurrencyValue: Set the currencyValue from input.
const [currencyValue, setCurrencyValue] = useState(0);
const search = async () => {
setSearching(true);
setError(false);
try {
const result = await axios.get(
`https://restcountries.eu/rest/v2/name/${searchInput}`
);
setCountry(result.data[0]);
//Set the Currency key from the country we search for e.x (Denmark will have key "DK")
setCurrencyKey(result.data[0].currencies[0].code);
} catch (error) {
setError(true);
}
setSearching(false);
};
const convertHandler = e => {
e.preventDefault();
//check that our fromCurrency (SEK) is not the same as the value we want to convert to
if (fromCurrency !== currencyKey) {
axios
.get(
//fromCurrency (SEK), currencyKey (what we search for)
`https://api.exchangeratesapi.io/latest?base=${fromCurrency}&symbols=${currencyKey}`
)
.then(response => {
//currencyValue: the value from our input
//currencyKey Key from the country we search for
const result = currencyValue * response.data.rates[currencyKey];
//Result: Set the update value for Result
setResult(result.toFixed(5));
})
.catch(err => {
console.log(err.message);
});
}
};
const handleInputChange = e => {
setSearchInput(e.target.value);
};
const handleCurrencyValue = e => {
setCurrencyValue(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
search();
};
const sectionStyle = {
width: "100%",
height: "100%",
backgroundColor: "#fff"
};
return (
<div className="App">
<section style={sectionStyle}>
<CssBaseline />
<Container maxWidth="sm">
<Header />
<Loading />
<CountrySearch
handleSubmit={handleSubmit}
handleInputChange={handleInputChange}
searchInput={searchInput}
/>
{searching && <Loading />}
{error && (
<div style={{ color: `red` }}>
<h1>There is no country such as {searchInput}</h1>
</div>
)}
{country && <Country country={country} />}
{country && (
<Converter
convertCurrnecy={convertHandler}
convertInputChange={handleCurrencyValue}
>
{result && (
<p>
{result} {currencyKey}
</p>
)}
</Converter>
)}
</Container>
</section>
</div>
);
};
export default App;
|
Python | UTF-8 | 1,151 | 3.265625 | 3 | [] | no_license | class Solution(object):
def partitionLabels(self, Tree, D):
"""
:type S: str
:rtype: List[int]
"""
# Solution 1 32ms
length = len(Tree)
ans = []
history = [[-1 for i in range(D+1)] for j in range(length)]
for i in range (length):
curlevel = 0
curnode = i
while (curlevel != D):
if curnode == -1:
curlevel = D
ans.append(-1)
break
record = history[curnode][D-curlevel]
if record != -1:
print("got")
ans.append(record)
curlevel = D
else:
curlevel += 1
curnode = Tree[curnode]
history[i][curlevel] = curnode
if curlevel == D:
ans.append(curnode)
print(history,curlevel,curnode)
print(ans)
print(ans)
return ans
tree = [-1,0,4,2,1]
d = 3
# tree = [-1,0,1,2,3]
# d = 2
s = Solution()
s.partitionLabels(tree,d) |
Ruby | UTF-8 | 4,290 | 2.53125 | 3 | [
"MIT"
] | permissive | # Copyright (c) 2012
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Runcible
module Extensions
class Consumer < Runcible::Resources::Consumer
# Bind a consumer to all repositories with a given ID
#
# @param [String] id the consumer ID
# @param [String] repo_id the repo ID to bind to
# @return [RestClient::Response] set of tasks representing each bind operation
def self.bind_all(id, repo_id)
Runcible::Extensions::Repository.retrieve_with_details(repo_id)['distributors'].collect do |d|
self.bind(id, repo_id, d['id'])
end.flatten
end
# Unbind a consumer to all repositories with a given ID
#
# @param [String] id the consumer ID
# @param [String] repo_id the repo ID to unbind from
# @return [RestClient::Response] set of tasks representing each unbind operation
def self.unbind_all(id, repo_id)
Runcible::Extensions::Repository.retrieve_with_details(repo_id)['distributors'].collect do |d|
self.unbind(id, repo_id, d['id'])
end.flatten
end
# Install content to a consumer
#
# @param [String] id the consumer ID
# @param [String] type_id the type of content to install (e.g. rpm, errata)
# @param [Array] units array of units to install
# @return [RestClient::Response] task representing the install operation
def self.install_content(id, type_id, units)
self.install_units(id, generate_content(type_id, units))
end
# Update content on a consumer
#
# @param [String] id the consumer ID
# @param [String] type_id the type of content to update (e.g. rpm, errata)
# @param [Array] units array of units to update
# @return [RestClient::Response] task representing the update operation
def self.update_content(id, type_id, units)
self.update_units(id, generate_content(type_id, units))
end
# Uninstall content from a consumer
#
# @param [String] id the consumer ID
# @param [String] type_id the type of content to uninstall (e.g. rpm, errata)
# @param [Array] units array of units to uninstall
# @return [RestClient::Response] task representing the uninstall operation
def self.uninstall_content(id, type_id, units)
self.uninstall_units(id, generate_content(type_id, units))
end
# Generate the content units used by other functions
#
# @param [String] type_id the type of content (e.g. rpm, errata)
# @param [Array] units array of units
# @return [Array] array of formatted content units
def self.generate_content(type_id, units)
content = []
units.each do |unit|
content_unit = {}
content_unit[:type_id] = type_id
content_unit[:unit_key] = { :name => unit }
content.push(content_unit)
end
content
end
end
end
end
|
Markdown | UTF-8 | 1,789 | 2.78125 | 3 | [
"MIT"
] | permissive | ## Description
This is my third project for UA's coding bootcamp. It is a secure password generator.
## Installation
To install this project all you need to do is download the repository and open index.html using your browser of choice. Alternatively, you could just go to the github page for this website.
## Usage
To use this project, select the criteria you wish for your password to contain (upper/lower case letters, special characters, numbers) and the password length. Then click the "Generate Password" button.
Your password will appear in the textarea and you may change it my manually typing in your edits. Then you may copy the password to your clipboard using the "Copy to Clipboard" button.
## License
MIT License
Copyright (c) 2019 Kaylee Nelson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|
PHP | UTF-8 | 978 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
namespace MPScholten\RequestParser\Validator;
class StringLengthSmallerThanOrEqualToParser extends AbstractSmallerThanOrEqualToParser
{
protected function describe()
{
return "a string shorter than or equal to $this->maxValue characters";
}
/**
* @param $value
* @return int
*/
protected function parse($value)
{
if (strlen($value) <= $this->maxValue) {
return $value;
}
return null;
}
/**
* @param string $defaultValue
* @return string
*/
public function defaultsTo($defaultValue)
{
return parent::defaultsTo($defaultValue);
}
/**
* @throws \Exception
* @param string $invalidValueMessage
* @param string $notFoundMessage
* @return string
*/
public function required($invalidValueMessage = null, $notFoundMessage = null)
{
return parent::required($invalidValueMessage, $notFoundMessage);
}
} |
JavaScript | UTF-8 | 1,714 | 2.609375 | 3 | [] | no_license | 'use strict';
(function () {
var pinsContainer = document.querySelector('.map__pins');
var similarPinTemplate = document.querySelector('template').content.querySelector('.map__pin');
var isPinActive;
var markerParams = {
WIDTH: 50,
HEIGHT: 70
};
var pins = [];
var pinActive;
var filteredData;
var renderPin = function (advert) {
var pinElement = similarPinTemplate.cloneNode(true);
var adElement = window.card.render(advert);
pinElement.style.left = advert.location.x - markerParams.WIDTH / 2 + 'px';
pinElement.style.top = advert.location.y - markerParams.HEIGHT + 'px';
pinElement.querySelector('img').src = advert.author.avatar;
pinElement.querySelector('img').alt = advert.offer.title;
pins.push(pinElement);
pinElement.addEventListener('click', function () {
if (isPinActive) {
pinActive.classList.remove('map__pin--active');
}
window.card.show(adElement);
pinActive = pinElement;
pinActive.classList.add('map__pin--active');
isPinActive = true;
});
return pinElement;
};
var deactivatePin = function () {
pinActive.classList.remove('map__pin--active');
};
var initPin = function () {
filteredData = window.filters.get();
var fragmentPin = document.createDocumentFragment();
for (var i = 0; i < filteredData.length; i++) {
fragmentPin.appendChild(renderPin(filteredData[i]));
}
pinsContainer.appendChild(fragmentPin);
};
var closePin = function () {
pins.forEach(function (pin) {
pinsContainer.removeChild(pin);
});
pins = [];
};
window.pin = {
init: initPin,
close: closePin,
deactivate: deactivatePin
};
})();
|
Python | UTF-8 | 484 | 3.078125 | 3 | [] | no_license | class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
length = len(s)
s = list(s)
for i in range(0, length, 2*k):
start = i
end = i + k - 1 if i + k - 1 < length else length - 1
while start <= end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
return ''.join(s)
|
Java | UTF-8 | 557 | 2.359375 | 2 | [] | no_license | package com.businessApp.bean;
import java.util.ArrayList;
import java.util.List;
public class ConsumerHours
{
private String time;
private List<ConsumerServices> services;
public ConsumerHours() {
this.services = new ArrayList<>();
}
public String getTime()
{
return this.time;
}
public void setTime(String time)
{
this.time = time;
}
public List<ConsumerServices> getServices()
{
return this.services;
}
public void setServices(List<ConsumerServices> services)
{
this.services = services;
}
}
|
Python | UTF-8 | 8,327 | 2.671875 | 3 | [
"MIT"
] | permissive | import discord
from discord.ext import commands
from datetime import datetime, timedelta
from time import time
import platform
import robloxapi
import requests
from discord.ext.commands import BucketType
def setup(bot):
bot.add_cog(Information(bot))
class Information(commands.Cog):
def __init__(self,bot):
self.bot = bot
def botut(self):
delta_uptime = datetime.utcnow() - self.bot.launch_time
hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
ut = f"{days}d, {hours}h, {minutes}m, {seconds}s"
return ut
@commands.command(name="userinfo",aliases=["ui","whois","uinfo"],description="Show a user's information", usage='`userinfo [member]`')
async def user_info(self, ctx, member:discord.Member=None):
member = member or ctx.author
roles = [role for role in member.roles]
embed = discord.Embed(colour=self.bot.defaultcolour, description=f"Some useful information about {member.name}",timestamp=datetime.utcnow())
#Shows the user's highest roles' colour. For a custom colour replace member.colour with 0xhexcode; an example will be: colour=0xffff00
embed.set_author(name=member)
embed.set_footer(text=f"USER ID: {member.id}")
embed.set_thumbnail(url=member.avatar_url)
fields = [("Created",member.created_at.strftime("%d-%m-%Y %H:%M")),
("Joined",member.joined_at.strftime("%d-%m-%Y %H:%M")),
("Roles", " ,".join([role.mention for role in roles]))]
for name, value in fields:
embed.add_field(name=name,value=value,inline=False)
await ctx.send(embed=embed)
@commands.command(name="serverinfo",aliases=["si","sinfo"],description="serverinfo Shows the server's information")
async def server_info(self, ctx):
try:
x = datetime.now()
a= x.strftime("%x")
embed = discord.Embed(title=ctx.guild.name, colour=self.bot.defaultcolour, description=f"Some useful information about {ctx.guild.name}",timestamp=datetime.utcnow())
#Shows the user's highest roles' colour. For a custom colour replace member.colour with 0xhexcode; an example will be: colour=0xffff00
statuses = [len(list(filter(lambda m: str(m.status) == "online", ctx.guild.members))),
len(list(filter(lambda m: str(m.status) == "idle", ctx.guild.members))),
len(list(filter(lambda m: str(m.status) == "dnd", ctx.guild.members))),
len(list(filter(lambda m: str(m.status) == "offline", ctx.guild.members))),
len(list(filter(lambda m: str(m.status) == "streaming", ctx.guild.members)))]
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_footer(text=ctx.author.name)
fields = [("ID",ctx.guild.id),
("Owner", ctx.guild.owner),
("Created", a),
("Channels", f"Text: {len(ctx.guild.text_channels)}\nVoice: {len(ctx.guild.voice_channels)}"),
("Members", f"\\🟢 {statuses[0]} \\🟡 {statuses[1]} \\🔴 {statuses[2]} \\⚪ {statuses[3]} \\🟣 {statuses[4]}\nTotal: {len(ctx.guild.members)}"),
("Roles", len(ctx.guild.roles)),
("Server Region",ctx.guild.region)]
for name, value in fields:
embed.add_field(name=name, value=value, inline=False)
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(e)
@commands.command(name="ping",description="Shows the ping")
async def botping(self, ctx):
start = time()
embed = discord.Embed(colour=self.bot.defaultcolour,description="Pinging...")
message = await ctx.send(embed=embed)
end = time()
rbxstart = time()
await self.bot.robloxclient.get_user_by_id(611401554)
rbxend = time()
newEmbed = discord.Embed(colour=self.bot.defaultcolour, title="Pong! 🏓",timestamp=datetime.utcnow(),
description=f"""DWSP latency: {self.bot.latency*1000:,.0f} ms.
Response time: {(end-start)*1000:,.0f} ms.
RobloxApi response time: {(rbxend-rbxstart)*1000:,.0f} ms. """)
newEmbed.set_footer(text=ctx.author.name)
await message.edit(embed=newEmbed)
@commands.command(name="invite", description="Invite the bot to your other server with this command")
async def botinvite(self, ctx):
embed=discord.Embed(timestamp=datetime.utcnow(),colour=self.bot.defaultcolour,title="Invite",description=f"https://discord.com/api/oauth2/authorize?client_id={self.bot.user.id}&permissions=8&scope=bot")
embed.add_field(name="Source", value="https://github.com/ItsArtemiz/Roblox-Discord-Bot")
embed.set_footer(text=ctx.author.name)
await ctx.send(embed=embed)
@commands.command(name="botinfo",description="Some useful information about the bot", aliases=["stats"])
async def botinformation(self, ctx):
start = time()
embed = discord.Embed(colour=self.bot.defaultcolour,description="Retreiving useful information...")
message = await ctx.send(embed=embed)
end = time()
rbxstart = time()
await self.bot.robloxclient.get_user_by_id(611401554)
rbxend = time()
newEmbed = discord.Embed(colour=self.bot.defaultcolour,title="Bot Info",timestamp=datetime.utcnow())
newEmbed.set_footer(text=ctx.author.name)
fields=[("Bot Developer","ItsArtemiz#8858"),
("Source","https://github.com/ItsArtemiz/Roblox-Discord-Bot"),
("Bot Version",self.bot.version),
("Uptime",self.botut()),
("Language","Python"),
("Python Version",platform.python_version()),
("discord.py Version", discord.__version__),
("DWSP latency",f"{self.bot.latency*1000:,.0f} ms."),
("Response Time", f"{(end-start)*1000:,.0f} ms"),
("RobloxApi Response Time",f"{(rbxend-rbxstart)*1000:,.0f} ms.")]
for name, value in fields:
newEmbed.add_field(name=name, value=value)
await message.edit(embed = newEmbed)
@commands.command(name="uptime",description="Shows bot's uptime", aliases=["ut"])
async def botuptime(self, ctx):
delta_uptime = datetime.utcnow() - self.bot.launch_time
hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
await ctx.send(f"Uptime: **{days}d, {hours}h, {minutes}m, {seconds}s**")
@commands.command(name="source",description="Bot's Github Source", timestamp=datetime.utcnow())
async def botsource(self, ctx):
embed=discord.Embed(colour=self.bot.defaultcolour,title="Source",timestamp=datetime.utcnow(),description="https://github.com/ItsArtemiz/Roblox-Discord-Bot")
embed.set_footer(text="ItsArtemiz")
await ctx.send(embed=embed)
@commands.command(name="avatar",aliases=["av"],description="Shows the avatar of a user", usage="`avatar [member]`")
async def av_member(self,ctx, member:discord.Member = None):
member = member or ctx.author
ava = member.avatar_url_as(static_format='png')
embed = discord.Embed(colour=self.bot.defaultcolour,title="Avatar")
embed.set_image(url=member.avatar_url)
embed.set_author(name=member, icon_url=member.avatar_url, url=ava)
await ctx.send(embed=embed)
@commands.command(name="membercount",aliases=["mc"],description="Shows the membercount of the server")
async def member_count(self, ctx):
embed =discord.Embed(colour=self.bot.defaultcolour, timestamp=datetime.utcnow(),title="Member Count",
description=f"Total: {len(ctx.guild.members)}\nHumans: {len([Member for Member in ctx.guild.members if not Member.bot])}\nBots: {len([Member for Member in ctx.guild.members if Member.bot])}")
embed.set_footer(text=ctx.author.name)
await ctx.send(embed=embed)
|
PHP | UTF-8 | 458 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
class Email_Templates_m extends CI_Model {
var $details;
function __construct()
{
parent:: __construct();
}
function get_mail_template( $varname ) {
// Build a query to retrieve the email template's details
// based on the received template name
$query = $this->db->query("Select * from email_templates where template_name='$varname'");
return $row = $query->row_array();
}
}
?> |
Java | UTF-8 | 1,970 | 2.796875 | 3 | [] | no_license | package xyz.hui_yi.keywords.utils.file;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class FileType {
private static Properties properties = null;
static {
try {
InputStream inputStream = FileType.class.getClassLoader().getResourceAsStream("arrow_upload_filetype.properties");
properties = new Properties();
properties.load(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 根据扩展名验证上传文件是否属于pdf文件
* @param fileName filename.pdf
* @return
*/
public static boolean validateFileTypeByFileName(String fileName){
if(fileName != null){
String ext = fileName.substring(fileName.lastIndexOf('.')+1).toLowerCase();
List<String> arrowType = new ArrayList<String>();
for(Object key : properties.keySet()){
String value = (String)properties.get(key);
String[] values = value.split(",");
for(String v : values){
arrowType.add(v.trim());
}
}
return arrowType.contains(fileName.toLowerCase()) && properties.keySet().contains(ext);
}else
return false;
}
/**
* 验证上传文件是否属于pdf 文件
* @param contentType application/pdf
* @return
*/
public static boolean validateFileTypeByMimeType(String contentType){
if(contentType != null){
List<String> arrowType = new ArrayList<String>();
for(Object key : properties.keySet()){
String value = (String)properties.get(key);
arrowType.add(value);
}
return arrowType.contains(contentType);
}else {
return false;
}
}
}
|
Python | UTF-8 | 1,820 | 3.34375 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error
#creating regressors
#importing prexisting dataset diabetes
diabetes=datasets.load_diabetes()
#slicing dataset and taking only one feature and only one label
diabetes_X=diabetes.data #index 2 e jei feature chilo seta 1 column e dibe arary of array hisabe
#train test splitting. full dataset er kichu data model train e use kora hoy baki data test korte
diabetes_X_train=diabetes_X[:-30] # ekhane diabetes_X er last 30 ta nicche
diabetes_X_test=diabetes_X[-30:] # ekhane diabetes_X er last 20 ta nicche
diabetes_Y_train=diabetes.target[:-30] #diabetes_X_train=diabetes_X[:-30]er corresponding feature. that means
#diabetes_X_train=diabetes_X[:-30] er jei feature tar label hocche eita tai[:-30]same
diabetes_Y_test=diabetes.target[-30:]
#x axis e features and y axis e labels thakbe
#creating linear model
model=linear_model.LinearRegression()
#linearmodel ke feedkorano hoise
#fitting data means data diye ekta line banabo jeta ei linear model e save hoye jabe
model.fit(diabetes_X_train,diabetes_Y_train) #training data fit koraye model train korano hoche
#checking model prediction
diabetes_Y_predicted=model.predict(diabetes_X_test) #testing our model with test data
print("Mean squared error is:", mean_squared_error(diabetes_Y_test,diabetes_Y_predicted))#predicted values and actual values
print("Weight:",model.coef_)
print("intercept",model.intercept_)
#scatter plot
#plt.scatter(diabetes_X_test,diabetes_Y_test)
#plt.plot(diabetes_X_test,diabetes_Y_predicted)
#plt.show()
#Mean squared error is: 3035.0601152912686 when diabetes_X=diabetes.data[:, np.newaxis,2]
#Weight: [941.43097333]
#intercept 153.39713623331698
|
Markdown | UTF-8 | 909 | 2.796875 | 3 | [] | no_license | # Article R251-41
Est puni des peines prévues par les contraventions de la 5e classe :
1° Le fait d'exercer une activité sur un matériel au sens de l'article R. 251-26 sans détenir l'agrément prévu à cet article
ou sans respecter les conditions de cet agrément ;
2° Le fait de mettre en circulation ou d'introduire du matériel sans la lettre officielle d'autorisation prévue à l'article
R. 251-26 ;
3° Le fait de mettre en circulation des végétaux, produits végétaux et autres objets mentionnés à l'article R. 251-37 sans
avoir obtenu la mainlevée officielle.
**Liens relatifs à cet article**
_Codifié par_:
- Décret n°2003-768 2003-08-01
_Créé par_:
- Décret n°2003-768 2003-08-01 art. 2, annexe JORF 7 août 2003
- Décret n°2003-768 du 1 août 2003 - art. 2 (V) JORF 7 août 2003
_Cite_:
- Code rural - art. R251-26 (V)
- Code rural - art. R251-37 (V)
|
Shell | UTF-8 | 224 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | git checkout $1 2> /dev/null
echo -n $1 "$(git log -1 --date=format:'%Y/%m/%d' --format='%ad') "
cloc . | egrep "Kotlin|^C\+\+|Java " | sed 's/[ \t]\+/ /g' | cut -f 1,5 -d ' ' | tr ' ' '=' | tr '\n' ',' | sed 's/,$//'
echo
|
Java | UTF-8 | 956 | 3.359375 | 3 | [] | no_license | package enumWithAnnotation.item34;
public class OperationTest {
public static void main(String[] args) {
double x = Double.parseDouble("2");
double y = Double.parseDouble("4");
for(Operation op : Operation.values()) {
System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}
System.out.println(Operation.fromString("+").isPresent() ? Operation.fromString("+").get() : "값 없음");
System.out.println(Operation.fromString("++").isPresent() ? Operation.fromString("++").get() : "값 없음");
System.out.println(Operation.TIMES);
System.out.println(PayrollDay.MONDAY.pay(500,10));
System.out.println(PayrollDay.TUESDAY.pay(500, 10));
System.out.println(PayrollDay.WEDNESDAY.pay(500,10));
System.out.println(PayrollDay.THURSDAY.pay(500, 10));
System.out.println(PayrollDay.FRIDAY.pay(500, 10));
System.out.println(PayrollDay.SATURDAY.pay(500, 10));
System.out.println(PayrollDay.SUNDAY.pay(500, 10));
}
}
|
TypeScript | UTF-8 | 1,035 | 2.59375 | 3 | [] | no_license | import { Components } from "gd-sprest-bs";
/**
* The click event for 'Command 2'
* @param items - The selected list items.
*/
export const Command2 = (items: Array<any>) => {
// Create html to display in a dialog
let content = "";
// Parse the items
for (let i = 0; i < items.length; i++) {
let item = items[i];
// Add the item info
content += "<p>" + item.Title + "</p>";
}
// Get the element to render the modal to
let elModal = document.querySelector("#jslink-dlg");
if (elModal == null) {
// Create the element
elModal = document.createElement("div");
elModal.id = "jslink-dlg";
document.body.appendChild(elModal);
}
// Create a dialog
let dlg = Components.Modal({
el: elModal,
title: "Selected Items",
body: content,
onClose: (el) => {
// Remove the element from the page
document.body.removeChild(dlg.el);
}
});
// Show the dialog
dlg.show();
} |
Markdown | UTF-8 | 34,860 | 2.546875 | 3 | [] | no_license | Source: [US20130150723](https://patents.google.com/patent/US20130150723)
# [US20130150723](US20130150723.md) - Ultrasound diagnostic apparatus
## Details
* Date: 2010-09-06
* Inventor: Fujifilm Corp
* Beneficiary: Yoshiaki Satoh
## Other patents
### Backwards
* US4819652A
* US5475307A
* [US5724976A](US5724976A.md)
* US6251073B1
* US20020016545A1
* US20030097071A1
* US20050148873A1
* US20090093719A1
* US20100286527A1
* [US20110112405A1](US20110112405A1.md)
* US20110306886A1
### Forward
* US20120123270A1
* US20140116143A1
* EP2837949A1
## Abstract
Abstract
An ultrasound diagnostic apparatus includes an ultrasound probe including a transducer array, and a back unit connected to the ultrasound probe by wireless communication and generating an ultrasound image based on reception signals outputted from the transducer array, the ultrasound probe including a middle unit connected to the back unit by wireless communication and a front unit detachably connected to the middle unit and including the transducer array, and the front unit having a transmission driver that supplies drive signals to the transducer array and causes the transducer array to transmit an ultrasonic beam and a preamplifier that amplifies reception signals outputted from the transducer array.
An ultrasound diagnostic apparatus includes an ultrasound probe including a transducer array, and a back unit connected to the ultrasound probe by wireless communication and generating an ultrasound image based on reception signals outputted from the transducer array, the ultrasound probe including a middle unit connected to the back unit by wireless communication and a front unit detachably connected to the middle unit and including the transducer array, and the front unit having a transmission driver that supplies drive signals to the transducer array and causes the transducer array to transmit an ultrasonic beam and a preamplifier that amplifies reception signals outputted from the transducer array.
BACKGROUND OF THE INVENTION
[0001] The present invention relates to an ultrasound diagnostic apparatus and particularly to an ultrasound diagnostic apparatus permitting interchange of transducer arrays of an ultrasound probe.
[0002] Conventionally, ultrasound diagnostic apparatus using ultrasound images are employed in medicine. In general, this type of ultrasound diagnostic apparatus comprises an ultrasound probe having a built-in transducer array and an apparatus body connected to the ultrasound probe. The ultrasound probe transmits an ultrasonic wave toward a subject, receives an ultrasonic echo from the subject, and the apparatus body electrically processes reception signals to generate an ultrasound image.
[0003] In recent years, there have been developed portable ultrasound diagnostic apparatus that can be transported and placed near a bed or brought to a site where emergency medical care is needed. There have also been conceived ultrasound diagnostic apparatus having a configuration whereby the ultrasound probe and the apparatus body are connected to each other by wireless communication to improve operability. Such ultrasound diagnostic apparatus are required to be available in reduced dimensions for convenience.
[0004] Ultrasound diagnostic apparatus are used to diagnose subjects for various diagnosis purposes depending on which an appropriate frequency band may often vary. Thus, one may consider using an ultrasound probe selected according to the diagnosis purpose from a plurality of ultrasound probes having different frequency bands kept ready for use and connecting the selected probe to the apparatus body. However, because the ultrasound probes are generally expensive, keeping a plurality of ultrasound probes available for use increases the costs. Thus, there is a demand for a transducer array that is detachably provided in the ultrasound probe so that a transducer array having a suitable frequency band for the diagnosis purpose may be selected and used.
[0005] For example, Patent Literature 1 describes an ultrasound diagnostic system wherein an ultrasound probe is comprised of a transducer head containing a transducer array and a beamforming module for processing the signals from the transducer head for beamforming, and wherein the transducer head is detachably mounted to the beamforming module.
[0006] Patent Literature 2 describes an ultrasound diagnostic apparatus wherein an ultrasound probe is comprised of a transducer array and a housing for holding the transducer array, and wherein the transducer array is detachably mounted to the housing.
CITATION LIST
[0000]
PATENT LITERATURE 1: JP 2003-190159 A
PATENT LITERATURE 2: JP 2009-50992 A
SUMMARY OF THE INVENTION
[0009] In the ultrasound probe of the apparatus described in Patent Literature 1, because the transducer head containing the transducer array is detachable from the beamforming module, a transducer array having an appropriate frequency band according to the diagnosis purpose can be used. However, such configuration has a problem in which the beamforming module is required to have therein mounted a broadband preamplifier with a bandwidth of, for example, about 2 to 20 MHz in order to enable operation with a plurality of transducer arrays having different frequency bands, and a pulser capable of a high drive voltage for a transducer array having a maximum drive voltage among the plurality of transducer arrays, resulting in increased dimensions of the apparatus.
[0010] Likewise, although the ultrasound probe of the apparatus described in Patent Literature 2 permits use of a transducer array having an appropriate frequency band according to the diagnosis purpose, the housing is required to have mounted therein a broadband amplifier and a high drive-voltage pulser, resulting in increased dimensions of the apparatus.
[0011] The present invention has been made to solve the above problems in the art and has an object of providing an ultrasound diagnostic apparatus permitting interchange of transducer arrays to select one having a suitable frequency band for an intended diagnosis purpose, while achieving reduction in dimensions and improvement of operability.
[0012] An ultrasound diagnostic apparatus according to the present invention comprises: an ultrasound probe including a transducer array; and a back unit connected to the ultrasound probe by wireless communication and generating an ultrasound image based on reception signals outputted from the transducer array, wherein the ultrasound probe includes a middle unit connected to the back unit by wireless communication and a front unit detachably connected to the middle unit and including the transducer array, and wherein the front unit has a transmission driver that supplies drive signals to the transducer array and causes the transducer array to transmit an ultrasonic beam and a preamplifier that amplifies reception signals outputted from the transducer array.
BRIEF DESCRIPTION OF DRAWINGS
[0013] FIG. 1 is a block diagram illustrating a configuration of an ultrasound diagnostic apparatus according to Embodiment 1 of the invention.
[0014] FIG. 2 is a flow chart illustrating the operation of Embodiment 1.
[0015] FIG. 3 is a flow chart illustrating an examination mode in Embodiment 1.
[0016] FIG. 4 is a block diagram illustrating a configuration of a front unit used in Embodiment 2.
[0017] FIG. 5 is a block diagram illustrating a configuration of a front unit used in Embodiment 3.
[0018] FIG. 6 is a block diagram illustrating a configuration of a front unit used in a variation of Embodiment 3.
[0019] FIG. 7 is a block diagram illustrating a configuration of a front unit used in Embodiment 4.
[0020] FIG. 8 is a block diagram illustrating a configuration of a front unit used in a variation of Embodiment 4.
[0021] FIG. 9 is a block diagram illustrating a configuration of a middle unit used in Embodiment 5.
DETAILED DESCRIPTION OF THE INVENTION
[0022] Embodiments of the present invention will be described below based on the attached drawings.
Embodiment 1
[0023] FIG. 1 illustrates a configuration of an ultrasound diagnostic apparatus according to Embodiment 1 of the invention. The ultrasound diagnostic apparatus comprises an ultrasound probe 1 and a back unit 2 that is connected to the ultrasound probe 1 via wireless communication.
[0024] The ultrasound probe 1 comprises a front unit 3 and a middle unit 4. The front unit 3 is detachably connected via a connector 5 to the middle unit 4.
[0025] The front unit 3 comprises a one-dimensional or two-dimensional transducer array 6 including a plurality of ultrasound transducers. A preamplifier 8 and a transmission driver 9 are connected in parallel to the transducer array 6 via a transmission/reception selector switch 7. A CPU (central processing unit) 10 is connected to the transmission driver 9.
[0026] The middle unit 4 comprises an A/D converter (analog-digital converter circuit) 11 that is connected to the preamplifier 8 of the front unit 3 via the connector 5. A reception signal processor 12 is connected to the A/D converter 11, and a wireless communication unit 14 is connected to the reception signal processor 12 via a parallel/serial converter 13. A CPU 15 is connected to the reception signal processor 12 and the parallel/serial converter 13, and the CPU 15 is connected to the CPU 10 of the front unit 3 via the connector 5.
[0027] The transducers of the transducer array 6 each transmit ultrasonic waves according to drive signals supplied from the transmission driver 9 and receive ultrasonic echoes from a subject to output reception signals. Each of the transducers is constituted, for example, by a vibrator including a piezoelectric body made of a piezoelectric ceramic typified by PZT (lead zirconate titanate) or a polymeric piezoelectric element typified by PVDF (polyvinylidene fluoride) and electrodes provided on both ends of the piezoelectric body.
[0028] When the electrodes of the vibrators are supplied with a pulsed voltage or a continuous-wave voltage, the piezoelectric bodies expand and contract to cause the vibrators to produce pulsed or continuous ultrasonic waves. The ultrasonic waves are combined to form an ultrasonic beam. Upon reception of a propagating ultrasonic wave, each vibrator expands and contracts to produce an electric signal, which is then outputted as reception signal of the ultrasonic wave.
[0029] Under the control of the CPU 10, the transmission/reception selector switch 7 selectively connects the transducer array 6 to one of the preamplifier 8 and the transmission driver 9.
[0030] The preamplifier 8 amplifies the reception signals outputted from the respective channels of the ultrasonic transducers of the transducer array 6.
[0031] The transmission driver 9 comprises, for example, a plurality of pulse generators and adjusts the delay amounts of drive signals for the respective transducers based on a transmission delay pattern selected by the CPU 10 so that the ultrasonic waves transmitted from the transducer array 6 form a broad ultrasonic beam covering an area of a tissue in the subject and supplies the transducers of the transducer array 6 with the adjusted drive signals.
[0032] The CPU 10 controls the transmission driver 9 according to various control signals transmitted from the CPU 15 of the middle unit 4 connected via the connector 5.
[0033] The transducer array 6 has a specific frequency band and a specific drive voltage. The preamplifier 8 used has a frequency band corresponding to the frequency band of the transducer array 6. The transmission driver 9 used outputs a drive voltage corresponding to the drive voltage for the transducer array 6.
[0034] The A/D converter 11 digitizes the reception signals amplified by the preamplifier 8.
[0035] Under the control of the CPU 15, the reception signal processor 12 subjects the reception signals digitized by the A/D converter 11 to quadrature detection or quadrature sampling to produce complex baseband signals, samples the complex baseband signals to generate sample data containing information on the area of the tissue, and supplies the sample data to the parallel/serial converter 13. Otherwise, the reception signal processor 12 may generate sample data by performing data compression on the data obtained by sampling the complex baseband signals for high-efficiency coding.
[0036] The parallel/serial converter 13 converts the parallel sample data generated by the reception signal processor 12 having a plurality of channels into serial sample data.
[0037] The wireless communication unit 14 performs carrier modulation based on the serial sample data to generate transmission signals and supplies an antenna with the transmission signals so that the antenna transmits radio waves thereby to transmit the serial sample data. The modulation methods that may be employed herein include ASK (Amplitude Shift Keying), PSK (Phase Shift Keying), QPSK (Quadrature Phase Shift Keying), and 16QAM (16 Quadrature Amplitude Modulation).
[0038] The wireless communication unit 14 transmits the sample data to the back unit 2 and receives various control signals from the back unit 2 through wireless communication with the back unit 2, outputting the received control signals to the CPU 15.
[0039] Based on the control signal received from the back unit 2, the CPU 15 transmits a signal to the CPU 10 of the front unit 3 for the control of the transmission driver 9 and controls the wireless communication unit 14 so that sample data may be transmitted at a set transmission radio field intensity.
[0040] The connector 5 detachably connects the front unit 3 and the middle unit 4 and comprises a reception signal line for transmitting reception signals amplified by the preamplifier 8 of the front unit 3 to the A/D converter 11 of the middle unit 4 and a communication line for transmitting signals between the CPU 10 of the front unit 3 and the CPU 15 of the middle unit 4.
[0041] The ultrasound probe 1 includes a built-in battery, not shown, which supplies power to the circuits in the front unit 3 and the middle unit 4 in the ultrasound probe 1.
[0042] The front unit 3 of the ultrasound probe 1 illustrated in FIG. 1 is compatible with a sector scan mode.
[0043] The back unit 2 includes a wireless communication unit 16. An image forming unit 18 is connected to the wireless communication unit 16 via a serial/parallel converter 17, and a display unit 19 is connected to the image forming unit 18. A CPU 20 is connected to the wireless communication unit 16, the serial/parallel converter 17, and the image forming unit 18. Further, an operating unit 21 for an operator to perform input operations is connected to the CPU 20.
[0044] The wireless communication unit 16 transmits various control signals to the ultrasound probe 1 through wireless communication with the ultrasound probe 1. The wireless communication unit 16 demodulates the signal received by an antenna to output serial sample data.
[0045] The serial/parallel converter 17 converts the serial sample data outputted from the wireless communication unit 16 into parallel sample data.
[0046] The image forming unit 18 performs reception focusing on the sample data to generate image signals representing an ultrasound diagnostic image. The image forming unit 18 includes a phasing adder and an image processor.
[0047] The phasing adder selects one reception delay pattern from a plurality of previously stored reception delay patterns according to the reception direction that is set by the CPU 20 and, based on the selected reception delay pattern, provides a plurality of complex baseband signals represented by the sample data with their respective delays and adds them up to perform the reception focusing. This reception focusing yields a baseband signal (sound ray signal) where the ultrasonic echo is well focused.
[0048] The image processor generates a B-mode image signal, which is tomographic image information on, for example, a tissue inside the subject, according to the sound ray signal generated by the phasing adder. The image processor includes an STC (sensitivity time control) unit and a DSC (digital scan converter). The STC unit corrects the sound ray signal for the attenuation due to distance according to the depth of the reflection position of the ultrasonic wave. The DSC converts the sound ray signal corrected by the STC unit into an image signal compatible with an ordinary scanning method of television signals (raster conversion), and generates an image signal through required image processing such as gradation processing.
[0049] The display unit 19 displays an ultrasound diagnostic image based on image signals generated by the image forming unit 18 and includes a display device such as LCD.
[0050] Based on the instruction inputted by an operator from the operating unit 21, the CPU 20 controls the wireless communication unit 16 so that various control signals are transmitted at a set transmission radio field intensity, causes the image forming unit 18 to generate image signals, and causes the display unit 19 to display an ultrasound diagnostic image.
[0051] In Embodiment 1, the front unit 3 of the ultrasound probe 1 is detachably connected to the middle unit 4 via the connector 5. Thus, with a plurality of front units 3 including transducer arrays 6 having different frequency bands as well as preamplifiers 8 and transmission drivers 9 corresponding to the transducer arrays 6 available for use, a front unit 3 comprising a transducer array 6 having a suitable frequency band for an intended diagnosis purpose can be selected and connected to the middle unit 4.
[0052] Next, the operation of Embodiment 1 will be described with reference to the flowchart of FIG. 2.
[0053] First, examination information including patient information and examination instructions is entered from the operating unit 21 of the back unit 2 in the examination information input mode in step S1, whereupon the CPU 20 of the back unit 2 selects one front unit 3 containing the transducer array 6 having a suitable or usable frequency band according to the entered patient information.
[0054] In step S2 to follow, the CPU 20 of the back unit 2 inquires of the CPU 15 of the middle unit 4 by wireless communication, whereupon the CPU 15 of the middle unit 4 checks with the CPU 10 of the front unit 3, so that the CPU 20 of the back unit 2 may recognize whether or not the front unit 3 selected in step S1 has been connected to the middle unit 4.
[0055] Upon recognizing that the selected front unit 3 has been connected to the middle unit 4, the CPU 20 of the back unit 2 awaits the operator's instruction to start examination in step S3 and, upon receiving the instruction to start examination, proceeds to step S4 to execute an examination mode and, in step S5, awaits the operator's instruction to terminate the examination. When instruction to terminate the examination is entered, a series of examination processes is terminated, whereas when instruction to continue the examination is entered, the CPU 20 returns to step S1 to receive examination information again.
[0056] In step S4, one or more of previously set examination modes such as B mode, CF mode, PW mode, and M mode, as shown by way of example in FIG. 3, may be selected and executed. The CPU 20 of the back unit 2 checks examination information entered in step S1 to determine which mode has been designated and, upon verifying designation of B mode in step S11, proceeds to step S12 to execute examination in B mode. Upon verifying designation of CF mode in step S13, the CPU 20 proceeds to step S14 to execute examination in CF mode. Upon verifying designation of PW mode in step S15, the CPU 20 proceeds to step S16 to execute examination in PW mode. Upon verifying designation of M mode in step S17, the CPU 20 proceeds to step S18 to execute examination in M mode. When the termination of examination carried out based on the current examination information is verified in step S19, the CPU 20 proceeds to step S5 shown in FIG. 2.
[0057] The examinations in the respective modes are executed as follows.
[0058] First, operation control command is transmitted from the CPU 20 of the back unit 2 to the ultrasound probe 1 via the wireless communication unit 16. The operation control command is received by the wireless communication unit 14 of the middle unit 4 and transmitted to the CPU 15. Then, the CPU 15 outputs a command for driving the transducer array 6 to the CPU 10 of the front unit 3 via the connector 5.
[0059] The CPU 10 of the front unit 3 that received the above command operates the transmission/reception selector switch 7 to connect the transmission driver 9 to the transducer array 6, and the ultrasound transducers constituting the transducer array 6 transmit ultrasonic waves according to drive signals supplied from the transmission driver 9. Thereafter, the CPU 10 causes the transmission/reception selector switch 7 to operate so that the preamplifier 8 is now connected to the transducer array 6, and reception signals outputted respectively from the transducers of the transducer array 6 that received ultrasound echoes from a subject are amplified by the preamplifier 8 and then transmitted to the middle unit 4 via the connector 5.
[0060] The reception signals transmitted to the middle unit 4 are digitized by the A/D converter 11 and supplied to the reception signal processor 12, where sample data is generated. The sample data is serialized through the parallel/serial converter 13 and wirelessly transmitted from the wireless communication unit 14 to the back unit 2.
[0061] The sample data received by the wireless communication unit 16 of the back unit 2 is converted into parallel data through the serial/parallel converter 17, whereupon the image forming unit 18 produces an image signal appropriate for the executed examination mode, so that the display unit 19 displays an ultrasound diagnostic image based on the image signal.
[0062] As described above, the front unit 3 detachably connected to the middle unit 4 incorporates, besides the transducer array 6 having a specific frequency band, the preamplifier 8 having a frequency band corresponding to the frequency band of the transducer array 6 and the transmission driver 9 for outputting a drive voltage corresponding to the drive voltage for the transducer array 6. Thus, one need not employ an over-engineered system configuration, as conventionally required, equipped with a broadband preamplifier having a bandwidth of about, for example, 2 to 20 MHz and enabling operation with a plurality of transducer arrays having different frequency bands and a transmission driver capable of a high drive voltage adapted to a transducer array having a maximum drive voltage among a plurality of transducer arrays. Thus, a compact ultrasound diagnostic apparatus with enhanced operability can be realized.
[0063] Further, in Embodiment 1 above, the front unit 3 and the middle unit 4 are exclusively provided with the CPU 10 and the CPU 15 respectively, so that the CPU 10 controls the components in the front unit 3 while the CPU 15 controls the components in the middle unit 4. Thus, the number of control signal lines for connecting the front unit 3 and the middle unit 4 can be reduced, and both units can be detachably connected by a compact connector 5.
Embodiment 2
[0064] Although the front unit 3 of the ultrasound probe 1 used in Embodiment 1 above is compatible with a sector scan mode, the invention is not limited thereto. The front unit 3 may be compatible with other scan modes including, for example, a linear scan mode and a convex scan mode.
[0065] FIG. 4 illustrates a configuration of a front unit 31 used in Embodiment 2. As compared with the front unit 3 in Embodiment 1 illustrated in FIG. 1, the front unit 31 has a multiplexer 32 connected between the transducer array 6 and the transmission/reception selector switch 7 to acquire compatibility with the linear scan mode and the convex scan mode.
[0066] Under the control of the CPU 10, some transducers among those constituting the transducer array 6 are sequentially selected and perform transmission and reception of ultrasonic waves. This enables acquisition of an ultrasound diagnostic image by the linear scan mode or the convex scan mode.
[0067] When equipped with both the front unit 3 compatible with the sector scan mode as illustrated in FIG. 1 and the front unit 31 compatible with the linear scan mode and the convex scan mode as used in Embodiment 2, one may select one of these front units according to the scan mode and connect it to the middle unit 4.
Embodiment 3
[0068] FIG. 5 illustrates a configuration of a front unit 41 used in an ultrasound diagnostic apparatus according to Embodiment 3. As compared with the front unit 3 in Embodiment 1 illustrated in FIG. 1, the front unit 41 does not have the transmission/reception selector switch 7, and in place of the transducer array 6, has a reception transducer array 42 for only reception connected to the preamplifier 8 and a transmission transducer array 43 for only transmission connected to the transmission driver 9.
[0069] The front unit 41 is compatible with the sector scan mode.
[0070] Because the reception transducer array 42 dedicated to reception and the transmission transducer array 43 dedicated to transmission are provided, cross talk occurring in transmission of ultrasonic waves can be prevented and ultrasound diagnosis can be given with enhanced accuracy.
[0071] Although the front unit 41 illustrated in FIG. 5 is compatible with the sector scan mode, the invention is not so limited; as in a front unit 51 illustrated in FIG. 6, a front unit compatible with the linear scan mode and the convex scan mode may be configured by connecting a multiplexer 52 between the reception transducer array 42 and the preamplifier 8 and connecting a multiplexer 53 between the transmission transducer array 43 and the transmission driver 9.
Embodiment 4
[0072] FIG. 7 illustrates a configuration of a front unit 61 used in an ultrasound diagnostic apparatus according to Embodiment 4. As compared with the front unit 3 in Embodiment 1 illustrated in FIG. 1, the front unit 61 has a harmonic component reception transducer array 62 connected to the preamplifier 8 in addition to the transducer array 6 used for both transmission and reception.
[0073] The front unit 61 is compatible with the sector scan mode.
[0074] The harmonic component reception transducer array 62 is a transducer array having a frequency band especially adapted to harmonic components. With such a harmonic component reception transducer array 62 provided, a harmonic component can be received by the harmonic component reception transducer array 62 while an ultrasonic echo in a basic frequency band is received by the transducer array 6 that is used for both transmission and reception, enabling a still more accurate ultrasound diagnosis.
[0075] Although the front unit 61 illustrated in FIG. 7 is compatible with the sector scan mode, the invention is not so limited; as in a front unit 71 illustrated in FIG. 8, a front unit compatible with the linear scan mode and the convex scan mode may be configured by connecting a multiplexer 72 between the transducer array 6 used for both transmission and reception and the transmission/reception selector switch 7 and connecting a multiplexer 73 between the harmonic component reception transducer array 62 and the preamplifier 8.
Embodiment 5
[0076] FIG. 9 illustrates a configuration of a middle unit 81 used in an ultrasound diagnostic apparatus according to Embodiment 5. As compared with the middle unit 4 in Embodiment 1 illustrated in FIG. 1, the middle unit 81 has an operating unit 82 for performing input operation into the ultrasound diagnostic apparatus and a display unit 83 for displaying information, both of which are connected to the CPU 15.
[0077] With the operating unit 82 provided in the middle unit 81 of the ultrasound probe 1, various kinds of information may be entered from the ultrasound probe 1 connected to the back unit 2 by wireless communication to operate the ultrasound diagnostic apparatus from the ultrasound probe 1.
[0078] Further with the display unit 83 provided in the middle unit 81 of the ultrasound probe 1, such information as a name and a kind of the front unit connected to the middle unit 81 through the connector 5 can be displayed on the ultrasound probe 1, enhancing operability and convenience.
[0079] Although Embodiment 5 includes both the operating unit 82 and the display unit 83 in the middle unit 81, only one of the operating unit 82 and the display unit 83 may be connected to the CPU 15 of the middle unit 81.
What is claimed is:
1. An ultrasound diagnostic apparatus comprising:
an ultrasound probe including a transducer array; and a back unit connected to the ultrasound probe by wireless communication and generating an ultrasound image based on reception signals outputted from the transducer array, wherein the ultrasound probe includes a middle unit connected to the back unit by wireless communication and a front unit detachably connected to the middle unit and including the transducer array, and wherein the front unit has a transmission driver that supplies drive signals to the transducer array and causes the transducer array to transmit an ultrasonic beam and a preamplifier that amplifies reception signals outputted from the transducer array.
2. The ultrasound diagnostic apparatus according to claim 1, wherein the front unit and the middle unit comprise dedicated CPUs and are detachably connected to each other through a connector that includes a reception signal line for transmitting reception signals amplified by the preamplifier of the front unit and a communication line for transmitting signals between both CPUs.
3. The ultrasound diagnostic apparatus according to claim 2, wherein the front unit comprises a multiplexer connected to the transducer array.
4. The ultrasound diagnostic apparatus according to claim 1, wherein the transducer array comprises a transmission transducer array dedicated to transmission and a reception transducer array dedicated to reception.
5. The ultrasound diagnostic apparatus according to claim 2, wherein the transducer array comprises a transmission transducer array dedicated to transmission and a reception transducer array dedicated to reception.
6. The ultrasound diagnostic apparatus according to claim 3, wherein the transducer array comprises a transmission transducer array dedicated to transmission and a reception transducer array dedicated to reception.
7. The ultrasound diagnostic apparatus according to claim 1, wherein the transducer array comprises a dual-purpose transducer array for transmission and reception and a harmonic transducer array for harmonic component reception.
8. The ultrasound diagnostic apparatus according to claim 2, wherein the transducer array comprises a dual-purpose transducer array for transmission and reception and a harmonic transducer array for harmonic component reception.
9. The ultrasound diagnostic apparatus according to claim 3, wherein the transducer array comprises a dual-purpose transducer array for transmission and reception and a harmonic transducer array for harmonic component reception.
10. The ultrasound diagnostic apparatus according to claim 1, wherein the middle unit comprises an A/D converter converting reception signals amplified by the preamplifier of the front unit into a digital signal, a reception signal processor frequency-modulating the digital signal obtained through conversion by the A/D converter to a baseband frequency, and a parallel/serial converter serializing the signal that is frequency-modulated by the reception signal processor.
11. The ultrasound diagnostic apparatus according to claim 2, wherein the middle unit comprises an A/D converter converting reception signals amplified by the preamplifier of the front unit into a digital signal, a reception signal processor frequency-modulating the digital signal obtained through conversion by the A/D converter to a baseband frequency, and a parallel/serial converter serializing the signal that is frequency-modulated by the reception signal processor.
12. The ultrasound diagnostic apparatus according to claim 3, wherein the middle unit comprises an A/D converter converting reception signals amplified by the preamplifier of the front unit into a digital signal, a reception signal processor frequency-modulating the digital signal obtained through conversion by the A/D converter to a baseband frequency, and a parallel/serial converter serializing the signal that is frequency-modulated by the reception signal processor.
13. The ultrasound diagnostic apparatus according to claim 6, wherein the middle unit comprises an A/D converter converting reception signals amplified by the preamplifier of the front unit into a digital signal, a reception signal processor frequency-modulating the digital signal obtained through conversion by the A/D converter to a baseband frequency, and a parallel/serial converter serializing the signal that is frequency-modulated by the reception signal processor.
14. The ultrasound diagnostic apparatus according to claim 9, wherein the middle unit comprises an A/D converter converting reception signals amplified by the preamplifier of the front unit into a digital signal, a reception signal processor frequency-modulating the digital signal obtained through conversion by the A/D converter to a baseband frequency, and a parallel/serial converter serializing the signal that is frequency-modulated by the reception signal processor.
15. The ultrasound diagnostic apparatus according to claim 1, wherein the middle unit comprises at least one of an operating unit performing input operation into the ultrasound diagnostic apparatus and a display unit displaying information.
16. The ultrasound diagnostic apparatus according to claim 13, wherein the middle unit comprises at least one of an operating unit performing input operation into the ultrasound diagnostic apparatus and a display unit displaying information.
17. The ultrasound diagnostic apparatus according to claim 14, wherein the middle unit comprises at least one of an operating unit performing input operation into the ultrasound diagnostic apparatus and a display unit displaying information. |
Java | UTF-8 | 2,017 | 1.820313 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intel.hibench.stormbench.topologies;
import com.intel.hibench.stormbench.spout.KafkaSpoutFactory;
import com.intel.hibench.stormbench.util.StormBenchConfig;
import org.apache.storm.Config;
import org.apache.storm.StormSubmitter;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.topology.base.BaseRichSpout;
public abstract class SingleSpoutTops {
protected StormBenchConfig config;
public SingleSpoutTops(StormBenchConfig config) {
this.config = config;
}
public void run() throws Exception {
StormSubmitter.submitTopology(config.benchName, getConf(), getBuilder().createTopology());
}
private Config getConf() {
Config conf = new Config();
conf.setNumWorkers(config.workerCount);
conf.put(Config.TOPOLOGY_BACKPRESSURE_ENABLE, false);
if (!config.ackon) {
conf.setNumAckers(0);
}
return conf;
}
public TopologyBuilder getBuilder() {
TopologyBuilder builder = new TopologyBuilder();
BaseRichSpout spout = KafkaSpoutFactory.getSpout(config);
builder.setSpout("spout", spout, config.spoutThreads);
setBolts(builder);
return builder;
}
public abstract void setBolts(TopologyBuilder builder);
}
|
JavaScript | UTF-8 | 595 | 2.890625 | 3 | [
"MIT"
] | permissive | var requestParam=function()
{
}
/**
*
* @param {key key to be set for request parameter type e.g for header key can be "Authentication"}
* @param {value value to be set for the given key}
*/
requestParam.prototype.setKeyValue=function(key,value)
{
this[key]=value;
}
/**
* get the key value pair set using the setKeyValue method
*/
requestParam.prototype.getKeyValuePair=function()
{
keys=Object.keys(this);
value=Object.values(this);
return keys.reduce(function(map,key,index){
map[key]=value[index];
return map;
},{});
}
module.exports=requestParam; |
Python | UTF-8 | 1,415 | 3.171875 | 3 | [] | no_license | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
url = "./thefile.csv"
#url = "./data.csv"
#names = ['Year','Name', 'Price', 'Mileage', 'Body Type', 'Description']
names = ['Year','Brand', 'Model', 'Mileage','Engine','Color','Type','Description','MOT','Price']
df = pd.read_csv(url, names=names)
df = df.dropna()
df = df.drop(['Brand','Model','Engine','Color','Description'], axis=1)
X = df.drop('Price', axis=1)
y = df[['Price']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=1)
reg = LinearRegression()
reg.fit(X_train[['Mileage']], y_train)
y_predicted = reg.predict(X_test[['Mileage']])
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_predicted))
print('R²: %.2f' % r2_score(y_test, y_predicted))
fig, ax = plt.subplots()
ax.scatter(y_test, y_predicted)
ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'k--', lw=4)
ax.set_xlabel('measured')
ax.set_ylabel('predicted')
#plt.show()
diagonal = np.linspace(15000, 20000, 10000)
plt.plot(diagonal, diagonal, '-r')
plt.xlabel('Predicted ask price ($)')
plt.ylabel('Ask price ($)')
plt.show()
|
Python | UTF-8 | 1,253 | 3.421875 | 3 | [] | no_license | #!/usr/bin/python3
import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**25) # new thread will get stack of such size
class Tree:
def read(self):
self.n = int(sys.stdin.readline())
self.key = [0 for i in range(self.n)]
self.left = [0 for i in range(self.n)]
self.right = [0 for i in range(self.n)]
for i in range(self.n):
[a, b, c] = map(int, sys.stdin.readline().split())
self.key[i] = a
self.left[i] = b
self.right[i] = c
def IsBinarySearchTree(self,ind,result):
# Implement correct algorithm here
if self.n == 0:
return 1
if ind == -1:
return 1
flag = self.IsBinarySearchTree(self.left[ind],result)
if flag == 0:
return 0
else:
n = len(result)
if n != 0:
if result[n - 1] >= self.key[ind]:
return 0
result.append(self.key[ind])
flag = self.IsBinarySearchTree(self.right[ind],result)
return flag
def main():
tr = Tree()
tr.read()
result = []
flag = tr.IsBinarySearchTree(0, result)
if flag == 1:
print("CORRECT")
else:
print("INCORRECT")
threading.Thread(target=main).start()
|
Rust | UTF-8 | 2,615 | 3.53125 | 4 | [
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"Apache-2.0",
"Unlicense",
"BSD-3-Clause"
] | permissive | use core::ops;
/// A specialized copy-on-write byte string.
///
/// The purpose of this type is to permit usage of a "borrowed or owned
/// byte string" in a way that keeps std/no-std compatibility. That is, in
/// no-std mode, this type devolves into a simple &[u8] with no owned variant
/// available. We can't just use a plain Cow because Cow is not in core.
#[derive(Clone, Debug)]
pub struct CowBytes<'a>(Imp<'a>);
// N.B. We don't use std::borrow::Cow here since we can get away with a
// Box<[u8]> for our use case, which is 1/3 smaller than the Vec<u8> that
// a Cow<[u8]> would use.
#[cfg(feature = "std")]
#[derive(Clone, Debug)]
enum Imp<'a> {
Borrowed(&'a [u8]),
Owned(Box<[u8]>),
}
#[cfg(not(feature = "std"))]
#[derive(Clone, Debug)]
struct Imp<'a>(&'a [u8]);
impl<'a> ops::Deref for CowBytes<'a> {
type Target = [u8];
#[inline(always)]
fn deref(&self) -> &[u8] {
self.as_slice()
}
}
impl<'a> CowBytes<'a> {
/// Create a new borrowed CowBytes.
#[inline(always)]
pub fn new<B: ?Sized + AsRef<[u8]>>(bytes: &'a B) -> CowBytes<'a> {
CowBytes(Imp::new(bytes.as_ref()))
}
/// Create a new owned CowBytes.
#[cfg(feature = "std")]
#[inline(always)]
pub fn new_owned(bytes: Box<[u8]>) -> CowBytes<'static> {
CowBytes(Imp::Owned(bytes))
}
/// Return a borrowed byte string, regardless of whether this is an owned
/// or borrowed byte string internally.
#[inline(always)]
pub fn as_slice(&self) -> &[u8] {
self.0.as_slice()
}
/// Return an owned version of this copy-on-write byte string.
///
/// If this is already an owned byte string internally, then this is a
/// no-op. Otherwise, the internal byte string is copied.
#[cfg(feature = "std")]
#[inline(always)]
pub fn into_owned(self) -> CowBytes<'static> {
match self.0 {
Imp::Borrowed(b) => CowBytes::new_owned(Box::from(b)),
Imp::Owned(b) => CowBytes::new_owned(b),
}
}
}
impl<'a> Imp<'a> {
#[cfg(feature = "std")]
#[inline(always)]
pub fn new(bytes: &'a [u8]) -> Imp<'a> {
Imp::Borrowed(bytes)
}
#[cfg(not(feature = "std"))]
#[inline(always)]
pub fn new(bytes: &'a [u8]) -> Imp<'a> {
Imp(bytes)
}
#[cfg(feature = "std")]
#[inline(always)]
pub fn as_slice(&self) -> &[u8] {
match self {
Imp::Owned(ref x) => x,
Imp::Borrowed(x) => x,
}
}
#[cfg(not(feature = "std"))]
#[inline(always)]
pub fn as_slice(&self) -> &[u8] {
self.0
}
}
|
C++ | UTF-8 | 618 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int chk_fl(int n){
int num=1, fl=0, odd=1;
while (n>num){
num += odd;
odd += 2;
fl++;
}
return fl-1;
}
int lastnum(int n){
int num=1, odd=1;
while (n>num){
num += odd;
odd += 2;
}
return num;
}
int chk(int n){
int last = lastnum(n);
if ((last-n)%2==0) return 1; //คว่ำ
return 0; //หงาย
}
int wall(int n){
if (n==1) return 0;
if (chk(n)==0){
return chk_fl(n)*2;
}
return chk_fl(n)*2-1;
}
int main(){
int n;
cin >> n;
cout << wall(n);
} |
Markdown | UTF-8 | 1,654 | 3.171875 | 3 | [
"MIT"
] | permissive | # rongzhuang.me
My personal website hosted on Github, built with Jekyll, Liquid and MarkDown.
<kbd></kbd>
<kbd></kbd>
<kbd></kbd>
# Function
This website is mainly used to demonstrate my portfolios and share my knowledge about software development through tutorials.
* Profile - Introduction of myself.
* Portfolio - Over 15 software portfolios with detailed explanation and live demos
* Tutorial - Over 160 tutorials for software development, including iOS, Android, Angular, React, Docker, etc.
* Blog - My technical blogs.
* Favorite - Popular open-source projects and useful online tools for software development.
# Demo
Two available demos:
* `Live Demo on GitHub:` <a href="https://rongzhuang.me/" target="\_blank">https://rongzhuang.me/</a>
* `Live Demo on Netlify:` <a href="https://jojozhuang.netlify.com/" target="\_blank">https://jojozhuang.netlify.com/</a>
# Setup Locally
```bash
git clone https://github.com/jojozhuang/jojozhuang.github.io.git
cd jojozhuang.github.io
bundle exec jekyll serve --port 12001
```
Access http://localhost:12001/ in web browser, enjoy!
# Deployment
Follow tutorial [Deploying Jekyll Website to Netlify](https://rongzhuang.me/popular/jekyll/deploying-jekyll-website-to-netlify/) to continuously deploy this personal website to Netlify.
# Tutorial
Read tutorial [Setting up Jekyll on Ubuntu and macOS](https://rongzhuang.me/popular/jekyll/setting-up-jekyll-on-ubuntu-and-macos/) and follow-on tutorials to learn how to build personal website and deploy to GitHub Pages.
|
Python | UTF-8 | 1,549 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 14:22:28 2018
@author: miile7
"""
import my_utilities
import View.ToolWizard.Tool
import DataHandling.DataContainer
class BackgroundSubtractionTool(View.ToolWizard.Tool.Tool):
def __init__(self):
"""Initialize the tool"""
super(BackgroundSubtractionTool, self).__init__("background_subtraction",
title="Subtract Background",
tooltip="Subtract the background data from a sample",
action_name="Subtract Background",
calculating_text="Subtracting Background...",
icon=my_utilities.image("icon_difference.svg"),
needs_background_datacontainer=True,
needs_measurement_type=True
)
def initializeTool(self):
"""Initialize the tool"""
self.addCalculation(self.subtractBackground)
@property
def preview(self):
wizard = self.wizard
return(wizard.measurement_variable,
DataHandling.DataContainer.DataContainer.MAGNETIZATION)
@preview.setter
def preview(self, value):
return False
def subtractBackground(self):
"""Subtract the background for the wizards datacontainers. This is the
calculation callback"""
self.wizard.result_datacontainer = self.wizard.controller.subtractBackgroundData(
self.wizard.result_datacontainer,
self.wizard.background_datacontainer
) |
Shell | UTF-8 | 418 | 2.53125 | 3 | [] | no_license | #!/bin/bash
cd /home/mfeys/work/data/event_mall/splits
for dir in *
do
echo $dir
cd /home/mfeys/work/data/event_mall/splits/$dir
sudo chmod 666 *
read ndocs filename <<< $(wc -l docids)
nclusters=$(python -c "import numpy as np; print 4*np.sqrt($ndocs)")
sudo /home/mfeys/work/eventmall/bin/vcluster matrix $nclusters -clustfile=clust -cltreefile=tree -showtree -zscores -colmodel=none -showfeatures > features
done
|
C++ | UTF-8 | 437 | 3.59375 | 4 | [] | no_license | //
// Created by May on 2018/10/31.
//
#include "1_inline_functions.h"
#include "iostream"
inline double square(double x) {
return x * x;
}
int inline_square() {
double a = 12;
double b = 3.14;
std::cout << "square of " << a << " is: " << square(a) << std::endl;
std::cout << "square of " << b << " is: " << square(b) << std::endl;
std::cout << "square of " << a + b << " is: " << square(a + b) << std::endl;
} |
Java | UTF-8 | 320 | 2.046875 | 2 | [] | no_license | package gr.codehub.app;
public class Main {
public static void main(String[] args) {
UI ui = new UI();
Basket basket = new Basket();
ui.manageBasket(basket);
//basket.add(new Product("A1", "Ice Cream", 1.3f, 12));
//basket.add(new Product("A2", "Potato", 1.1f, 7));
}
}
|
Shell | UTF-8 | 2,570 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash
# PGP - based on the Panamax.io installer
BLU="\033[0;31;34m"
WHT="\033[0m\033[31;37m"
END="\033[0m"
function displayLogo1 {
tput clear
echo -e "\033[0;31;34m█████╗ ██████╗ ███████╗ \033[0m\033[31;37m ██╗ ██████╗ ██║╔██ ╔██\033[0m"
echo -e "\033[0;31;34m██╔═ ██╗ ╚═══██╗ ███╗ ███╗\033[0m\033[31;37m ██║ ╚═══██╗ ██║╔██ ║██\033[0m"
echo -e "\033[0;31;34m██║ ║██║ ███████║ ███║ ███║\033[0m\033[31;37m ██║ ███████║ ██║╔██ ║██\033[0m"
echo -e "\033[0;31;34m██╚═ ██║ ██╔═╗██║ ███║ ███║\033[0m\033[31;37m ██╚═══╗ ██╔═╗██║ ██║╔██ ║██\033[0m"
echo -e "\033[0;31;34m█████╗ ███████║ ███║ ███║\033[0m\033[31;37m ██████║ ███████║ ██████████\033[0m"
echo ""
echo "Danlaw Labs - http://www.danlawinc.com/"
}
function displayLogo2 {
echo -e " $BLU█████ ██████ ███████ ██ ██████ ██ ██ ██$END"
echo -e "$WHT ╔═$BLU██$WHT═══$BLU██$WHT═══════$BLU██$WHT══$BLU█████████$WHT══$BLU██$WHT═══════════$BLU██$WHT══$BLU██$WHT══$BLU██$WHT══$BLU██$END"
echo -e "$WHT╔ $BLU██ ██ ███████ ███ ███ ██ ███████ ██ ██ ██$END"
echo -e "$WHT║ $BLU██ ██ ██ ██ ███ ███ ██ ██ ██ ██ ██ ██$END"
echo -e "$WHT╚ $BLU█████ ███████ ███ ███ ██████ ███████ ██████████$END"
echo -e "$WHT ╚═══════════════════════════╗$END"
echo -e "$WHT ╚═══════╗$END"
echo -e "$WHT ╚═════╗ $END"
echo -e "$WHT ╚═══╗ $END"
echo -e "$WHT ╚═╗ $END"
echo ""
echo "Danlaw Labs - http://www.danlawinc.com/"
}
displayLogo1
echo
displayLogo2
|
Java | UTF-8 | 3,751 | 2 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2016 seleniumQuery authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endtoend.functions.jquery.events;
import static io.github.seleniumquery.SeleniumQuery.$;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static testinfrastructure.testutils.DriverInTest.isEdgeDriver;
import static testinfrastructure.testutils.DriverInTest.isFirefoxDriver;
import static testinfrastructure.testutils.DriverInTest.isHtmlUnitDriver;
import static testinfrastructure.testutils.DriverInTest.isIEDriver;
import static testinfrastructure.testutils.DriverInTest.isOperaDriver;
import static testinfrastructure.testutils.DriverInTest.isPhantomJSDriver;
import static testinfrastructure.testutils.DriverInTest.isSafariDriver;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import testinfrastructure.junitrule.SetUpAndTearDownDriver;
import testinfrastructure.junitrule.annotation.JavaScriptEnabledOnly;
public class DoubleClickFunctionTest {
@ClassRule @Rule public static SetUpAndTearDownDriver setUpAndTearDownDriverRule = new SetUpAndTearDownDriver();
@Test @JavaScriptEnabledOnly
public void dblclick_function() {
assertThat($("div").size(), is(0));
$("#i1").dblclick();
int operaDiff = 0;
int otherDiff = 0;
WebDriver driver = $.driver().get();
if (isOperaDriver(driver)) {
operaDiff++;
} else if (isHtmlUnitDriver(driver)
|| isIEDriver(driver)
|| isPhantomJSDriver(driver)
|| isSafariDriver(driver)
|| isFirefoxDriver(driver)
|| isEdgeDriver(driver)) {
otherDiff++;
}
assertThat($("div.click.i1").size(), is(1 + operaDiff + otherDiff)); // 2 when simulated manually
assertThat($("div.click.body").size(), is(1 + operaDiff + otherDiff)); // 2
assertThat($("div.dblclick.i1").size(), is(1));
assertThat($("div.dblclick.body").size(), is(1));
assertThat($("div").size(), is(4 + operaDiff*2 + otherDiff*2)); // 6
$("#i2").dblclick();
assertThat($("div.click.i1").size(), is(1 + operaDiff + otherDiff)); // 2
assertThat($("div.dblclick.i1").size(), is(1));
assertThat($("div.click.i2").size(), is(1 + operaDiff + otherDiff)); // 2
assertThat($("div.dblclick.i2").size(), is(1));
assertThat($("div.click.body").size(), is(1+1 + operaDiff*2 + otherDiff*2)); // 2+2
assertThat($("div.dblclick.body").size(), is(1+1));
assertThat($("div").size(), is(8 + operaDiff*4 + otherDiff*4)); // 12
$("body").dblclick();
assertThat($("div.click.i1").size(), is(1 + operaDiff*3 + otherDiff)); // 2
assertThat($("div.dblclick.i1").size(), is(1 + operaDiff));
assertThat($("div.click.i2").size(), is(1 + operaDiff + otherDiff)); // 2
assertThat($("div.dblclick.i2").size(), is(1));
assertThat($("div.click.body").size(), is(2+1 + operaDiff*3 + otherDiff*3)); // 4+2
assertThat($("div.dblclick.body").size(), is(2+1));
assertThat($("div").size(), is(10 + operaDiff*8 + otherDiff*5)); // 15
}
}
|
C# | UTF-8 | 2,485 | 2.59375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SimpleApi.Data;
using SimpleApi.Models;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace SimpleApi.Controllers
{
[Route("api/[controller]")]
public class LecturerController : Controller
{
private readonly ApiContext _context;
public LecturerController(ApiContext context)
{
_context = context;
}
// GET: api/values
[HttpGet]
public IEnumerable<Lecturer> Get()
{
return _context.Lecturer.ToList();
}
// GET api/values/5
[HttpGet("{id}", Name = "GetLecturer")]
public Lecturer Get(int id)
{
return _context.Lecturer.FirstOrDefault(t => t.ID == id);
}
// POST api/values
[HttpPost]
public IActionResult Post([FromBody] Lecturer value)
{
if (value == null)
{
return BadRequest();
}
_context.Add(value);
_context.SaveChanges();
return CreatedAtRoute("GetLecturer", new { id = value.ID }, value);
}
// PUT api/values/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Lecturer value)
{
if (value.ID != id || value == null)
{
return BadRequest();
}
var lecturer = _context.Lecturer.FirstOrDefault(t => t.ID == id);
if (lecturer == null)
{
return NotFound();
}
lecturer.Research = value.Research;
lecturer.Name = value.Name;
lecturer.Nip = value.Nip;
_context.Lecturer.Update(lecturer);
_context.SaveChanges();
return new NoContentResult();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var lecturer = _context.Lecturer.FirstOrDefault(t => t.ID == id);
if (lecturer == null)
{
return NotFound();
}
var entity = _context.Lecturer.First(t => t.ID == id);
_context.Lecturer.Remove(entity);
_context.SaveChanges();
return new NoContentResult();
}
}
}
|
C++ | UTF-8 | 5,078 | 3.015625 | 3 | [] | no_license | //
// main.cpp
// server
//
// Created by Admin on 02.12.2020.
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <fstream>
#include <chrono>
#include <iomanip>
#include "../include/cpp_httplib/httplib.h"
#include "../include/nlohmann/json.hpp"
using json = nlohmann::json;
using namespace httplib;
std::string html_str;
void json_init(const Result& res, json& new_json)
{
if (res)
{
if (res->status == 200)
new_json = json::parse(res->body);
else
std::cout << "Status code: " << res->status << std::endl;
}
else
{
auto err = res.error();
std::cout << "Error code: " << err << std::endl;
}
}
std::string current_time_str()
{
auto current_time = std::chrono::system_clock::now();
std::time_t current_time_t = std::chrono::system_clock::to_time_t(current_time);
std::string date_new;
date_new = ctime(¤t_time_t);
std::string time_now;
if (date_new[11] != '0')
time_now += date_new[11];
time_now += date_new[12];
return time_now;
}
int current_time_int()
{
auto current_time = std::chrono::system_clock::now();
std::time_t current_time_t = std::chrono::system_clock::to_time_t(current_time);
std::string date_new;
date_new = ctime(¤t_time_t);
std::string time_now;
if (date_new[11] != '0')
time_now += date_new[11];
time_now += date_new[12];
return atoi(time_now.c_str());
}
void html_editing(std::string& html_str, const std::string& raw_arg, const std::string& arg)
{
std::size_t position = html_str.find(raw_arg);
while (position != std::string::npos)
{
html_str.replace(position, raw_arg.size(), arg);
position = html_str.find(raw_arg, position + arg.size());
}
}
void gen_response(const Request& req, Response& res)
{
html_editing(html_str, "{hourly[i].temp}", current_time_str());
json tmp;
std::fstream cache("cache.txt");
if (!cache.is_open())
std::cerr << "Error!\nFile not open\n";
else
cache >> tmp;
std::string description_raw = tmp[current_time_int()]["description"].dump();
std::string description;
for (int i = 0; i < description_raw.size(); i++)
if (description_raw[i] != char(34) && description_raw[i] != '\\')
description += description_raw[i];
html_editing(html_str, "{hourly[i].weather[0].description}", description);
std::string icon_raw = tmp[current_time_int()]["icon"].dump();
std::string icon;
for (int i = 0; i < icon_raw.size(); i++)
if (icon_raw[i] != char(34) && icon_raw[i] != '\\')
icon += icon_raw[i];
html_editing(html_str, "{hourly[i].weather[0].icon}", icon);
cache.close();
res.set_content(html_str, "text/html;charset=utf-8");
}
void gen_response_raw(const Request& req, Response& res)
{
std::fstream cache("cache.txt");
std::string rawR;
if (cache.is_open())
getline(cache, rawR, '\0');
else
{
std::cerr << "Error!\nFile not open\n";
return;
}
std::string raw;
for (int i = 0; i < rawR.length(); i++)
{
if (rawR[i] == '\\')
{
i++;
continue;
}
raw += rawR[i];
}
res.set_content(raw, "text/plain;charset=utf-8");
}
int main() {
Server svr;
Client openweather_cli("http://api.openweathermap.org");
auto openweather_res = openweather_cli.Get("/data/2.5/onecall?id=524901&appid=ff1484a9c853eaf0e82bdeee8b3cae19&lang=ru&units=metric&lat=44.95719&lon=34.11079&exclude=current,minutely,daily,alerts");
json openweather_json;
json_init(openweather_res, openweather_json);
Client worldtime_cli("http://worldtimeapi.org");
auto worldtime_res = worldtime_cli.Get("/api/timezone/Europe/Simferopol");
json worldtime_json;
json_init(worldtime_res, worldtime_json);
json tmp = json::array();
json* tmp_arr = new json[48];
for (int i = 0; i < 48; i++)
{
tmp_arr[i]["time"] = i;
tmp_arr[i]["temp"] = (int)openweather_json["hourly"][i]["temp"];
std::string description = openweather_json["hourly"][i]["weather"][0]["description"].dump();
std::string icon = openweather_json["hourly"][i]["weather"][0]["icon"].dump();
tmp_arr[i]["icon"] = icon;
tmp_arr[i]["description"] = description;
tmp[i] = tmp_arr[i];
}
delete[] tmp_arr;
std::string cache_str = tmp.dump();
std::ofstream cache("cache.txt");
if (!cache.is_open())
std::cerr << "Error!\nFile not open\n";
else
cache << cache_str;
cache.close();
std::ifstream html_file("widget.html");
if (html_file.is_open())
getline(html_file, html_str, '\0');
else
std::cerr << "Error!\nFile not open\n";
html_file.close();
svr.Get("/", gen_response);
svr.Get("/raw", gen_response_raw);
std::cout << "\nStart server... OK\n";
svr.listen("localhost", 3000);
return 0;
}
|
C# | UTF-8 | 3,237 | 2.78125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace NetFrame.auto
{
public class MessageEncoding:BaseEncode
{
/// <summary>
/// 消息体序列化,此时传入的model.Message是byte[]转成的object类型,由外部选择消息体的具体序列化方式
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static byte[] Encode(object value) {
MessageModel model = value as MessageModel;
byte[] m = model.Message == null ? null : model.Message as byte[];
//byte占位一个字节,int占位4个字节,uint16占位2个字节
int basel = 4;
int l = basel + (m == null ? 0 : m.Length);
byte[] r = new byte[l];
EncodeInt(r, 0, model.ID);
Buffer.BlockCopy(m, 0, r, basel, m.Length);
return r;
#region 性能不好放弃
//SocketModel model = value as SocketModel;
//ByteArray ba = new ByteArray();
//ba.write(model.Type);
//ba.write(model.Area);
//ba.write(model.Command);
////判断消息体是否为空,不为空则直接写入
//if (model.Message != null)
// //ba.write(SerializeUtil.Encode(model.Message));
// ba.write(model.Message as byte[]);
//byte[] result = ba.getBuff();
//ba.Close();
//return result;
#endregion
}
/// <summary>
/// 消息体反序列化,此时传出的model.Message是byte[]转成的object类型,由外部选择消息体的具体序列化方式
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object Decode(byte[] value) {
MessageModel model = new MessageModel();
model.ID = DecodeInt(value, 0);
if (value.Length > 4) {
byte[] message = new byte[value.Length - 4];
Buffer.BlockCopy(value, 4, message, 0, message.Length);
model.Message = message;
}
return model;
#region 性能不好放弃
//ByteArray ba = new ByteArray(value);
//SocketModel model = new SocketModel();
//byte type;
//int area;
//int command;
////从数据中读取三层协议,读取数据顺序必须和写入顺序保持一致
//ba.read(out type);
//ba.read(out area);
//ba.read(out command);
//model.Type = type;
//model.Area = area;
//model.Command = command;
////判断读取完协议后,是否还有数据需要读取,是则说明有消息体,进行消息体读取
//if (ba.Readable) {
// byte[] message;
// //将剩余数据全部读取出来
// ba.read(out message, ba.Length - ba.Position);
// //剩余数据赋值为消息体
// model.Message = message;
//}
//ba.Close();
//return model;
#endregion
}
}
}
|
PHP | UTF-8 | 194 | 2.875 | 3 | [] | no_license | <?php
class Source
{
// The first argument of mixin functions should be $Self,
// which is a fake reference to $this
public function Foo($Self, $String = 'foo')
{
return $String;
}
}
|
Markdown | UTF-8 | 5,098 | 3.546875 | 4 | [] | no_license | # 1、操作符-区间 映射
这个章节我们继续来探索vim映射的神奇功能:“操作符-区间 映射”,让我们先来弄懂这个名词的意义,然后在使用他。
一个操作符是一个等待你来输入一个移动命令的命令,然后对你当前位置到移动后的位置之间的文本做操作。
常见的操作符有d,y,c。例如:
<pre><code>
Operator
vvvvvv
dw " Delete to next word
ci( " Change inside parents
yt, " Yank until comman
^^^^^^^^
Movement
</code></pre>
在vim里,你创建的移动命令可以和所有现存的命令配合使用。运行下面的命令:
`:onoremap p i(`
现在把下面的文本输入到vim里:
`return person.get_pets(type="cat",fluffy_only=True)`
把光标放在“cat”上,然后输入dp,会发生什么呢?vim会删除括号里的文本。你可以认为这里面的动作是“选中参数”。
上面的 onoremap 命令让vim是告诉vim当他在等待一个动作时,如果输入了p,那么就把它映射成i(。当我们输入dp的时候,就像是在说“删除参数”一样,对vim而言就是“删除括号里的内容”。
我们可以对所有的命令使用这种新映射方式,把之前的文本再次输入vim:
`return person.get_pets(type="cat", fluffy_only=True)`
把光标放在“cat”上,然后输入cp,这次又发生了什么呢?Vim还是会删除括号里的文本,不同的是这次vim会停留在inset模式,因为你用了“替换”命令,而不是“删除”命令。
下面我们看看另外一个例子,运行下面的命令:
`:onoremap b /return<cr>`
现在在vim里输入以下文本:
<pre><code>
def count(i):
i += 1
print i
return foo
</code></pre>
把光标移动到第二行的i上面,然后按下db。会出现什么呢?Vim会删除函数体里的内容,一直到“return”语句,这是因为我们的映射使用了vim的normal模式下的搜索。
当你在考虑怎么来定义一个新的操作符-区间的动作时,你可以按照下面的思路来考虑:
- 从当前位置开始;
- 进入visual模式;
- 然后是动作的映射
- 最后你要操作的文本都已经选定了
你要做的是把第三步替换成你想要的功能。
# 改变初始位置
对于我们之前学习的功能,你可能发现了一个问题,如果我们的操作只能从当前位置开始的话,这样会限制我们想要做的。
不过Vim并不会限制我们能过什么,所以这个问题还是有办法来解决的。运行下面的命令:
`:onoremap in( :<c-u>normal! f(vi(<cr`
这个命令看起来很难,不过我们可以先试试这个命令。把下面的文本输入到vim里:
`print foo(bar)`
把你的光标移动到单词“print”的任何位置上,然后输入cin(。Vim会删除括号里的内容,然后把你的光标放在中间,并且是处于insert模式下。
你可以把这个映射当做“在下一个括号里”,它会对当当前行的下一个括号里的内容执行操作符所对应的操作。
接下来我们来做一个和上面相对的命令“在上一个括号里面”。运行下面的命令:
`:onoremap il( :<c-u>normal! F)vi(<cr>`
你自己可以输入一些文本来测试上面的映射,确保它确实有效。
那么这个映射到底是怎么工作的呢?首先,<c-u>是一个现在可以暂时不考虑的命令——只要知道它的功能是为了让这个映射在所有的情况下都能正常工作的。剔除<c-u>的话,就剩下:
`:normal! F)vi(<cr>`
:normal!使我们后面将会讨论的一个命令,现在只需要知道它的功能是模拟在normal模式下按下键盘。例如:normal! dddd会删除两行文本,就像按下dddd一样。末尾的<cr>表示执行输入的命令。
所以排除上面的那些命令,就只剩下
`F)vi(`
现在就变得很简单了:
- F) :移动到最近的‘)’字符;
- vi(:进入visual模式,并且选中括号里的文本。
最后我们在visual模式下选中了我们要操作的文本,vim接着就会执行我们指定的操作。
# 常用的规则
操作符-区间 映射的创建方式多种多样,记住下面两条准则可以帮助你方便的来创建操作符-区间映射:
- 如果你的映射最后的结果是在visual模式下选择了一些文本的话,那么vim会对这些文本进行操作;
- 否则的话,vim会对光标之前的位置和当前位置之间的文本进行操作。
# 练习
- 为“靠近下一个括号”和“靠近上一个括号”建立操作符-区间映射;
- 对大括号建立上面四种映射;
- 创建一个“在下一个邮件地址里”的映射,这样的话你就可以来修改下一个邮件地址。in@是一个对实现这个映射有帮助的命令。不过你可能会用/....正则表达式..<cr>来实现。
- 阅读:help omap-info 看看你能否找到<c-u>的作用。
|
Markdown | UTF-8 | 5,334 | 2.6875 | 3 | [] | no_license | # Yehuda - Building Rich Apps
## If all I'm doing is sending JSON back and forth, what's the point of Rails? Wouldn't Sinatra or something like that be better?
- Rails is more than the surface area (HTML)
- Hides a lot of complexity very well
- Rewind to 2006 - DHH's REST keynote
- More than just HTML
- JSON, XML, iCal
- Rails as not just an HTML geenrator
- Much has been built to this end in the last few years, particularly for Rails 3
- Richness is not immediately evident
## Rails *is* a rich HTTP abstraction
- Worthwhile to read the HTTP spec (and the HTML spec)
- Sidenote - even IE is compliant with most of the spec
- Fat model, skinny controller - typical rails app is very heavy on domain logic
- Background jobs
- ActiveRecord
- Authentication
- Authorization
- Think about what percentage of your app is straight HTML rendering before you make the decision to use Rails v. Sinatra
## ActionDispatch
- Much cleaner in Rails 3 (thanks to Josh Peek)
- Middleware - getting everything to work together cleanly (Rack::Cookies, Rack::Cache) is non-trivial, edge cases are maddening
- Rapidly turns into a massive headache
- Turns into a half-assed implementation of Rails
- Ex. session - multiple stores
- Ex. standards mode (X-UA-Compatible)
- Ex. signed and permanent cookies
- Ex. parameters (JSON/XML/Nested)
- Ex. routing engine, caching, reloading, security (IP spoofing, timing attacks - google it), etc.
- Stuff that users of the framework really should not have to think about
- The reality is that ActionView is a tiny part of Rails and its ecosystem, especially in the context of your application. And HTTP is non-trivial.
- Rails is designed for this!
## Architecture
- Normal MVC
- Browser <-> Router <-> Controller <-> View (authentication/authorization happening in the controller)
- Rich client MVC is very similar, but the controller packages up the state in a serializable format for transport
- Replace view layer with a representation layout
- State of JS templating in 2005 was not good
- Rails helpers were too attractive, so people punted
- Much better now
- Eco, mustache, handlebars, dust, etc.
- No reason not to run your templates in the client
- Don't let the thought of moving your actionview layer to the client scare you
- The state transfer mechanism is the same
## "API"
- Guidance is missing
- Compare to AR - foreign key conventions, etc.
- For example
- how do you nest child resources?
- Naming/structuring keys is up to you
- Error reporting/formatting is up to you
- Makes it very difficult to write a single client - they end up being very ad-hoc
- Strobe is building a pure-API server to package a lot of this up
- ActiveResource requires way too much configuration - not very Railsy
- Difficult to make it work for both web and internal APIs
- Rules for API design
- Root needs to have 1 or more keys that indicate the type of what you're representing
- Think of it like a URL
- Lets the client figure out what's in the packet and stand alone
- No nested resources
- Difficult to infer the structure of resources or guess
- Use URL params if needed
- Remember that this is a computer protocol - humans won't see it
- An alternative could be using *only* nested resources, but has limitations around enumerating all
- Response-nested children should follow the same rules
- Don't do a mix of the nested object/list of IDs approach - pick one!
- Want to make it detectable
- Ultimate goal is one client for all of your resources
- Convention over configuration!
- Canary is: Conventional ActiveResource should be possible - work most of the time exactly like AR does
## Bulk
- Latency and response size are important considerations in mobile apps
- No current conventions for doing subset bulk operations - right now it's one or all
- Don't want to build special actions all over the place
- Ex. mark all done - 100 requests (like an N+1 but multiplied) is unacceptable
- Ideally would like to have it possible in 1 call
- Solution - bulk_api plugin (http://github.com/drogus/bulk_api) - same guy as Rails 3.1 engines
- Principles
- 1 true way to represent resource
- All requests go through a single endpoint (little ugly, but doesn't map nicely to REST)
- GET to fetch /api/bulk?posts=all, /api/bulk?posts=1,2
- POST with a nested hash of things to create
- PUT to update
- Batched updates
- Conventions
- Proxy directly to ActiveRecord absent any other configuration
- Use ApplicationResource to customize authentication/authorization with hooks
- Can't really use controllers for this which is why it's a separate object
- Can use controller-like customizations if you want (but you shouldn't)
- We're at the point where this should be easy
- Like the rest of Rails - convention over configuration
- Simple cases shouldn't cost anything
- ...but be powerful enough for advanced cases
- Machine protocols should be optimized for efficiency and consistency, not human aesthetics
- Rails is great for JSON APIs
## Q&A
- Cool stuff in Chrome around multi-request compression and SPDY
- API versions is kind of unnecessary if you have a decent representation
- Conceptual differences do fundamentally require changes |
Shell | UTF-8 | 12,760 | 4.0625 | 4 | [] | no_license | #!/bin/bash
#styleChecker: A tool to help check style in programs, according to Ord's specs
#Made by Anish Kannan
#Thanks to Nick Crow (Nack) for regex help
#TODO Check mix of tabs and spaces. Indentation. Suggests that are
#directly copypastable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
totalLinesOver80=0
totalMagicNums=0
totalBadVarNames=0
verbose=0
showSteps=0
totalNumLines=0
totalNumComments=0
totalMissingFileHeaders=0
totalMissingMethodHeaders=0
totalMissingClassHeaders=0
show_help()
{
echo "Usage: [OPTION] FILE..."
echo "Checks style for FILE(s). Ord-style"
echo "-v, --verbose print the results of each grep to find which lines have issues."
echo "-s, --show show all of the steps along the way."
}
while getopts "h?v" opt; do
case "$opt" in
h|\?)
show_help
exit 0
;;
v) verbose=1
;;
s) showSteps=1
;;
esac
done
shift $((OPTIND-1))
if (($# < 1)); then
show_help
exit 0
fi
#Loop through files.
for fileName in "$@"
do
localLinesOver80=0
localMagicNums=0
localBadVarNames=0
localNumLines=0
localNumComments=0
localMissingFileHeaders=0
localMissingMethodHeaders=0
localMissingClassHeaders=0
echo "Checking $fileName"
#####################COMMENT PROPORTIONS###############
if (($showSteps == 1)); then
echo "Checking for comment proportions."
fi
#Handle // comments
localNumLines=$(wc -l < $fileName)
localNumComments=$(grep -E -c "\/\/" $fileName)
#For later to keep track of which lines are comments
doubleSlashCommentLines=$(grep -n "\/\/" $fileName | cut -f1 -d ":")
#Initializing it for each file.
unset commentArray
unset doubleSlashCommentArray
read -a doubleSlashCommentArray <<< $doubleSlashCommentLines
#Looping through line nums to put into the array.
DSArraySize=$((${#doubleSlashCommentArray[@]} - 1))
for commentArrayIndex in `seq 0 $DSArraySize`
do
#To check whether a line is a comment, just check the value at line number.
#A double slash comment is 1
commentArray[${doubleSlashCommentArray[$commentArrayIndex]}]=1
done
#Handle /* */ comments
startCommentLines=$(grep -n "\/\*" $fileName | cut -f1 -d ":")
endCommentLines=$(grep -n "\*\/" $fileName | cut -f1 -d ":")
#Initializing for each file.
unset startCommentArray
unset endCommentArray
#Putting these in an array.
read -a startCommentArray <<< $startCommentLines
read -a endCommentArray <<< $endCommentLines
arraySize=$((${#startCommentArray[@]} - 1))
#Actually checking the lengths of multiline comments.
index=0
for index in `seq 0 $arraySize`
do
localNumComments=$((${endCommentArray[$index]} - ${startCommentArray[$index]} + $localNumComments))
#For later, to keep track of which lines are comments. A "/* */" comment
#is 2.
for commentArrayIndex in `seq ${startCommentArray[$index]} ${endCommentArray[$index]}`
do
commentArray[$commentArrayIndex]=2
done
done
proportion=$(bc <<< "scale=2; $localNumComments / $localNumLines * 100")
echo "** $proportion% of $fileName is comments. 25%-50% is usually good."
echo
totalNumLines=$(($localNumLines + $totalNumLines))
totalNumComments=$(($localNumComments + $totalNumComments))
##########################LONG LINES###################
if (($showSteps == 1)); then
echo "Checking for lines over 80 chars..."
fi
if (($verbose == 1)); then
grep -EnH '.{81}' $fileName
fi
localLinesOver80=$(grep -Ec '.{81}' "$fileName")
totalLinesOver80=$(($localLinesOver80 + $totalLinesOver80))
if (($localLinesOver80 != 0)); then
echo " ** $localLinesOver80 lines over 80 chars in $fileName"
echo
fi
#######################BAD VARIABLE NAMES##############
#Catches when the variable is assigned.
#Catches single letter vars with numbers, ex. i1
#Updated: 5/28/15 21:11 (Purag Moumdjian)
if (($showSteps == 1)); then
echo "Checking for 1 letter variable names."
fi
if (($verbose == 1)); then
grep -PinH "([a-z]+(\s?\[\])*\s)([a-z]([0-9]*)\s?(?=[;:=]))" $fileName
fi
localBadVarNames=$(grep -Pci "([a-z]+(\s?\[\])*\s)([a-z]([0-9]*)\s?(?=[;:=]))" $fileName)
totalBadVarNames=$(($localBadVarNames + $totalBadVarNames))
if (($localBadVarNames != 0)); then
echo "** $localBadVarNames single-letter names in $fileName"
echo
fi
############FILE HEADERS################
#Unintelligent, looking for the word "login" lines after "/*"
#Case-insensitive.
#Thank you stack overflow
if (($showSteps == 1)); then
echo "Checking for missing file headers..."
fi
localMissingFileHeaders=$(grep -Pzic "(?s)(\/\*|\/\/).*\n.*login" $fileName)
if (($localMissingFileHeaders == 0)); then
echo "** Missing File Header in $fileName"
echo
totalMissingFileHeaders=$((1+$totalMissingFileHeaders))
fi
############METHOD/CLASS HEADERS################
#First looks for access modifiers then checks for names of classes.
#Case-insensitive.
#First get the lines with an access modifier: These are classes,
#instance variables, and methods.
linesWithAccessModifier=$(grep -Eon "public|private" $fileName | cut -f1 -d ":")
#Initializing for each file.
unset accessModifierLinesArray
read -a accessModifierLinesArray <<< $linesWithAccessModifier
lastLineIndexToCheck=$((${#accessModifierLinesArray[@]} - 1))
#Initializing for each file
methodIndex=0
classIndex=0
instanceVarIndex=0
#Arrays.
unset methodNames
unset classNames
unset instanceVarLines
#Get all the names we will search for. Looking for open parens
for lineNumIndex in `seq 0 $lastLineIndexToCheck`
do
#First removing instance var objects with same line declaration and initialization.
instanceVarCheck=$(sed "${accessModifierLinesArray[$lineNumIndex]}!d" $fileName | grep -Eo "=")
#If there is an "=", this must be an instance variable.
if [[ ! -z "$instanceVarCheck" ]]; then
instanceVarLines[$instanceVarIndex]=${accessModifierLinesArray[$lineNumIndex]}
instanceVarIndex=$(($instanceVarIndex + 1))
else
#Check for method names
result=$(sed "${accessModifierLinesArray[$lineNumIndex]}!d" $fileName | grep -Po "\S+(?=\()")
#If the word is a valid method then put it in methodNames
if [[ ! -z "$result" ]]; then
methodNames[$methodIndex]=$result
methodIndex=$(($methodIndex + 1))
#If the word is not a method then check if it is a class
else
result=$(sed "${accessModifierLinesArray[$lineNumIndex]}!d" $fileName | grep -Po "class\s+[^{\s]+" | cut -f2 -d " ")
#If the word is a valid class then put it in classNames
if [[ ! -z "$result" ]]; then
classNames[$classIndex]=$result
classIndex=$(($classIndex + 1))
#Must be an instance variable. Store the line number to check for magic vars.
else
instanceVarLines[$instanceVarIndex]=${accessModifierLinesArray[$lineNumIndex]}
instanceVarIndex=$(($instanceVarIndex + 1))
fi
fi
fi
done
if (($showSteps == 1)); then
echo "Checking for missing method headers..."
fi
lastMethodIndexToCheck=$((${#methodNames[@]} - 1))
#Grep the names of methods to see if there is an appropriate comment.
for methodName in `seq 0 $lastMethodIndexToCheck`
do
result=$(grep -Eic "Name:\s*${methodNames[$methodName]}" $fileName)
if ((result == 0)); then
echo "** Missing method header for ${methodNames[$methodName]} in $fileName"
totalMissingMethodHeaders=$((1+$totalMissingMethodHeaders))
fi
done
lastClassIndexToCheck=$((${#classNames[@]} - 1))
if (($showSteps == 1)); then
echo "Checking for missing class headers..."
fi
#Grep the names of classes to see if there is an appropriate comment.
for className in `seq 0 $lastClassIndexToCheck`
do
result=$(grep -Eic "Name:\s*${classNames[$className]}" $fileName)
if (($result == 0)); then
echo "** Missing class Header for ${classNames[$className]} in $fileName"
totalMissingClassHeaders=$((1+$totalMissingClassHeaders))
fi
done
#################MAGIC NUMBERS#########################
if (($showSteps == 1)); then
echo "Checking for magic numbers..."
fi
#initializing it for each file.
unset magicNumsArray
magicNumLines=$(grep -Pon '[\s,\+\-\/\*=](([2-9]\d*)|(1\d+))' $fileName | cut -f1 -d ":")
read -a magicNumsArray <<< $magicNumLines
lastNumIndexToCheck=$((${#magicNumsArray[@]} - 1))
lastInstanceVarIndex=$((${#instanceVarLines[@]} - 1))
#From these magic numbers, remove those that are actually instance variables.
numLine=0
while [ $numLine -lt $lastNumIndexToCheck ]
do
#First check if the magic number appeared in a "//" comment.
isBad=1
if [[ ${commentArray[${magicNumsArray[$numLine]}]} -eq 1 ]]; then
#We know there is a comment on the line, want to check if it starts before the number.
#Eg: "int potato = 0 //64 is my favorite number" should be ok.
checkCommentInLine=$(sed "${commentArray[${magicNumsArray[$numLine]}]}!d" $fileName | awk -F "//" '{print $1}')
#Need to remove extraneous matches that are due to commented out portions.
numsToBeIgnored=$(sed "${commentArray[${magicNumsArray[$numLine]}]}!d" $fileName | awk -F "//" '{print $2}')
#Note there is a space here before numsToBeIgnored in case the magic num is right after the "//".
commentIgnoreResult=$( echo " $numsToBeIgnored" | grep -Po '[\s,\+\-\/\*=]([2-9]\d*)|(1\d+)' | wc -l)
#If there are commented magic numbers, then increment numLine to skip those.
if [[ -z $commentResult ]]; then
numLine=$(($numLine+ $commentIgnoreResult))
#We've already removed magic nums after the comment. Any other
#matches are actual magic numbers.
commentArray[${magicNumsArray[$numLine]}]=3
fi
#Still need to check if this number is magic.
commentResult=$( echo " $checkCommentInLine" | grep -Pon '[\s,\+\-\/\*=]([2-9]\d*)|(1\d+)' | cut -f1 -d ":")
#If the grep didn't find the number, then it was after the "//"
if [[ -z $commentResult ]]; then
isBad=0
fi
#If the magic number appeared in a "/* */" comment.
else
if [[ ${commentArray[${magicNumsArray[$numLine]}]} -eq 2 ]]; then
isBad=0
fi
fi
#If it is still bad, then check it's an instance variable.
#If so then it isn't a magic number. Note: ignoring static and final.
#public instance variables are also ok.
if [[ $isBad -eq 1 ]]; then
for numInstanceVar in `seq 0 $lastInstanceVarIndex`
do
if [[ ${magicNumsArray[$numLine]} -eq ${instanceVarLines[$numInstanceVar]} ]]; then
isBad=0
fi
done
fi
if (($isBad == 1)); then
localMagicNums=$(($localMagicNums + 1))
if (($verbose == 1)); then
echo -n "Line ${magicNumsArray[$numLine]}:"
sed "${magicNumsArray[$numLine]}!d" $fileName
fi
fi
#Increment for loop.
numLine=$(($numLine + 1))
done
totalMagicNums=$(($localMagicNums + $totalMagicNums))
if [[ !$localMagicNums -eq 0 ]]; then
echo "** $localMagicNums magic nums in $fileName"
echo
fi
done
proportion=$(bc <<< "scale=2; $totalNumComments / $totalNumLines * 100")
echo "-----RESULTS-----"
echo "$proportion% of files are comments. 25%-50% is usually good."
echo "$totalMissingMethodHeaders missing method headers."
echo "$totalMissingClassHeaders missing class headers."
echo "$totalMissingFileHeaders missing file headers."
echo "$totalBadVarNames bad variable names."
echo "$totalLinesOver80 lines over 80."
echo "$totalMagicNums magic numbers."
|
JavaScript | UTF-8 | 1,122 | 3.171875 | 3 | [] | no_license | var QueueDOMManipulator = function(player) {
this.$player = player;
};
QueueDOMManipulator.prototype.onPlaySong = function(songURL, songIndex){
var sourceElement = this.createSourceElement(songURL);
this.$player.appendChild(sourceElement);
this.$player.play();
this.updateHighlighting(songIndex);
};
QueueDOMManipulator.prototype.onPause = function(){
this.$player.pause();
};
QueueDOMManipulator.prototype.onResume = function(){
this.$player.play();
};
QueueDOMManipulator.prototype.updateHighlighting = function(songIndex){
var $currentSongRow = this.getCurrentSongRowElement(songIndex);
$currentSongRow.addClass("playing-now");
var $previousSongRow = $currentSongRow.prev("tr.song-row");
$previousSongRow.removeClass("playing-now");
};
QueueDOMManipulator.prototype.createSourceElement = function(songURL){
var sourceElement = document.createElement('source');
sourceElement.type = 'audio/mp3';
sourceElement.src = songURL;
return sourceElement;
};
QueueDOMManipulator.prototype.getCurrentSongRowElement = function(songIndex){
return $("tr.song-row:eq(" + songIndex + ")");
};
|
Java | UTF-8 | 1,032 | 3.46875 | 3 | [] | no_license | public class BagLauncher {
public static void main (String[] args) {
System.out.println("Three Rings for the Elven-kings under the sky, \n" +
"Seven for the Dwarf-lords in halls of stone, \n" +
"Nine for Mortal Men, doomed to die, \n" +
"One for the Dark Lord on his dark throne \n" +
"In the Land of Mordor where the Shadows lie. \n" +
"One Ring to rule them all, One Ring to find them, \n" +
"One Ring to bring them all and in the darkness bind them. \n" +
"In the Land of Mordor where the Shadows lie.");
System.out.println("=====================================================");
Mordor Khand = new Mordor();
Khand.printStory();
Bag frodosBag = new Bag("big", "brown");
System.out.println("The hobbit bag that Sauron is holding is " +
frodosBag.getColor() + " and its " + frodosBag.getSize() + ".");
frodosBag.initializeStack();
}
}
|
Python | UTF-8 | 536 | 2.84375 | 3 | [] | no_license | import os
from random import choice, seed, randint
seed(os.urandom(10))
folder = os.path.dirname(__file__)
def build_tweet():
files = [myfile for myfile in os.listdir(folder) if myfile.endswith('.txt')]
with open(folder + '/' + choice(files),'r') as fp:
song = ''.join(fp.readlines())
artist, title = os.path.basename(fp.name).replace('_',' ').replace('.txt','').split('-')
start = randint(0, len(song) - 120)
lyrics = song[start:start + 120]
return lyrics + '\n\nfrom: ' + artist + ' - ' + title
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.